text stringlengths 2 1.04M | meta dict |
|---|---|
package org.encuestame.core.service.imp;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.encuestame.core.service.ServiceOperations;
import org.encuestame.persistence.domain.AccessRate;
import org.encuestame.persistence.domain.HashTag;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.Survey;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.encuestame.persistence.exception.EnMeExpcetion;
import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
import org.encuestame.persistence.exception.EnMeSearchException;
import org.encuestame.utils.enums.HitCategory;
import org.encuestame.utils.enums.SearchPeriods;
import org.encuestame.utils.enums.Status;
import org.encuestame.utils.enums.TypeSearchResult;
import org.encuestame.utils.json.HomeBean;
import org.encuestame.utils.json.LinksSocialBean;
import org.encuestame.utils.json.TweetPollBean;
import org.encuestame.utils.web.HashTagBean;
import org.encuestame.utils.web.PollBean;
import org.encuestame.utils.web.ProfileRatedTopBean;
import org.encuestame.utils.web.SurveyBean;
import org.encuestame.utils.web.stats.GenericStatsBean;
import org.encuestame.utils.web.stats.HashTagRankingBean;
/**
* Implementation for Front End Service.
* @author Picado, Juan juanATencuestame.org
* @since Oct 17, 2010 11:29:51 AM
* @version $Id:$
*/
public interface IFrontEndService extends ServiceOperations {
/**
* Search Items By TweetPoll.
* @param maxResults limit of results to return.
* @return result of the search.
* @throws EnMeSearchException search exception.
*/
List<TweetPollBean> searchItemsByTweetPoll(
final String period,
final Integer start,
Integer maxResults,
final HttpServletRequest request)
throws EnMeSearchException;
/**
* Search Items By TweetPoll.
* @param period period of time to limit results
* @param start pagination start
* @param maxResults limit of results
* @param request {@link HttpServletRequest}
* @param addResults define if the search will add results (this makes it slower the operation)
* @return
* @throws EnMeSearchException
*/
List<TweetPollBean> searchItemsByTweetPoll(
final String period,
final Integer start,
Integer maxResults,
final HttpServletRequest request,
final Boolean addResults) throws EnMeSearchException;
/**
* Search items by poll.
* @param period period of time to limit results
* @param start pagination start
* @param maxResults limit of results
* @return
* @throws EnMeSearchException
*/
List<PollBean> searchItemsByPoll(
final String period,
final Integer start,
Integer maxResults,
final HttpServletRequest request)
throws EnMeSearchException;
/**
* Search items by poll.
* @param period period of time to limit results
* @param start pagination start
* @param maxResults limit of results
* @param addResults define if the search will add results (this makes it slower the operation)
* @return
* @throws EnMeSearchException
*/
List<PollBean> searchItemsByPoll(
final String period,
final Integer start,
Integer maxResults,
final HttpServletRequest request,
final Boolean addResults) throws EnMeSearchException;
/**
* List Hash tags
* @param maxResults
* @param start
* @param tagCriteria
* @return
*/
List<HashTagBean> getHashTags(
Integer maxResults,
final Integer start,
final String tagCriteria);
/**
* Get hashTag item.
* @param tagName
* @return
* @throws EnMeNoResultsFoundException
*/
HashTag getHashTagItem(final String tagName) throws EnMeNoResultsFoundException;
/**
* Get TweetPolls by hashTag id.
* @param hashTagId
* @param limit
* @param request
* @return
*/
List<TweetPollBean> getTweetPollsbyHashTagName(final String tagName, final Integer initResults,
final Integer limit, final String filter,
final HttpServletRequest request, final SearchPeriods searchPeriods);
/**
* Get frontEnd items.
* @param period
* @param start
* @param maxResults
* @param request
* @return
* @throws EnMeSearchException
* @throws EnMeNoResultsFoundException
*/
List<HomeBean> getFrontEndItems(final String period, final Integer start,
Integer maxResults, final HttpServletRequest request)
throws EnMeSearchException, EnMeNoResultsFoundException;
/**
* Return a collection of all items
* @param period period of time to limit results
* @param start pagination start
* @param maxResults limit of results
* @param request {@link HttpServletRequest}
* @param addResults define if the search will add results (this makes it slower the operation)
* @return
* @throws EnMeSearchException
* @throws EnMeNoResultsFoundException
*/
List<HomeBean> getFrontEndItems(
final String period,
final Integer start,
final Integer maxResults,
final Boolean addResults,
final HttpServletRequest request) throws EnMeSearchException, EnMeNoResultsFoundException;
/**
* Check previous item hit.
* @param ipAddress
* @param id
* @param searchHitby
* @return
*/
Boolean checkPreviousHit(final String ipAddress, final Long id, final TypeSearchResult searchHitby);
/**
* Register hit.
* @param tweetPoll
* @param poll
* @param survey
* @param tag
* @param ip
* @return
* @throws EnMeNoResultsFoundException
*/
Boolean registerHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
final String ip, final HitCategory hitCategory) throws EnMeNoResultsFoundException;
/**
* Register access rate.
* @param type
* @param itemId
* @param ipAddress
* @param rate
* @return
* @throws EnMeExpcetion
*/
AccessRate registerAccessRate(final TypeSearchResult type,
final Long itemId, final String ipAddress, final Boolean rate)
throws EnMeExpcetion;
/**
* Search items by survey.
* @param period
* @param start
* @param maxResults
* @param request
* @return
* @throws EnMeSearchException
*/
List<SurveyBean> searchItemsBySurvey(final String period,
final Integer start, Integer maxResults,
final HttpServletRequest request) throws EnMeSearchException;
/**
* Process items to calculate relevance on home page.
* @param tweetPollList
* @param pollList
* @param surveyList
* @param datebefore
* @param todayDate
*/
void processItemstoCalculateRelevance(
final List<TweetPoll> tweetPollList,
final List<Poll> pollList,
final List<Survey> surveyList,
final SearchPeriods periods);
/**
* Get the list with the users rated top.
* @param status
* @return
* @throws EnMeNoResultsFoundException
*/
List<ProfileRatedTopBean> getTopRatedProfile(final Boolean status)
throws EnMeNoResultsFoundException;
/**
* Return last publications by {@link HashTag}.
* @param hashTag {@link HashTag}
* @param keyword keyword if not null, the search should be by keyword.
* @param limit limit of items
* @param filter order by
* @param request {@link HttpServletRequest}.
* @return
**/
List<HomeBean> searchLastPublicationsbyHashTag(
final HashTag hashTag, final String keyword, final Integer initResults, final Integer limit,
final String filter, final HttpServletRequest request);
/**
*
* @param hash
* @param start
* @param max
* @return
*/
List<LinksSocialBean> getHashTagLinks(final HashTag hash, final Integer start,
final Integer max);
/**
* Get hashTag ranking.
* @param tagName
* @return
*/
List<HashTagRankingBean> getHashTagRanking(final String tagName);
/**
* Generic stats for {@link TweetPoll}, {@link Poll}, {@link Survey} or {@link HashTag}.
* @param itemId
* @param itemType
* @return
* @throws EnMeNoResultsFoundException
*/
GenericStatsBean retrieveGenericStats(final String itemId,
final TypeSearchResult itemType, final HttpServletRequest request)
throws EnMeNoResultsFoundException;
/**
* Return the last items published from {@link UserAccount}.
* @param username
* @param maxResults
* @param showUnSharedItems
* @param request
* @return
* @throws EnMeNoResultsFoundException
*/
List<HomeBean> getLastItemsPublishedFromUserAccount(
final String username,
final Integer maxResults,
final Boolean showUnSharedItems,
final HttpServletRequest request) throws EnMeNoResultsFoundException;
/**
* Get TweetPolls by hashTag.
* @param tagId
* @param initResults
* @param maxResults
* @param filter
* @return
List<TweetPoll> getTweetPollsByHashTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter);*/
/**
*
* @return
* @throws EnMeNoResultsFoundException
*/
Status registerVote(
final Long itemId,
final TypeSearchResult searchResult,
final String ipAddress) throws EnMeExpcetion;
/**
* Retrieve total items published by User
* @param user
* @param status
* @param typeSearch
* @return
* @throws EnMeSearchException
*/
Long getTotalItemsPublishedByType(final UserAccount user,
final Boolean status, final TypeSearchResult typeSearch)
throws EnMeSearchException;
} | {
"content_hash": "463f7577efa0633db311350c56ca56ac",
"timestamp": "",
"source": "github",
"line_count": 327,
"max_line_length": 107,
"avg_line_length": 31.828746177370032,
"alnum_prop": 0.6662182936202921,
"repo_name": "cristiani/encuestame",
"id": "a0c7cf1d769f3f334326cb57fa1c8f7954837348",
"size": "11178",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "enme-core/src/main/java/org/encuestame/core/service/imp/IFrontEndService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9772228"
},
{
"name": "HTML",
"bytes": "552"
},
{
"name": "Java",
"bytes": "4752329"
},
{
"name": "JavaScript",
"bytes": "7194351"
},
{
"name": "Ruby",
"bytes": "1012"
},
{
"name": "Shell",
"bytes": "4346"
}
],
"symlink_target": ""
} |
#include <gtest/gtest.h>
#include <proxygen/lib/http/HTTPHeaderSize.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include <proxygen/lib/http/codec/HTTP1xCodec.h>
using namespace proxygen;
using namespace std;
class HTTP1xCodecCallback : public HTTPCodec::Callback {
public:
HTTP1xCodecCallback() {}
void onMessageBegin(HTTPCodec::StreamID stream, HTTPMessage* msg) {}
void onPushMessageBegin(HTTPCodec::StreamID stream,
HTTPCodec::StreamID assocStream,
HTTPMessage* msg) {}
void onHeadersComplete(HTTPCodec::StreamID stream,
std::unique_ptr<HTTPMessage> msg) {
headersComplete++;
headerSize = msg->getIngressHeaderSize();
}
void onBody(HTTPCodec::StreamID stream,
std::unique_ptr<folly::IOBuf> chain) {}
void onChunkHeader(HTTPCodec::StreamID stream, size_t length) {}
void onChunkComplete(HTTPCodec::StreamID stream) {}
void onTrailersComplete(HTTPCodec::StreamID stream,
std::unique_ptr<HTTPHeaders> trailers) {}
void onMessageComplete(HTTPCodec::StreamID stream, bool upgrade) {}
void onError(HTTPCodec::StreamID stream,
const HTTPException& error, bool newTxn) {
LOG(ERROR) << "parse error";
}
uint32_t headersComplete{0};
HTTPHeaderSize headerSize;
};
unique_ptr<folly::IOBuf> getSimpleRequestData() {
string req("GET /yeah HTTP/1.1\nHost: www.facebook.com\n\n");
auto buffer = folly::IOBuf::copyBuffer(req);
return std::move(buffer);
}
TEST(HTTP1xCodecTest, TestSimpleHeaders) {
HTTP1xCodec codec(TransportDirection::DOWNSTREAM);
HTTP1xCodecCallback callbacks;
codec.setCallback(&callbacks);
auto buffer = getSimpleRequestData();
codec.onIngress(*buffer);
EXPECT_EQ(callbacks.headersComplete, 1);
EXPECT_EQ(buffer->length(), callbacks.headerSize.uncompressed);
EXPECT_EQ(callbacks.headerSize.compressed, 0);
}
unique_ptr<folly::IOBuf> getChunkedRequest1st() {
string req("GET /aha HTTP/1.1\n");
auto buffer = folly::IOBuf::copyBuffer(req);
return std::move(buffer);
}
unique_ptr<folly::IOBuf> getChunkedRequest2nd() {
string req("Host: m.facebook.com\nAccept-Encoding: meflate\n\n");
auto buffer = folly::IOBuf::copyBuffer(req);
return std::move(buffer);
}
TEST(HTTP1xCodecTest, TestChunkedHeaders) {
HTTP1xCodec codec(TransportDirection::DOWNSTREAM);
HTTP1xCodecCallback callbacks;
codec.setCallback(&callbacks);
// test a sequence of requests to make sure we're resetting the size counter
for (int i = 0; i < 3; i++) {
callbacks.headersComplete = 0;
auto buffer1 = getChunkedRequest1st();
codec.onIngress(*buffer1);
EXPECT_EQ(callbacks.headersComplete, 0);
auto buffer2 = getChunkedRequest2nd();
codec.onIngress(*buffer2);
EXPECT_EQ(callbacks.headersComplete, 1);
EXPECT_EQ(callbacks.headerSize.uncompressed,
buffer1->length() + buffer2->length());
}
}
TEST(HTTP1xCodecTest, TestChunkedUpstream) {
HTTP1xCodec codec(TransportDirection::UPSTREAM);
auto txnID = codec.createStream();
HTTPMessage msg;
msg.setHTTPVersion(1, 1);
msg.setURL("https://www.facebook.com/");
msg.getHeaders().set("Host", "www.facebook.com");
msg.getHeaders().set("Transfer-Encoding", "chunked");
msg.setIsChunked(true);
HTTPHeaderSize size;
folly::IOBufQueue buf(folly::IOBufQueue::cacheChainLength());
codec.generateHeader(buf, txnID, msg, 0, false, &size);
auto headerFromBuf = buf.split(buf.chainLength());
string req1("Hello");
auto body1 = folly::IOBuf::copyBuffer(req1);
string req2("World");
auto body2 = folly::IOBuf::copyBuffer(req2);
codec.generateBody(buf, txnID, std::move(body1), false);
auto bodyFromBuf = buf.split(buf.chainLength());
ASSERT_EQ("5\r\nHello\r\n", bodyFromBuf->moveToFbString());
codec.generateBody(buf, txnID, std::move(body2), true);
LOG(WARNING) << "len chain" << buf.chainLength();
auto eomFromBuf = buf.split(buf.chainLength());
ASSERT_EQ("5\r\nWorld\r\n0\r\n\r\n", eomFromBuf->moveToFbString());
}
| {
"content_hash": "1e67cd59b442f86e19f1794e08a7e0e7",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 78,
"avg_line_length": 33.47107438016529,
"alnum_prop": 0.7039506172839506,
"repo_name": "luxuan/proxygen",
"id": "9bc2e8b284fe3b523bf4cddbd12e3929bebebc99",
"size": "4357",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "proxygen/lib/http/codec/test/HTTP1xCodecTest.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "1476453"
},
{
"name": "Python",
"bytes": "6822"
},
{
"name": "Shell",
"bytes": "3773"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Sphaceloma allophylli Wani, Thirum. & M.D. Whitehead
### Remarks
null | {
"content_hash": "93b81cffc7be82d736be1d8a94ee9574",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 52,
"avg_line_length": 12.076923076923077,
"alnum_prop": 0.7070063694267515,
"repo_name": "mdoering/backbone",
"id": "21124ef960525491637f5cc130cb86af114fed73",
"size": "233",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Myriangiales/Elsinoaceae/Sphaceloma/Sphaceloma allophylli/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* Current page query parameters host class.
*
* @class FM.MlHostQueryParams
* @memberOf FM
* @extends FM.MlHost
* @param {FM.AppObject} app application object
* @param {object} [attrs] DOM node attributes
* @param {DOMnode} node DOM node
*/
FM.MlHostQueryParams = FM.defineClass('MlHostQueryParams',FM.MlHost);
FM.MlHostQueryParams.prototype._init = function(app,attrs,node) {
this._super("_init",app,attrs,node);
this.objectSubClass ="QueryParams";
}
FM.MlHostQueryParams.prototype.run = function() {
this._super("run");
this.setDmObject(new FM.DmObject(FM.getArgs()));
}
FM.MlHost.addHost("QueryParams",FM.MlHostQueryParams,'GLOBAL');
| {
"content_hash": "7be8eea483fb19cfc47b78b0cad02f50",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 77,
"avg_line_length": 27.68,
"alnum_prop": 0.6907514450867052,
"repo_name": "rbelusic/fm-js",
"id": "f392f3b26fa5c75a4d63e1f581af0392391e385c",
"size": "692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lm/ml/hosts/lm.MlHostQueryParams.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "15943"
},
{
"name": "JavaScript",
"bytes": "391189"
},
{
"name": "Shell",
"bytes": "1335"
}
],
"symlink_target": ""
} |
#include "guest_channel.h"
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "guest_limits.h"
#include "guest_types.h"
#include "guest_debug.h"
#include "guest_unix.h"
typedef struct {
bool inuse;
bool char_device;
int sock;
char dev_name[GUEST_DEVICE_NAME_MAX_CHAR];
} GuestChannelT;
static GuestChannelT _channel[GUEST_MAX_CONNECTIONS];
// ****************************************************************************
// Guest Channel - Find Empty
// ==========================
static GuestChannelIdT guest_channel_find_empty( void )
{
GuestChannelT* channel = NULL;
unsigned int channel_id;
for (channel_id=0; GUEST_MAX_CONNECTIONS > channel_id; ++channel_id)
{
channel = &(_channel[channel_id]);
if (!channel->inuse)
return channel_id;
}
return GUEST_CHANNEL_ID_INVALID;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Find
// ====================
static GuestChannelT* guest_channel_find( GuestChannelIdT channel_id )
{
GuestChannelT* channel = NULL;
if ((0 <= channel_id)&&(GUEST_MAX_CONNECTIONS > channel_id))
{
channel = &(_channel[channel_id]);
if (channel->inuse)
return channel;
}
return NULL;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Send
// ====================
GuestErrorT guest_channel_send(
GuestChannelIdT channel_id, void* msg, int msg_size )
{
GuestChannelT* channel;
ssize_t result;
channel = guest_channel_find(channel_id);
if (NULL == channel)
{
DPRINTFE("Invalid channel identifier, channel_id=%i.", channel_id);
return GUEST_FAILED;
}
result = write(channel->sock, msg, msg_size);
if (0 > result)
{
if (ENODEV == errno)
{
DPRINTFI("Channel %i on device %s disconnected.", channel_id,
channel->dev_name);
return GUEST_OKAY;
} else {
DPRINTFE("Failed to write to channel on device %s, error=%s.",
channel->dev_name, strerror(errno));
return GUEST_FAILED;
}
}
DPRINTFV("Sent message over channel on device %s.", channel->dev_name);
return GUEST_OKAY;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Receive
// =======================
GuestErrorT guest_channel_receive(
GuestChannelIdT channel_id, char* msg_buf, int msg_buf_size,
int* msg_size )
{
GuestChannelT* channel;
ssize_t result;
channel = guest_channel_find(channel_id);
if (NULL == channel)
{
DPRINTFE("Invalid channel identifier, channel_id=%i.", channel_id);
return GUEST_FAILED;
}
result = read(channel->sock, msg_buf, msg_buf_size);
if (0 > result)
{
if (EINTR == errno)
{
DPRINTFD("Interrupted on socket read, error=%s.", strerror(errno));
return GUEST_INTERRUPTED;
} else if (ENODEV == errno) {
DPRINTFI("Channel %i on device %s disconnected.", channel_id,
channel->dev_name);
*msg_size = 0;
return GUEST_OKAY;
} else {
DPRINTFE("Failed to read from socket, error=%s.", strerror(errno));
return GUEST_FAILED;
}
} else if (0 == result) {
DPRINTFD("No message received from socket.");
*msg_size = 0;
return GUEST_OKAY;
} else {
DPRINTFV("Received message, msg_size=%i.", result);
*msg_size = result;
}
return GUEST_OKAY;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Open
// ====================
GuestErrorT guest_channel_open( char dev_name[], GuestChannelIdT* channel_id )
{
int fd;
int result;
struct stat stat_data;
GuestChannelIdT empty_channel_id;
GuestChannelT* channel;
GuestErrorT error;
empty_channel_id = guest_channel_find_empty();
if (GUEST_CHANNEL_ID_INVALID == empty_channel_id)
{
DPRINTFE("Allocation of channel failed, no free resources.");
return GUEST_FAILED;
}
channel = &(_channel[empty_channel_id]);
memset(channel, 0, sizeof(GuestChannelT));
result = stat(dev_name, &stat_data);
if (0 > result)
{
int err = errno;
if (err == ENOENT)
{
DPRINTFI("Failed to stat, error=%s.", strerror(err));
DPRINTFI("%s file does not exist, guest heartbeat not configured.",
dev_name);
return GUEST_NOT_CONFIGURED;
}
else {
DPRINTFE("Failed to stat, error=%s.", strerror(err));
return GUEST_FAILED;
}
}
if (S_ISCHR(stat_data.st_mode))
{
fd = open(dev_name, O_RDWR);
if (0 > fd)
{
DPRINTFE("Failed to open device %s, error=%s.", dev_name,
strerror(errno));
return GUEST_FAILED;
}
result = fcntl(fd, F_SETFD, FD_CLOEXEC);
if (0 > result)
{
DPRINTFE("Failed to set to close on exec, error=%s.",
strerror(errno));
close(fd);
return GUEST_FAILED;
}
result = fcntl(fd, F_SETOWN, getpid());
if (0 > result)
{
DPRINTFE("Failed to set socket ownership, error=%s.",
strerror(errno));
close(fd);
return GUEST_FAILED;
}
result = fcntl(fd, F_GETFL);
if (0 > result)
{
DPRINTFE("Failed to get socket options, error=%s.",
strerror(errno));
close(fd);
return GUEST_FAILED;
}
result = fcntl(fd, F_SETFL, result | O_NONBLOCK | O_ASYNC);
if (0 > result)
{
DPRINTFE("Failed to set socket options, error=%s.",
strerror(errno));
close(fd);
return GUEST_FAILED;
}
DPRINTFI("Opened character device %s", dev_name);
} else {
error = guest_unix_open(&fd);
if (GUEST_OKAY != error)
{
DPRINTFE("Failed to open unix socket %s, error=%s.",
dev_name, guest_error_str(error));
return error;
}
error = guest_unix_connect(fd, dev_name);
if (GUEST_OKAY != error)
{
DPRINTFE("Failed to connect unix socket %s, error=%s.",
dev_name, guest_error_str(error));
close(fd);
return error;
}
DPRINTFI("Opened unix socket %s", dev_name);
}
channel->inuse = true;
snprintf(channel->dev_name, sizeof(channel->dev_name), "%s", dev_name);
channel->char_device = S_ISCHR(stat_data.st_mode);
channel->sock = fd;
*channel_id = empty_channel_id;
DPRINTFD("Opened channel over device %s.", channel->dev_name);
return GUEST_OKAY;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Close
// =====================
GuestErrorT guest_channel_close( GuestChannelIdT channel_id )
{
GuestChannelT* channel;
channel = guest_channel_find(channel_id);
if (NULL != channel)
{
if (channel->inuse)
{
if (0 <= channel->sock)
close(channel->sock);
DPRINTFD("Closed channel over device %s.", channel->dev_name);
memset(channel, 0, sizeof(GuestChannelT));
}
}
return GUEST_OKAY;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Get Selection Object
// ====================================
int guest_channel_get_selobj( GuestChannelIdT channel_id )
{
GuestChannelT *channel;
channel = guest_channel_find(channel_id);
if (NULL != channel)
return channel->sock;
return -1;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Initialize
// ==========================
GuestErrorT guest_channel_initialize( void )
{
memset(_channel, 0, sizeof(_channel));
return GUEST_OKAY;
}
// ****************************************************************************
// ****************************************************************************
// Guest Channel - Finalize
// ========================
GuestErrorT guest_channel_finalize( void )
{
memset(_channel, 0, sizeof(_channel));
return GUEST_OKAY;
}
// ****************************************************************************
| {
"content_hash": "d3fbf25729fd883b0c71e55c4e7a993c",
"timestamp": "",
"source": "github",
"line_count": 324,
"max_line_length": 79,
"avg_line_length": 28.935185185185187,
"alnum_prop": 0.4596266666666667,
"repo_name": "Wind-River/titanium-server",
"id": "557baabdcd145878620055c01a7894f5001ec7f9",
"size": "10931",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "guest-API-SDK/17.06/wrs-guest-heartbeat-3.0.1/guest_client/src/guest_channel.c",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "799451"
},
{
"name": "Makefile",
"bytes": "44481"
},
{
"name": "Shell",
"bytes": "29366"
}
],
"symlink_target": ""
} |
<!--
~ Copyright 2010 Ning, Inc.
~
~ Ning 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ning.maven.plugins.duplicate-finder-maven-plugin</groupId>
<artifactId>first-class-jar</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<defaultGoal>package</defaultGoal>
</build>
</project>
| {
"content_hash": "0686e7523facceeb83e716c03ef7543a",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 105,
"avg_line_length": 39.25806451612903,
"alnum_prop": 0.705012325390304,
"repo_name": "ning/maven-duplicate-finder-plugin",
"id": "ed875e89893d7b6771524f63f5bf7a92e7c74012",
"size": "1217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/it/setup-class-jars/first-class-jar/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "31221"
},
{
"name": "Java",
"bytes": "49728"
}
],
"symlink_target": ""
} |
package org.openengsb.labs.endtoend.util;
import java.util.Objects;
public class BinaryKey<Key1, Key2> {
private final Key1 key1;
private final Key2 key2;
public BinaryKey(Key1 key1, Key2 key2) {
this.key1 = key1;
this.key2 = key2;
}
@Override
public int hashCode() {
return Objects.hash(key1, key2);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof BinaryKey) {
return Objects.equals(key1, ((BinaryKey<?, ?>) obj).key1) && Objects.equals(key2, ((BinaryKey<?, ?>) obj).key2);
}
return false;
}
}
| {
"content_hash": "212f8d7ef0e4e79b8b411c37375b3046",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 118,
"avg_line_length": 23.115384615384617,
"alnum_prop": 0.6189683860232945,
"repo_name": "openengsb-labs/labs-endtoend",
"id": "c4d12a91d6cfdfce25234cf40ec0b7b375805dd2",
"size": "601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/openengsb/labs/endtoend/util/BinaryKey.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "80558"
}
],
"symlink_target": ""
} |
import {inject} from "mobx-react";
import * as React from "react";
import {ResolvedPageData} from "../../../src/common/bundles/page-resolver/resolved-page-data";
import {TemplateHead} from "./renderer-head";
export interface RendererMainProps {
resolvedPage: ResolvedPageData;
}
export function MainContent({resolvedPage}: RendererMainProps) {
if (!resolvedPage.found) {
return <div>404</div>;
}
const nav = resolvedPage.site.childLinks.map((link: any) => (
<li key={link.child._id}>{link.child.name}, {link.child._id}</li>
));
const pageNav = resolvedPage.page.childLinks.map((link: any) => (
<li key={link.child._id}>{link.child.name}, {link.child._id}</li>
));
return (
<div>
<h1>site: {resolvedPage.site.name}</h1>
<ul>{nav}</ul>
<h2>page children</h2>
<ul>{pageNav}</ul>
<p>{JSON.stringify(resolvedPage)}</p>
</div>
);
}
export function RendererMain({resolvedPage}: RendererMainProps) {
return (
<div>
<TemplateHead/>
<MainContent resolvedPage={resolvedPage}/>
</div>
);
}
const WrappedRendererMain = inject("resolvedPage")(RendererMain);
export {WrappedRendererMain};
| {
"content_hash": "e9c2fe06560d96c9661b9c701fbb6169",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 94,
"avg_line_length": 28.133333333333333,
"alnum_prop": 0.6074249605055292,
"repo_name": "evilfer/riacms",
"id": "30fb63ef5480a834b707e0d1badfac40e71d763a",
"size": "1266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo-site/src/template/renderer-main.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4934"
},
{
"name": "JavaScript",
"bytes": "3658381"
},
{
"name": "TypeScript",
"bytes": "306410"
}
],
"symlink_target": ""
} |
package co.nubetech.crux.dao;
import java.util.List;
import org.hibernate.JDBCException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import co.nubetech.crux.model.ReportDesign;
import co.nubetech.crux.util.CruxException;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
public class ReportDesignDAO {
@SessionTarget
Session session;
@TransactionTarget
Transaction transaction;
public ReportDesign findById(Long id) {
ReportDesign report = (ReportDesign) session
.get(ReportDesign.class, id);
return report;
}
public long save(ReportDesign report) throws CruxException {
try {
transaction.begin();
session.saveOrUpdate(report);
transaction.commit();
} catch (JDBCException e) {
transaction.rollback();
throw new CruxException(e.getSQLException().getMessage(), e);
}
return report.getId();
}
public long delete(ReportDesign report) throws CruxException {
long id = report.getId();
try {
transaction.begin();
session.delete(report);
transaction.commit();
} catch (JDBCException e) {
transaction.rollback();
throw new CruxException(e.getSQLException().getMessage(), e);
}
return id;
}
public List<ReportDesign> findAll() {
List<ReportDesign> result = session.createQuery("from ReportDesign")
.list();
return result;
}
}
| {
"content_hash": "00257b0c75af2d2f582b148ab96d1aca",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 79,
"avg_line_length": 23.85,
"alnum_prop": 0.7470300489168413,
"repo_name": "sonalgoyal/crux",
"id": "5a906811f1d6f6343c55c97fb312acf004aee40e",
"size": "2025",
"binary": false,
"copies": "1",
"ref": "refs/heads/aggregation",
"path": "src/main/java/co/nubetech/crux/dao/ReportDesignDAO.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "19954"
},
{
"name": "Groovy",
"bytes": "64"
},
{
"name": "Java",
"bytes": "1031932"
},
{
"name": "JavaScript",
"bytes": "8854027"
},
{
"name": "PHP",
"bytes": "3981"
},
{
"name": "Perl",
"bytes": "260452"
},
{
"name": "Python",
"bytes": "2803"
},
{
"name": "Racket",
"bytes": "139671"
},
{
"name": "Shell",
"bytes": "17085"
},
{
"name": "XML",
"bytes": "47635"
}
],
"symlink_target": ""
} |
package org.pmiops.workbench.workspaceadmin;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo;
import com.google.common.collect.ImmutableList;
import com.google.monitoring.v3.Point;
import com.google.monitoring.v3.TimeSeries;
import com.google.protobuf.util.Timestamps;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.inject.Provider;
import javax.mail.MessagingException;
import org.apache.commons.lang3.StringUtils;
import org.pmiops.workbench.access.AccessTierService;
import org.pmiops.workbench.actionaudit.ActionAuditQueryService;
import org.pmiops.workbench.actionaudit.auditors.AdminAuditor;
import org.pmiops.workbench.actionaudit.auditors.LeonardoRuntimeAuditor;
import org.pmiops.workbench.db.dao.CohortDao;
import org.pmiops.workbench.db.dao.ConceptSetDao;
import org.pmiops.workbench.db.dao.DataSetDao;
import org.pmiops.workbench.db.dao.UserService;
import org.pmiops.workbench.db.dao.WorkspaceDao;
import org.pmiops.workbench.db.model.DbAccessTier;
import org.pmiops.workbench.db.model.DbUser;
import org.pmiops.workbench.db.model.DbWorkspace;
import org.pmiops.workbench.exceptions.BadRequestException;
import org.pmiops.workbench.exceptions.NotFoundException;
import org.pmiops.workbench.firecloud.FireCloudService;
import org.pmiops.workbench.firecloud.FirecloudTransforms;
import org.pmiops.workbench.firecloud.model.FirecloudWorkspaceACLUpdate;
import org.pmiops.workbench.firecloud.model.FirecloudWorkspaceDetails;
import org.pmiops.workbench.google.CloudMonitoringService;
import org.pmiops.workbench.google.CloudStorageClient;
import org.pmiops.workbench.leonardo.LeonardoApiClient;
import org.pmiops.workbench.leonardo.model.LeonardoListRuntimeResponse;
import org.pmiops.workbench.leonardo.model.LeonardoRuntimeStatus;
import org.pmiops.workbench.mail.MailService;
import org.pmiops.workbench.model.AccessReason;
import org.pmiops.workbench.model.AdminLockingRequest;
import org.pmiops.workbench.model.AdminWorkspaceCloudStorageCounts;
import org.pmiops.workbench.model.AdminWorkspaceObjectsCounts;
import org.pmiops.workbench.model.AdminWorkspaceResources;
import org.pmiops.workbench.model.CloudStorageTraffic;
import org.pmiops.workbench.model.FileDetail;
import org.pmiops.workbench.model.ListRuntimeDeleteRequest;
import org.pmiops.workbench.model.ListRuntimeResponse;
import org.pmiops.workbench.model.TimeSeriesPoint;
import org.pmiops.workbench.model.UserRole;
import org.pmiops.workbench.model.WorkspaceAccessLevel;
import org.pmiops.workbench.model.WorkspaceAdminView;
import org.pmiops.workbench.model.WorkspaceAuditLogQueryResponse;
import org.pmiops.workbench.model.WorkspaceUserAdminView;
import org.pmiops.workbench.notebooks.NotebookUtils;
import org.pmiops.workbench.notebooks.NotebooksService;
import org.pmiops.workbench.utils.mappers.LeonardoMapper;
import org.pmiops.workbench.utils.mappers.UserMapper;
import org.pmiops.workbench.utils.mappers.WorkspaceMapper;
import org.pmiops.workbench.workspaces.WorkspaceAuthService;
import org.pmiops.workbench.workspaces.WorkspaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class WorkspaceAdminServiceImpl implements WorkspaceAdminService {
private static final Logger log = Logger.getLogger(WorkspaceAdminServiceImpl.class.getName());
private static final Duration TRAILING_TIME_TO_QUERY = Duration.ofHours(6);
private final AccessTierService accessTierService;
private final ActionAuditQueryService actionAuditQueryService;
private final AdminAuditor adminAuditor;
private final CloudMonitoringService cloudMonitoringService;
private final CloudStorageClient cloudStorageClient;
private final CohortDao cohortDao;
private final ConceptSetDao conceptSetDao;
private final DataSetDao dataSetDao;
private final FireCloudService fireCloudService;
private final LeonardoMapper leonardoMapper;
private final LeonardoApiClient leonardoNotebooksClient;
private final LeonardoRuntimeAuditor leonardoRuntimeAuditor;
private final MailService mailService;
private final NotebooksService notebooksService;
private final Provider<DbUser> userProvider;
private final UserMapper userMapper;
private final UserService userService;
private final WorkspaceDao workspaceDao;
private final WorkspaceMapper workspaceMapper;
private final WorkspaceService workspaceService;
private final WorkspaceAuthService workspaceAuthService;
@Autowired
public WorkspaceAdminServiceImpl(
AccessTierService accessTierService,
ActionAuditQueryService actionAuditQueryService,
AdminAuditor adminAuditor,
CloudMonitoringService cloudMonitoringService,
CloudStorageClient cloudStorageClient,
CohortDao cohortDao,
ConceptSetDao conceptSetDao,
DataSetDao dataSetDao,
FireCloudService fireCloudService,
LeonardoMapper leonardoMapper,
LeonardoApiClient leonardoNotebooksClient,
LeonardoRuntimeAuditor leonardoRuntimeAuditor,
MailService mailService,
NotebooksService notebooksService,
Provider<DbUser> userProvider,
UserMapper userMapper,
UserService userService,
WorkspaceDao workspaceDao,
WorkspaceMapper workspaceMapper,
WorkspaceService workspaceService,
WorkspaceAuthService workspaceAuthService) {
this.accessTierService = accessTierService;
this.actionAuditQueryService = actionAuditQueryService;
this.adminAuditor = adminAuditor;
this.cloudMonitoringService = cloudMonitoringService;
this.cloudStorageClient = cloudStorageClient;
this.cohortDao = cohortDao;
this.conceptSetDao = conceptSetDao;
this.dataSetDao = dataSetDao;
this.fireCloudService = fireCloudService;
this.leonardoMapper = leonardoMapper;
this.leonardoNotebooksClient = leonardoNotebooksClient;
this.leonardoRuntimeAuditor = leonardoRuntimeAuditor;
this.mailService = mailService;
this.notebooksService = notebooksService;
this.userProvider = userProvider;
this.userMapper = userMapper;
this.userService = userService;
this.workspaceDao = workspaceDao;
this.workspaceMapper = workspaceMapper;
this.workspaceService = workspaceService;
this.workspaceAuthService = workspaceAuthService;
}
@Override
public Optional<DbWorkspace> getFirstWorkspaceByNamespace(String workspaceNamespace) {
return workspaceDao.findFirstByWorkspaceNamespaceOrderByFirecloudNameAsc(workspaceNamespace);
}
@Override
public AdminWorkspaceObjectsCounts getAdminWorkspaceObjects(long workspaceId) {
int cohortCount = cohortDao.countByWorkspaceId(workspaceId);
int conceptSetCount = conceptSetDao.countByWorkspaceId(workspaceId);
int dataSetCount = dataSetDao.countByWorkspaceId(workspaceId);
return new AdminWorkspaceObjectsCounts()
.cohortCount(cohortCount)
.conceptSetCount(conceptSetCount)
.datasetCount(dataSetCount);
}
@Override
public AdminWorkspaceCloudStorageCounts getAdminWorkspaceCloudStorageCounts(
String workspaceNamespace, String workspaceName) {
String bucketName =
fireCloudService
.getWorkspaceAsService(workspaceNamespace, workspaceName)
.getWorkspace()
.getBucketName();
// NOTE: all of these may be undercounts, because we're only looking at the first Page of
// Storage List results
int notebookFilesCount =
notebooksService
.getNotebooksAsService(bucketName, workspaceNamespace, workspaceName)
.size();
int nonNotebookFilesCount = getNonNotebookFileCount(bucketName);
long storageSizeBytes = getStorageSizeBytes(bucketName);
return new AdminWorkspaceCloudStorageCounts()
.notebookFileCount(notebookFilesCount)
.nonNotebookFileCount(nonNotebookFilesCount)
.storageBytesUsed(storageSizeBytes)
.storageBucketPath(String.format("gs://%s", bucketName));
}
@Override
public CloudStorageTraffic getCloudStorageTraffic(String workspaceNamespace) {
CloudStorageTraffic response = new CloudStorageTraffic().receivedBytes(new ArrayList<>());
String googleProject = getWorkspaceByNamespaceOrThrow(workspaceNamespace).getGoogleProject();
for (TimeSeries timeSeries :
cloudMonitoringService.getCloudStorageReceivedBytes(
googleProject, TRAILING_TIME_TO_QUERY)) {
for (Point point : timeSeries.getPointsList()) {
response.addReceivedBytesItem(
new TimeSeriesPoint()
.timestamp(Timestamps.toMillis(point.getInterval().getEndTime()))
.value(point.getValue().getDoubleValue()));
}
}
response.getReceivedBytes().sort(Comparator.comparing(TimeSeriesPoint::getTimestamp));
return response;
}
@Override
public WorkspaceAdminView getWorkspaceAdminView(String workspaceNamespace) {
final DbWorkspace dbWorkspace = getWorkspaceByNamespaceOrThrow(workspaceNamespace);
final String workspaceFirecloudName = dbWorkspace.getFirecloudName();
final List<WorkspaceUserAdminView> collaborators =
workspaceService.getFirecloudUserRoles(workspaceNamespace, workspaceFirecloudName).stream()
.map(this::toWorkspaceUserAdminView)
.collect(Collectors.toList());
final AdminWorkspaceObjectsCounts adminWorkspaceObjects =
getAdminWorkspaceObjects(dbWorkspace.getWorkspaceId());
final AdminWorkspaceCloudStorageCounts adminWorkspaceCloudStorageCounts =
getAdminWorkspaceCloudStorageCounts(
dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName());
final List<ListRuntimeResponse> workbenchListRuntimeResponses =
leonardoNotebooksClient.listRuntimesByProjectAsService(dbWorkspace.getGoogleProject())
.stream()
.map(leonardoMapper::toApiListRuntimeResponse)
.collect(Collectors.toList());
final AdminWorkspaceResources adminWorkspaceResources =
new AdminWorkspaceResources()
.workspaceObjects(adminWorkspaceObjects)
.cloudStorage(adminWorkspaceCloudStorageCounts)
.runtimes(workbenchListRuntimeResponses);
final FirecloudWorkspaceDetails firecloudWorkspace =
fireCloudService
.getWorkspaceAsService(workspaceNamespace, workspaceFirecloudName)
.getWorkspace();
return new WorkspaceAdminView()
.workspace(workspaceMapper.toApiWorkspace(dbWorkspace, firecloudWorkspace))
.workspaceDatabaseId(dbWorkspace.getWorkspaceId())
.collaborators(collaborators)
.resources(adminWorkspaceResources);
}
@Override
public List<ListRuntimeResponse> deleteRuntimesInWorkspace(
String workspaceNamespace, ListRuntimeDeleteRequest req) {
final String googleProject =
getWorkspaceByNamespaceOrThrow(workspaceNamespace).getGoogleProject();
List<LeonardoListRuntimeResponse> runtimesToDelete =
filterByRuntimesInList(
leonardoNotebooksClient.listRuntimesByProjectAsService(googleProject).stream(),
req.getRuntimesToDelete())
.collect(Collectors.toList());
runtimesToDelete.forEach(
runtime ->
leonardoNotebooksClient.deleteRuntimeAsService(
runtime.getGoogleProject(), runtime.getRuntimeName()));
List<LeonardoListRuntimeResponse> runtimesInProjectAffected =
filterByRuntimesInList(
leonardoNotebooksClient.listRuntimesByProjectAsService(googleProject).stream(),
req.getRuntimesToDelete())
.collect(Collectors.toList());
// DELETED is an acceptable status from an implementation standpoint, but we will never
// receive runtimes with that status from Leo. We don't want to because we reuse runtime
// names and thus could have >1 deleted runtimes with the same name in the project.
List<LeonardoRuntimeStatus> acceptableStates =
ImmutableList.of(LeonardoRuntimeStatus.DELETING, LeonardoRuntimeStatus.ERROR);
runtimesInProjectAffected.stream()
.filter(runtime -> !acceptableStates.contains(runtime.getStatus()))
.forEach(
runtimeInBadState ->
log.log(
Level.SEVERE,
String.format(
"Runtime %s/%s is not in a deleting state",
runtimeInBadState.getGoogleProject(), runtimeInBadState.getRuntimeName())));
leonardoRuntimeAuditor.fireDeleteRuntimesInProject(
googleProject,
runtimesToDelete.stream()
.map(LeonardoListRuntimeResponse::getRuntimeName)
.collect(Collectors.toList()));
return runtimesInProjectAffected.stream()
.map(leonardoMapper::toApiListRuntimeResponse)
.collect(Collectors.toList());
}
private DbWorkspace getWorkspaceByNamespaceOrThrow(String workspaceNamespace) {
return getFirstWorkspaceByNamespace(workspaceNamespace)
.orElseThrow(
() ->
new NotFoundException(
String.format("No workspace found for namespace %s", workspaceNamespace)));
}
@Override
public WorkspaceAuditLogQueryResponse getAuditLogEntries(
String workspaceNamespace,
Integer limit,
Long afterMillis,
@Nullable Long beforeMillisNullable) {
final long workspaceDatabaseId =
getWorkspaceByNamespaceOrThrow(workspaceNamespace).getWorkspaceId();
final Instant after = Instant.ofEpochMilli(afterMillis);
final Instant before =
Optional.ofNullable(beforeMillisNullable).map(Instant::ofEpochMilli).orElse(Instant.now());
return actionAuditQueryService.queryEventsForWorkspace(
workspaceDatabaseId, limit, after, before);
}
@Override
public String getReadOnlyNotebook(
String workspaceNamespace, String notebookNameWithFileExtension, AccessReason accessReason) {
if (StringUtils.isBlank(accessReason.getReason())) {
throw new BadRequestException("Notebook viewing access reason is required");
}
final String workspaceName =
getWorkspaceByNamespaceOrThrow(workspaceNamespace).getFirecloudName();
adminAuditor.fireViewNotebookAction(
workspaceNamespace, workspaceName, notebookNameWithFileExtension, accessReason);
return notebooksService.adminGetReadOnlyHtml(
workspaceNamespace, workspaceName, notebookNameWithFileExtension);
}
// NOTE: may be an undercount since we only retrieve the first Page of Storage List results
@Override
public List<FileDetail> listFiles(String workspaceNamespace) {
final String workspaceName =
getWorkspaceByNamespaceOrThrow(workspaceNamespace).getFirecloudName();
final String bucketName =
fireCloudService
.getWorkspaceAsService(workspaceNamespace, workspaceName)
.getWorkspace()
.getBucketName();
Set<String> workspaceUsers =
workspaceAuthService.getFirecloudWorkspaceAcls(workspaceNamespace, workspaceName).keySet();
return cloudStorageClient.getBlobPage(bucketName).stream()
.map(blob -> cloudStorageClient.blobToFileDetail(blob, bucketName, workspaceUsers))
.collect(Collectors.toList());
}
@Override
public void setAdminLockedState(
String workspaceNamespace, AdminLockingRequest adminLockingRequest) {
log.info(String.format("called setAdminLockedState on wsns %s", workspaceNamespace));
DbWorkspace dbWorkspace = getWorkspaceByNamespaceOrThrow(workspaceNamespace);
dbWorkspace.setAdminLocked(true).setAdminLockedReason(adminLockingRequest.getRequestReason());
dbWorkspace = workspaceDao.save(dbWorkspace);
adminAuditor.fireLockWorkspaceAction(dbWorkspace.getWorkspaceId(), adminLockingRequest);
final List<DbUser> owners =
workspaceService.getFirecloudUserRoles(workspaceNamespace, dbWorkspace.getFirecloudName())
.stream()
.filter(userRole -> userRole.getRole() == WorkspaceAccessLevel.OWNER)
.map(UserRole::getEmail)
.map(userService::getByUsernameOrThrow)
.collect(Collectors.toList());
try {
mailService.sendWorkspaceAdminLockingEmail(
dbWorkspace, adminLockingRequest.getRequestReason(), owners);
} catch (final MessagingException e) {
log.log(Level.WARNING, e.getMessage());
}
}
@Override
public void setAdminUnlockedState(String workspaceNamespace) {
log.info(String.format("called setAdminUnlockedState on wsns %s", workspaceNamespace));
DbWorkspace dbWorkspace = getWorkspaceByNamespaceOrThrow(workspaceNamespace);
workspaceDao.save(dbWorkspace.setAdminLocked(false));
adminAuditor.fireUnlockWorkspaceAction(dbWorkspace.getWorkspaceId());
}
@Override
public DbWorkspace setPublished(
String workspaceNamespace, String firecloudName, boolean publish) {
final DbWorkspace dbWorkspace = workspaceDao.getRequired(workspaceNamespace, firecloudName);
final WorkspaceAccessLevel accessLevel =
publish ? WorkspaceAccessLevel.READER : WorkspaceAccessLevel.NO_ACCESS;
// Enable all users in RT or higher tiers to see all published workspaces regardless of tier
// Note: keep in sync with WorkspaceAuthService.updateWorkspaceAcls.
final DbAccessTier dbAccessTier = accessTierService.getRegisteredTierOrThrow();
final String registeredTierGroupEmail = dbAccessTier.getAuthDomainGroupEmail();
final FirecloudWorkspaceACLUpdate aclUpdate =
FirecloudTransforms.buildAclUpdate(registeredTierGroupEmail, accessLevel);
fireCloudService.updateWorkspaceACL(
dbWorkspace.getWorkspaceNamespace(),
dbWorkspace.getFirecloudName(),
Collections.singletonList(aclUpdate));
dbWorkspace.setPublished(publish);
return workspaceDao.saveWithLastModified(dbWorkspace, userProvider.get());
}
// NOTE: may be an undercount since we only retrieve the first Page of Storage List results
private int getNonNotebookFileCount(String bucketName) {
return (int)
cloudStorageClient
.getBlobPageForPrefix(bucketName, NotebookUtils.NOTEBOOKS_WORKSPACE_DIRECTORY).stream()
.filter(((Predicate<Blob>) notebooksService::isNotebookBlob).negate())
.count();
}
// NOTE: may be an undercount since we only retrieve the first Page of Storage List results
private long getStorageSizeBytes(String bucketName) {
return cloudStorageClient.getBlobPage(bucketName).stream()
.map(BlobInfo::getSize)
.reduce(0L, Long::sum);
}
// This is somewhat awkward, as we want to tolerate collaborators who aren't in the database
// anymore.
// TODO(jaycarlton): is this really what we want, or can we make this return an Optional that's
// empty
// when the user isn't in the DB. The assumption is that the fields agree between the UserRole and
// the DbUser, but we don't check that here.
private WorkspaceUserAdminView toWorkspaceUserAdminView(UserRole userRole) {
return userService
.getByUsername(userRole.getEmail())
.map(u -> userMapper.toWorkspaceUserAdminView(u, userRole))
.orElse(
new WorkspaceUserAdminView() // the MapStruct-generated method won't handle a partial
// conversion
.role(userRole.getRole())
.userModel(userMapper.toApiUser(userRole, null)));
}
private static Stream<LeonardoListRuntimeResponse> filterByRuntimesInList(
Stream<LeonardoListRuntimeResponse> runtimesToFilter, List<String> runtimeNames) {
// Null means keep all runtimes.
return runtimesToFilter.filter(
runtime -> runtimeNames == null || runtimeNames.contains(runtime.getRuntimeName()));
}
}
| {
"content_hash": "0275c231204bd9b7ac8c9fd37ff7ea4c",
"timestamp": "",
"source": "github",
"line_count": 446,
"max_line_length": 100,
"avg_line_length": 45.11883408071749,
"alnum_prop": 0.7661382497639517,
"repo_name": "all-of-us/workbench",
"id": "2d2441b15d468aeedcce9821dc167e4e405f2e57",
"size": "20123",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "api/src/main/java/org/pmiops/workbench/workspaceadmin/WorkspaceAdminServiceImpl.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "14709"
},
{
"name": "Dockerfile",
"bytes": "1601"
},
{
"name": "Groovy",
"bytes": "5004"
},
{
"name": "HTML",
"bytes": "354263"
},
{
"name": "Java",
"bytes": "4258561"
},
{
"name": "JavaScript",
"bytes": "104985"
},
{
"name": "Jupyter Notebook",
"bytes": "12135"
},
{
"name": "Kotlin",
"bytes": "76275"
},
{
"name": "Mustache",
"bytes": "126650"
},
{
"name": "Python",
"bytes": "52410"
},
{
"name": "R",
"bytes": "1157"
},
{
"name": "Ruby",
"bytes": "237944"
},
{
"name": "Shell",
"bytes": "507090"
},
{
"name": "TypeScript",
"bytes": "3656309"
},
{
"name": "wdl",
"bytes": "31820"
}
],
"symlink_target": ""
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MessageDemoComponent } from './message-demo.component';
describe('MessageDemoComponent', () => {
let component: MessageDemoComponent;
let fixture: ComponentFixture<MessageDemoComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MessageDemoComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MessageDemoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"content_hash": "be2236382c81ebceccfa547962093471",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 73,
"avg_line_length": 26.56,
"alnum_prop": 0.6867469879518072,
"repo_name": "Sudheer-Reddy/Wave-Widgets",
"id": "6f1a8865ad74877e69e77a114b004897b25c3122",
"size": "664",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/showcase/components/message/message-demo.component.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "243260"
},
{
"name": "HTML",
"bytes": "47727"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "TypeScript",
"bytes": "90582"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<title>npm-outdated</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-outdated.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-outdated.html">npm-outdated</a></h1> <p>Check for outdated packages</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm outdated [<name> [<name> ...]]
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>This command will check the registry to see if any (or, specific) installed
packages are currently outdated.</p>
<p>The resulting field 'wanted' shows the latest version according to the
version specified in the package.json, the field 'latest' the very latest
version of the package.</p>
<h2 id="configuration">CONFIGURATION</h2>
<h3 id="json">json</h3>
<ul>
<li>Default: false</li>
<li>Type: Boolean</li>
</ul>
<p>Show information in JSON format.</p>
<h3 id="long">long</h3>
<ul>
<li>Default: false</li>
<li>Type: Boolean</li>
</ul>
<p>Show extended information.</p>
<h3 id="parseable">parseable</h3>
<ul>
<li>Default: false</li>
<li>Type: Boolean</li>
</ul>
<p>Show parseable output instead of tree view.</p>
<h3 id="global">global</h3>
<ul>
<li>Default: false</li>
<li>Type: Boolean</li>
</ul>
<p>Check packages in the global install prefix instead of in the current
project.</p>
<h3 id="depth">depth</h3>
<ul>
<li>Type: Int</li>
</ul>
<p>Max depth for checking dependency tree.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-update.html">npm-update(1)</a></li>
<li><a href="../misc/npm-registry.html">npm-registry(7)</a></li>
<li><a href="../files/npm-folders.html">npm-folders(5)</a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-outdated — npm@1.4.18</p>
| {
"content_hash": "1c779a17d23dd7351445881186b10ca1",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 807,
"avg_line_length": 56.23943661971831,
"alnum_prop": 0.7004758327072377,
"repo_name": "rameshlamba/triospace",
"id": "26a73d6f04a3018b9f39e692d231955e715974cc",
"size": "3993",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/node_modules/npm/html/doc/cli/npm-outdated.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "41782"
},
{
"name": "JavaScript",
"bytes": "1230519"
},
{
"name": "Shell",
"bytes": "2764"
},
{
"name": "TeX",
"bytes": "21376"
}
],
"symlink_target": ""
} |
package org.locationtech.geomesa.kafka.consumer.offsets
import java.util.Properties
import kafka.common.{OffsetAndMetadata, TopicAndPartition}
import kafka.consumer.ConsumerConfig
import kafka.message.Message
import kafka.producer.{KeyedMessage, Producer, ProducerConfig}
import kafka.serializer.StringDecoder
import org.junit.runner.RunWith
import org.locationtech.geomesa.kafka.{HasEmbeddedKafka, HasEmbeddedZookeeper}
import org.specs2.mutable.Specification
import org.specs2.runner
@RunWith(classOf[runner.JUnitRunner])
class OffsetManagerIntegrationTest extends Specification with HasEmbeddedKafka {
sequential // this doesn't really need to be sequential, but we're trying to reduce zk load
"OffsetManager" should {
"find offsets" >> {
val props = new Properties
props.put("group.id", "mygroup")
props.put("metadata.broker.list", brokerConnect)
props.put("zookeeper.connect", zkConnect)
val config = new ConsumerConfig(props)
val offsetManager = new OffsetManager(config)
val topic = "test"
val producerProps = new Properties()
producerProps.put("metadata.broker.list", brokerConnect)
producerProps.put("serializer.class", "kafka.serializer.DefaultEncoder")
val producer = new Producer[Array[Byte], Array[Byte]](new ProducerConfig(producerProps))
for (i <- 0 until 10) {
producer.send(new KeyedMessage(topic, i.toString.getBytes("UTF-8"), s"test $i".getBytes("UTF-8")))
}
producer.close()
"by number" >> {
offsetManager.getOffsets(topic, SpecificOffset(1)) mustEqual Map(TopicAndPartition(topic, 0) -> 1)
}
"by earliest" >> {
offsetManager.getOffsets(topic, EarliestOffset) mustEqual Map(TopicAndPartition(topic, 0) -> 0)
}
"by latest" >> {
offsetManager.getOffsets(topic, LatestOffset) mustEqual Map(TopicAndPartition(topic, 0) -> 10)
}
"by group" >> {
offsetManager.commitOffsets(Map(TopicAndPartition(topic, 0) -> OffsetAndMetadata(5)))
offsetManager.getOffsets(topic, GroupOffset) mustEqual Map(TopicAndPartition(topic, 0) -> 5)
}
"by binary search" >> {
val decoder = new StringDecoder()
val offset = FindOffset((m: Message) => {
val bb = Array.ofDim[Byte](m.payload.remaining())
m.payload.get(bb)
decoder.fromBytes(bb).substring(5).toInt.compareTo(7)
})
offsetManager.getOffsets(topic, offset) mustEqual Map(TopicAndPartition(topic, 0) -> 7)
}
}
}
step { shutdown() }
}
| {
"content_hash": "f13b1d1e9bd6692add1129b056939059",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 106,
"avg_line_length": 36.642857142857146,
"alnum_prop": 0.6927875243664717,
"repo_name": "mcharles/geomesa",
"id": "76c2ea80576a01a985222a7438ed920247bf5621",
"size": "2888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "geomesa-kafka/geomesa-kafka-datastore/src/test/scala/org/locationtech/geomesa/kafka/consumer/offsets/OffsetManagerIntegrationTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "20218"
},
{
"name": "Java",
"bytes": "68447"
},
{
"name": "JavaScript",
"bytes": "7418"
},
{
"name": "Scala",
"bytes": "2926309"
},
{
"name": "Shell",
"bytes": "22356"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 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.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="64dp"
android:height="64dp"
android:viewportWidth="64"
android:viewportHeight="64">
<group
android:translateX="45.500000"
android:translateY="42.000000">
<path
android:fillColor="#757575"
android:strokeWidth="1"
android:pathData="M 0.685714286 9.82857143 L 3.73333333 9.82857143 L 3.73333333 15.9238095 L 8.3047619 6.78095238 L 5.25714286 6.78095238 L 5.25714286 0.685714286 Z" />
</group>
<path
android:fillType="evenOdd"
android:strokeWidth="1"
android:pathData="M 0 0 H 64 V 64 H 0 V 0 Z" />
</vector> | {
"content_hash": "a6a43da82a44f64b3956d125410db78a",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 180,
"avg_line_length": 39.285714285714285,
"alnum_prop": 0.6741818181818182,
"repo_name": "arsi-apli/NBANDROID-V2",
"id": "f8fe2f8b81d82452a79df4f2db86aa72b227750d",
"size": "1375",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "nbandroid.layout.lib/src/main/layoutlib_v28_res/data/res/drawable/ic_instant_icon_badge_bolt.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "747732"
},
{
"name": "GAP",
"bytes": "9978"
},
{
"name": "GLSL",
"bytes": "632"
},
{
"name": "HTML",
"bytes": "51779"
},
{
"name": "Java",
"bytes": "3770028"
}
],
"symlink_target": ""
} |
{% extends 'emails/email_template.html' %}
{% block content %}
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="100%"
style="border-collapse:collapse;background-color:#ffffff;border-top:0;border-bottom:0">
<tbody>
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="600"
style="border-collapse:collapse">
<tbody>
<tr>
<td valign="top" style="padding-top:10px;padding-bottom:10px">
<table border="0" cellpadding="0" cellspacing="0" width="100%"
style="border-collapse:collapse">
<tbody>
<tr>
<td valign="top">
<table align="left" border="0" cellpadding="0"
cellspacing="0" width="600"
style="border-collapse:collapse">
<tbody>
<tr>
<td valign="top"
style="padding-top:9px;padding-right:18px;padding-bottom:9px;padding-left:18px;color:#606060;font-family:Helvetica;font-size:15px;line-height:150%;text-align:left">
<h1 style="margin:0;padding:0;display:block;font-family:Helvetica;font-size:40px;font-style:normal;font-weight:bold;line-height:125%;letter-spacing:-1px;text-align:left;color:#606060!important">
Hello {{ listing.listing_name }},</h1>
<p style="margin:1em 0;padding:0;color:#606060;font-family:Helvetica;font-size:15px;line-height:150%;text-align:left">
Thank you for claiming your listing on Picasso. Please reply to this email if you have any concerns or questions.</p>
<p style="margin:1em 0;padding:0;color:#606060;font-family:Helvetica;font-size:15px;line-height:150%;text-align:left">
<br>
Let us know what you think of Picasso by
replying to this email.<br>
<br>
Cheers,<br>
<strong>Picasso Team</strong></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
{% endblock %} | {
"content_hash": "03aa55138464206644fbe01c75385cf5",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 254,
"avg_line_length": 59.06153846153846,
"alnum_prop": 0.3308153164886689,
"repo_name": "TejasM/picasso",
"id": "1513006a3722addb5a7a42e1dfbc30af475553e4",
"size": "3839",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "picasso/templates/emails/confirm_claim_email.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "297283"
},
{
"name": "JavaScript",
"bytes": "303260"
},
{
"name": "PHP",
"bytes": "9305"
},
{
"name": "Python",
"bytes": "206248"
},
{
"name": "Shell",
"bytes": "5120"
}
],
"symlink_target": ""
} |
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-strap/dist/angular-strap.min.js',
'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/scripts/resources.js',
'app/scripts/authoring-app.js',
'app/scripts/controllers/student/intro.js',
//'app/scripts/**/*.js',
//'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
| {
"content_hash": "bf3ac361c1b1f806af50d6b510dc264c",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 85,
"avg_line_length": 28.93103448275862,
"alnum_prop": 0.634684147794994,
"repo_name": "UTMQ/utmq-core",
"id": "c2cb9cb90d38530f3a8a17ce9bd17547e744cec7",
"size": "1678",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "karma.conf.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1349"
},
{
"name": "JavaScript",
"bytes": "2442299"
}
],
"symlink_target": ""
} |
package org.apache.pulsar.tests.integration.offload;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.tests.integration.containers.S3Container;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
@Slf4j
public class TestS3Offload extends TestBaseOffload {
private S3Container s3Container;
@Override
protected void beforeStartCluster() throws Exception {
super.beforeStartCluster();
log.info("s3 container init");
s3Container = new S3Container(
pulsarCluster.getClusterName(),
S3Container.NAME)
.withNetwork(pulsarCluster.getNetwork())
.withNetworkAliases(S3Container.NAME);
s3Container.start();
log.info("s3 container start finish.");
}
@AfterClass(alwaysRun = true)
public void teardownS3() {
if (null != s3Container) {
s3Container.stop();
}
}
@Test(dataProvider = "ServiceAndAdminUrls")
public void testPublishOffloadAndConsumeViaCLI(Supplier<String> serviceUrl, Supplier<String> adminUrl) throws Exception {
super.testPublishOffloadAndConsumeViaCLI(serviceUrl.get(), adminUrl.get());
}
@Test(dataProvider = "ServiceAndAdminUrls")
public void testPublishOffloadAndConsumeViaThreshold(Supplier<String> serviceUrl, Supplier<String> adminUrl) throws Exception {
super.testPublishOffloadAndConsumeViaThreshold(serviceUrl.get(), adminUrl.get());
}
@Test(dataProvider = "ServiceAndAdminUrls")
public void testPublishOffloadAndConsumeDeletionLag(Supplier<String> serviceUrl, Supplier<String> adminUrl) throws Exception {
super.testPublishOffloadAndConsumeDeletionLag(serviceUrl.get(), adminUrl.get());
}
@Override
protected Map<String, String> getEnv() {
Map<String, String> result = new HashMap<>();
result.put("managedLedgerMaxEntriesPerLedger", String.valueOf(getNumEntriesPerLedger()));
result.put("managedLedgerMinLedgerRolloverTimeMinutes", "0");
result.put("managedLedgerOffloadDriver", "aws-s3");
result.put("s3ManagedLedgerOffloadBucket", "pulsar-integtest");
result.put("s3ManagedLedgerOffloadServiceEndpoint", "http://" + S3Container.NAME + ":9090");
return result;
}
}
| {
"content_hash": "5e14951724442fac60e043739a82ee25",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 131,
"avg_line_length": 34.84057971014493,
"alnum_prop": 0.7063227953410982,
"repo_name": "massakam/pulsar",
"id": "eb87aeb9751b78e29d66b868efc30bb423d4ef19",
"size": "3211",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/integration/src/test/java/org/apache/pulsar/tests/integration/offload/TestS3Offload.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "15099"
},
{
"name": "Dockerfile",
"bytes": "20057"
},
{
"name": "Go",
"bytes": "117008"
},
{
"name": "HCL",
"bytes": "14529"
},
{
"name": "HTML",
"bytes": "822"
},
{
"name": "Java",
"bytes": "31626049"
},
{
"name": "JavaScript",
"bytes": "1385"
},
{
"name": "Lua",
"bytes": "5454"
},
{
"name": "Python",
"bytes": "243009"
},
{
"name": "Shell",
"bytes": "159955"
}
],
"symlink_target": ""
} |
@implementation TIFlurryProvider
#if TIA_FLURRY_EXISTS
-(id) initialize: (NSDictionary *) tokens {
NSString* flurrytoken = [tokens objectForKey:@"flurry"];
[Flurry setCrashReportingEnabled:NO];
[Flurry startSession:flurrytoken];
return self;
}
-(void) trackEvent: (NSString *) name properties: (NSDictionary *) properties sendToTrackers: (bool) sendToTrackers {
[Flurry logEvent:name withParameters:properties];
}
#endif
@end
| {
"content_hash": "cabffa5b9d0aaae99d17567a37d2886a",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 117,
"avg_line_length": 24.5,
"alnum_prop": 0.7505668934240363,
"repo_name": "wayd-labs/touchin-analytics",
"id": "e348419dd1db606210cb96d22523c16934f1a4cc",
"size": "581",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Providers/TIFlurryProvider.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "25848"
},
{
"name": "Ruby",
"bytes": "2386"
}
],
"symlink_target": ""
} |
{
function T() {
}
console.log('typeof T = ' + (typeof T)); // function
console.log('T instanceof Object = ' + (T instanceof Object)); // true
console.log('T instanceof Function = ' + (T instanceof Function)); // true
console.log('T instanceof T = ' + (T instanceof T)); // false
// 作为函数,其constructor属性实际是属于Function“类”的
console.log('T.constructor = ' + T.constructor); // function Function() { [native code] }
}
console.log();
// > 作为“类”的声明,实际提供的是类的构造器
{
function T() {
}
var t = new T();
console.log('typeof t = ' + (typeof t)); // object
console.log('t instanceof Object = ' + (t instanceof Object)); // true
console.log('t instanceof Function = ' + (t instanceof Function)); // false
console.log('t instanceof T = ' + (t instanceof T)); // true
// 作为“类”
// > 提供了constructor
console.log('t.constructor = ' + t.constructor); // function T() { }
}
| {
"content_hash": "ed0c5cc10614b1b1a8397a082c38fc18",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 90,
"avg_line_length": 21.5609756097561,
"alnum_prop": 0.6176470588235294,
"repo_name": "bblue000/nodejs_tutorials",
"id": "ffa6e7e3259f6261b5be111edaf127c7acea8590",
"size": "1127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "基本语法讲解/function/def_function_asclass.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "14210"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Reloader (Play! 2.x Provider for Play! 2.6.x 1.0.0-rc2 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Reloader (Play! 2.x Provider for Play! 2.6.x 1.0.0-rc2 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Reloader.html">Use</a></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><a href="../../../../../../../com/google/code/play2/provider/play26/run/NamedURLClassLoader.html" title="class in com.google.code.play2.provider.play26.run"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../com/google/code/play2/provider/play26/run/ReloaderApplicationClassLoaderProvider.html" title="class in com.google.code.play2.provider.play26.run"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/provider/play26/run/Reloader.html" target="_top">Frames</a></li>
<li><a href="Reloader.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.google.code.play2.provider.play26.run</div>
<h2 title="Class Reloader" class="title">Class Reloader</h2>
<map id="G" name="G">
<area shape="rect" id="node1_0" href="./ReloaderPlayDevServer.html" title="com.google.code.play2.provider.play26.run.ReloaderPlayDevServer" alt="" coords="16,25,164,49"/>
<area shape="rect" id="node1" href="./ReloaderPlayDevServer.html" title="<TABLE>" alt="" coords="5,13,175,61"/>
<area shape="rect" id="node3_1" href="./Reloader.html" title="com.google.code.play2.provider.play26.run.Reloader" alt="" coords="299,129,367,153"/>
<area shape="rect" id="node3" href="./Reloader.html" title="<TABLE>" alt="" coords="288,117,377,165"/>
<area shape="rect" id="node2_2" href="./ReloaderApplicationClassLoaderProvider.html" title="com.google.code.play2.provider.play26.run.ReloaderApplicationClassLoaderProvider" alt="" coords="210,25,455,49"/>
<area shape="rect" id="node2" href="./ReloaderApplicationClassLoaderProvider.html" title="<TABLE>" alt="" coords="199,13,466,61"/>
<area shape="rect" id="node5_3" href="http://java.sun.com/j2se/1.4.2/docs/api/com/google/code/play2/provider/api/Play2Builder.html" title="com.google.code.play2.provider.api.Play2Builder" alt="" coords="249,219,416,272"/>
<area shape="rect" id="node5" href="http://java.sun.com/j2se/1.4.2/docs/api/com/google/code/play2/provider/api/Play2Builder.html" title="<TABLE>" alt="" coords="239,213,427,277"/>
<area shape="rect" id="node4_4" href="http://java.sun.com/j2se/1.4.2/docs/api/play/core/BuildLink.html" title="play.core.BuildLink" alt="" coords="501,11,580,64"/>
<area shape="rect" id="node4" href="http://java.sun.com/j2se/1.4.2/docs/api/play/core/BuildLink.html" title="<TABLE>" alt="" coords="491,5,591,69"/>
</map>
<!-- UML diagram added by UMLGraph version R5_6-24-gf6e263 (http://www.umlgraph.org/) -->
<div align="center"><img src="Reloader.png" alt="Package class diagram package Reloader" usemap="#G" border=0/></div>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.google.code.play2.provider.play26.run.Reloader</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>play.core.BuildLink</dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">Reloader</span>
extends java.lang.Object
implements play.core.BuildLink</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../../com/google/code/play2/provider/play26/run/Reloader.html#Reloader-com.google.code.play2.provider.api.Play2Builder-java.lang.ClassLoader-java.io.File-java.util.List-java.util.Map-">Reloader</a></span>(<a href="https://play2-maven-plugin.github.io/play2-maven-plugin/1.0.0-rc2/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2Builder.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2Builder</a> buildLink,
java.lang.ClassLoader baseLoader,
java.io.File projectPath,
java.util.List<java.io.File> outputDirectories,
java.util.Map<java.lang.String,java.lang.String> devSettings)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.Object[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../com/google/code/play2/provider/play26/run/Reloader.html#findSource-java.lang.String-java.lang.Integer-">findSource</a></span>(java.lang.String className,
java.lang.Integer line)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../com/google/code/play2/provider/play26/run/Reloader.html#forceReload--">forceReload</a></span>()</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.io.File</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../com/google/code/play2/provider/play26/run/Reloader.html#projectPath--">projectPath</a></span>()</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>java.lang.Object</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../com/google/code/play2/provider/play26/run/Reloader.html#reload--">reload</a></span>()</code>
<div class="block">Contrary to its name, this doesn't necessarily reload the app.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>java.util.Map<java.lang.String,java.lang.String></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../com/google/code/play2/provider/play26/run/Reloader.html#settings--">settings</a></span>()</code> </td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>static java.net.URL[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../com/google/code/play2/provider/play26/run/Reloader.html#toUrls-java.util.List-">toUrls</a></span>(java.util.List<java.io.File> cp)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Reloader-com.google.code.play2.provider.api.Play2Builder-java.lang.ClassLoader-java.io.File-java.util.List-java.util.Map-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Reloader</h4>
<pre>public Reloader(<a href="https://play2-maven-plugin.github.io/play2-maven-plugin/1.0.0-rc2/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2Builder.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2Builder</a> buildLink,
java.lang.ClassLoader baseLoader,
java.io.File projectPath,
java.util.List<java.io.File> outputDirectories,
java.util.Map<java.lang.String,java.lang.String> devSettings)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="reload--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>reload</h4>
<pre>public java.lang.Object reload()</pre>
<div class="block">Contrary to its name, this doesn't necessarily reload the app. It is invoked on every request, and will only
trigger a reload of the app if something has changed.
Since this communicates across classloaders, it must return only simple objects.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>reload</code> in interface <code>play.core.BuildLink</code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Either
- Throwable - If something went wrong (eg, a compile error).
- ClassLoader - If the classloader has changed, and the application should be reloaded.
- null - If nothing changed.</dd>
</dl>
</li>
</ul>
<a name="settings--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>settings</h4>
<pre>public java.util.Map<java.lang.String,java.lang.String> settings()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>settings</code> in interface <code>play.core.BuildLink</code></dd>
</dl>
</li>
</ul>
<a name="forceReload--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>forceReload</h4>
<pre>public void forceReload()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>forceReload</code> in interface <code>play.core.BuildLink</code></dd>
</dl>
</li>
</ul>
<a name="findSource-java.lang.String-java.lang.Integer-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findSource</h4>
<pre>public java.lang.Object[] findSource(java.lang.String className,
java.lang.Integer line)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>findSource</code> in interface <code>play.core.BuildLink</code></dd>
</dl>
</li>
</ul>
<a name="projectPath--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>projectPath</h4>
<pre>public java.io.File projectPath()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>projectPath</code> in interface <code>play.core.BuildLink</code></dd>
</dl>
</li>
</ul>
<a name="toUrls-java.util.List-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>toUrls</h4>
<pre>public static java.net.URL[] toUrls(java.util.List<java.io.File> cp)
throws java.net.MalformedURLException</pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.net.MalformedURLException</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Reloader.html">Use</a></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><a href="../../../../../../../com/google/code/play2/provider/play26/run/NamedURLClassLoader.html" title="class in com.google.code.play2.provider.play26.run"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../com/google/code/play2/provider/play26/run/ReloaderApplicationClassLoaderProvider.html" title="class in com.google.code.play2.provider.play26.run"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/provider/play26/run/Reloader.html" target="_top">Frames</a></li>
<li><a href="Reloader.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013–2018. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "ec539e2629831740b6524d4f53b8e283",
"timestamp": "",
"source": "github",
"line_count": 402,
"max_line_length": 553,
"avg_line_length": 43.34577114427861,
"alnum_prop": 0.6553228120516499,
"repo_name": "play2-maven-plugin/play2-maven-plugin.github.io",
"id": "d866981154a0c97b1aede62c0830145d5b3261dd",
"size": "17425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "play2-maven-plugin/1.0.0-rc2/play2-providers/play2-provider-play26/apidocs/com/google/code/play2/provider/play26/run/Reloader.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2793124"
},
{
"name": "HTML",
"bytes": "178221432"
},
{
"name": "JavaScript",
"bytes": "120742"
}
],
"symlink_target": ""
} |
title: "Eviter de partager l'état"
weight: 6
---
{{% notice info %}}
<i class="fas fa-language"></i> Page being translated from
English to French. Do you speak French? Help us to translate
it by sending us pull requests!
{{% /notice %}}
Although mentioned in several places it is worth mentioning again. Ensure
tests are isolated from one another.
Don't share test data. Imagine several tests that each query the database
for valid orders before picking one to perform an action on. Should two tests
pick up the same order you are likely to get unexpected behaviour.
Clean up stale data in the application that might be picked up by another
test e.g. invalid order records.
Create a new WebDriver instance per test. This helps ensure test isolation
and makes parallelisation simpler.
| {
"content_hash": "a5e2aa173ad5f01dc3a6ca3ef49dd411",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 77,
"avg_line_length": 36.04545454545455,
"alnum_prop": 0.7704918032786885,
"repo_name": "SeleniumHQ/docs",
"id": "b4e263e9a4898b831ebd6184ca0026399045e0fc",
"size": "798",
"binary": false,
"copies": "1",
"ref": "refs/heads/old_docs",
"path": "docs_source_files/content/guidelines_and_recommendations/avoid_sharing_state.fr.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "538174"
},
{
"name": "HTML",
"bytes": "29471342"
},
{
"name": "JavaScript",
"bytes": "295575"
},
{
"name": "Shell",
"bytes": "589"
}
],
"symlink_target": ""
} |
<?php
namespace Drak\NativeSession;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler;
/**
* NativeMemcachedSessionHandler.
*
* Driver for the memcached session save handler provided by the memcached PHP extension.
*
* @see http://php.net/memcached.sessions
*
* @author Drak <drak@zikula.org>
*/
class NativeMemcachedSessionHandler extends NativeSessionHandler
{
/**
* Constructor.
*
* @param string $savePath Comma separated list of servers: e.g. memcache1.example.com:11211,memcache2.example.com:11211
* @param array $options Session configuration options.
*/
public function __construct($savePath = '127.0.0.1:11211', array $options = array())
{
if (!extension_loaded('memcached')) {
throw new \RuntimeException('PHP does not have "memcached" session module registered');
}
if (null === $savePath) {
$savePath = ini_get('session.save_path');
}
ini_set('session.save_handler', 'memcached');
ini_set('session.save_path', $savePath);
$this->setOptions($options);
}
/**
* Set any memcached ini values.
*
* @see https://github.com/php-memcached-dev/php-memcached/blob/master/memcached.ini
*/
protected function setOptions(array $options)
{
$validOptions = array_flip(array(
'memcached.sess_locking', 'memcached.sess_lock_wait',
'memcached.sess_prefix', 'memcached.compression_type',
'memcached.compression_factor', 'memcached.compression_threshold',
'memcached.serializer',
));
foreach ($options as $key => $value) {
if (isset($validOptions[$key])) {
ini_set($key, $value);
}
}
}
}
| {
"content_hash": "46935c30421c15536806e9af782903f2",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 124,
"avg_line_length": 29.177419354838708,
"alnum_prop": 0.6213377556661138,
"repo_name": "zikula/NativeSession",
"id": "ff3449e4698587ce5788d77d2809143faaf845df",
"size": "2038",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Drak/NativeSession/NativeMemcachedSessionHandler.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "12973"
}
],
"symlink_target": ""
} |
package store
import (
"github.com/cilium/cilium/pkg/logging"
"github.com/cilium/cilium/pkg/logging/logfields"
)
var log = logging.DefaultLogger.WithField(logfields.LogSubsys, "node")
| {
"content_hash": "f3f146a488989f0b042e32915ef9a779",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 70,
"avg_line_length": 23.5,
"alnum_prop": 0.776595744680851,
"repo_name": "tgraf/cilium",
"id": "1f105aa033e72f28bd0fae0d1f26eb95defaf37a",
"size": "783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/node/store/logfields.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1109708"
},
{
"name": "C++",
"bytes": "6557"
},
{
"name": "Dockerfile",
"bytes": "27333"
},
{
"name": "Go",
"bytes": "9930421"
},
{
"name": "HCL",
"bytes": "1127"
},
{
"name": "Makefile",
"bytes": "72210"
},
{
"name": "Mustache",
"bytes": "1457"
},
{
"name": "Python",
"bytes": "11099"
},
{
"name": "Ruby",
"bytes": "392"
},
{
"name": "Shell",
"bytes": "369722"
},
{
"name": "SmPL",
"bytes": "6540"
},
{
"name": "Smarty",
"bytes": "10858"
},
{
"name": "TeX",
"bytes": "416"
},
{
"name": "sed",
"bytes": "1336"
}
],
"symlink_target": ""
} |
import * as tslib_1 from "tslib";
import * as React from 'react';
import { css } from '@microsoft/office-ui-fabric-react-bundle';
import styles from './MobilePreviewDimensionInput.module.scss';
import strings from '../MobilePreview.resx';
var MobilePreviewDimensionInput = /** @class */ (function (_super) {
tslib_1.__extends(MobilePreviewDimensionInput, _super);
function MobilePreviewDimensionInput(props) {
return _super.call(this, props) || this;
}
MobilePreviewDimensionInput.prototype.render = function () {
var xContainerClassName = css(styles.mobilePreviewTextfieldXY, styles.xField);
var yContainerClassName = css(styles.mobilePreviewTextfieldXY, styles.yField);
return (React.createElement("div", null,
React.createElement("div", { className: xContainerClassName },
React.createElement("label", { className: styles.xyLabels }, strings.Width + ":"),
React.createElement("input", { "aria-label": strings.Width, className: styles.xyTextfields, onChange: this.props.onChangedX, value: this.props.currentDevice.width.toString() })),
React.createElement("div", { className: yContainerClassName },
React.createElement("label", { className: styles.xyLabels }, strings.Height + ":"),
React.createElement("input", { "aria-label": strings.Height, className: styles.xyTextfields, onChange: this.props.onChangedY, value: this.props.currentDevice.height.toString() }))));
};
return MobilePreviewDimensionInput;
}(React.Component));
export default MobilePreviewDimensionInput;
//# sourceMappingURL=MobilePreviewDimensionInput.js.map | {
"content_hash": "0b23f14481f0c8328f1911261030e755",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 198,
"avg_line_length": 66.84,
"alnum_prop": 0.7079593058049073,
"repo_name": "SharePoint/sp-dev-fx-webparts",
"id": "2a64c34155c111bead19da227064e1709af66db7",
"size": "1671",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/react-enhanced-powerapps/temp/workbench-packages/@microsoft_sp-webpart-workbench/lib/components/mobilePreview/mobilePreviewDimensionInput/MobilePreviewDimensionInput.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15907"
},
{
"name": "JavaScript",
"bytes": "11884"
},
{
"name": "TypeScript",
"bytes": "57801"
}
],
"symlink_target": ""
} |
:root {
--sidebar-width: 320px;
}
/*to show and hide the side nav*/
.expandable { transform: translateX(var(--sidebar-width))}
.expandable:target {transform: translateX(0)}
.w-sidebar-lg {
width: var(--sidebar-width);
}
.m-sidebar {
margin-right: var(--sidebar-width);
}
| {
"content_hash": "6055992c7eab194f62b86e2f574d8ef8",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 58,
"avg_line_length": 16.705882352941178,
"alnum_prop": 0.6619718309859155,
"repo_name": "Frontmatter/brooklinebooksmith",
"id": "0bec3c93edcc9eba10afda2793566ba620b53789",
"size": "284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_app/css/modules/_expandable.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "191471"
},
{
"name": "HTML",
"bytes": "58328"
},
{
"name": "JavaScript",
"bytes": "4750"
},
{
"name": "Ruby",
"bytes": "3911"
},
{
"name": "Shell",
"bytes": "189"
}
],
"symlink_target": ""
} |
package carbon.view;
import carbon.widget.OnTransformationChangedListener;
public interface TransformationView {
void addOnTransformationChangedListener(OnTransformationChangedListener listener);
void removeOnTransformationChangedListener(OnTransformationChangedListener listener);
void clearOnTransformationChangedListeners();
}
| {
"content_hash": "0ac140cde82b8f731bfe4e0cece31460",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 89,
"avg_line_length": 28.916666666666668,
"alnum_prop": 0.8559077809798271,
"repo_name": "ZieIony/Carbon",
"id": "d5572c53daba5c499cb9c0fa131624da73e1168c",
"size": "347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "carbon/src/main/java/carbon/view/TransformationView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1763490"
},
{
"name": "Kotlin",
"bytes": "64361"
}
],
"symlink_target": ""
} |
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.7-5-b-208
description: >
Object.defineProperties - 'descObj' is a Number object which
implements its own [[Get]] method to get 'get' property (8.10.5
step 7.a)
---*/
var obj = {};
var descObj = new Number(-9);
descObj.get = function () {
return "Number";
};
Object.defineProperties(obj, {
property: descObj
});
assert.sameValue(obj.property, "Number", 'obj.property');
| {
"content_hash": "46cac353af434e6b783bb906a380fc08",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 70,
"avg_line_length": 25.583333333333332,
"alnum_prop": 0.5977198697068404,
"repo_name": "baslr/ArangoDB",
"id": "687a062c89f8f79cb8d71951f09e9ab2f3c37f46",
"size": "614",
"binary": false,
"copies": "3",
"ref": "refs/heads/3.1-silent",
"path": "3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Object/defineProperties/15.2.3.7-5-b-208.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "391227"
},
{
"name": "Awk",
"bytes": "4272"
},
{
"name": "Batchfile",
"bytes": "62892"
},
{
"name": "C",
"bytes": "7932707"
},
{
"name": "C#",
"bytes": "96430"
},
{
"name": "C++",
"bytes": "284363933"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "681903"
},
{
"name": "CSS",
"bytes": "1036656"
},
{
"name": "CWeb",
"bytes": "174166"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "259402"
},
{
"name": "Emacs Lisp",
"bytes": "14637"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Groovy",
"bytes": "131"
},
{
"name": "HTML",
"bytes": "2318016"
},
{
"name": "Java",
"bytes": "2325801"
},
{
"name": "JavaScript",
"bytes": "67878359"
},
{
"name": "LLVM",
"bytes": "24129"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "M4",
"bytes": "600550"
},
{
"name": "Makefile",
"bytes": "509612"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "28404"
},
{
"name": "Objective-C",
"bytes": "19321"
},
{
"name": "Objective-C++",
"bytes": "2503"
},
{
"name": "PHP",
"bytes": "98503"
},
{
"name": "Pascal",
"bytes": "145688"
},
{
"name": "Perl",
"bytes": "720157"
},
{
"name": "Perl 6",
"bytes": "9918"
},
{
"name": "Python",
"bytes": "5859911"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "R",
"bytes": "5123"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Roff",
"bytes": "1010686"
},
{
"name": "Ruby",
"bytes": "922159"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "511077"
},
{
"name": "Swift",
"bytes": "116"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "Vim script",
"bytes": "4075"
},
{
"name": "Visual Basic",
"bytes": "11568"
},
{
"name": "XSLT",
"bytes": "551977"
},
{
"name": "Yacc",
"bytes": "53005"
}
],
"symlink_target": ""
} |
SHELL=/bin/bash
KANGODIR=/opt/kango-framework/
up:
(git status && git pull)
ci:
git status
git pull
git add src/common/* EXTENSIONS/*
git ci -m '.' -a
git push
_build:
python $(KANGODIR)/kango.py build ./
build:
rm -rf `find . -name '.DS_Store'`
rm -rf `find . -name DEADJOE`
rm -f src/common/static/bootstrap/css/bootstrap-theme.css
rm -f src/common/static/bootstrap/css/bootstrap-theme.css.map
rm -f src/common/static/bootstrap/css/bootstrap-theme.min.css
rm -f src/common/static/bootstrap/css/bootstrap.css
rm -f src/common/static/bootstrap/css/bootstrap.css.map
rm -f src/common/static/bootstrap/js/bootstrap.js
rm -f src/common/static/bootstrap/js/npm.js
python $(KANGODIR)/kango.py build ./
cp `ls -1 output/mantisbugtracker*.crx | sort -r | head -n 1` EXTENSIONS/mantisbugtrackerbrowserextention.crx
cp `ls -1 output/mantisbugtracker*.xpi | sort -r | head -n 1` EXTENSIONS/mantisbugtrackerbrowserextention.xpi
| {
"content_hash": "fbb31340f4d4566e04ebe95610461a52",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 110,
"avg_line_length": 32.41379310344828,
"alnum_prop": 0.7361702127659574,
"repo_name": "norbornen/extension-mantis-bug-tracker-rss",
"id": "19409cd5d95fbd63c589440aae24239e9a216114",
"size": "940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3412"
},
{
"name": "HTML",
"bytes": "6979"
},
{
"name": "JavaScript",
"bytes": "14252"
},
{
"name": "Makefile",
"bytes": "940"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Esthar.Core;
namespace Esthar.Data.Transform
{
public sealed class XmlLocationWriter : ILocationWriter
{
private readonly string _xmlPath;
private XmlElement _root;
public XmlLocationWriter(string xmlPath)
{
_xmlPath = Exceptions.CheckArgumentNullOrEmprty(xmlPath, "xmlPath");
}
public bool BeginWrite()
{
FileCommander.EnsureDirectoryExists(_xmlPath);
_root = File.Exists(_xmlPath) ? XmlHelper.LoadDocument(_xmlPath) : XmlHelper.CreateDocument("Location");
return true;
}
public bool EndWrite()
{
FileCommander.EnsureDirectoryExists(_xmlPath);
_root.GetOwnerDocument().Save(_xmlPath);
return true;
}
public void WriteTags(UserTagCollection tags)
{
XmlElement node = _root.EnsureChildElement("Tags");
node.RemoveAll();
bool isExists = tags != null && tags.Count > 0;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
node.SetString("Value", String.Join(";", tags.Select(tag => tag.Name)));
}
public void WriteTitle(string tags)
{
XmlElement node = _root.EnsureChildElement("Title");
node.RemoveAll();
bool isExists = !string.IsNullOrEmpty(tags);
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
node.SetString("Value", tags);
}
public void WritePvP(uint? pvp)
{
XmlElement node = _root.EnsureChildElement("PVP");
node.RemoveAll();
bool isExists = pvp != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
node.SetUInt32("Value", pvp.Value);
}
public void WriteInformation(FieldInfo info)
{
XmlElement node = _root.EnsureChildElement("FieldInfo");
node.RemoveAll();
bool isExists = info != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
node.SetString("Name", info.Name);
node.SetByte("Direction", info.Direction);
node.SetUInt16("FocusHeight", info.FocusHeight);
XmlElement cameraRanges = node.EnsureChildElement("CameraRanges");
foreach (RectInt16 range in info.CameraRanges)
Write(range, cameraRanges.CreateChildElement("Range"));
XmlElement screenRanges = node.EnsureChildElement("ScreenRanges");
foreach (RectInt16 range in info.ScreenRanges)
Write(range, screenRanges.CreateChildElement("Range"));
XmlElement gateways = node.EnsureChildElement("Gateways");
foreach (FieldGateway gateway in info.Gateways)
Write(gateway, gateways.CreateChildElement("Gateway"));
XmlElement triggers = node.EnsureChildElement("Triggers");
foreach (FieldTrigger trigger in info.Triggers)
Write(trigger, triggers.CreateChildElement("Trigger"));
if (info.PvP != null)
node.SetUInt32("PvP", info.PvP.Value);
node.SetUInt32("Unknown", info.Unknown);
}
public void WriteMonologues(LocalizableStrings monologues)
{
XmlElement node = _root.EnsureChildElement("Monologues");
node.RemoveAll();
bool isExists = monologues != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
string dlgPath = Path.ChangeExtension(_xmlPath, ".dlg.xml");
node = XmlHelper.CreateDocument("Monologues");
foreach (LocalizableString monologue in monologues)
{
XmlElement child = node.CreateChildElement("Monologue");
child.SetInt32("Order", monologue.Order);
child.SetBoolean("IsIndent", monologue.IsIndent);
child.SetString("Current", monologue.Current);
child.SetString("Original", monologue.Original);
}
node.GetOwnerDocument().Save(dlgPath);
}
public void WriteExtraFonts(GameFont extraFont)
{
XmlElement node = _root.EnsureChildElement("ExtraFont");
node.RemoveAll();
bool isExists = extraFont != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
string exfDirPath = Path.ChangeExtension(_xmlPath, ".exf");
GameFontWriter.ToDirectory(extraFont, exfDirPath);
}
public void WriteBackground(GameImage background)
{
XmlElement node = _root.EnsureChildElement("Background");
node.RemoveAll();
bool isExists = background != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
GameImageWriter.ToDirectory(background, Path.ChangeExtension(_xmlPath, ".bgr"));
}
public void WriteWalkmesh(Walkmesh walkmesh)
{
XmlElement node = _root.EnsureChildElement("Walkmesh");
node.RemoveAll();
bool isExists = walkmesh != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
string wlkPath = Path.ChangeExtension(_xmlPath, ".wlk.xml");
node = XmlHelper.CreateDocument("Walkmesh");
XmlElement triangles = node.EnsureChildElement("Triangles");
foreach (WalkmeshTriangle triangle in walkmesh.Triangles)
Write(triangle, triangles.CreateChildElement("Triangle"));
XmlElement passability = node.EnsureChildElement("Passability");
foreach (WalkmeshPassability pass in walkmesh.Passability)
Write(pass, passability.CreateChildElement("Pass"));
node.GetOwnerDocument().Save(wlkPath);
}
public void WriteCamera(FieldCameras fieldCameras)
{
XmlElement node = _root.EnsureChildElement("FieldCameras");
node.RemoveAll();
bool isExists = fieldCameras != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
foreach (FieldCamera camera in fieldCameras)
Write(camera, node.CreateChildElement("FieldCamera"));
}
public void WriteMoviesCameras(MovieCameras movieCameras)
{
XmlElement node = _root.EnsureChildElement("MovieCameras");
node.RemoveAll();
bool isExists = movieCameras != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
foreach (MovieCamera camera in movieCameras)
Write(camera, node.CreateChildElement("MovieCamera"));
}
public void WritePlaceables(Placeables placeables)
{
XmlElement node = _root.EnsureChildElement("Placeables");
node.RemoveAll();
bool isExists = placeables != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
foreach (Placeable placeable in placeables)
node.CreateChildElement("Placeable").SetUInt64("Value", BitConverter.ToUInt64(placeable.Unknown, 0));
}
public void WriteAmbient(Ambient ambient)
{
XmlElement node = _root.EnsureChildElement("Ambient");
node.RemoveAll();
bool isExists = ambient != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
foreach (uint soundId in ambient.SoundsIds)
node.CreateChildElement("Sound").SetUInt32("Id", soundId);
}
public void WriteEncounters(Encounters encounters)
{
XmlElement node = _root.EnsureChildElement("Encounters");
node.RemoveAll();
bool isExists = encounters != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
node.SetByte("Frequency", encounters.Frequency);
foreach (ushort enemyId in encounters.EnemiesID)
node.CreateChildElement("Enemy").SetUInt16("Id", enemyId);
}
public void WriteScripts(AsmCollection scripts)
{
XmlElement node = _root.EnsureChildElement("Scripts");
node.RemoveAll();
bool isExists = scripts != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
string scriptsFile = Path.ChangeExtension(_xmlPath, ".sct");
using (Stream output = new FileStream(scriptsFile, FileMode.Create, FileAccess.Write, FileShare.None))
using (BinaryWriter bw = new BinaryWriter(output, Encoding.UTF8))
{
bw.Write("FF8S");
bw.Write(scripts.Count);
foreach (AsmModule module in scripts.GetOrderedModulesByIndex())
{
bw.Write(module.ExecutionOrder);
bw.Write(module.Label);
bw.Write(module.Title);
bw.Write((int)module.Type);
bw.Write(module.Count);
foreach (AsmEvent script in module.GetOrderedEvents())
{
bw.Write(script.Title);
bw.Write(script.Count);
foreach (JsmOperation operation in script)
bw.Write(operation.Operation);
}
}
}
}
public void WriteModels(SafeHGlobalHandle oneContent)
{
XmlElement node = _root.EnsureChildElement("Models");
node.RemoveAll();
bool isExists = oneContent != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
string oneFile = PathEx.ChangeName(_xmlPath, Path.ChangeExtension(_xmlPath, ".one"));
using (Stream input = oneContent.OpenStream(FileAccess.Read))
using (Stream output = new FileStream(oneFile, FileMode.Create, FileAccess.Write, FileShare.None))
input.CopyTo(output);
}
public void WriteParticles(Particles particles)
{
XmlElement node = _root.EnsureChildElement("Particles");
node.RemoveAll();
bool isExists = particles != null;
node.SetBoolean("IsExists", isExists);
if (!isExists)
return;
string pmdFile = PathEx.ChangeName(_xmlPath, Path.ChangeExtension(_xmlPath, ".pmd"));
string pmpFile = PathEx.ChangeName(_xmlPath, Path.ChangeExtension(_xmlPath, ".pmp"));
using (Stream input = particles.PMDContent.OpenStream(FileAccess.Read))
using (Stream output = new FileStream(pmdFile, FileMode.Create, FileAccess.Write, FileShare.None))
input.CopyTo(output);
using (Stream input = particles.PMPContent.OpenStream(FileAccess.Read))
using (Stream output = new FileStream(pmpFile, FileMode.Create, FileAccess.Write, FileShare.None))
input.CopyTo(output);
}
private void Write(FieldGateway gateway, XmlElement node)
{
node.SetUInt16("DestinationId", gateway.DestinationId);
if (gateway.Unknown1 != null)
node.SetInt32("Unknown1", gateway.Unknown1.Value);
if (gateway.Unknown2 != null)
node.SetInt32("Unknown2", gateway.Unknown2.Value);
node.SetInt32("Unknown3", gateway.Unknown3);
Write(gateway.Boundary, node.CreateChildElement("Boundary"));
Write(gateway.DestinationPoint, node.CreateChildElement("DestinationPoint"));
}
private void Write(FieldTrigger trigger, XmlElement node)
{
node.SetByte("DoorID", trigger.DoorID);
Write(trigger.Boundary, node.CreateChildElement("Boundary"));
}
private void Write(WalkmeshTriangle triangle, XmlElement node)
{
foreach (Vector3 coord in triangle.Coords)
Write(coord, node.CreateChildElement("Coord"));
}
private void Write(WalkmeshPassability pass, XmlElement node)
{
foreach (ushort edge in pass.Edges)
node.CreateChildElement("Edge").SetUInt16("Value", edge);
}
private void Write(FieldCamera camera, XmlElement node)
{
Write(camera.XAxis, node.CreateChildElement("XAxis"));
Write(camera.YAxis, node.CreateChildElement("YAxis"));
Write(camera.ZAxis, node.CreateChildElement("ZAxis"));
Write(camera.Position, node.CreateChildElement("Position"));
node.SetInt16("Zoom", camera.Zoom);
}
private void Write(MovieCamera camera, XmlElement node)
{
Write(camera.TopLeft, node.CreateChildElement("TopLeft"));
Write(camera.TopRight, node.CreateChildElement("TopRight"));
Write(camera.BottomRight, node.CreateChildElement("BottomRight"));
Write(camera.BottomLeft, node.CreateChildElement("BottomLeft"));
}
private void Write(Vector3 vector, XmlElement node)
{
node.SetInt16("X", vector.X);
node.SetInt16("Y", vector.Y);
node.SetInt16("Z", vector.Z);
}
private void Write(Vector3Int32 vector, XmlElement node)
{
node.SetInt32("X", vector.X);
node.SetInt32("Y", vector.Y);
node.SetInt32("Z", vector.Z);
}
private void Write(Line3 line, XmlElement node)
{
Write(line.Begin, node.CreateChildElement("Begin"));
Write(line.End, node.CreateChildElement("End"));
}
private void Write(RectInt16 rectInt16, XmlElement node)
{
node.SetInt16("Top", rectInt16.Top);
node.SetInt16("Bottom", rectInt16.Bottom);
node.SetInt16("Right", rectInt16.Right);
node.SetInt16("Left", rectInt16.Left);
}
}
} | {
"content_hash": "2416a2b1f46c1dcd992adfdf2e69f10b",
"timestamp": "",
"source": "github",
"line_count": 424,
"max_line_length": 117,
"avg_line_length": 34.70990566037736,
"alnum_prop": 0.5706326017530747,
"repo_name": "Albeoris/Esthar",
"id": "0463762279a37c9b4f3bef223b159d87c2d819ae",
"size": "14719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Esthar.Transform/Locations/IO/XmlLocationWriter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "885014"
},
{
"name": "Smalltalk",
"bytes": "13498"
}
],
"symlink_target": ""
} |
package org.apache.ignite.yardstick.cache.load;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryListenerException;
import javax.cache.event.CacheEntryUpdatedListener;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCompute;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheEntryEventSerializableFilter;
import org.apache.ignite.cache.CacheMemoryMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CacheTypeMetadata;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.QueryIndex;
import org.apache.ignite.cache.affinity.Affinity;
import org.apache.ignite.cache.query.ContinuousQuery;
import org.apache.ignite.cache.query.Query;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.ScanQuery;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.SqlQuery;
import org.apache.ignite.cluster.ClusterGroup;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.lang.IgniteBiPredicate;
import org.apache.ignite.lang.IgniteRunnable;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.transactions.TransactionConcurrency;
import org.apache.ignite.transactions.TransactionIsolation;
import org.apache.ignite.yardstick.IgniteAbstractBenchmark;
import org.apache.ignite.yardstick.IgniteBenchmarkUtils;
import org.apache.ignite.yardstick.cache.load.model.ModelUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.yardstickframework.BenchmarkConfiguration;
import org.yardstickframework.BenchmarkUtils;
/**
* Ignite cache random operation benchmark.
*/
public class IgniteCacheRandomOperationBenchmark extends IgniteAbstractBenchmark {
/** */
public static final int operations = Operation.values().length;
/***/
public static final int CONTINUOUS_QUERY_PER_CACHE = 3;
/** Scan query predicate. */
private static BenchmarkIgniteBiPredicate igniteBiPred = new BenchmarkIgniteBiPredicate();
/** Amount partitions. */
private static final int SCAN_QUERY_PARTITION_AMOUNT = 10;
/** List off all available cache. */
private List<IgniteCache<Object, Object>> availableCaches;
/** List of available transactional cache. */
private List<IgniteCache<Object, Object>> txCaches;
/** List of affinity cache. */
private List<IgniteCache<Object, Object>> affCaches;
/** Map cache name on key classes. */
private Map<String, Class[]> keysCacheClasses;
/** Map cache name on value classes. */
private Map<String, Class[]> valuesCacheClasses;
/** List of query descriptors by cache names. */
private Map<String, List<SqlCacheDescriptor>> cacheSqlDescriptors;
/** List of SQL queries. */
private List<TestQuery> queries;
/** List of allowed cache operations which will be executed. */
private List<Operation> allowedLoadTestOps;
/**
* Replace value entry processor.
*/
private BenchmarkReplaceValueEntryProcessor replaceEntryProc;
/**
* Remove entry processor.
*/
private BenchmarkRemoveEntryProcessor rmvEntryProc;
/**
* Map of statistic information.
*/
private Map<String, AtomicLong> operationStatistics;
/** {@inheritDoc} */
@Override public void setUp(BenchmarkConfiguration cfg) throws Exception {
super.setUp(cfg);
searchCache();
preLoading();
}
/** {@inheritDoc} */
@Override public void onException(Throwable e) {
BenchmarkUtils.error("The benchmark of random operation failed.", e);
super.onException(e);
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> map) throws Exception {
if (nextBoolean()) {
executeInTransaction(map);
executeOutOfTx(map, true);
}
else
executeOutOfTx(map, false);
return true;
}
/** {@inheritDoc} */
@Override public void tearDown() throws Exception {
try {
BenchmarkUtils.println("Benchmark statistics");
for (String cacheName : ignite().cacheNames()) {
BenchmarkUtils.println(String.format("Operations over cache '%s'", cacheName));
for (Operation op : Operation.values()) {
BenchmarkUtils.println(cfg, String.format("%s: %s", op,
operationStatistics.get(op + "_" + cacheName)));
}
}
}
finally {
super.tearDown();
}
}
/**
* @throws Exception If failed.
*/
private void searchCache() throws Exception {
availableCaches = new ArrayList<>(ignite().cacheNames().size());
txCaches = new ArrayList<>();
affCaches = new ArrayList<>();
keysCacheClasses = new HashMap<>();
valuesCacheClasses = new HashMap<>();
replaceEntryProc = new BenchmarkReplaceValueEntryProcessor(null);
rmvEntryProc = new BenchmarkRemoveEntryProcessor();
cacheSqlDescriptors = new HashMap<>();
operationStatistics = new HashMap<>();
loadQueries();
loadAllowedOperations();
for (String cacheName : ignite().cacheNames()) {
IgniteCache<Object, Object> cache = ignite().cache(cacheName);
for (Operation op : Operation.values())
operationStatistics.put(op + "_" + cacheName, new AtomicLong(0));
CacheConfiguration configuration = cache.getConfiguration(CacheConfiguration.class);
if (isClassDefinedInConfig(configuration)) {
if (configuration.getMemoryMode() == CacheMemoryMode.OFFHEAP_TIERED &&
configuration.getQueryEntities().size() > 2) {
throw new IgniteException("Off-heap mode is unsupported by the load test due to bugs IGNITE-2982" +
" and IGNITE-2997");
}
ArrayList<Class> keys = new ArrayList<>();
ArrayList<Class> values = new ArrayList<>();
if (configuration.getQueryEntities() != null) {
Collection<QueryEntity> entries = configuration.getQueryEntities();
for (QueryEntity queryEntity : entries) {
try {
if (queryEntity.getKeyType() != null) {
Class keyCls = Class.forName(queryEntity.getKeyType());
if (ModelUtil.canCreateInstance(keyCls))
keys.add(keyCls);
else
throw new IgniteException("Class is unknown for the load test. Make sure you " +
"specified its full name [clsName=" + queryEntity.getKeyType() + ']');
}
if (queryEntity.getValueType() != null) {
Class valCls = Class.forName(queryEntity.getValueType());
if (ModelUtil.canCreateInstance(valCls))
values.add(valCls);
else
throw new IgniteException("Class is unknown for the load test. Make sure you " +
"specified its full name [clsName=" + queryEntity.getKeyType() + ']');
configureCacheSqlDescriptor(cacheName, queryEntity, valCls);
}
} catch (ClassNotFoundException e) {
BenchmarkUtils.println(e.getMessage());
BenchmarkUtils.println("This can be a BinaryObject. Ignoring exception.");
if (!cacheSqlDescriptors.containsKey(cacheName))
cacheSqlDescriptors.put(cacheName, new ArrayList<SqlCacheDescriptor>());
}
}
}
if (configuration.getTypeMetadata() != null) {
Collection<CacheTypeMetadata> entries = configuration.getTypeMetadata();
for (CacheTypeMetadata cacheTypeMetadata : entries) {
try {
if (cacheTypeMetadata.getKeyType() != null) {
Class keyCls = Class.forName(cacheTypeMetadata.getKeyType());
if (ModelUtil.canCreateInstance(keyCls))
keys.add(keyCls);
else
throw new IgniteException("Class is unknown for the load test. Make sure you " +
"specified its full name [clsName=" + cacheTypeMetadata.getKeyType() + ']');
}
if (cacheTypeMetadata.getValueType() != null) {
Class valCls = Class.forName(cacheTypeMetadata.getValueType());
if (ModelUtil.canCreateInstance(valCls))
values.add(valCls);
else
throw new IgniteException("Class is unknown for the load test. Make sure you " +
"specified its full name [clsName=" + cacheTypeMetadata.getKeyType() + ']');
}
} catch (ClassNotFoundException e) {
BenchmarkUtils.println(e.getMessage());
BenchmarkUtils.println("This can be a BinaryObject. Ignoring exception.");
if (!cacheSqlDescriptors.containsKey(cacheName))
cacheSqlDescriptors.put(cacheName, new ArrayList<SqlCacheDescriptor>());
}
}
}
keysCacheClasses.put(cacheName, keys.toArray(new Class[] {}));
valuesCacheClasses.put(cacheName, values.toArray(new Class[] {}));
}
else
keysCacheClasses.put(cacheName, new Class[] {randomKeyClass(cacheName)});
valuesCacheClasses.put(cacheName, determineValueClasses(cacheName));
if (configuration.getCacheMode() != CacheMode.LOCAL)
affCaches.add(cache);
if (configuration.getAtomicityMode() == CacheAtomicityMode.TRANSACTIONAL)
txCaches.add(cache);
availableCaches.add(cache);
}
}
/**
* Load allowed operation from parameters.
*/
private void loadAllowedOperations() {
allowedLoadTestOps = new ArrayList<>();
if (args.allowedLoadTestOps().isEmpty())
Collections.addAll(allowedLoadTestOps, Operation.values());
else {
for (String opName : args.allowedLoadTestOps())
allowedLoadTestOps.add(Operation.valueOf(opName.toUpperCase()));
}
}
/**
* Load query from file.
*
* @throws Exception If fail.
*/
private void loadQueries() throws Exception {
queries = new ArrayList<>();
if (args.loadTestQueriesFile() != null) {
try (FileReader fr = new FileReader(args.loadTestQueriesFile())) {
try (BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty())
continue;
boolean distributedJoins = false;
int commentIdx = line.lastIndexOf('#');
if (commentIdx >= 0) {
if (line.toUpperCase().indexOf("DISTRIBUTEDJOINS", commentIdx) > 0)
distributedJoins = true;
line = line.substring(0, commentIdx);
}
line = line.trim();
TestQuery qry = new TestQuery(line, distributedJoins);
queries.add(qry);
BenchmarkUtils.println("Loaded query: " + qry);
}
}
}
}
}
/**
* @param cacheName Ignite cache name.
* @param qryEntity Query entry.
* @param valCls Class of value.
* @throws ClassNotFoundException If fail.
*/
private void configureCacheSqlDescriptor(String cacheName, QueryEntity qryEntity, Class valCls)
throws ClassNotFoundException {
List<SqlCacheDescriptor> descs = cacheSqlDescriptors.get(cacheName);
if (descs == null) {
descs = new ArrayList<>();
cacheSqlDescriptors.put(cacheName, descs);
}
Map<String, Class> indexedFields = new HashMap<>();
for (QueryIndex index : qryEntity.getIndexes()) {
for (String iField : index.getFieldNames()) {
indexedFields.put(iField,
Class.forName(qryEntity.getFields().get(iField)));
}
}
descs.add(new SqlCacheDescriptor(valCls, qryEntity.getFields().keySet(),
indexedFields));
}
/**
* @param configuration Ignite cache configuration.
* @return True if defined.
*/
private boolean isClassDefinedInConfig(CacheConfiguration configuration) {
return (configuration.getIndexedTypes() != null && configuration.getIndexedTypes().length > 0)
|| !CollectionUtils.isEmpty(configuration.getQueryEntities())
|| !CollectionUtils.isEmpty(configuration.getTypeMetadata());
}
/**
* @throws Exception If fail.
*/
private void preLoading() throws Exception {
if (args.preloadAmount() > args.range())
throw new IllegalArgumentException("Preloading amount (\"-pa\", \"--preloadAmount\") must by less then the" +
" range (\"-r\", \"--range\").");
Thread[] threads = new Thread[availableCaches.size()];
for (int i = 0; i < availableCaches.size(); i++) {
final String cacheName = availableCaches.get(i).getName();
threads[i] = new Thread() {
@Override public void run() {
try (IgniteDataStreamer<Object, Object> dataLdr = ignite().dataStreamer(cacheName)) {
for (int i = 0; i < args.preloadAmount() && !isInterrupted(); i++)
dataLdr.addData(createRandomKey(i, cacheName), createRandomValue(i, cacheName));
}
}
};
threads[i].start();
}
for (Thread thread : threads)
thread.join();
}
/**
* Building a map that contains mapping of node ID to a list of partitions stored on the node.
*
* @param cacheName Name of Ignite cache.
* @return Node to partitions map.
*/
private Map<UUID, List<Integer>> personCachePartitions(String cacheName) {
// Getting affinity for person cache.
Affinity<Object> affinity = ignite().affinity(cacheName);
// Building a list of all partitions numbers.
List<Integer> rndParts = new ArrayList<>(10);
if (affinity.partitions() <= SCAN_QUERY_PARTITION_AMOUNT)
for (int i = 0; i < affinity.partitions(); i++)
rndParts.add(i);
else {
for (int i = 0; i < SCAN_QUERY_PARTITION_AMOUNT; i++) {
int partNum;
do
partNum = nextRandom(affinity.partitions());
while (rndParts.contains(partNum));
rndParts.add(partNum);
}
}
Collections.sort(rndParts);
// Getting partition to node mapping.
Map<Integer, ClusterNode> partPerNodes = affinity.mapPartitionsToNodes(rndParts);
// Building node to partitions mapping.
Map<UUID, List<Integer>> nodesToPart = new HashMap<>();
for (Map.Entry<Integer, ClusterNode> entry : partPerNodes.entrySet()) {
List<Integer> nodeParts = nodesToPart.get(entry.getValue().id());
if (nodeParts == null) {
nodeParts = new ArrayList<>();
nodesToPart.put(entry.getValue().id(), nodeParts);
}
nodeParts.add(entry.getKey());
}
return nodesToPart;
}
/**
* @param id Object identifier.
* @param cacheName Name of Ignite cache.
* @return Random object.
*/
private Object createRandomKey(int id, String cacheName) {
Class clazz = randomKeyClass(cacheName);
return ModelUtil.create(clazz, id);
}
/**
* @param cacheName Ignite cache name.
* @return Random key class.
*/
private Class randomKeyClass(String cacheName) {
Class[] keys = keysCacheClasses.containsKey(cacheName)
? keysCacheClasses.get(cacheName) : ModelUtil.keyClasses();
return keys[nextRandom(keys.length)];
}
/**
* @param cacheName Cache name.
* @return Set classes for cache.
*/
private Class[] determineValueClasses(@NotNull String cacheName) {
return cacheName.toLowerCase().contains("fat-values") ? ModelUtil.fatValueClasses() :
ModelUtil.simpleValueClasses();
}
/**
* @param id Object identifier.
* @param cacheName Name of Ignite cache.
* @return Random object.
*/
private Object createRandomValue(int id, String cacheName) {
Class clazz = randomValueClass(cacheName);
return ModelUtil.create(clazz, id);
}
/**
* @param cacheName Ignite cache name.
* @return Random value class.
*/
private Class randomValueClass(String cacheName) {
Class[] values = valuesCacheClasses.containsKey(cacheName)
? valuesCacheClasses.get(cacheName) : ModelUtil.valueClasses();
return values[nextRandom(values.length)];
}
/**
* @param map Parameters map.
* @param withoutTransactionCache Without transaction cache.
* @throws Exception If fail.
*/
private void executeOutOfTx(Map<Object, Object> map, boolean withoutTransactionCache) throws Exception {
for (IgniteCache<Object, Object> cache : availableCaches) {
if (withoutTransactionCache && txCaches.contains(cache))
continue;
executeRandomOperation(map, cache);
}
}
/**
* @param map Parameters map.
* @param cache Ignite cache.
* @throws Exception If fail.
*/
private void executeRandomOperation(Map<Object, Object> map, IgniteCache<Object, Object> cache) throws Exception {
Operation op = nextRandomOperation();
switch (op) {
case PUT:
doPut(cache);
break;
case PUT_ALL:
doPutAll(cache);
break;
case GET:
doGet(cache);
break;
case GET_ALL:
doGetAll(cache);
break;
case INVOKE:
doInvoke(cache);
break;
case INVOKE_ALL:
doInvokeAll(cache);
break;
case REMOVE:
doRemove(cache);
break;
case REMOVE_ALL:
doRemoveAll(cache);
break;
case PUT_IF_ABSENT:
doPutIfAbsent(cache);
break;
case REPLACE:
doReplace(cache);
break;
case SCAN_QUERY:
doScanQuery(cache);
break;
case SQL_QUERY:
doSqlQuery(cache);
break;
case CONTINUOUS_QUERY:
doContinuousQuery(cache, map);
}
storeStatistics(cache.getName(), map, op);
}
/**
* @return Operation.
*/
@NotNull private Operation nextRandomOperation() {
return allowedLoadTestOps.get(nextRandom(allowedLoadTestOps.size()));
}
/**
* @param cacheName Ignite cache name.
* @param map Parameters map.
* @param op Operation.
*/
private void storeStatistics(String cacheName, Map<Object, Object> map, Operation op) {
String opCacheKey = op + "_" + cacheName;
Long opAmount = (Long)map.get("amount");
opAmount = opAmount == null ? 1L : opAmount + 1;
Integer opCacheCnt = (Integer)map.get(opCacheKey);
opCacheCnt = opCacheCnt == null ? 1 : opCacheCnt + 1;
if (opAmount % 100 == 0)
updateStat(map);
else
map.put(opCacheKey, opCacheCnt);
map.put("amount", opAmount);
}
/**
* @param map Parameters map.
*/
private void updateStat(Map<Object, Object> map) {
for (Operation op: Operation.values())
for (String cacheName: ignite().cacheNames()) {
String opCacheKey = op + "_" + cacheName;
Integer val = (Integer)map.get(opCacheKey);
if (val != null) {
operationStatistics.get(opCacheKey).addAndGet(val.longValue());
map.put(opCacheKey, 0);
}
}
}
/**
* Execute operations in transaction.
* @param map Parameters map.
* @throws Exception if fail.
*/
private void executeInTransaction(final Map<Object, Object> map) throws Exception {
IgniteBenchmarkUtils.doInTransaction(ignite().transactions(),
TransactionConcurrency.fromOrdinal(nextRandom(TransactionConcurrency.values().length)),
TransactionIsolation.fromOrdinal(nextRandom(TransactionIsolation.values().length)),
new Callable<Object>() {
@Override public Object call() throws Exception {
for (IgniteCache<Object, Object> cache : txCaches)
if (nextBoolean())
executeRandomOperation(map, cache);
return null;
}
});
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doPut(IgniteCache<Object, Object> cache) throws Exception {
int i = nextRandom(args.range());
cache.put(createRandomKey(i, cache.getName()), createRandomValue(i, cache.getName()));
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doPutAll(IgniteCache<Object, Object> cache) throws Exception {
Map<Object, Object> putMap = new TreeMap<>();
Class keyCass = randomKeyClass(cache.getName());
for (int cnt = 0; cnt < args.batch(); cnt++) {
int i = nextRandom(args.range());
putMap.put(ModelUtil.create(keyCass, i), createRandomValue(i, cache.getName()));
}
cache.putAll(putMap);
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doGet(IgniteCache<Object, Object> cache) throws Exception {
int i = nextRandom(args.range());
cache.get(createRandomKey(i, cache.getName()));
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doGetAll(IgniteCache<Object, Object> cache) throws Exception {
Set<Object> keys = new TreeSet<>();
Class keyCls = randomKeyClass(cache.getName());
for (int cnt = 0; cnt < args.batch(); cnt++) {
int i = nextRandom(args.range());
keys.add(ModelUtil.create(keyCls, i));
}
cache.getAll(keys);
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doInvoke(final IgniteCache<Object, Object> cache) throws Exception {
final int i = nextRandom(args.range());
if (nextBoolean())
cache.invoke(createRandomKey(i, cache.getName()), replaceEntryProc,
createRandomValue(i + 1, cache.getName()));
else
cache.invoke(createRandomKey(i, cache.getName()), rmvEntryProc);
}
/**
* Entry processor for local benchmark replace value task.
*/
private static class BenchmarkReplaceValueEntryProcessor implements EntryProcessor<Object, Object, Object>, Serializable {
/**
* New value for update during process by default.
*/
private Object newVal;
/**
* @param newVal default new value
*/
private BenchmarkReplaceValueEntryProcessor(Object newVal) {
this.newVal = newVal;
}
/** {@inheritDoc} */
@Override public Object process(MutableEntry<Object, Object> entry, Object... arguments) {
Object newVal = arguments == null || arguments[0] == null ? this.newVal : arguments[0];
Object oldVal = entry.getValue();
entry.setValue(newVal);
return oldVal;
}
}
/**
* Entry processor for local benchmark remove entry task.
*/
private static class BenchmarkRemoveEntryProcessor implements EntryProcessor<Object, Object, Object>, Serializable {
/** {@inheritDoc} */
@Override public Object process(MutableEntry<Object, Object> entry, Object... arguments) {
Object oldVal = entry.getValue();
entry.remove();
return oldVal;
}
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doInvokeAll(IgniteCache<Object, Object> cache) throws Exception {
Map<Object, EntryProcessor<Object, Object, Object>> map = new TreeMap<>();
Class keyCls = randomKeyClass(cache.getName());
for (int cnt = 0; cnt < args.batch(); cnt++) {
int i = nextRandom(args.range());
Object key = ModelUtil.create(keyCls, i);
if (nextBoolean())
map.put(key,
new BenchmarkReplaceValueEntryProcessor(createRandomValue(i + 1, cache.getName())));
else
map.put(key, rmvEntryProc);
}
cache.invokeAll(map);
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doRemove(IgniteCache<Object, Object> cache) throws Exception {
int i = nextRandom(args.range());
cache.remove(createRandomKey(i, cache.getName()));
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doRemoveAll(IgniteCache<Object, Object> cache) throws Exception {
Set<Object> keys = new TreeSet<>();
Class keyCls = randomKeyClass(cache.getName());
for (int cnt = 0; cnt < args.batch(); cnt++) {
int i = nextRandom(args.range());
keys.add(ModelUtil.create(keyCls, i));
}
cache.removeAll(keys);
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doPutIfAbsent(IgniteCache<Object, Object> cache) throws Exception {
int i = nextRandom(args.range());
cache.putIfAbsent(createRandomKey(i, cache.getName()), createRandomValue(i, cache.getName()));
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doReplace(IgniteCache<Object, Object> cache) throws Exception {
int i = nextRandom(args.range());
cache.replace(createRandomKey(i, cache.getName()),
createRandomValue(i, cache.getName()),
createRandomValue(i + 1, cache.getName()));
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doScanQuery(IgniteCache<Object, Object> cache) throws Exception {
if (!affCaches.contains(cache))
return;
Map<UUID, List<Integer>> partitionsMap = personCachePartitions(cache.getName());
ScanQueryBroadcastClosure c = new ScanQueryBroadcastClosure(cache.getName(), partitionsMap);
ClusterGroup clusterGrp = ignite().cluster().forNodeIds(partitionsMap.keySet());
IgniteCompute compute = ignite().compute(clusterGrp);
compute.broadcast(c);
}
/**
* @param cache Ignite cache.
* @throws Exception If failed.
*/
private void doSqlQuery(IgniteCache<Object, Object> cache) throws Exception {
List<SqlCacheDescriptor> descriptors = cacheSqlDescriptors.get(cache.getName());
if (descriptors != null) {
Query sq = null;
if (queries.isEmpty()) {
if (!descriptors.isEmpty()) {
SqlCacheDescriptor randomDesc = descriptors.get(nextRandom(descriptors.size()));
int id = nextRandom(args.range());
sq = nextBoolean() ? randomDesc.getSqlQuery(id) : randomDesc.getSqlFieldsQuery(id);
}
}
else {
TestQuery qry = queries.get(nextRandom(queries.size()));
String sql = randomizeSql(qry.sql);
sq = new SqlFieldsQuery(sql);
((SqlFieldsQuery)sq).setDistributedJoins(qry.distributedJoin);
}
if (sq != null)
try (QueryCursor cursor = cache.query(sq)) {
for (Object obj : cursor) {
// No-op.
}
}
}
}
/**
* @return SQL string.
*/
private String randomizeSql(String sql) {
int cnt = StringUtils.countOccurrencesOf(sql, "%s");
Integer[] sub = new Integer[cnt];
for (int i = 0; i< cnt; i++)
sub[i] = nextRandom(args.range());
sql = String.format(sql, sub);
return sql;
}
/**
* @param cache Ignite cache.
* @param map Parameters map.
* @throws Exception If failed.
*/
private void doContinuousQuery(IgniteCache<Object, Object> cache, Map<Object, Object> map) throws Exception {
List<QueryCursor> cursors = (ArrayList<QueryCursor>)map.get(cache.getName());
if (cursors == null) {
cursors = new ArrayList<>(CONTINUOUS_QUERY_PER_CACHE);
map.put(cache.getName(), cursors);
}
if (cursors.size() == CONTINUOUS_QUERY_PER_CACHE) {
QueryCursor cursor = cursors.get(nextRandom(cursors.size()));
cursor.close();
cursors.remove(cursor);
}
ContinuousQuery qry = new ContinuousQuery();
qry.setLocalListener(new ContinuousQueryUpdater());
qry.setRemoteFilterFactory(FactoryBuilder.factoryOf(new ContinuousQueryFilter()));
cursors.add(cache.query(qry));
}
/**
* @return Nex random boolean value.
*/
private boolean nextBoolean() {
return ThreadLocalRandom.current().nextBoolean();
}
/**
* Continuous query updater class.
*/
private static class ContinuousQueryUpdater implements CacheEntryUpdatedListener, Serializable {
/** {@inheritDoc} */
@Override public void onUpdated(Iterable iterable) throws CacheEntryListenerException {
for (Object o : iterable) {
// No-op.
}
}
}
/**
* Continuous query filter class.
*/
private static class ContinuousQueryFilter implements CacheEntryEventSerializableFilter, Serializable {
/** */
private boolean flag = true;
/** {@inheritDoc} */
@Override public boolean evaluate(CacheEntryEvent evt) throws CacheEntryListenerException {
return flag =! flag;
}
}
/**
* Closure for scan query executing.
*/
private static class ScanQueryBroadcastClosure implements IgniteRunnable {
/**
* Ignite node.
*/
@IgniteInstanceResource
private Ignite node;
/**
* Information about partition.
*/
private Map<UUID, List<Integer>> cachePart;
/**
* Name of Ignite cache.
*/
private String cacheName;
/**
* @param cacheName Name of Ignite cache.
* @param cachePart Partition by node for Ignite cache.
*/
private ScanQueryBroadcastClosure(String cacheName, Map<UUID, List<Integer>> cachePart) {
this.cachePart = cachePart;
this.cacheName = cacheName;
}
/** {@inheritDoc} */
@Override public void run() {
IgniteCache cache = node.cache(cacheName);
// Getting a list of the partitions owned by this node.
List<Integer> myPartitions = cachePart.get(node.cluster().localNode().id());
for (Integer part : myPartitions) {
ScanQuery scanQry = new ScanQuery();
scanQry.setPartition(part);
scanQry.setFilter(igniteBiPred);
try (QueryCursor cursor = cache.query(scanQry)) {
for (Object obj : cursor) {
// No-op.
}
}
}
}
}
/**
* Scan query predicate class.
*/
private static class BenchmarkIgniteBiPredicate implements IgniteBiPredicate {
/**
* @param key Cache key.
* @param val Cache value.
* @return true If is hit.
*/
@Override public boolean apply(Object key, Object val) {
return true;
}
}
/**
* Query descriptor.
*/
private static class SqlCacheDescriptor {
/**
* Class of value.
*/
private Class valCls;
/**
* Select fields.
*/
private Set<String> fields;
/**
* Indexed fields.
*/
private Map<String, Class> indexedFieldsByCls;
/**
* @param valCls Class of value.
* @param fields All select fields.
* @param indexedFieldsByCls Indexed fields.
*/
SqlCacheDescriptor(Class valCls, Set<String> fields,
Map<String, Class> indexedFieldsByCls) {
this.valCls = valCls;
this.fields = fields;
this.indexedFieldsByCls = indexedFieldsByCls;
}
/**
* @param id Query id.
* @return Condition string.
*/
private String makeQuerySelect(int id) {
return StringUtils.collectionToDelimitedString(fields, ", ");
}
/**
* @param id Query id.
* @return Condition string.
*/
private String makeQueryCondition(int id) {
StringBuilder sb = new StringBuilder();
for (String iField : indexedFieldsByCls.keySet()) {
Class cl = indexedFieldsByCls.get(iField);
if (!Number.class.isAssignableFrom(cl) && !String.class.equals(cl))
continue;
if (sb.length() != 0) {
switch (id % 3 % 2) {
case 0:
sb.append(" OR ");
break;
case 1:
sb.append(" AND ");
break;
}
}
if (Number.class.isAssignableFrom(cl)) {
sb.append(iField);
switch (id % 2) {
case 0:
sb.append(" > ");
break;
case 1:
sb.append(" < ");
break;
}
sb.append(id);
}
else if (String.class.equals(cl))
sb.append("lower(").append(iField).append(") LIKE lower('%").append(id).append("%')");
}
return sb.toString();
}
/**
* @param id Query id.
* @return SQL query object.
*/
SqlQuery getSqlQuery(int id) {
return new SqlQuery(valCls, makeQueryCondition(id));
}
/**
* @param id Query id.
* @return SQL filed query object.
*/
SqlFieldsQuery getSqlFieldsQuery(int id) {
return new SqlFieldsQuery(String.format("SELECT %s FROM %s WHERE %s",
makeQuerySelect(id), valCls.getSimpleName(), makeQueryCondition(id)));
}
}
/**
* Cache operation enum.
*/
private enum Operation {
/** Put operation. */
PUT,
/** Put all operation. */
PUT_ALL,
/** Get operation. */
GET,
/** Get all operation. */
GET_ALL,
/** Invoke operation. */
INVOKE,
/** Invoke all operation. */
INVOKE_ALL,
/** Remove operation. */
REMOVE,
/** Remove all operation. */
REMOVE_ALL,
/** Put if absent operation. */
PUT_IF_ABSENT,
/** Replace operation. */
REPLACE,
/** Scan query operation. */
SCAN_QUERY,
/** SQL query operation. */
SQL_QUERY,
/** Continuous Query. */
CONTINUOUS_QUERY;
/**
* @param num Number of operation.
* @return Operation.
*/
public static Operation valueOf(int num) {
return values()[num];
}
}
/**
*
*/
private static class TestQuery {
/** */
private final String sql;
/** */
private final boolean distributedJoin;
/**
* @param sql SQL.
* @param distributedJoin Distributed join flag.
*/
public TestQuery(String sql, boolean distributedJoin) {
this.sql = sql;
this.distributedJoin = distributedJoin;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TestQuery.class, this);
}
}
}
| {
"content_hash": "c93508c4639026eb0a4f034f60e7c494",
"timestamp": "",
"source": "github",
"line_count": 1231,
"max_line_length": 126,
"avg_line_length": 31.91876523151909,
"alnum_prop": 0.5615392446299501,
"repo_name": "tkpanther/ignite",
"id": "d37cdca848299e3c760130d22c002a0f56868063",
"size": "40094",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "modules/yardstick/src/main/java/org/apache/ignite/yardstick/cache/load/IgniteCacheRandomOperationBenchmark.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "39783"
},
{
"name": "C",
"bytes": "7524"
},
{
"name": "C#",
"bytes": "3938369"
},
{
"name": "C++",
"bytes": "2016802"
},
{
"name": "CSS",
"bytes": "98406"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "411123"
},
{
"name": "Java",
"bytes": "24301775"
},
{
"name": "JavaScript",
"bytes": "963263"
},
{
"name": "M4",
"bytes": "5528"
},
{
"name": "Makefile",
"bytes": "98711"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "PowerShell",
"bytes": "6281"
},
{
"name": "Scala",
"bytes": "680703"
},
{
"name": "Shell",
"bytes": "577613"
},
{
"name": "Smalltalk",
"bytes": "1908"
}
],
"symlink_target": ""
} |
/**
* Singleton with "register" functionality.
*
* @see http://codereview.stackexchange.com/questions/15166/best-way-to-organize-javascript-for-website
*/
(function(exports) {
'use strict';
var initialized,
registry = []; // Collection of module.
// Adds module to collection:
exports.register = function(moduleDeclaration) {
registry.push(moduleDeclaration); // Add module to registry.
if (initialized) {
// If lib already initialized, register and execute module immediately:
moduleDeclaration.call(this);
}
};
// Executes every module:
exports.init = function() {
initialized = true; // Flippin' switches!
// Loop through each module and execute:
for (var i = 0, l = registry.length; i < l; i++) {
registry[i].call(this); // Call and execute module.
}
};
}(window.GHB = window.GHB || {})); // Use existing namespace or make a new object of that namespace.
| {
"content_hash": "fdd8204ce8288188802d72143f313d30",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 103,
"avg_line_length": 22.476190476190474,
"alnum_prop": 0.6557203389830508,
"repo_name": "mhulse/grunt-html-boiler",
"id": "7d814f765e33997659fe9d98b891cf1859fa369d",
"size": "944",
"binary": false,
"copies": "3",
"ref": "refs/heads/gh-pages",
"path": "dev/scripts/ghb.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10196"
},
{
"name": "HTML",
"bytes": "14653"
},
{
"name": "JavaScript",
"bytes": "72161"
}
],
"symlink_target": ""
} |
/**
* Created by sail on 2016/4/22.
*/
var path = require('path');
var webpack = require('webpack');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var HtmlWebpackPlugin = require('html-webpack-plugin');
//require("babel-polyfill");
module.exports = {
entry: {
'index': './public-src/index'
}, //入口文件输出配置
output: {
path: 'public', filename: '[name].bundle.js'//, publicPath: '/his/components/'
}, module: {
//加载器配置
loaders: [{
loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/, query: {
presets: ['es2015', 'stage-3']
}
},{test: require.resolve('jquery'), loader: 'expose?jQuery'},
{
test: /\.css$/, loader: 'style-loader!css-loader'
}, {test: /\.(jpg|png|svg)$/, loader: "url?"}, {test: /\.(ttf|eot|woff|woff2)$/, loader: "file-loader"}]
}, //其它解决方案配置
resolve: {
root: 'node_modules'
}, plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'public-src/index.html'
}),
//commonsPlugin,//new UglifyJsPlugin(),
//new CopyWebpackPlugin([
// { from: dir_html } // to: output.path
//]),
// Avoid publishing files when compilation fails
new webpack.NoErrorsPlugin()], stats: {
// Nice colored output
colors: true
}//, Create source maps for the bundle
//devtool: 'source-map'
}; | {
"content_hash": "5804b19627913304ee3a2c7c4c9b6985",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 106,
"avg_line_length": 29.068181818181817,
"alnum_prop": 0.6301798279906177,
"repo_name": "woodensail/project1",
"id": "8fad5aa3ff8b1b4ba52a287b82d89984a14a7e36",
"size": "1321",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webpack.config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3878"
},
{
"name": "HTML",
"bytes": "3417"
},
{
"name": "JavaScript",
"bytes": "14870"
}
],
"symlink_target": ""
} |
layout: default
---
## Administrative information
Administrative course information is available [here](https://uit.no/utdanning/emner/emne/508209/inf-2202)
The github org for this course is [inf-2202-f17](https://github.com/inf-2202-f17)
We use the [inf-2202-f17@list.uit.no](https://list.uit.no/sympa/info/inf-2202-f17) mailing list to send important information. The link is to the list's website; among other things it has an archive of old emails.
We have a [Slack team](https://inf-2202-f17.slack.com/). Join us and chat about the course and the assignments.
Please ruminate on [this page about citation, plagiarism, &c. from the university](https://uit.no/om/enhet/artikkel?p_document_id=473719). Norwegian only.
### We have the following rooms and hours:
* TUESDAY 1415-1600 REALF A016 (This will change around October, 1st due to renovation)
* THURSDAY 1415-1600 REALF B203
* FRIDAY 1215-1300 Teknobygget 1.023AUD
Refer to the lecture and mandatory assignment plan, and e-mails for which room is used when.
## Staff
* **Responsible Professor:** Lars Ailo Bongo
* **Admin person:** Einar Holsbø
* **Teaching assistant** Tengel Ekrem Skar
## Lecture plan
| Lecture | Date | Subject | Lecturer |
|---------|-----------|-----------------------------------------------|-----------|
| L1 | Fri 18/8 | [Introduction](public/01-introduction.pptx) and [practical information](https://inf-2202-f17.github.io/public/inf2202-17-info.pdf). | LAB, EH |
| L2 | Thu 24/8 | [Threads and synchronization primitives; Parallel architectures](https://github.com/inf-2202-f17/inf-2202-f17.github.io/blob/master/public/02-threads-synchronization.pptx) NB that nothing from slide 39 onward will be on the exam | Lars Tiede |
| L3 | Thu 31/8 | [Parallel programs](https://github.com/inf-2202-f17/inf-2202-f17.github.io/blob/master/public/03-1-parallelization-process-and-architectures.pptx?raw=true) Slides from pt. 2 (parallel processors from client to cloud, won't be on exam) available on request from Einar. | Lars Tiede |
| L4 | Thu 7/9 | [Asynchronous and Event-based Programming](https://github.com/inf-2202-f17/inf-2202-f17.github.io/blob/master/public/04-Asynchronous%20and%20Event-Based%20Programming.pptx?raw=true) | Dag Brattli |
| L5 | Thu 14/9 | Reactive vs Interactive Programming (in Fronter) | Dag Brattli |
| L6 | Thu 21/9 | Virtual Time Scheduling and Asynchronous Reactive Programming (in Fronter) | Dag Brattli |
| L7 | Thu 28/9 | [Performance evaluation 1](https://github.com/inf-2202-f17/inf-2202-f17.github.io/blob/master/public/2017-09-27-PerformanceEvaluation.pdf?raw=true) | Åge Kvalnes |
| L8 | Thu 5/10 | [Performance evaluation 2 - Distributed systems and web applications](public/2017-10-05-PerformanceEvaluationUit.pptx) | Steffen Viken Valvåg |
| L9 | Fri 29/9 | C# and Visual Studio | Fredrik Høisæther Rasch |
| L10 | Thu 12/10 | Cloud services: Monitoring, data, and analytics (in Fronter) | Tor Kreutzer and Jan-Ove Karlberg |
| L11 | Thu 19/10 | Getting the most out of cloud service logs (in Fronter) | Jan-Ove Karlberg and Tor Kreutzer |
| - | Thu 26/10 | No lecture | - |
| - | Thu 2/11 | No lecture | - |
| L12 | Thu 9/11 | The Fram Supercomputer | Steinar Trædal-Henden |
| L13 | Fri 10/11 | Summary lecture | LAB |
| Exam | Fri 23/11 | Exam | |
## Mandatory assignments
| Project | Start | Due | Subject | Presenter |
|---------|------------|----------|----------|---------|
| P1 | Tue 22/8 | Thu 7/9 23:00 | [Parallel programming using threads](https://github.com/inf-2202-f17/1st_mandatory) | EH |
| P2 | Mon 11/9 | Wed 4/10 | [Re:activity - A reactive bike computer](https://github.com/inf-2202-f17/2nd_mandatory) | DB |
| P3 | Fri 6/10 | Fri 3/11 23:00| [Techniques for working with cloud-scale datasets](https://github.com/inf-2202-f17/p3) | JK+TK |
## Previous exams
Previous exams given in this course are [here](https://uit.no/om/enhet/artikkel?p_document_id=319867&p_dimension_id=88131). The most relevant exams are from 2013, 2015 and 2016.
| {
"content_hash": "aba5e278f89565e4f3db627b9f132592",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 334,
"avg_line_length": 71.15873015873017,
"alnum_prop": 0.6310506357349989,
"repo_name": "inf-2202-f17/inf-2202-f17.github.io",
"id": "1c6b7d76994a46eee46efc941f63ca45f021a6db",
"size": "4493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11659"
},
{
"name": "HTML",
"bytes": "2972"
},
{
"name": "Ruby",
"bytes": "49"
}
],
"symlink_target": ""
} |
#include <regex>
#include "verifier.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace kythe {
namespace verifier {
namespace {
TEST(VerifierUnitTest, StringPrettyPrinter) {
StringPrettyPrinter c_string;
c_string.Print("c_string");
EXPECT_EQ("c_string", c_string.str());
StringPrettyPrinter std_string;
std_string.Print(std::string("std_string"));
EXPECT_EQ("std_string", std_string.str());
StringPrettyPrinter zero_ptrvoid;
void *zero = nullptr;
zero_ptrvoid.Print(zero);
EXPECT_EQ("0", zero_ptrvoid.str());
void *one = reinterpret_cast<void *>(1);
StringPrettyPrinter one_ptrvoid;
one_ptrvoid.Print(one);
// Some implementations might pad stringified void*s.
std::string one_str = one_ptrvoid.str();
std::regex ptrish_regex("0x0*1");
ASSERT_TRUE(std::regex_match(one_str, ptrish_regex));
}
TEST(VerifierUnitTest, QuotingPrettyPrinter) {
StringPrettyPrinter c_string;
QuoteEscapingPrettyPrinter c_string_quoting(c_string);
c_string_quoting.Print(R"("hello")");
EXPECT_EQ(R"(\"hello\")", c_string.str());
StringPrettyPrinter std_string;
QuoteEscapingPrettyPrinter std_string_quoting(std_string);
std_string_quoting.Print(std::string(R"(<"'
)"));
EXPECT_EQ(R"(<\"\'\n)", std_string.str());
StringPrettyPrinter zero_ptrvoid;
QuoteEscapingPrettyPrinter zero_ptrvoid_quoting(zero_ptrvoid);
void *zero = nullptr;
zero_ptrvoid_quoting.Print(zero);
EXPECT_EQ("0", zero_ptrvoid.str());
}
TEST(VerifierUnitTest, HtmlPrettyPrinter) {
StringPrettyPrinter c_string;
HtmlEscapingPrettyPrinter c_string_html(c_string);
c_string_html.Print(R"("hello")");
EXPECT_EQ(R"("hello")", c_string.str());
StringPrettyPrinter std_string;
HtmlEscapingPrettyPrinter std_string_html(std_string);
std_string_html.Print(std::string(R"(x<>&"ml)"));
EXPECT_EQ(R"(x<>&"ml)", std_string.str());
StringPrettyPrinter zero_ptrvoid;
HtmlEscapingPrettyPrinter zero_ptrvoid_html(zero_ptrvoid);
void *zero = nullptr;
zero_ptrvoid_html.Print(zero);
EXPECT_EQ("0", zero_ptrvoid.str());
}
TEST(VerifierUnitTest, UnescapeStringLiterals) {
std::string tmp = "tmp";
EXPECT_TRUE(AssertionParser::Unescape(R"("")", &tmp));
EXPECT_EQ("", tmp);
EXPECT_FALSE(AssertionParser::Unescape("", &tmp));
EXPECT_TRUE(AssertionParser::Unescape(R"("foo")", &tmp));
EXPECT_EQ("foo", tmp);
EXPECT_TRUE(AssertionParser::Unescape(R"("\"foo\"")", &tmp));
EXPECT_EQ("\"foo\"", tmp);
EXPECT_FALSE(AssertionParser::Unescape(R"("\foo")", &tmp));
EXPECT_FALSE(AssertionParser::Unescape(R"("foo\")", &tmp));
EXPECT_TRUE(AssertionParser::Unescape(R"("\\")", &tmp));
EXPECT_EQ("\\", tmp);
}
TEST(VerifierUnitTest, TrivialHappyCase) {
Verifier v;
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, EmptyProtoIsNotWellFormed) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
})"));
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, EmptyVnameIsNotWellFormed) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { }
fact_name: "testname"
fact_value: "testvalue"
})"));
ASSERT_FALSE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, NoRulesIsOk) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, DuplicateFactsNotWellFormed) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
}
entries {
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
})"));
ASSERT_FALSE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, DuplicateFactsNotWellFormedEvenIfYouSeparateThem) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
}
entries {
source { root: "2" }
fact_name: "testname"
fact_value: "testvalue"
}
entries {
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
})"));
ASSERT_FALSE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, DuplicateEdgesAreUseless) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root: "1" }
edge_kind: "somekind"
target { root: "2" }
fact_name: "/"
fact_value: ""
}
entries {
source { root: "1" }
edge_kind: "somekind"
target { root: "2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_FALSE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, EdgesCanSupplyMultipleOrdinals) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root: "1" }
edge_kind: "somekind"
target { root: "2" }
fact_name: "/kythe/ordinal"
fact_value: "42"
}
entries {
source { root: "1" }
edge_kind: "somekind"
target { root: "2" }
fact_name: "/kythe/ordinal"
fact_value: "43"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ConflictingFactsNotWellFormed) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
}
entries {
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue2"
})"));
ASSERT_FALSE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, OnlyTargetIsWrong) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
edge_kind: "somekind"
target { root: "2" }
fact_name: "/kythe/ordinal"
fact_value: "42"
})"));
ASSERT_FALSE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, MissingAnchorTextFails) {
Verifier v;
ASSERT_FALSE(v.LoadInlineProtoFile(R"(entries {
#- @text defines SomeNode
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
})"));
}
TEST(VerifierUnitTest, AmbiguousAnchorTextFails) {
Verifier v;
ASSERT_FALSE(v.LoadInlineProtoFile(R"(entries {
#- @text defines SomeNode
# text text
source { root: "1" }
fact_name: "testname"
fact_value: "testvalue"
})"));
}
TEST(VerifierUnitTest, GenerateAnchorEvarFailsOnEmptyDB) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(
#- @text defines SomeNode
# text
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ParseLiteralString) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(
#- @"text" defines SomeNode
# text
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ParseLiteralStringWithSpace) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(
#- @"text txet" defines SomeNode
# text txet
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ParseLiteralStringWithEscape) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(
#- @"text \"txet\" ettx" defines SomeNode
# text "txet" ettx
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateStartOffsetEVar) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- ANode.loc/start @^text
##text (line 3 column 2 offset 38-42)
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "38"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "42"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateEndOffsetEVar) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- ANode.loc/end @$text
##text (line 3 column 2 offset 38-42)
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "38"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "42"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvar) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- @text defines SomeNode
##text (line 3 column 2 offset 38-42)
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "38"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "42"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvarAtEndOfFile) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "384"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "388"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
#- @text defines SomeNode
##text (line 22 column 2 offset 384-388))"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvarAtEndOfFileWithSpaces) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "386"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "390"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
#- @text defines SomeNode
##text (line 22 column 2 offset 386-390))"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvarAtEndOfFileWithTrailingRule) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "384"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "388"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
#- @text defines SomeNode
##text (line 22 column 2 offset 384-388))
#- SomeAnchor defines SomeNode)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvarAcrossMultipleGoalLines) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- @text defines
#-
#- SomeNode
##text (line 5 column 2 offset 46-50)
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "46"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "50"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvarAcrossMultipleGoalLinesWithSpaces) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- @text defines
#-
#- SomeNode
##text (line 5 column 4 offset 51-55)
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "51"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "55"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvarWithBlankLines) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "384"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "388"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
#- @texx defines SomeNode
##texx (line 22 column 2 offset 384-388))
#- SomeAnchor defines SomeNode)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateAnchorEvarWithWhitespaceLines) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "384"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "388"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
#- @texx defines SomeNode
##texx (line 22 column 2 offset 384-388))
#- SomeAnchor defines SomeNode)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateTwoSeparatedAnchorEvars) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- @text defines SomeNode
##text (line 3 column 2 offset 38-42)
#- @more defines OtherNode
#more (line 5 column 1 offset 102-106
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "38"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "42"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
entries {
source { root:"3" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"3" }
fact_name: "/kythe/loc/start"
fact_value: "102"
}
entries {
source { root:"3" }
fact_name: "/kythe/loc/end"
fact_value: "106"
}
entries {
source { root:"3" }
edge_kind: "/kythe/edge/defines"
target { root:"4" }
fact_name: "/"
fact_value: ""
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateTwoSeparatedAnchorEvarsWithSpaces) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- @" text" defines SomeNode
## text (line 3 column 3 offset 42-47)
#- @" more " defines OtherNode
# more (line 5 column 1 offset 111-117
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "42"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "47"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
entries {
source { root:"3" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"3" }
fact_name: "/kythe/loc/start"
fact_value: "111"
}
entries {
source { root:"3" }
fact_name: "/kythe/loc/end"
fact_value: "117"
}
entries {
source { root:"3" }
edge_kind: "/kythe/edge/defines"
target { root:"4" }
fact_name: "/"
fact_value: ""
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GenerateTwoAnchorEvars) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- @more defines SomeNode
#- @text defines OtherNode
##text (line 4 column 2 offset 65-69) more (line 4 column 38 offset 101-105)
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "65"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "69"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
entries {
source { root:"3" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"3" }
fact_name: "/kythe/loc/start"
fact_value: "101"
}
entries {
source { root:"3" }
fact_name: "/kythe/loc/end"
fact_value: "105"
}
entries {
source { root:"3" }
edge_kind: "/kythe/edge/defines"
target { root:"4" }
fact_name: "/"
fact_value: ""
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ContentFactPasses) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content 42
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, EVarsUnsetAfterNegatedBlock) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{vname(_,_,Root?="3",_,_) defines SomeNode}
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
size_t call_count = 0;
bool evar_unset = false;
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals([&call_count, &evar_unset](
Verifier *cxt, const std::string &key, EVar *evar) {
++call_count;
if (key == "Root" && !evar->current()) {
evar_unset = true;
}
return true;
}));
EXPECT_EQ(1, call_count);
EXPECT_TRUE(evar_unset);
}
TEST(VerifierUnitTest, NegatedBlocksDontLeak) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{vname(_,_,Root="3",_,_) defines SomeNode}
#- !{vname(_,_,Root?,_,_) notanedge OtherNode}
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
size_t call_count = 0;
bool evar_unset = false;
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals([&call_count, &evar_unset](
Verifier *cxt, const std::string &key, EVar *evar) {
++call_count;
if (key == "Root" && !evar->current()) {
evar_unset = true;
}
return true;
}));
EXPECT_EQ(1, call_count);
EXPECT_TRUE(evar_unset);
}
TEST(VerifierUnitTest, UngroupedEVarsAvailableInGroupedContexts) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- vname(_,_,Root="3",_,_) defines SomeNode
#- !{vname(_,_,Root?,_,_) defines SomeNode}
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
entries {
source { root:"3" }
edge_kind: "/kythe/edge/defines"
target { root:"4" }
fact_name: "/"
fact_value: ""
})"));
size_t call_count = 0;
bool evar_set = false;
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals([&call_count, &evar_set](
Verifier *cxt, const std::string &key, EVar *evar) {
++call_count;
if (key == "Root" && evar->current()) {
if (Identifier *identifier = evar->current()->AsIdentifier()) {
if (cxt->symbol_table()->text(identifier->symbol()) == "3") {
evar_set = true;
}
}
}
return true;
}));
EXPECT_EQ(1, call_count);
EXPECT_TRUE(evar_set);
}
TEST(VerifierUnitTest, UngroupedEVarsAvailableInGroupedContextsReordered) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{vname(_,_,Root?,_,_) defines SomeNode}
#- vname(_,_,Root="3",_,_) defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
entries {
source { root:"3" }
edge_kind: "/kythe/edge/defines"
target { root:"4" }
fact_name: "/"
fact_value: ""
})"));
size_t call_count = 0;
bool evar_set = false;
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals([&call_count, &evar_set](
Verifier *cxt, const std::string &key, EVar *evar) {
++call_count;
if (key == "Root" && evar->current()) {
if (Identifier *identifier = evar->current()->AsIdentifier()) {
if (cxt->symbol_table()->text(identifier->symbol()) == "3") {
evar_set = true;
}
}
}
return true;
}));
EXPECT_EQ(1, call_count);
EXPECT_TRUE(evar_set);
}
TEST(VerifierUnitTest, EVarsReportedAfterFailedNegatedBlock) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{vname(_,_,Root?="1",_,_) defines SomeNode}
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
size_t call_count = 0;
bool evar_set = false;
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals([&call_count, &evar_set](
Verifier *cxt, const std::string &key, EVar *evar) {
++call_count;
if (key == "Root" && evar->current()) {
if (Identifier *identifier = evar->current()->AsIdentifier()) {
if (cxt->symbol_table()->text(identifier->symbol()) == "1") {
evar_set = true;
}
}
}
return true;
}));
EXPECT_EQ(1, call_count);
EXPECT_TRUE(evar_set);
}
TEST(VerifierUnitTest, GroupFactFails) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- { SomeNode.content 43 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
// Slightly brittle in that it depends on the order we try facts.
TEST(VerifierUnitTest, FailWithCutInGroups) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- { SomeNode.content SomeValue }
#- { SomeNode.content 43 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
}
entries {
source { root:"2" }
fact_name: "/kythe/content"
fact_value: "43"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
// Slightly brittle in that it depends on the order we try facts.
TEST(VerifierUnitTest, FailWithCut) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content SomeValue
#- { SomeNode.content 43 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
}
entries {
source { root:"2" }
fact_name: "/kythe/content"
fact_value: "43"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, PassWithoutCut) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content SomeValue
#- SomeNode.content 43
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
}
entries {
source { root:"2" }
fact_name: "/kythe/content"
fact_value: "43"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GroupFactPasses) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- { SomeNode.content 42 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, CompoundGroups) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content 42
#- !{ OtherNode.content 43
#- AnotherNode.content 44 }
#- !{ LastNode.content 45 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
}
entries {
source { root:"2" }
fact_name: "/kythe/content"
fact_value: "43"
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ConjunctionInsideNegatedGroupPassFail) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{ SomeNode.content 42
#- OtherNode.content 44 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
}
entries {
source { root:"2" }
fact_name: "/kythe/content"
fact_value: "43"
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ConjunctionInsideNegatedGroupPassPass) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{ SomeNode.content 42
#- OtherNode.content 43 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
}
entries {
source { root:"2" }
fact_name: "/kythe/content"
fact_value: "43"
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, AntiContentFactFails) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{ SomeNode.content 42 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, AntiContentFactPasses) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- !{ SomeNode.content 43 }
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, SpacesAreOkay) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content 42
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, ContentFactFails) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content 42
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "43"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, SpacesDontDisableRules) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content 42
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "43"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, DefinesEdgePasses) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, IsParamEdgePasses) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeParam is_param.1 SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/is_param"
target { root:"2" }
fact_name: "/kythe/ordinal"
fact_value: "1"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, IsParamEdgeFailsOnWrongOrdinal) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeParam is_param.1 SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/is_param"
target { root:"2" }
fact_name: "/kythe/ordinal"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, IsParamEdgeFailsOnMissingOrdinalInGoal) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeParam is_param SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/is_param"
target { root:"2" }
fact_name: "/kythe/ordinal"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, IsParamEdgeFailsOnMissingOrdinalInFact) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeParam is_param.42 SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/is_param"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, EvarsShareANamespace) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor defines SomeNode
#- SomeNode defines SomeAnchor
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, DefinesEdgePassesSymmetry) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
entries {
#- SomeNode defined_by SomeAnchor
source { root:"2" }
edge_kind: "/kythe/edge/defined_by"
target { root:"1" }
fact_name: "/"
fact_value: ""
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, EvarsStillShareANamespace) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
}
entries {
#- SomeAnchor defined_by SomeNode
source { root:"2" }
edge_kind: "/kythe/edge/defined_by"
target { root:"1" }
fact_name: "/"
fact_value: ""
}
)"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, InspectionCalledFailure) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor? defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals(
[](Verifier *cxt, const std::string &key, EVar *evar) { return false; }));
}
TEST(VerifierUnitTest, EvarsAreSharedAcrossInputFiles) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor? defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.LoadInlineProtoFile(R"(
#- SomeAnchor? defines _
)"));
ASSERT_TRUE(v.PrepareDatabase());
EVar *seen_evar = nullptr;
int seen_count = 0;
ASSERT_TRUE(v.VerifyAllGoals([&seen_evar, &seen_count](
Verifier *cxt, const std::string &key, EVar *evar) {
if (key == "SomeAnchor") {
++seen_count;
if (seen_evar == nullptr) {
seen_evar = evar;
} else if (seen_evar != evar) {
return false;
}
}
return true;
}));
ASSERT_EQ(2, seen_count);
ASSERT_NE(nullptr, seen_evar);
}
TEST(VerifierUnitTest, InspectionCalledSuccess) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor? defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals(
[](Verifier *cxt, const std::string &key, EVar *evar) { return true; }));
}
TEST(VerifierUnitTest, InspectionHappensMoreThanOnceAndThatsOk) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor? defines SomeNode
#- SomeAnchor? defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
size_t inspect_count = 0;
ASSERT_TRUE(v.VerifyAllGoals(
[&inspect_count](Verifier *cxt, const std::string &key, EVar *evar) {
++inspect_count;
return true;
}));
ASSERT_EQ(2, inspect_count);
}
TEST(VerifierUnitTest, InspectionCalledCorrectly) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor? defines SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
size_t call_count = 0;
bool key_was_someanchor = false;
bool evar_init = false;
bool evar_init_to_correct_vname = false;
ASSERT_TRUE(v.VerifyAllGoals(
[&call_count, &key_was_someanchor, &evar_init_to_correct_vname](
Verifier *cxt, const std::string &key, EVar *evar) {
++call_count;
// Check for equivalence to `App(#vname, (#"", #"", 1, #"", #""))`
key_was_someanchor = (key == "SomeAnchor");
if (AstNode *node = evar->current()) {
if (App *app = node->AsApp()) {
if (Tuple *tuple = app->rhs()->AsTuple()) {
if (app->lhs() == cxt->vname_id() && tuple->size() == 5 &&
tuple->element(0) == cxt->empty_string_id() &&
tuple->element(1) == cxt->empty_string_id() &&
tuple->element(3) == cxt->empty_string_id() &&
tuple->element(4) == cxt->empty_string_id()) {
if (Identifier *identifier =
tuple->element(2)->AsIdentifier()) {
evar_init_to_correct_vname =
cxt->symbol_table()->text(identifier->symbol()) == "1";
}
}
}
}
}
return true;
}));
EXPECT_EQ(1, call_count);
EXPECT_TRUE(key_was_someanchor);
EXPECT_TRUE(evar_init_to_correct_vname);
}
TEST(VerifierUnitTest, FactsAreNotLinear) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor? defines SomeNode?
#- AnotherAnchor? defines AnotherNode?
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
AstNode *some_anchor = nullptr;
AstNode *some_node = nullptr;
AstNode *another_anchor = nullptr;
AstNode *another_node = nullptr;
ASSERT_TRUE(v.VerifyAllGoals(
[&some_anchor, &some_node, &another_anchor, &another_node](
Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (key == "SomeAnchor") {
some_anchor = node;
} else if (key == "SomeNode") {
some_node = node;
} else if (key == "AnotherAnchor") {
another_anchor = node;
} else if (key == "AnotherNode") {
another_node = node;
} else {
return false;
}
return true;
}
return false;
}));
EXPECT_EQ(some_anchor, another_anchor);
EXPECT_EQ(some_node, another_node);
EXPECT_NE(some_anchor, some_node);
EXPECT_NE(another_anchor, another_node);
}
TEST(VerifierUnitTest, OrdinalsGetUnified) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeAnchor is_param.Ordinal? SomeNode
source { root:"1" }
edge_kind: "/kythe/edge/is_param"
target { root:"2" }
fact_name: "/kythe/ordinal"
fact_value: "42"
})"));
ASSERT_TRUE(v.PrepareDatabase());
size_t call_count = 0;
bool key_was_ordinal = false;
bool evar_init = false;
bool evar_init_to_correct_ordinal = false;
ASSERT_TRUE(v.VerifyAllGoals([&call_count, &key_was_ordinal, &evar_init,
&evar_init_to_correct_ordinal](
Verifier *cxt, const std::string &key, EVar *evar) {
++call_count;
key_was_ordinal = (key == "Ordinal");
if (AstNode *node = evar->current()) {
evar_init = true;
if (Identifier *identifier = node->AsIdentifier()) {
evar_init_to_correct_ordinal =
cxt->symbol_table()->text(identifier->symbol()) == "42";
}
}
return true;
}));
EXPECT_EQ(1, call_count);
EXPECT_TRUE(key_was_ordinal);
EXPECT_TRUE(evar_init_to_correct_ordinal);
}
TEST(VerifierUnitTest, EvarsAndIdentifiersCanHaveTheSameText) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- vname(Signature?, "Signature", Root?, Path?, Language?) defines SomeNode
source {
signature:"Signature"
corpus:"Signature"
root:"Root"
path:"Path"
language:"Language"
}
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
bool signature = false;
bool root = false;
bool path = false;
bool language = false;
ASSERT_TRUE(v.VerifyAllGoals([&signature, &root, &path, &language](
Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
std::string ident_content = cxt->symbol_table()->text(ident->symbol());
if (ident_content == key) {
if (key == "Signature") signature = true;
if (key == "Root") root = true;
if (key == "Path") path = true;
if (key == "Language") language = true;
}
}
return true;
}
return false;
}));
EXPECT_TRUE(signature);
EXPECT_TRUE(root);
EXPECT_TRUE(path);
EXPECT_TRUE(language);
}
TEST(VerifierUnitTest, EvarsAndIdentifiersCanHaveTheSameTextAndAreNotRebound) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- vname(Signature?, "Signature", Signature?, Path?, Language?) defines SomeNode
source {
signature:"Signature"
corpus:"Signature"
root:"Signature"
path:"Path"
language:"Language"
}
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
bool signature = false;
bool path = false;
bool language = false;
ASSERT_TRUE(v.VerifyAllGoals([&signature, &path, &language](
Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
std::string ident_content = cxt->symbol_table()->text(ident->symbol());
if (ident_content == key) {
if (key == "Signature") signature = true;
if (key == "Path") path = true;
if (key == "Language") language = true;
}
}
return true;
}
return false;
}));
EXPECT_TRUE(signature);
EXPECT_TRUE(path);
EXPECT_TRUE(language);
}
TEST(VerifierUnitTest, EqualityConstraintWorks) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- One is vname(_,_,Two? = "2",_,_)
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"2" }
} entries {
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"3" }
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(
v.VerifyAllGoals([](Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
return cxt->symbol_table()->text(ident->symbol()) == "2";
}
}
return false;
}));
}
TEST(VerifierUnitTest, EqualityConstraintWorksOnAnchors) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- Tx?=@text defines SomeNode
##text (line 3 column 2 offset 42-46)
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "42"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "46"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(
v.VerifyAllGoals([](Verifier *cxt, const std::string &key, EVar *evar) {
return (key == "Tx" && evar->current() != nullptr);
}));
}
// It's possible to match Tx against {root:7}:
TEST(VerifierUnitTest, EqualityConstraintWorksOnAnchorsPossibleConstraint) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- @text defines SomeNode
##text (line 3 column 2 offset 38-42)
#- Tx.node/kind notananchor
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"7" }
fact_name: "/kythe/node/kind"
fact_value: "notananchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "38"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "42"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
// It's impossible to match Tx against {root:7} if we constrain Tx to equal
// an anchor specifier.
TEST(VerifierUnitTest, EqualityConstraintWorksOnAnchorsImpossibleConstraint) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- Tx?=@text defines SomeNode
##text (line 3 column 2 offset 42-46)
#- Tx.node/kind notananchor
source { root:"1" }
fact_name: "/kythe/node/kind"
fact_value: "anchor"
}
entries {
source { root:"7" }
fact_name: "/kythe/node/kind"
fact_value: "notananchor"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/start"
fact_value: "42"
}
entries {
source { root:"1" }
fact_name: "/kythe/loc/end"
fact_value: "46"
}
entries {
source { root:"1" }
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, EqualityConstraintWorksWithOtherSortedRules) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- One is vname(_,_,Three? = "3",_,_)
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"2" }
} entries {
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"3" }
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(
v.VerifyAllGoals([](Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
return cxt->symbol_table()->text(ident->symbol()) == "3";
}
}
return false;
}));
}
TEST(VerifierUnitTest, EqualityConstraintFails) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- One is vname(_,_,Two = "2",_,_)
#- One is vname(_,_,Three = "3",_,_)
#- One is vname(_,_,Two = Three,_,_)
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"2" }
} entries {
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"3" }
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, IdentityEqualityConstraintSucceeds) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- One is vname(_,_,Two = Two,_,_)
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"2" }
} entries {
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"3" }
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_TRUE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, TransitiveIdentityEqualityConstraintFails) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- One is vname(_,_,Two = Dos = Two,_,_)
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"2" }
} entries {
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"3" }
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, GraphEqualityConstraintFails) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- One is Two = vname(_,_,Two,_,_)
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"2" }
} entries {
source { root:"1" }
fact_name: "/"
fact_value: ""
edge_kind: "/kythe/edge/is"
target { root:"3" }
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
}
TEST(VerifierUnitTest, UnifyVersusVname) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- vname(Signature?, Corpus?, Root?, Path?, Language?) defines SomeNode
source {
signature:"Signature"
corpus:"Corpus"
root:"Root"
path:"Path"
language:"Language"
}
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
bool signature = false;
bool corpus = false;
bool root = false;
bool path = false;
bool language = false;
ASSERT_TRUE(v.VerifyAllGoals([&signature, &corpus, &root, &path, &language](
Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
std::string ident_content = cxt->symbol_table()->text(ident->symbol());
if (ident_content == key) {
if (key == "Signature") signature = true;
if (key == "Corpus") corpus = true;
if (key == "Root") root = true;
if (key == "Path") path = true;
if (key == "Language") language = true;
}
}
return true;
}
return false;
}));
EXPECT_TRUE(signature);
EXPECT_TRUE(corpus);
EXPECT_TRUE(root);
EXPECT_TRUE(path);
EXPECT_TRUE(language);
}
TEST(VerifierUnitTest, UnifyVersusVnameWithDontCare) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- vname(Signature?, Corpus?, Root?, _?, Language?) defines SomeNode
source {
signature:"Signature"
corpus:"Corpus"
root:"Root"
path:"Path"
language:"Language"
}
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
bool signature = false;
bool corpus = false;
bool root = false;
bool path = false;
bool language = false;
ASSERT_TRUE(v.VerifyAllGoals([&signature, &corpus, &root, &path, &language](
Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
std::string ident_content = cxt->symbol_table()->text(ident->symbol());
if ((key != "Path" && ident_content == key) ||
(key == "_" && ident_content == "Path")) {
if (key == "Signature") signature = true;
if (key == "Corpus") corpus = true;
if (key == "Root") root = true;
if (key == "_") path = true;
if (key == "Language") language = true;
}
}
return true;
}
return false;
}));
EXPECT_TRUE(signature);
EXPECT_TRUE(corpus);
EXPECT_TRUE(root);
EXPECT_TRUE(path);
EXPECT_TRUE(language);
}
TEST(VerifierUnitTest, UnifyVersusVnameWithEmptyStringSpelledOut) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- vname(Signature?, Corpus?, Root?, "", Language?) defines SomeNode
source {
signature:"Signature"
corpus:"Corpus"
root:"Root"
language:"Language"
}
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
bool signature = false;
bool corpus = false;
bool root = false;
bool path = false;
bool language = false;
ASSERT_TRUE(v.VerifyAllGoals([&signature, &corpus, &root, &path, &language](
Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
std::string ident_content = cxt->symbol_table()->text(ident->symbol());
if (ident_content == key) {
if (key == "Signature") signature = true;
if (key == "Corpus") corpus = true;
if (key == "Root") root = true;
if (key == "Language") language = true;
}
}
return true;
}
return false;
}));
EXPECT_TRUE(signature);
EXPECT_TRUE(corpus);
EXPECT_TRUE(root);
EXPECT_TRUE(language);
}
TEST(VerifierUnitTest, UnifyVersusVnameWithEmptyStringBound) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- vname(Signature?, Corpus?, Root?, Path?, Language?) defines SomeNode
source {
signature:"Signature"
corpus:"Corpus"
root:"Root"
language:"Language"
}
edge_kind: "/kythe/edge/defines"
target { root:"2" }
fact_name: "/"
fact_value: ""
})"));
ASSERT_TRUE(v.PrepareDatabase());
bool signature = false;
bool corpus = false;
bool root = false;
bool path = false;
bool language = false;
ASSERT_TRUE(v.VerifyAllGoals([&signature, &corpus, &root, &path, &language](
Verifier *cxt, const std::string &key, EVar *evar) {
if (AstNode *node = evar->current()) {
if (Identifier *ident = node->AsIdentifier()) {
std::string ident_content = cxt->symbol_table()->text(ident->symbol());
if ((key != "Path" && ident_content == key) ||
(key == "Path" && ident == cxt->empty_string_id())) {
if (key == "Signature") signature = true;
if (key == "Corpus") corpus = true;
if (key == "Root") root = true;
if (key == "Path") path = true;
if (key == "Language") language = true;
}
}
return true;
}
return false;
}));
EXPECT_TRUE(signature);
EXPECT_TRUE(corpus);
EXPECT_TRUE(root);
EXPECT_TRUE(path);
EXPECT_TRUE(language);
}
TEST(VerifierUnitTest, LastGoalToFailIsSelected) {
Verifier v;
ASSERT_TRUE(v.LoadInlineProtoFile(R"(entries {
#- SomeNode.content 43
#- SomeNode.content 43
#- SomeNode.content 42
#- SomeNode.content 46
source { root:"1" }
fact_name: "/kythe/content"
fact_value: "43"
})"));
ASSERT_TRUE(v.PrepareDatabase());
ASSERT_FALSE(v.VerifyAllGoals());
ASSERT_EQ(2, v.highest_goal_reached());
}
} // anonymous namespace
} // namespace verifier
} // namespace kythe
int main(int argc, char **argv) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::InitGoogleLogging(argv[0]);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| {
"content_hash": "1b447a8986bbc9af853efdb6bf4665a6",
"timestamp": "",
"source": "github",
"line_count": 1990,
"max_line_length": 80,
"avg_line_length": 24.480402010050252,
"alnum_prop": 0.6498070449133755,
"repo_name": "gameduell/kythe",
"id": "7dc8ed830a150c546e06e0d50f4009d0c4f767e6",
"size": "49329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cxx/verifier/verifier_unit_test.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1720"
},
{
"name": "C++",
"bytes": "789673"
},
{
"name": "CSS",
"bytes": "10113"
},
{
"name": "Clojure",
"bytes": "41249"
},
{
"name": "Go",
"bytes": "414463"
},
{
"name": "HTML",
"bytes": "7579"
},
{
"name": "Java",
"bytes": "336656"
},
{
"name": "JavaScript",
"bytes": "1164"
},
{
"name": "Lex",
"bytes": "5222"
},
{
"name": "Makefile",
"bytes": "222"
},
{
"name": "Objective-C",
"bytes": "32"
},
{
"name": "Protocol Buffer",
"bytes": "39869"
},
{
"name": "Python",
"bytes": "91535"
},
{
"name": "Ruby",
"bytes": "3939"
},
{
"name": "Shell",
"bytes": "72034"
},
{
"name": "TeX",
"bytes": "2455"
},
{
"name": "Yacc",
"bytes": "4330"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="E:\androidstudio\gradle\gradle-2.2.1" />
<option name="gradleJvm" value="1.7" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/shapeloading" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project> | {
"content_hash": "821a0b0d3c1f4cfc513c79ec6a252d54",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 81,
"avg_line_length": 36.9,
"alnum_prop": 0.592140921409214,
"repo_name": "canmeidanxue/android-shapeLoadingView-master",
"id": "74c2b7425b14d9012666be0e12ee2d0201499920",
"size": "738",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": ".idea/gradle.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "23000"
}
],
"symlink_target": ""
} |
<resources>
<string name="app_name">ShortifierDemo</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources> | {
"content_hash": "8f4a7fbd91986f57439204ed4144eb93",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 60,
"avg_line_length": 30.375,
"alnum_prop": 0.7078189300411523,
"repo_name": "Azure-Samples/UrlShortener-Android-Client",
"id": "62db284ba191963eefa44d0e36599371d6419c95",
"size": "243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/res/values/strings.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "20800"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_162) on Tue Mar 24 11:10:01 PDT 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.core.util.TextBuffer (Jackson-core 2.11.0.rc1 API)</title>
<meta name="date" content="2020-03-24">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.core.util.TextBuffer (Jackson-core 2.11.0.rc1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.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?com/fasterxml/jackson/core/util/class-use/TextBuffer.html" target="_top">Frames</a></li>
<li><a href="TextBuffer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.fasterxml.jackson.core.util.TextBuffer" class="title">Uses of Class<br>com.fasterxml.jackson.core.util.TextBuffer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</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="#com.fasterxml.jackson.core.base">com.fasterxml.jackson.core.base</a></td>
<td class="colLast">
<div class="block">Base classes used by concrete Parser and Generator implementations;
contain functionality that is not specific to JSON or input
abstraction (byte vs char).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.core.io">com.fasterxml.jackson.core.io</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.core.util">com.fasterxml.jackson.core.util</a></td>
<td class="colLast">
<div class="block">Utility classes used by Jackson Core functionality.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.core.base">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a> in <a href="../../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> declared as <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a></code></td>
<td class="colLast"><span class="typeNameLabel">ParserBase.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/core/base/ParserBase.html#Z:Z_textBuffer">_textBuffer</a></span></code>
<div class="block">Buffer that contains contents of String values, including
field names if necessary (name split across boundary,
contains escape sequence, or access needed to char array)</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.core.io">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a> in <a href="../../../../../../com/fasterxml/jackson/core/io/package-summary.html">com.fasterxml.jackson.core.io</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/fasterxml/jackson/core/io/package-summary.html">com.fasterxml.jackson.core.io</a> that return <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a></code></td>
<td class="colLast"><span class="typeNameLabel">IOContext.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/core/io/IOContext.html#constructTextBuffer--">constructTextBuffer</a></span>()</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.core.util">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a> in <a href="../../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a> that return <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.util">TextBuffer</a></code></td>
<td class="colLast"><span class="typeNameLabel">TextBuffer.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html#fromInitial-char:A-">fromInitial</a></span>(char[] initialSegment)</code>
<div class="block">Factory method for constructing an instance with no allocator, and
with initial full segment.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/fasterxml/jackson/core/util/TextBuffer.html" title="class in com.fasterxml.jackson.core.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?com/fasterxml/jackson/core/util/class-use/TextBuffer.html" target="_top">Frames</a></li>
<li><a href="TextBuffer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2008–2020 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "08875113b428dc37ba60c4f36f8d194c",
"timestamp": "",
"source": "github",
"line_count": 223,
"max_line_length": 345,
"avg_line_length": 47.874439461883405,
"alnum_prop": 0.6554889471712252,
"repo_name": "FasterXML/jackson-core",
"id": "53f047834deed804782f724922a79b2e621aa7af",
"size": "10676",
"binary": false,
"copies": "1",
"ref": "refs/heads/2.15",
"path": "docs/javadoc/2.11.rc1/com/fasterxml/jackson/core/util/class-use/TextBuffer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4192574"
},
{
"name": "Logos",
"bytes": "42257"
},
{
"name": "Shell",
"bytes": "40"
}
],
"symlink_target": ""
} |
// NPM IMPORTS
// COMMON IMPORTS
import ServiceConsumerByUrl from './service_consumer_by_url'
/**
* Contextual constant for this file logs.
* @private
* @type {string}
*/
let context = 'common/services/service_consumer'
/**
* Service consumer base class.
* @abstract
*
* @author Luc BORIES
* @license Apache-2.0
*/
export default class ServiceConsumer extends ServiceConsumerByUrl
{
/**
* Create a service by url consumer.
*
* @param {string} arg_consumer_name - consumer name.
* @param {Service} arg_service_instance - service instance.
* @param {string} arg_context - logging context label.
*
* @returns {nothing}
*/
constructor(arg_consumer_name, arg_service_instance, arg_context)
{
super(arg_consumer_name, arg_service_instance, arg_context ? arg_context : context)
}
}
| {
"content_hash": "8e3ef419dbdbd4527795765ffd1f6431",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 85,
"avg_line_length": 21.473684210526315,
"alnum_prop": 0.6948529411764706,
"repo_name": "lucbories/devapt-core-common",
"id": "63183c657f38534a486c0a0692396bc71c73cad1",
"size": "816",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/js/services/service_consumer.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "726969"
}
],
"symlink_target": ""
} |
package com.lightrail.snapost;
import org.appcelerator.titanium.ITiAppInfo;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiProperties;
import org.appcelerator.titanium.util.Log;
/* GENERATED CODE
* Warning - this class was generated from your application's tiapp.xml
* Any changes you make here will be overwritten
*/
public class SnapostAppInfo implements ITiAppInfo
{
private static final String LCAT = "AppInfo";
public SnapostAppInfo(TiApplication app) {
}
public String getId() {
return "com.lightrail.snapost";
}
public String getName() {
return "Snapost";
}
public String getVersion() {
return "1.1";
}
public String getPublisher() {
return "Kevin Whinnery for Appcelerator Inc.";
}
public String getUrl() {
return "http://appcelerator.com";
}
public String getCopyright() {
return "2010 by Appcelerator";
}
public String getDescription() {
return "Snapost is the easiest way to share photos from your mobile device.";
}
public String getIcon() {
return "snapost_icon57.png";
}
public boolean isAnalyticsEnabled() {
return true;
}
public String getGUID() {
return "ceb92217583a431eb0db67d76e79c2d6";
}
}
| {
"content_hash": "e21a22518662b30a39453f7b0822b84b",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 79,
"avg_line_length": 20.982758620689655,
"alnum_prop": 0.7304847986852917,
"repo_name": "appcelerator-titans/Snapost",
"id": "3a9d5c4726095841e5d3d98a58162cedec0084a6",
"size": "1217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "1.1.x/Snapost/build/android/src/com/lightrail/snapost/SnapostAppInfo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "1797"
},
{
"name": "Java",
"bytes": "3415"
},
{
"name": "JavaScript",
"bytes": "155586"
},
{
"name": "Objective-C",
"bytes": "183136"
},
{
"name": "Shell",
"bytes": "4370"
}
],
"symlink_target": ""
} |
(function () {
'use strict';
angular
.module('patternizeApp')
.controller('PatternsController', [
PatternsController
]);
function PatternsController () {
var vm = this;
}
}());
| {
"content_hash": "1f7f8c35390468fbe25ffff0a3524907",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 43,
"avg_line_length": 19.833333333333332,
"alnum_prop": 0.5210084033613446,
"repo_name": "highzenith/patternize",
"id": "ab3c6e34e8a1dbdbce69af8cb06a0c2780847976",
"size": "238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "patterns/patterns.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "145550"
},
{
"name": "JavaScript",
"bytes": "8027"
}
],
"symlink_target": ""
} |
package com.suse.salt.netapi.calls;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.suse.salt.netapi.client.SaltClient;
import com.suse.salt.netapi.client.impl.HttpAsyncClientImpl;
import com.suse.salt.netapi.datatypes.AuthMethod;
import com.suse.salt.netapi.datatypes.Batch;
import com.suse.salt.netapi.datatypes.Token;
import com.suse.salt.netapi.datatypes.target.Glob;
import com.suse.salt.netapi.errors.GenericError;
import com.suse.salt.netapi.errors.JsonParsingError;
import com.suse.salt.netapi.event.WebSocketEventStream;
import com.suse.salt.netapi.event.AbstractEventsTest;
import com.suse.salt.netapi.event.EventStream;
import com.suse.salt.netapi.exception.SaltException;
import com.suse.salt.netapi.results.Result;
import com.suse.salt.netapi.utils.ClientUtils;
import com.suse.salt.netapi.utils.TestUtils;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.websocket.DeploymentException;
/**
* Tests for callAsync() taking an event stream to return results as they come in.
*/
public class CallAsyncEventsTest extends AbstractEventsTest {
private static final int MOCK_HTTP_PORT = 8888;
@Rule
public WireMockRule wireMockRule = new WireMockRule(MOCK_HTTP_PORT);
static final AuthMethod AUTH = new AuthMethod(new Token());
private SaltClient client;
private CloseableHttpAsyncClient closeableHttpAsyncClient;
@Override
@Before
public void init() throws URISyntaxException, DeploymentException {
super.init();
URI uri = URI.create("http://localhost:" + MOCK_HTTP_PORT);
closeableHttpAsyncClient = TestUtils.defaultClient();
client = new SaltClient(uri, new HttpAsyncClientImpl(closeableHttpAsyncClient));
}
@After
public void cleanup() {
super.cleanup();
try {
closeableHttpAsyncClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public Class<?> config() {
return CallAsyncEventsTestMessages.class;
}
public static <T> CompletableFuture<T> completeAfter(T value, Duration duration) {
final CompletableFuture<T> promise = new CompletableFuture<>();
SCHEDULER.schedule(
() -> promise.complete(value), duration.toMillis(), MILLISECONDS
);
return promise;
}
private static final ScheduledExecutorService SCHEDULER =
Executors.newScheduledThreadPool(1);
private String json(String name) {
return ClientUtils.streamToString(CallAsyncEventsTest
.class.getResourceAsStream(name));
}
@Test
public void testAsyncCall() throws SaltException, InterruptedException {
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_via_event_test_ping_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_test_ping_response.json"))));
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_via_event_list_job_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_list_job_response.json"))));
EventStream events = new WebSocketEventStream(uri, new Token("token"), 0, 0, 0);
Map<String, CompletionStage<Result<Boolean>>> call =
com.suse.salt.netapi.calls.modules.Test.ping().callAsync(
client,
Glob.ALL,
AUTH,
events,
completeAfter(
new GenericError("canceled"),
Duration.of(7, ChronoUnit.SECONDS)
),
Optional.empty()
).toCompletableFuture().join().get();
CountDownLatch countDownLatch = new CountDownLatch(5);
Map<String, Result<Boolean>> results = new HashMap<>();
Map<String, Long> times = new HashMap<>();
call.forEach((key, value) -> {
value.whenComplete((v, e) -> {
if (v != null) {
results.put(key, v);
}
times.put(key, System.currentTimeMillis());
countDownLatch.countDown();
});
});
countDownLatch.await(10, TimeUnit.SECONDS);
assertEquals(5, results.size());
assertTrue(results.get("minion1").result().get());
assertTrue(results.get("minion2").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $",
((JsonParsingError) results.get("minion2").error().get())
.getThrowable().getMessage());
long delay12 = times.get("minion2") - times.get("minion1");
assertTrue(delay12 >= 1000);
assertTrue(results.get("minion3").result().get());
long delay23 = times.get("minion3") - times.get("minion2");
assertTrue(delay23 >= 1000);
assertTrue(results.get("minion4").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $", ((JsonParsingError)
results.get("minion4").error().get()).getThrowable().getMessage());
long delay42 = times.get("minion4") - times.get("minion2");
assertTrue(delay42 >= 1000);
assertTrue(results.get("minion5").error().get() instanceof GenericError);
assertEquals("canceled",
((GenericError) results.get("minion5").error().get()).getMessage());
}
@Test
public void testAsyncBatchCall() throws SaltException, InterruptedException {
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_batch_via_event_test_ping_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_test_ping_response.json"))));
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_via_event_list_job_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_list_job_response.json"))));
EventStream events = new WebSocketEventStream(uri, new Token("token"), 0, 0, 0);
Map<String, CompletionStage<Result<Boolean>>> call =
com.suse.salt.netapi.calls.modules.Test.ping().callAsync(
client,
Glob.ALL,
AUTH,
events,
completeAfter(
new GenericError("canceled"),
Duration.of(7, ChronoUnit.SECONDS)
),
Optional.of(Batch.asAmount(1))
).toCompletableFuture().join().get();
CountDownLatch countDownLatch = new CountDownLatch(5);
Map<String, Result<Boolean>> results = new HashMap<>();
Map<String, Long> times = new HashMap<>();
call.forEach((key, value) -> {
value.whenComplete((v, e) -> {
if (v != null) {
results.put(key, v);
}
times.put(key, System.currentTimeMillis());
countDownLatch.countDown();
});
});
countDownLatch.await(10, TimeUnit.SECONDS);
assertEquals(5, results.size());
assertTrue(results.get("minion1").result().get());
assertTrue(results.get("minion2").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $",
((JsonParsingError) results.get("minion2").error().get())
.getThrowable().getMessage());
long delay12 = times.get("minion2") - times.get("minion1");
assertTrue(delay12 >= 1000);
assertTrue(results.get("minion3").result().get());
long delay23 = times.get("minion3") - times.get("minion2");
assertTrue(delay23 >= 1000);
assertTrue(results.get("minion4").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $", ((JsonParsingError)
results.get("minion4").error().get()).getThrowable().getMessage());
long delay42 = times.get("minion4") - times.get("minion2");
assertTrue(delay42 >= 1000);
assertTrue(results.get("minion5").error().get() instanceof GenericError);
assertEquals("canceled",
((GenericError) results.get("minion5").error().get()).getMessage());
}
}
| {
"content_hash": "048331449ae4c23689cd08c6380b6f2d",
"timestamp": "",
"source": "github",
"line_count": 262,
"max_line_length": 88,
"avg_line_length": 39.48854961832061,
"alnum_prop": 0.6130871834525421,
"repo_name": "mbologna/saltstack-netapi-client-java",
"id": "dcabacec1386af0fb1a762536291c27dfb2a5be3",
"size": "10346",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/test/java/com/suse/salt/netapi/calls/CallAsyncEventsTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "238364"
},
{
"name": "Shell",
"bytes": "757"
}
],
"symlink_target": ""
} |
package com.amcharts.json;
import java.util.List;
import com.amcharts.api.IsAmAngularChart;
import com.amcharts.api.IsFacePattern;
import com.amcharts.api.IsGaugeArrow;
import com.amcharts.api.IsGaugeAxis;
public final class AmAngularGauge implements IsAmAngularChart
{
private Boolean adjustSize;
private List<IsGaugeArrow> arrows;
private List<IsGaugeAxis> axes;
private Boolean clockWiseOnly;
private double faceAlpha;
private double faceBorderAlpha;
private String faceBorderColor;
private double faceBorderWidth;
private String faceColor;
private IsFacePattern facePattern;
private double gaugeX;
private double gaugeY;
private double marginBottom;
private double marginLeft;
private double marginRight;
private double marginTop;
private double minRadius;
private double startDuration;
private String startEffect;
/**
* Uses the whole space of the canvas to draw the gauge.
*/
@Override
public Boolean isAdjustSize()
{
return adjustSize;
}
/**
* Uses the whole space of the canvas to draw the gauge.
*/
@Override
public void setAdjustSize( Boolean adjustSize )
{
this.adjustSize = adjustSize;
}
/**
* Array of arrows.
*/
@Override
public List<IsGaugeArrow> getArrows()
{
return arrows;
}
/**
* Array of arrows.
*/
@Override
public void setArrows( List<IsGaugeArrow> arrows )
{
this.arrows = arrows;
}
/**
* Array of axes.
*/
@Override
public List<IsGaugeAxis> getAxes()
{
return axes;
}
/**
* Array of axes.
*/
@Override
public void setAxes( List<IsGaugeAxis> axes )
{
this.axes = axes;
}
/**
* In case you use gauge to create a clock, set this to true.
*/
@Override
public Boolean isClockWiseOnly()
{
return clockWiseOnly;
}
/**
* In case you use gauge to create a clock, set this to true.
*/
@Override
public void setClockWiseOnly( Boolean clockWiseOnly )
{
this.clockWiseOnly = clockWiseOnly;
}
/**
* Gauge face opacity.
*/
@Override
public double getFaceAlpha()
{
return faceAlpha;
}
/**
* Gauge face opacity.
*/
@Override
public void setFaceAlpha( double faceAlpha )
{
this.faceAlpha = faceAlpha;
}
/**
* Gauge face border opacity.
*/
@Override
public double getFaceBorderAlpha()
{
return faceBorderAlpha;
}
/**
* Gauge face border opacity.
*/
@Override
public void setFaceBorderAlpha( double faceBorderAlpha )
{
this.faceBorderAlpha = faceBorderAlpha;
}
/**
* Gauge face border color.
*/
@Override
public String getFaceBorderColor()
{
return faceBorderColor;
}
/**
* Gauge face border color.
*/
@Override
public void setFaceBorderColor( String faceBorderColor )
{
this.faceBorderColor = faceBorderColor;
}
/**
* Gauge face border width.
*/
@Override
public double getFaceBorderWidth()
{
return faceBorderWidth;
}
/**
* Gauge face border width.
*/
@Override
public void setFaceBorderWidth( double faceBorderWidth )
{
this.faceBorderWidth = faceBorderWidth;
}
/**
* Gauge face color, requires faceAlpha > 0
*/
@Override
public String getFaceColor()
{
return faceColor;
}
/**
* Gauge face color, requires faceAlpha > 0
*/
@Override
public void setFaceColor( String faceColor )
{
this.faceColor = faceColor;
}
/**
* "Gauge face image-pattern.Example: {'url':'../amcharts/patterns/black/pattern1.png', 'width':4, 'height':4}"
*/
@Override
public IsFacePattern getFacePattern()
{
return facePattern;
}
/**
* "Gauge face image-pattern.Example: {'url':'../amcharts/patterns/black/pattern1.png', 'width':4, 'height':4}"
*/
@Override
public void setFacePattern( IsFacePattern facePattern )
{
this.facePattern = facePattern;
}
/**
* Gauge's horizontal position in pixel, origin is the center. Centered by default.
*/
@Override
public double getGaugeX()
{
return gaugeX;
}
/**
* Gauge's horizontal position in pixel, origin is the center. Centered by default.
*/
@Override
public void setGaugeX( double gaugeX )
{
this.gaugeX = gaugeX;
}
/**
* Gauge's vertical position in pixel, origin is the center. Centered by default.
*/
@Override
public double getGaugeY()
{
return gaugeY;
}
/**
* Gauge's vertical position in pixel, origin is the center. Centered by default.
*/
@Override
public void setGaugeY( double gaugeY )
{
this.gaugeY = gaugeY;
}
/**
* Bottom spacing between chart and container.
*/
@Override
public double getMarginBottom()
{
return marginBottom;
}
/**
* Bottom spacing between chart and container.
*/
@Override
public void setMarginBottom( double marginBottom )
{
this.marginBottom = marginBottom;
}
/**
* Left-hand spacing between chart and container.
*/
@Override
public double getMarginLeft()
{
return marginLeft;
}
/**
* Left-hand spacing between chart and container.
*/
@Override
public void setMarginLeft( double marginLeft )
{
this.marginLeft = marginLeft;
}
/**
* Right-hand spacing between chart and container.
*/
@Override
public double getMarginRight()
{
return marginRight;
}
/**
* Right-hand spacing between chart and container.
*/
@Override
public void setMarginRight( double marginRight )
{
this.marginRight = marginRight;
}
/**
* Top spacing between chart and container.
*/
@Override
public double getMarginTop()
{
return marginTop;
}
/**
* Top spacing between chart and container.
*/
@Override
public void setMarginTop( double marginTop )
{
this.marginTop = marginTop;
}
/**
* Minimum radius of a gauge.
*/
@Override
public double getMinRadius()
{
return minRadius;
}
/**
* Minimum radius of a gauge.
*/
@Override
public void setMinRadius( double minRadius )
{
this.minRadius = minRadius;
}
/**
* Duration of arrow animation.
*/
@Override
public double getStartDuration()
{
return startDuration;
}
/**
* Duration of arrow animation.
*/
@Override
public void setStartDuration( double startDuration )
{
this.startDuration = startDuration;
}
/**
* Transition effect of the arrows, possible effects: easeOutSine, easeInSine, elastic, bounce.
*/
@Override
public String getStartEffect()
{
return startEffect;
}
/**
* Transition effect of the arrows, possible effects: easeOutSine, easeInSine, elastic, bounce.
*/
@Override
public void setStartEffect( String startEffect )
{
this.startEffect = startEffect;
}
}
| {
"content_hash": "3a33b5e5166ebf36e81c23b1ddd3db0f",
"timestamp": "",
"source": "github",
"line_count": 391,
"max_line_length": 112,
"avg_line_length": 16.452685421994886,
"alnum_prop": 0.690968443960827,
"repo_name": "sillysachin/gwt-amcharts-project",
"id": "4171714dadc362163ae466001bbe5a076552b6df",
"size": "6433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gwt-amcharts/src/main/java/com/amcharts/json/AmAngularGauge.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1902"
},
{
"name": "HTML",
"bytes": "56924"
},
{
"name": "Java",
"bytes": "1350600"
},
{
"name": "JavaScript",
"bytes": "535994"
}
],
"symlink_target": ""
} |
/*web css*/ | {
"content_hash": "4337c4fccb6c13c29d206858070741ef",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 11,
"avg_line_length": 11,
"alnum_prop": 0.5454545454545454,
"repo_name": "Angel-fund/gitlab.fastnote.com",
"id": "ec95364266e06f8492e672c5a4e917cdae1d3158",
"size": "11",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Redwood/WebBundle/Resources/public/css/web.css",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.sql.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/** Defines values for SecurityAlertPolicyUseServerDefault. */
public enum SecurityAlertPolicyUseServerDefault {
/** Enum value Enabled. */
ENABLED("Enabled"),
/** Enum value Disabled. */
DISABLED("Disabled");
/** The actual serialized value for a SecurityAlertPolicyUseServerDefault instance. */
private final String value;
SecurityAlertPolicyUseServerDefault(String value) {
this.value = value;
}
/**
* Parses a serialized value to a SecurityAlertPolicyUseServerDefault instance.
*
* @param value the serialized value to parse.
* @return the parsed SecurityAlertPolicyUseServerDefault object, or null if unable to parse.
*/
@JsonCreator
public static SecurityAlertPolicyUseServerDefault fromString(String value) {
SecurityAlertPolicyUseServerDefault[] items = SecurityAlertPolicyUseServerDefault.values();
for (SecurityAlertPolicyUseServerDefault item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
}
| {
"content_hash": "873999e0ac48eb5eb8814ed29b6a5b50",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 99,
"avg_line_length": 32.04255319148936,
"alnum_prop": 0.700531208499336,
"repo_name": "Azure/azure-sdk-for-java",
"id": "74d334b9292070d7445b98df393ab744b08b8142",
"size": "1506",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SecurityAlertPolicyUseServerDefault.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Tue Apr 17 08:42:04 IDT 2018 -->
<title>com.exlibris.repository.procauto</title>
<meta name="date" content="2018-04-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.exlibris.repository.procauto";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</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><a href="../../../../com/exlibris/repository/persistence/sip/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/exlibris/repository/set/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/exlibris/repository/procauto/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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">
<h1 title="Package" class="title">Package com.exlibris.repository.procauto</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/exlibris/repository/procauto/ProcessExecutionStatusInfo.html" title="class in com.exlibris.repository.procauto">ProcessExecutionStatusInfo</a></td>
<td class="colLast">
<div class="block">Java bean to display the informations of ProcessExecution</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</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><a href="../../../../com/exlibris/repository/persistence/sip/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/exlibris/repository/set/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/exlibris/repository/procauto/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 ======= -->
</body>
</html>
| {
"content_hash": "0b4b9faac4d8bddbe67d7c69ca93984a",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 193,
"avg_line_length": 35.00704225352113,
"alnum_prop": 0.6296519814926574,
"repo_name": "ExLibrisGroup/Rosetta.dps-sdk-projects",
"id": "9e1e2f26daaf56ed572094ec7887413dbcbf0307",
"size": "4971",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "5.5.0/javadoc/com/exlibris/repository/procauto/package-summary.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "4697410"
},
{
"name": "Shell",
"bytes": "297"
}
],
"symlink_target": ""
} |
"""Testing the impact of graph node _tftrt_op_max_batch_size annotation on TRTEngineOp attributes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from tensorflow.core.framework import attr_value_pb2
from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test
class MaxBatchSizesTestBase(trt_test.TfTrtIntegrationTestBase):
@classmethod
def setUpClass(cls):
if cls is MaxBatchSizesTestBase:
raise unittest.SkipTest(
'MaxBatchSizesTestBase defines base class for other tests.')
super(MaxBatchSizesTestBase, cls).setUpClass()
@property
def tensor_shapes(self):
return [[1, 512, 1, 1], [64, 2, 2, 2], [32, 4, 2, 2], [16, 8, 2, 2]]
@property
def max_batch_sizes(self):
return [shape[0] for shape in self.tensor_shapes]
def GetParams(self):
"""Gets the build parameters for the test."""
return self.BuildParams(
self.GraphFn,
dtype=dtypes.float32,
input_shapes=[self.tensor_shapes[0]],
output_shapes=[self.tensor_shapes[-1]])
def ShouldRunTest(self, run_params):
# The maximum batch size for dynamic engines will be the actual batch size
# detected at runtime. Therefore, we don't run the test with dynamic
# engines.
return (not run_params.dynamic_engine, 'test static engine only.')
def GetConversionParams(self, run_params):
"""Returns a ConversionParams for test."""
conversion_params = super(MaxBatchSizesTestBase,
self).GetConversionParams(run_params)
conversion_params._replace(
max_batch_size=min(self.max_batch_sizes), maximum_cached_engines=1)
rewrite_config_with_trt = self.GetTrtRewriterConfig(
run_params=run_params,
conversion_params=conversion_params,
use_implicit_batch=True,
disable_non_trt_optimizers=True)
return conversion_params._replace(
rewriter_config_template=rewrite_config_with_trt)
def ExpectedEnginesToBuild(self, run_params):
"""Checks that the expected engine is built.
Args:
run_params: the run parameters.
Returns:
the expected engines to build.
There shall be engines generated for each maximum batch size.
"""
return [
'TRTEngineOp_{}'.format(seq_id)
for seq_id in range(len(self.max_batch_sizes))
]
def ExpectedMaxBatchSizes(self, run_params):
"""Checks that the expected maximum batch sizes for the generated engines.
Args:
run_params: the run parameters.
Returns:
the expected maximum batch sizes for the generated engines.
There shall be engines generated for each maximum batch size.
"""
return self.max_batch_sizes
class AnnotateMaxBatchSizesTest(MaxBatchSizesTestBase):
def GraphFn(self, inp):
"""Builds a tf.Graph for the test."""
tensor = inp * 2.0
tensor = array_ops.reshape(tensor, [-1] + self.tensor_shapes[1][1:])
with ops.get_default_graph()._attr_scope({
'_tftrt_op_max_batch_size':
attr_value_pb2.AttrValue(i=self.max_batch_sizes[1])
}):
tensor = tensor + 3.0
tensor = array_ops.reshape(tensor, [-1] + self.tensor_shapes[2][1:])
with ops.get_default_graph()._attr_scope({
'_tftrt_op_max_batch_size':
attr_value_pb2.AttrValue(i=self.max_batch_sizes[2])
}):
tensor = tensor * 4.0
tensor = array_ops.reshape(tensor, [-1] + self.tensor_shapes[3][1:])
with ops.get_default_graph()._attr_scope({
'_tftrt_op_max_batch_size':
attr_value_pb2.AttrValue(i=self.max_batch_sizes[3])
}):
tensor += tensor + 5.0
return array_ops.identity(tensor, name='output_0')
class StaticBatchSizeTest(MaxBatchSizesTestBase):
def GraphFn(self, inp):
"""Builds a tf.Graph for the test."""
tensor = inp * 2.0
tensor = array_ops.reshape(tensor, self.tensor_shapes[1])
tensor = tensor + 3.0
tensor = array_ops.reshape(tensor, self.tensor_shapes[2])
tensor = tensor * 4.0
tensor = array_ops.reshape(tensor, self.tensor_shapes[3])
tensor += tensor + 5.0
return array_ops.identity(tensor, name='output_0')
if __name__ == '__main__':
test.main()
| {
"content_hash": "6b1b88b34e59bc77a0ca85bffef451ba",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 101,
"avg_line_length": 33.41353383458647,
"alnum_prop": 0.6757425742574258,
"repo_name": "aam-at/tensorflow",
"id": "7eadb0017083e09547dbb267c96af7d199425812",
"size": "5133",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/python/compiler/tensorrt/test/annotate_max_batch_sizes_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3568"
},
{
"name": "Batchfile",
"bytes": "16049"
},
{
"name": "C",
"bytes": "784149"
},
{
"name": "C#",
"bytes": "8446"
},
{
"name": "C++",
"bytes": "69481042"
},
{
"name": "CMake",
"bytes": "204596"
},
{
"name": "Dockerfile",
"bytes": "73667"
},
{
"name": "Go",
"bytes": "1670128"
},
{
"name": "HTML",
"bytes": "4680118"
},
{
"name": "Java",
"bytes": "844222"
},
{
"name": "Jupyter Notebook",
"bytes": "1665601"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "101287"
},
{
"name": "Objective-C",
"bytes": "104023"
},
{
"name": "Objective-C++",
"bytes": "182460"
},
{
"name": "PHP",
"bytes": "17733"
},
{
"name": "Pascal",
"bytes": "3407"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "49451363"
},
{
"name": "RobotFramework",
"bytes": "891"
},
{
"name": "Ruby",
"bytes": "4697"
},
{
"name": "Shell",
"bytes": "495434"
},
{
"name": "Smarty",
"bytes": "27495"
},
{
"name": "Swift",
"bytes": "56155"
},
{
"name": "TSQL",
"bytes": "921"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.zenika.systemmanager</groupId>
<artifactId>application</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>application-bundle</artifactId>
<packaging>bundle</packaging>
<name>OSGi :: Application</name>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.graniteds-osgi</groupId>
<artifactId>granite-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.graniteds-osgi</groupId>
<artifactId>granite-gravity-ea</artifactId>
<version>1.0.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.ipojo.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.ipojo.handler.eventadmin</artifactId>
<version>1.6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>com.zenika.systemmanager</groupId>
<artifactId>application-swf</artifactId>
<version>${project.version}</version>
<type>swf</type>
<overWrite>true</overWrite>
<destFileName>SystemManager.swf</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Include-Resource>
<![CDATA[
${project.build.directory}/dependency
]]>
</Include-Resource>
<Export-Package>
com.zenika.systemmanager.application.service
</Export-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-ipojo-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>ipojo-bundle</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>graniteds-debug</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
| {
"content_hash": "b92c24d1530c00a156b90939ac6f4344",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 104,
"avg_line_length": 35.52554744525548,
"alnum_prop": 0.46989932196424905,
"repo_name": "diorcety/system-manager",
"id": "bf0400a7721b3c463aa425e33cf3a63e40ea7c23",
"size": "4867",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/application-bundle/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "8346"
},
{
"name": "Java",
"bytes": "75349"
}
],
"symlink_target": ""
} |
dropdown-events.html | {
"content_hash": "61e094823c590fec260ee86b46fab4e2",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 20,
"avg_line_length": 20,
"alnum_prop": 0.9,
"repo_name": "frontui/BrickPlus",
"id": "fec6c1ea2d80dfb76eed3f35638c487048d27666",
"size": "20",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "template/BrickPlus_page/pages/dropdown-events.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "881573"
},
{
"name": "HTML",
"bytes": "850874"
},
{
"name": "JavaScript",
"bytes": "755619"
},
{
"name": "Smarty",
"bytes": "4719"
}
],
"symlink_target": ""
} |
namespace RESIN {
class Material;
typedef std::shared_ptr<Material> MaterialRef;
class ShaderMaterial;
typedef std::shared_ptr<ShaderMaterial> ShaderMaterialRef;
}
| {
"content_hash": "86451ff0f7eac5fd6e8a24a5e3716174",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 58,
"avg_line_length": 20.75,
"alnum_prop": 0.8072289156626506,
"repo_name": "safetydank/resinlib",
"id": "daf5136ecb968500f373cdb47c852c861e7aff45",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/resin/materials/MaterialsFwd.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "68794"
},
{
"name": "C++",
"bytes": "1431411"
},
{
"name": "JavaScript",
"bytes": "816010"
},
{
"name": "Shell",
"bytes": "1057"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Exception: Selenium::WebDriver::Error::NoSuchElementError
— Documentation by YARD 0.8.5.2
</title>
<link rel="stylesheet" href="../../../css/style.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="../../../css/common.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript" charset="utf-8">
hasFrames = window.top.frames.main ? true : false;
relpath = '../../../';
framesUrl = "../../../frames.html#!" + escape(window.location.href);
</script>
<script type="text/javascript" charset="utf-8" src="../../../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../../../js/app.js"></script>
</head>
<body>
<div id="header">
<div id="menu">
<a href="../../../_index.html">Index (N)</a> »
<span class='title'><span class='object_link'><a href="../../../Selenium.html" title="Selenium (module)">Selenium</a></span></span> » <span class='title'><span class='object_link'><a href="../../WebDriver.html" title="Selenium::WebDriver (module)">WebDriver</a></span></span> » <span class='title'><span class='object_link'><a href="../Error.html" title="Selenium::WebDriver::Error (module)">Error</a></span></span>
»
<span class="title">NoSuchElementError</span>
<div class="noframes"><span class="title">(</span><a href="." target="_top">no frames</a><span class="title">)</span></div>
</div>
<div id="search">
<a class="full_list_link" id="class_list_link"
href="../../../class_list.html">
Class List
</a>
<a class="full_list_link" id="method_list_link"
href="../../../method_list.html">
Method List
</a>
<a class="full_list_link" id="file_list_link"
href="../../../file_list.html">
File List
</a>
</div>
<div class="clear"></div>
</div>
<iframe id="search_frame"></iframe>
<div id="content"><h1>Exception: Selenium::WebDriver::Error::NoSuchElementError
</h1>
<dl class="box">
<dt class="r1">Inherits:</dt>
<dd class="r1">
<span class="inheritName"><span class='object_link'><a href="WebDriverError.html" title="Selenium::WebDriver::Error::WebDriverError (class)">WebDriverError</a></span></span>
<ul class="fullTree">
<li>Object</li>
<li class="next">StandardError</li>
<li class="next"><span class='object_link'><a href="WebDriverError.html" title="Selenium::WebDriver::Error::WebDriverError (class)">WebDriverError</a></span></li>
<li class="next">Selenium::WebDriver::Error::NoSuchElementError</li>
</ul>
<a href="#" class="inheritanceTree">show all</a>
</dd>
<dt class="r2 last">Defined in:</dt>
<dd class="r2 last">rb/lib/selenium/webdriver/common/error.rb</dd>
</dl>
<div class="clear"></div>
<h2>Overview</h2><div class="docstring">
<div class="discussion">
<p>An element could not be located on the page using the given search
parameters.</p>
</div>
</div>
<div class="tags">
</div>
</div>
<div id="footer">
Generated on Tue Apr 9 23:39:01 2013 by
<a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a>
0.8.5.2 (ruby-2.0.0).
</div>
</body>
</html> | {
"content_hash": "cb907dd6e96cb3e629ba3e41f9039819",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 431,
"avg_line_length": 26.04895104895105,
"alnum_prop": 0.5881879194630872,
"repo_name": "lummyare/lummyare-test",
"id": "080ef5bdb5dc83e3bd66c7056b42b25a27336dfb",
"size": "3725",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "docs/api/rb/Selenium/WebDriver/Error/NoSuchElementError.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "825"
},
{
"name": "ApacheConf",
"bytes": "4611"
},
{
"name": "AppleScript",
"bytes": "2614"
},
{
"name": "C",
"bytes": "51663"
},
{
"name": "C#",
"bytes": "2261991"
},
{
"name": "C++",
"bytes": "1518332"
},
{
"name": "CSS",
"bytes": "23493"
},
{
"name": "Diff",
"bytes": "4559"
},
{
"name": "HTML",
"bytes": "2004746"
},
{
"name": "Java",
"bytes": "8179662"
},
{
"name": "JavaScript",
"bytes": "4192904"
},
{
"name": "Makefile",
"bytes": "4655"
},
{
"name": "Objective-C",
"bytes": "320338"
},
{
"name": "Objective-C++",
"bytes": "21847"
},
{
"name": "Python",
"bytes": "633839"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3086"
},
{
"name": "Ruby",
"bytes": "790996"
},
{
"name": "Shell",
"bytes": "6702"
},
{
"name": "XSLT",
"bytes": "1047"
}
],
"symlink_target": ""
} |
package p166
import (
"bytes"
"strconv"
)
/**
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
**/
// 按照小学生时候的那种长除法来计算
// 注意处理正负号的问题,都是用正数计算,前面加上符号就好
// 不必担心会出现无线不循环小数,因为无线不循环小数就是无理数了,而这里计算的都是有理数
// 答案共分为三部分,小数点之前的部分,紧跟小数点后不循环的部分,可能的小数点最后循环的部分
func fractionToDecimal(numerator int, denominator int) string {
buf := bytes.Buffer{}
if numerator < 0 && denominator > 0 {
numerator = -numerator
buf.WriteByte('-')
}
if numerator > 0 && denominator < 0 {
denominator = -denominator
buf.WriteByte('-')
}
integer := numerator / denominator
numerator = numerator % denominator
decimals := make([]byte, 0)
reminders := make(map[int]int)
var loop string
for numerator != 0 {
if v, ok := reminders[numerator]; ok {
//loop
loop = string(decimals[v:])
decimals = decimals[:v]
break
}
reminders[numerator] = len(decimals)
numerator *= 10
decimals = append(decimals, byte(numerator/denominator)+'0')
numerator %= denominator
}
buf.WriteString(strconv.Itoa(integer))
if len(decimals) > 0 || len(loop) > 0 {
buf.WriteByte('.')
}
buf.WriteString(string(decimals))
if len(loop) > 0 {
buf.WriteByte('(')
buf.WriteString(loop)
buf.WriteByte(')')
}
return buf.String()
}
| {
"content_hash": "083527ef75cd7345e8d621e9b2658294",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 114,
"avg_line_length": 23.257575757575758,
"alnum_prop": 0.6938110749185668,
"repo_name": "baishuai/leetcode",
"id": "ff27db3e0c6338b2880f8ac8f672cccf16194d64",
"size": "1793",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "algorithms/p166/166.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "243910"
},
{
"name": "CMake",
"bytes": "577"
},
{
"name": "Go",
"bytes": "652457"
},
{
"name": "Java",
"bytes": "900"
},
{
"name": "Python",
"bytes": "13694"
},
{
"name": "Shell",
"bytes": "276"
}
],
"symlink_target": ""
} |
namespace policy {
// A dialog shown when there is non-trivial work that has to be finished
// before any Chrome window can be opened during startup. This dialog is only
// enabled by enterprise policy. For example, cloud policy enrollment or forced
// upgrade.
class EnterpriseStartupDialog {
public:
// Callback when dialog is closed.
// |was_accepted| is true iff user confirmed the dialog. False if user
// canceled the dialog.
// |can_show_browser_window| is true if dialog is dismissed automatically once
// the non-trivial work is finished and browser window can be displayed.
// Otherwise, it's false. For example, user close the dialog or
// click 'Relaunch Chrome' button on the dialog.
using DialogResultCallback =
base::OnceCallback<void(bool was_accepted, bool can_show_browser_window)>;
virtual ~EnterpriseStartupDialog() = default;
// Show the dialog. Please note that the dialog won't contain any
// useful content until |Display*()| is called.
static std::unique_ptr<EnterpriseStartupDialog> CreateAndShowDialog(
DialogResultCallback callback);
// Display |information| with a throbber. Changes the content of dialog
// without re-opening it.
virtual void DisplayLaunchingInformationWithThrobber(
const base::string16& information) = 0;
// Display |error_message| with an error icon. Show confirm button with
// value |accept_button| if provided. Changes the content of dialog without
// re-opening it.
virtual void DisplayErrorMessage(
const base::string16& error_message,
const base::Optional<base::string16>& accept_button) = 0;
// Return true if dialog is being displayed.
virtual bool IsShowing() = 0;
protected:
EnterpriseStartupDialog() = default;
private:
DISALLOW_COPY_AND_ASSIGN(EnterpriseStartupDialog);
};
} // namespace policy
#endif // CHROME_BROWSER_UI_ENTERPRISE_STARTUP_DIALOG_H_
| {
"content_hash": "3a7ca65a94b7abf6c8396865ca804dde",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 80,
"avg_line_length": 39.645833333333336,
"alnum_prop": 0.7409353652128219,
"repo_name": "endlessm/chromium-browser",
"id": "62b53d85c450dd89b1d671a354a3f2bf662dfb4c",
"size": "2287",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/browser/ui/enterprise_startup_dialog.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.woniukeji.jianmerchant.affordwages;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.LazyStringArrayList;
import com.woniukeji.jianmerchant.R;
import com.woniukeji.jianmerchant.base.BaseActivity;
import com.woniukeji.jianmerchant.base.Constants;
import com.woniukeji.jianmerchant.entity.AffordUser;
import com.woniukeji.jianmerchant.entity.BaseBean;
import com.woniukeji.jianmerchant.eventbus.PayPassWordEvent;
import com.woniukeji.jianmerchant.eventbus.UserWagesEvent;
import com.woniukeji.jianmerchant.utils.ActivityManager;
import com.woniukeji.jianmerchant.utils.DateUtils;
import com.woniukeji.jianmerchant.utils.LogUtils;
import com.woniukeji.jianmerchant.utils.SPUtils;
import com.woniukeji.jianmerchant.widget.FixedRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;
public class CalculateActivity extends BaseActivity implements CalculateAdapter.deleteCallBack {
@InjectView(R.id.img_back) ImageView imgBack;
@InjectView(R.id.tv_title) TextView tvTitle;
@InjectView(R.id.img_share) ImageView imgShare;
@InjectView(R.id.list) FixedRecyclerView list;
@InjectView(R.id.tv_job_name) TextView tvJobName;
@InjectView(R.id.tv_job_date) TextView tvJobDate;
@InjectView(R.id.ll_jobname) LinearLayout llJobname;
@InjectView(R.id.tv_title_sum) TextView tvTitleSum;
@InjectView(R.id.tv_job_wages) TextView tvJobWages;
@InjectView(R.id.btn_change_wages) Button btnChangeWages;
@InjectView(R.id.ll_jobinfo) LinearLayout llJobinfo;
@InjectView(R.id.ch_all) CheckBox chAll;
@InjectView(R.id.btn_pay_wages) Button btnPayWages;
@InjectView(R.id.tv_wages_sum) TextView tvWagesSum;
@InjectView(R.id.tv_choose_sum) TextView tvChooseSum;
private int MSG_GET_SUCCESS = 0;
private int MSG_GET_FAIL = 1;
private int MSG_DELETE_SUCCESS = 2;
private int MSG_DELETE_FAIL = 3;
private int MSG_POST_SUCCESS = 5;
private int MSG_POST_FAIL = 6;
private Handler mHandler = new Myhandler(this);
private Context mContext = CalculateActivity.this;
private CalculateAdapter adapter;
private int merchantid;
private List<Boolean> isSelected=new ArrayList<>();
private List<AffordUser.ListTUserInfoEntity> userList = new ArrayList<>();
// private List<HashMap<AffordUser.ListTUserInfoEntity,Boolean>> userList = new ArrayList<>();
private int mPosition;
private SweetAlertDialog sweetAlertDialog;
private int lastVisibleItem;
private LinearLayoutManager mLayoutManager;
private String jobid;
private String jobNid = "0";
private String moneyStr;
private String jobName;
private double money;
private boolean noData;
private String str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
}
@OnClick({R.id.btn_change_wages, R.id.ch_all, R.id.btn_pay_wages,R.id.img_back})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_change_wages:
new SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE)
.setTitleText("修改应发工资")
.setInputType("number")
.setContentEdit("请输入应发工资数目")
.setCancelText("取消")
.setConfirmText("确定")
.showCancelButton(true)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
money = Double.parseDouble(sweetAlertDialog.getEditContent());
tvJobWages.setText(money+str);
for (int i=0; i<userList.size();i++){
userList.get(i).setReal_money(money);
}
Calculate();
adapter.notifyDataSetChanged();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.show();
break;
case R.id.btn_pay_wages:
Mdialog mdialog=new Mdialog(mContext);
mdialog.show();
break;
case R.id.img_back:
finish();
break;
}
}
private static class Myhandler extends Handler {
private WeakReference<Context> reference;
public Myhandler(Context context) {
reference = new WeakReference<>(context);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
CalculateActivity activity = (CalculateActivity) reference.get();
switch (msg.what) {
case 0:
BaseBean<AffordUser> modleBaseBean = (BaseBean<AffordUser>) msg.obj;
List<AffordUser.ListTUserInfoEntity> tempList = null;
if (msg.arg1!=0){
tempList = modleBaseBean.getData().getList_t_user_info();
for (int i = 0; i <tempList.size() ; i++) {
activity.isSelected.add(activity.userList.size()+i,false);
}
}else {
tempList = modleBaseBean.getData().getList_t_user_info();
activity.userList.clear();
for (int i = 0; i <tempList.size() ; i++) {
activity.isSelected.add(i,false);
}
}
if (tempList.size()<10){
activity.noData=true;
}else {
activity.noData=false;
}
activity.userList.addAll(tempList);
for (int i=0; i<activity.userList.size();i++){
activity.userList.get(i).setReal_money(activity.money);
}
activity.tvTitleSum.setText("总计"+modleBaseBean.getData().getUser_sum()+"人");
activity.adapter.notifyDataSetChanged();
break;
case 1:
String ErrorMessage = (String) msg.obj;
Toast.makeText(activity, ErrorMessage, Toast.LENGTH_SHORT).show();
break;
case 2:
BaseBean baseBean = (BaseBean) msg.obj;
activity.userList.remove(activity.mPosition);
activity.adapter.notifyDataSetChanged();
activity.showShortToast("刪除模板成功!");
break;
case 3:
String sms = (String) msg.obj;
Toast.makeText(activity, sms, Toast.LENGTH_SHORT).show();
break;
case 5:
BaseBean Bean = (BaseBean) msg.obj;
String sum=Bean.getSum();
Toast.makeText(activity, "结算成功", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(activity,FinishActivity.class);
intent.putExtra("sum",sum);
activity.startActivityForResult(intent,0);
// activity.finish();
break;
case 6:
String sms6 = (String) msg.obj;
Toast.makeText(activity, sms6, Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
@Override
public void setContentView() {
setContentView(R.layout.activity_pay_wages);
ButterKnife.inject(this);
EventBus.getDefault().register(this);
Intent intent = getIntent();
jobName = intent.getStringExtra("name");
moneyStr = intent.getStringExtra("money");
str=moneyStr.substring(moneyStr.indexOf("/"));
money= Double.parseDouble(moneyStr.substring(0,moneyStr.indexOf("/")));
jobid = intent.getStringExtra("jobid");
jobNid = intent.getStringExtra("jobNid");
if (jobNid==null||jobNid.equals("null")){
jobNid="0";
}
}
@Override
public void initViews() {
tvTitle.setText("结算");
tvJobName.setText(jobName);
tvJobWages.setText(moneyStr);
adapter = new CalculateAdapter(userList, isSelected,this, String.valueOf(money), this);
mLayoutManager = new LinearLayoutManager(this);
//设置布局管理器
list.setLayoutManager(mLayoutManager);
//设置adapter
list.setAdapter(adapter);
//设置Item增加、移除动画
list.setItemAnimator(new DefaultItemAnimator());
//添加分割线
sweetAlertDialog = new SweetAlertDialog(CalculateActivity.this, SweetAlertDialog.PROGRESS_TYPE);
}
@Override
public void initListeners() {
chAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
for (int i = 0; i < isSelected.size(); i++) {
isSelected.set(i,true);
}
}else {
for (int i = 0; i < isSelected.size(); i++) {
isSelected.set(i,false);
}
}
adapter.notifyDataSetChanged();
}
});
}
@Override
public void initData() {
merchantid = (int) SPUtils.getParam(mContext, Constants.USER_INFO, Constants.USER_MERCHANT_ID, 0);
GetTask getTask = new GetTask("0");
getTask.execute();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onStart() {
super.onStart();
list.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (userList.size() > 5 && lastVisibleItem == userList.size()&&!noData) {
noData=true;//防止数据还未取回的时候重新触发数据接口
GetTask getTask = new GetTask(String.valueOf(lastVisibleItem));
getTask.execute();
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
}
});
}
@Override
public void addActivity() {
ActivityManager.getActivityManager().addActivity(this);
}
public void onEvent(UserWagesEvent event){
Calculate();
}
private void Calculate() {
int sum = 0;
int person=0;
for (int i = 0; i <userList.size() ; i++) {
if (isSelected.get(i)){
sum+= userList.get(i).getReal_money();
person++;
}
}
tvWagesSum.setText("合计:"+sum+"元");
tvChooseSum.setText("选中"+person+"人");
}
public void onEventMainThread(PayPassWordEvent event){
if (event.isCorrect){
if (!sweetAlertDialog.isShowing()){
sweetAlertDialog.setTitleText("结算提交中,请稍后");
sweetAlertDialog.getProgressHelper().setBarColor(R.color.app_bg);
sweetAlertDialog.show();
}
Map map=new HashMap();
List tempList=new ArrayList();
for (int i = 0; i <userList.size() ; i++) {
if (isSelected.get(i)){
tempList.add(userList.get(i));
LogUtils.e("json",userList.get(i).getReal_money()+"元");
}
}
map.put("list_t_wages_Bean",tempList);
String json=new Gson().toJson(map);
PostTask postTask= new PostTask(jobid,jobNid,json
);
postTask.execute();
}
}
// @Override
// public void deleOnClick(int job_id, int merchant_id, int position) {
// mPosition = position;
// DeleteTask deleteTask = new DeleteTask(String.valueOf(job_id), String.valueOf(merchant_id));
// deleteTask.execute();
// }
@Override
protected void onDestroy() {
ButterKnife.reset(this);
EventBus.getDefault().unregister(this);
super.onDestroy();
}
public class GetTask extends AsyncTask<Void, Void, Void> {
private String count = "0";
GetTask(String mCount) {
this.count = mCount;
}
@Override
protected Void doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
getJobUsers();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// sweetAlertDialog.dismissWithAnimation();
}
/**
* postInfo
*/
public void getJobUsers() {
String only = DateUtils.getDateTimeToOnly(System.currentTimeMillis());
OkHttpUtils
.get()
.url(Constants.GET_PAY_LIST)
.addParams("only", only)
.addParams("job_id", jobid)
.addParams("nv_job_id", jobNid)
.addParams("count", count)
.build()
.connTimeOut(60000)
.readTimeOut(20000)
.writeTimeOut(20000)
.execute(new Callback<BaseBean<AffordUser>>() {
@Override
public BaseBean<AffordUser> parseNetworkResponse(Response response, int id) throws Exception {
String string = response.body().string();
LogUtils.e("calculate",count);
BaseBean baseBean = new Gson().fromJson(string, new TypeToken<BaseBean<AffordUser>>() {
}.getType());
return baseBean;
}
@Override
public void onError(Call call, Exception e, int id) {
Message message = new Message();
message.obj = e.toString();
message.what = MSG_GET_FAIL;
mHandler.sendMessage(message);
}
@Override
public void onResponse(BaseBean<AffordUser> response, int id) {
if (response.getCode().equals("200")) {
// SPUtils.setParam(AuthActivity.this, Constants.LOGIN_INFO, Constants.SP_TYPE, "0");
Message message = new Message();
message.obj = response;
message.arg1= Integer.parseInt(count);
message.what = MSG_GET_SUCCESS;
mHandler.sendMessage(message);
} else {
Message message = new Message();
message.obj = response.getMessage();
message.what = MSG_GET_FAIL;
mHandler.sendMessage(message);
}
}
});
}
}
public class PostTask extends AsyncTask<Void, Void, Void> {
private String jobid;
private String loginid;
private String houle;
private String jobnid="";
private String remarks="";
private String json;
PostTask(String jobid, String jobnid,String json) {
this.jobid = jobid;
this.json=json;
if (jobnid!=null){
this.jobnid=jobnid;
}
}
@Override
protected Void doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
PostJobWages();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (!sweetAlertDialog.isShowing()){
sweetAlertDialog.setTitleText("结算提交中,请稍后");
sweetAlertDialog.getProgressHelper().setBarColor(R.color.app_bg);
sweetAlertDialog.show();
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (sweetAlertDialog.isShowing()){
sweetAlertDialog.dismiss();
}
}
/**
*/
public void PostJobWages() {
String only = DateUtils.getDateTimeToOnly(System.currentTimeMillis());
OkHttpUtils
.post()
.url(Constants.POST_PART_JOB_WAGES)
// .content(json)
.addParams("only", only)
// .addParams("hould_money", houle)
// .addParams("real_money", real)
.addParams("nv_job_id", jobnid)
.addParams("job_id", jobid)
.addParams("json", json)
.build()
.connTimeOut(50000)
.readTimeOut(300000)
.writeTimeOut(300000)
.execute(new Callback<BaseBean<AffordUser>>() {
@Override
public BaseBean<AffordUser> parseNetworkResponse(Response response, int id) throws Exception {
String string = response.body().string();
// LogUtils.e("calculate",count);
BaseBean baseBean = new Gson().fromJson(string, new TypeToken<BaseBean<AffordUser>>() {
}.getType());
return baseBean;
}
@Override
public void onError(Call call, Exception e, int id) {
Message message = new Message();
message.obj = e.toString();
message.what = MSG_GET_FAIL;
mHandler.sendMessage(message);
}
@Override
public void onResponse(BaseBean<AffordUser> response, int id) {
if (response.getCode().equals("200")) {
// SPUtils.setParam(AuthActivity.this, Constants.LOGIN_INFO, Constants.SP_TYPE, "0");
Message message = new Message();
message.obj = response;
// message.arg1= Integer.parseInt(count);
message.what = MSG_POST_SUCCESS;
mHandler.sendMessage(message);
} else {
Message message = new Message();
message.obj = response.getMessage();
message.what = MSG_GET_FAIL;
mHandler.sendMessage(message);
}
}
});
}
}
@Override
public void deleOnClick(String money, AffordUser.ListTUserInfoEntity user, int position) {
Intent intent = new Intent(mContext, ChangeActivity.class);
intent.putExtra("money",money);
intent.putExtra("user", user);
intent.putExtra("position", position);
// startActivity(intent);
startActivityForResult(intent,1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==1){//修改界面返回值
if (resultCode==RESULT_OK){
int position= data.getIntExtra("position",0);
AffordUser.ListTUserInfoEntity user= (AffordUser.ListTUserInfoEntity) data.getSerializableExtra("user");
userList.set(position,user);
Calculate();
LogUtils.e("json","修改"+user.getReal_money());
adapter.notifyDataSetChanged();
}
}else {
if (resultCode==RESULT_OK){
GetTask getTask = new GetTask("0");
getTask.execute();
}
}
}
}
| {
"content_hash": "86212d896b6a9619599a505a5444058c",
"timestamp": "",
"source": "github",
"line_count": 600,
"max_line_length": 120,
"avg_line_length": 38.06333333333333,
"alnum_prop": 0.5317453367195026,
"repo_name": "woniukeji/jianguo",
"id": "3e44302be593456eee0f8a0a090eacb31a485bc0",
"size": "23062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JianMerchant/src/main/java/com/woniukeji/jianmerchant/affordwages/CalculateActivity.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2958290"
}
],
"symlink_target": ""
} |
package org.elasticsearch.cluster.routing.allocation;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.AllocationId;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.cluster.routing.TestShardRouting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.cluster.ESAllocationTestCase;
import java.util.Arrays;
import java.util.Collections;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class StartedShardsRoutingTests extends ESAllocationTestCase {
public void testStartedShardsMatching() {
AllocationService allocation = createAllocationService();
logger.info("--> building initial cluster state");
AllocationId allocationId = AllocationId.newRelocation(AllocationId.newInitializing());
final IndexMetaData indexMetaData = IndexMetaData.builder("test")
.settings(settings(Version.CURRENT))
.numberOfShards(2).numberOfReplicas(0)
.putActiveAllocationIds(1, Collections.singleton(allocationId.getId()))
.build();
final Index index = indexMetaData.getIndex();
ClusterState.Builder stateBuilder = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY))
.nodes(DiscoveryNodes.builder().add(newNode("node1")).add(newNode("node2")))
.metaData(MetaData.builder().put(indexMetaData, false));
final ShardRouting initShard = TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.INITIALIZING);
final ShardRouting relocatingShard = TestShardRouting.newShardRouting(new ShardId(index, 1), "node1", "node2", true, ShardRoutingState.RELOCATING, allocationId);
stateBuilder.routingTable(RoutingTable.builder().add(IndexRoutingTable.builder(index)
.addIndexShard(new IndexShardRoutingTable.Builder(initShard.shardId()).addShard(initShard).build())
.addIndexShard(new IndexShardRoutingTable.Builder(relocatingShard.shardId()).addShard(relocatingShard).build())).build());
ClusterState state = stateBuilder.build();
logger.info("--> test starting of shard");
RoutingAllocation.Result result = allocation.applyStartedShards(state, Arrays.asList(initShard), false);
assertTrue("failed to start " + initShard + "\ncurrent routing table:" + result.routingTable().prettyPrint(), result.changed());
assertTrue(initShard + "isn't started \ncurrent routing table:" + result.routingTable().prettyPrint(),
result.routingTable().index("test").shard(initShard.id()).allShardsStarted());
logger.info("--> testing starting of relocating shards");
result = allocation.applyStartedShards(state, Arrays.asList(relocatingShard.getTargetRelocatingShard()), false);
assertTrue("failed to start " + relocatingShard + "\ncurrent routing table:" + result.routingTable().prettyPrint(), result.changed());
ShardRouting shardRouting = result.routingTable().index("test").shard(relocatingShard.id()).getShards().get(0);
assertThat(shardRouting.state(), equalTo(ShardRoutingState.STARTED));
assertThat(shardRouting.currentNodeId(), equalTo("node2"));
assertThat(shardRouting.relocatingNodeId(), nullValue());
}
}
| {
"content_hash": "31701dabd6091b3b6d1a35f94c278b33",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 169,
"avg_line_length": 58.39705882352941,
"alnum_prop": 0.752203475195165,
"repo_name": "girirajsharma/elasticsearch",
"id": "746880568925cd8e49481016e7df6ad7ce14f476",
"size": "4759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/org/elasticsearch/cluster/routing/allocation/StartedShardsRoutingTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "7728"
},
{
"name": "Batchfile",
"bytes": "15853"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "224870"
},
{
"name": "HTML",
"bytes": "5595"
},
{
"name": "Java",
"bytes": "34353697"
},
{
"name": "Perl",
"bytes": "7116"
},
{
"name": "Python",
"bytes": "76187"
},
{
"name": "Ruby",
"bytes": "1917"
},
{
"name": "Shell",
"bytes": "100400"
}
],
"symlink_target": ""
} |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
from django import forms
from django.utils.translation import ugettext_noop
from corehq.apps.programs.models import Program
from corehq.apps.products.models import Product
from corehq.apps.commtrack.util import all_sms_codes
import json
class CurrencyField(forms.DecimalField):
"""
Allows a field to accept human readable currency values.
Example: $1,400.25 will be accepted and stored as 1400.25
"""
def clean(self, value):
for c in ['$', ',']:
value = value.replace(c, '')
return super(CurrencyField, self).clean(value)
class ProductForm(forms.Form):
name = forms.CharField(max_length=100)
code = forms.CharField(label=ugettext_noop("Product ID"), max_length=100, required=False)
description = forms.CharField(max_length=500, required=False, widget=forms.Textarea)
unit = forms.CharField(label=ugettext_noop("Units"), max_length=100, required=False)
program_id = forms.ChoiceField(label=ugettext_noop("Program"), choices=(), required=True)
cost = CurrencyField(max_digits=8, decimal_places=2, required=False)
def __init__(self, product, *args, **kwargs):
self.product = product
kwargs['initial'] = self.product._doc
kwargs['initial']['code'] = self.product.code
super(ProductForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.label_class = 'col-sm-3 col-md-4 col-lg-2'
self.helper.field_class = 'col-sm-4 col-md-5 col-lg-3'
programs = Program.by_domain(self.product.domain, wrap=False)
self.fields['program_id'].choices = tuple((prog['_id'], prog['name']) for prog in programs)
# make sure to select default program if
# this is a new product
if not product._id:
self.initial['program_id'] = Program.default_for_domain(self.product.domain)._id
self.helper.layout = Layout(
'name',
'code',
'description',
'unit',
'program_id',
'cost'
)
def clean_name(self):
name = self.cleaned_data['name']
other_products = [p for p in Product.by_domain(self.product.domain) if p._id != self.product._id]
if name in [p.name for p in other_products]:
raise forms.ValidationError('name already in use')
return name
def clean_code(self):
code = self.cleaned_data['code'].lower()
conflict = None
sms_codes = all_sms_codes(self.product.domain)
if code in sms_codes:
conflict = sms_codes[code]
if conflict[0] == 'product' and conflict[1]._id == self.product._id:
conflict = None
if conflict:
conflict_name = {
'product': lambda o: o.name,
'action': lambda o: o.caption,
'command': lambda o: o['caption'],
}[conflict[0]](conflict[1])
raise forms.ValidationError('product id not unique (conflicts with %s "%s")' % (conflict[0], conflict_name))
return code.lower()
def save(self, instance=None, commit=True):
if self.errors:
raise ValueError('form does not validate')
product = instance or self.product
for field in ('name', 'code', 'program_id', 'unit', 'description', 'cost'):
setattr(product, field, self.cleaned_data[field])
product_data = self.data.get('product_data')
if product_data:
product.product_data = json.loads(product_data)
if commit:
product.save()
return product
| {
"content_hash": "d4bb9dc2258a2c74bb4f4d08a9ec1aee",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 120,
"avg_line_length": 34.24770642201835,
"alnum_prop": 0.6129118671309939,
"repo_name": "qedsoftware/commcare-hq",
"id": "684c09530612373a7e614263ac299d7fce5b1f08",
"size": "3733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "corehq/apps/products/forms.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "15950"
},
{
"name": "CSS",
"bytes": "508392"
},
{
"name": "HTML",
"bytes": "2869325"
},
{
"name": "JavaScript",
"bytes": "2395360"
},
{
"name": "PHP",
"bytes": "2232"
},
{
"name": "PLpgSQL",
"bytes": "125298"
},
{
"name": "Python",
"bytes": "14670713"
},
{
"name": "Shell",
"bytes": "37514"
}
],
"symlink_target": ""
} |
<?php
// module/Blog/src/Blog/Model/Category.php:
namespace Blog\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Category
{
public $id;
public $name_cat;
public $id_block;
protected $inputFilter;
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->name_cat = (isset($data['name_cat'])) ? $data['name_cat'] : null;
$this->id_block = (isset($data['id_block'])) ? $data['id_block'] : null;
$this->name_bl = (isset($data['name_bl'])) ? $data['name_bl'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'id_block',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'name_cat',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
} | {
"content_hash": "bd4e403b99e82a28a2dd5fa61eded616",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 80,
"avg_line_length": 29.189873417721518,
"alnum_prop": 0.41153512575888984,
"repo_name": "alex2041/blogZend",
"id": "b351c267f082fda59e400bcbc259a83d9e2f6502",
"size": "2306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Blog/src/Blog/Model/Category.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "711"
},
{
"name": "CSS",
"bytes": "4893"
},
{
"name": "HTML",
"bytes": "29880"
},
{
"name": "JavaScript",
"bytes": "346"
},
{
"name": "PHP",
"bytes": "73301"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
<bill>
<laws />
<billType>HR</billType>
<summaries>
<billSummaries>
<item>
<actionDesc>Introduced in House</actionDesc>
<actionDate>2017-05-01</actionDate>
<text><![CDATA[Provides for the relief of Arturo Hernandez-Garcia.]]></text>
<updateDate>2017-05-01T04:00:00Z</updateDate>
<lastSummaryUpdateDate>2017-05-02T08:03:51Z</lastSummaryUpdateDate>
<name>Introduced in House</name>
<versionCode>00</versionCode>
</item>
</billSummaries>
</summaries>
<originChamber>House</originChamber>
<billNumber>2280</billNumber>
<cboCostEstimates />
<committeeReports />
<titles>
<item>
<parentTitleType />
<titleType>Official Title as Introduced</titleType>
<title>For the relief of Arturo Hernandez-Garcia.</title>
<chamberName />
<chamberCode />
</item>
<item>
<parentTitleType />
<titleType>Display Title</titleType>
<title>For the relief of Arturo Hernandez-Garcia.</title>
<chamberName />
<chamberCode />
</item>
</titles>
<notes />
<congress>115</congress>
<introducedDate>2017-05-01</introducedDate>
<constitutionalAuthorityStatementText />
<amendments />
<updateDate>2017-06-02T16:00:09Z</updateDate>
<actions>
<actionTypeCounts>
<introducedInTheHouse>1</introducedInTheHouse>
<placeholderTextForH>1</placeholderTextForH>
<billReferrals>1</billReferrals>
<introducedInHouse>1</introducedInHouse>
</actionTypeCounts>
<item>
<actionDate>2017-05-05</actionDate>
<committee>
<systemCode>hsju01</systemCode>
<name>Immigration and Border Security Subcommittee</name>
</committee>
<links />
<sourceSystem>
<code>1</code>
<name>House committee actions</name>
</sourceSystem>
<text>Referred to the Subcommittee on Immigration and Border Security.</text>
<type>Committee</type>
</item>
<item>
<actionDate>2017-05-01</actionDate>
<sourceSystem>
<code>2</code>
<name>House floor actions</name>
</sourceSystem>
<actionCode>H11100</actionCode>
<links />
<committee>
<systemCode>hsju00</systemCode>
<name>Judiciary Committee</name>
</committee>
<text>Referred to the House Committee on the Judiciary.</text>
<type>IntroReferral</type>
</item>
<item>
<actionDate>2017-05-01</actionDate>
<sourceSystem>
<code>9</code>
<name>Library of Congress</name>
</sourceSystem>
<actionCode>Intro-H</actionCode>
<links />
<committee />
<text>Introduced in House</text>
<type>IntroReferral</type>
</item>
<item>
<actionDate>2017-05-01</actionDate>
<sourceSystem>
<code>9</code>
<name>Library of Congress</name>
</sourceSystem>
<actionCode>1000</actionCode>
<links />
<committee />
<text>Introduced in House</text>
<type>IntroReferral</type>
</item>
<actionByCounts>
<houseOfRepresentatives>4</houseOfRepresentatives>
</actionByCounts>
</actions>
<latestAction>
<actionDate>2017-05-05</actionDate>
<text>Referred to the Subcommittee on Immigration and Border Security.</text>
<links />
</latestAction>
<subjects>
<billSubjects>
<legislativeSubjects>
<item>
<name>Private Legislation</name>
</item>
</legislativeSubjects>
</billSubjects>
</subjects>
<sponsors>
<item>
<lastName>Perlmutter</lastName>
<middleName />
<state>CO</state>
<bioguideId>P000593</bioguideId>
<identifiers>
<lisID>1835</lisID>
<gpoId>7865</gpoId>
<bioguideId>P000593</bioguideId>
</identifiers>
<party>D</party>
<fullName>Rep. Perlmutter, Ed [D-CO-7]</fullName>
<firstName>Ed</firstName>
<district>7</district>
<byRequestType />
</item>
</sponsors>
<recordedVotes />
<cosponsors />
<calendarNumbers />
<committees>
<billCommittees>
<item>
<name>Judiciary Committee</name>
<systemCode>hsju00</systemCode>
<type>Standing</type>
<subcommittees>
<item>
<systemCode>hsju01</systemCode>
<activities>
<item>
<date>2017-05-05T13:43:14Z</date>
<name>Referred to</name>
</item>
</activities>
<name>Immigration and Border Security Subcommittee</name>
</item>
</subcommittees>
<activities>
<item>
<date>2017-05-01T16:00:24Z</date>
<name>Referred to</name>
</item>
</activities>
<chamber>House</chamber>
</item>
</billCommittees>
</committees>
<version>1.0.0</version>
<title>For the relief of Arturo Hernandez-Garcia.</title>
<relatedBills />
<createDate>2017-05-02T03:11:49Z</createDate>
<policyArea />
</bill>
<dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:format>text/xml</dc:format>
<dc:language>EN</dc:language>
<dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
<dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
<dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
</dublinCore>
</billStatus>
| {
"content_hash": "6ad667bde33496a78b7ba9de7a74bb9e",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 676,
"avg_line_length": 35.123655913978496,
"alnum_prop": 0.602020511250574,
"repo_name": "peter765/power-polls",
"id": "49f76736be7fa8cdeb202118090a28b314bd2226",
"size": "6533",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/bills/hr/hr2280/fdsys_billstatus.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "58567"
},
{
"name": "JavaScript",
"bytes": "7370"
},
{
"name": "Python",
"bytes": "22988"
}
],
"symlink_target": ""
} |
"""
Django settings for johnBio project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from unipath import Path
from secrets import SECRET_KEY
BASE_DIR = Path(__file__).ancestor(3)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'johnBio.urls'
WSGI_APPLICATION = 'johnBio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages"
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR.ancestor(1).child('static_app','media')
STATIC_ROOT = BASE_DIR.ancestor(1).child('static_app', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) | {
"content_hash": "953131eac9785d223083261011c7e957",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 71,
"avg_line_length": 25.689320388349515,
"alnum_prop": 0.7210884353741497,
"repo_name": "J-east/John-Bio",
"id": "eb002c6ab82b7c725de778730882b5378cec0a8b",
"size": "2646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "johnBio/settings/base.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8586"
},
{
"name": "HTML",
"bytes": "25170"
},
{
"name": "JavaScript",
"bytes": "1932"
},
{
"name": "Python",
"bytes": "8598"
}
],
"symlink_target": ""
} |
FROM nginx
MAINTAINER Michael Boudreau <mkboudreau@yahoo.com>
RUN apt-get update && apt-get install -y wget vim
### INSTALL CONFD
RUN wget https://github.com/kelseyhightower/confd/releases/download/v0.10.0/confd-0.10.0-linux-amd64
RUN mv confd-0.10.0-linux-amd64 /usr/local/bin/confd
RUN chmod +x /usr/local/bin/confd
RUN mkdir -p /etc/confd/conf.d /etc/confd/templates /etc/nginx/sites-enabled
COPY nginx.conf /etc/nginx/nginx.conf
COPY app-nginx.tmpl /etc/confd/templates/app-nginx.tmpl
COPY app-nginx.toml /etc/confd/conf.d/app-nginx.toml
COPY nginx-run.sh /
EXPOSE 80 443
ENTRYPOINT ["/nginx-run.sh"]
| {
"content_hash": "da7c94ff65770e7fd0fc297e7d5529ec",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 100,
"avg_line_length": 32.10526315789474,
"alnum_prop": 0.7639344262295082,
"repo_name": "mkboudreau/nginx-confd",
"id": "c35d84b8a2dd227a36944deb256cb42fb0630965",
"size": "610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Nginx",
"bytes": "1182"
},
{
"name": "Shell",
"bytes": "1422"
}
],
"symlink_target": ""
} |
/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */
/* stylelint-disable declaration-bang-space-before */
/* stylelint-disable declaration-bang-space-before */
.ant-calendar-picker-container {
position: absolute;
z-index: 1050;
}
.ant-calendar-picker-container.slide-up-enter.slide-up-enter-active.ant-calendar-picker-container-placement-topLeft,
.ant-calendar-picker-container.slide-up-enter.slide-up-enter-active.ant-calendar-picker-container-placement-topRight,
.ant-calendar-picker-container.slide-up-appear.slide-up-appear-active.ant-calendar-picker-container-placement-topLeft,
.ant-calendar-picker-container.slide-up-appear.slide-up-appear-active.ant-calendar-picker-container-placement-topRight {
-webkit-animation-name: antSlideDownIn;
animation-name: antSlideDownIn;
}
.ant-calendar-picker-container.slide-up-enter.slide-up-enter-active.ant-calendar-picker-container-placement-bottomLeft,
.ant-calendar-picker-container.slide-up-enter.slide-up-enter-active.ant-calendar-picker-container-placement-bottomRight,
.ant-calendar-picker-container.slide-up-appear.slide-up-appear-active.ant-calendar-picker-container-placement-bottomLeft,
.ant-calendar-picker-container.slide-up-appear.slide-up-appear-active.ant-calendar-picker-container-placement-bottomRight {
-webkit-animation-name: antSlideUpIn;
animation-name: antSlideUpIn;
}
.ant-calendar-picker-container.slide-up-leave.slide-up-leave-active.ant-calendar-picker-container-placement-topLeft,
.ant-calendar-picker-container.slide-up-leave.slide-up-leave-active.ant-calendar-picker-container-placement-topRight {
-webkit-animation-name: antSlideDownOut;
animation-name: antSlideDownOut;
}
.ant-calendar-picker-container.slide-up-leave.slide-up-leave-active.ant-calendar-picker-container-placement-bottomLeft,
.ant-calendar-picker-container.slide-up-leave.slide-up-leave-active.ant-calendar-picker-container-placement-bottomRight {
-webkit-animation-name: antSlideUpOut;
animation-name: antSlideUpOut;
}
.ant-calendar-picker {
position: relative;
display: inline-block;
outline: none;
font-size: 12px;
transition: opacity 0.3s;
}
.ant-calendar-picker-input {
outline: none;
display: block;
}
.ant-calendar-picker:hover .ant-calendar-picker-input:not(.ant-input-disabled) {
border-color: #108ee9;
}
.ant-calendar-picker-clear,
.ant-calendar-picker-icon {
position: absolute;
width: 14px;
height: 14px;
right: 8px;
top: 50%;
margin-top: -7px;
line-height: 14px;
font-size: 12px;
transition: all .3s;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.ant-calendar-picker-clear {
opacity: 0;
z-index: 1;
color: rgba(0, 0, 0, 0.25);
background: #fff;
pointer-events: none;
cursor: pointer;
}
.ant-calendar-picker-clear:hover {
color: rgba(0, 0, 0, 0.43);
}
.ant-calendar-picker:hover .ant-calendar-picker-clear {
opacity: 1;
pointer-events: auto;
}
.ant-calendar-picker-icon {
color: rgba(0, 0, 0, 0.43);
}
.ant-calendar-picker-icon:after {
content: "\e6bb";
font-family: "anticon";
font-size: 12px;
color: rgba(0, 0, 0, 0.43);
display: inline-block;
line-height: 1;
}
.ant-calendar {
position: relative;
outline: none;
width: 231px;
border: 1px solid #fff;
list-style: none;
font-size: 12px;
text-align: left;
background-color: #fff;
border-radius: 4px;
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
background-clip: padding-box;
line-height: 1.5;
}
.ant-calendar-input-wrap {
height: 34px;
padding: 6px;
border-bottom: 1px solid #e9e9e9;
}
.ant-calendar-input {
border: 0;
width: 100%;
cursor: auto;
outline: 0;
height: 22px;
color: rgba(0, 0, 0, 0.65);
background: #fff;
}
.ant-calendar-input::-moz-placeholder {
color: rgba(0, 0, 0, 0.25);
opacity: 1;
}
.ant-calendar-input:-ms-input-placeholder {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-input::-webkit-input-placeholder {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-week-number {
width: 286px;
}
.ant-calendar-week-number-cell {
text-align: center;
}
.ant-calendar-header {
height: 34px;
line-height: 34px;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
border-bottom: 1px solid #e9e9e9;
}
.ant-calendar-header a:hover {
color: #49a9ee;
}
.ant-calendar-header .ant-calendar-century-select,
.ant-calendar-header .ant-calendar-decade-select,
.ant-calendar-header .ant-calendar-year-select,
.ant-calendar-header .ant-calendar-month-select {
padding: 0 2px;
font-weight: bold;
display: inline-block;
color: rgba(0, 0, 0, 0.65);
line-height: 34px;
}
.ant-calendar-header .ant-calendar-century-select-arrow,
.ant-calendar-header .ant-calendar-decade-select-arrow,
.ant-calendar-header .ant-calendar-year-select-arrow,
.ant-calendar-header .ant-calendar-month-select-arrow {
display: none;
}
.ant-calendar-header .ant-calendar-prev-century-btn,
.ant-calendar-header .ant-calendar-next-century-btn,
.ant-calendar-header .ant-calendar-prev-decade-btn,
.ant-calendar-header .ant-calendar-next-decade-btn,
.ant-calendar-header .ant-calendar-prev-month-btn,
.ant-calendar-header .ant-calendar-next-month-btn,
.ant-calendar-header .ant-calendar-prev-year-btn,
.ant-calendar-header .ant-calendar-next-year-btn {
position: absolute;
top: 0;
color: rgba(0, 0, 0, 0.43);
font-family: Arial, "Hiragino Sans GB", "Microsoft Yahei", "Microsoft Sans Serif", sans-serif;
padding: 0 5px;
font-size: 16px;
display: inline-block;
line-height: 34px;
}
.ant-calendar-header .ant-calendar-prev-century-btn,
.ant-calendar-header .ant-calendar-prev-decade-btn,
.ant-calendar-header .ant-calendar-prev-year-btn {
left: 7px;
}
.ant-calendar-header .ant-calendar-prev-century-btn:after,
.ant-calendar-header .ant-calendar-prev-decade-btn:after,
.ant-calendar-header .ant-calendar-prev-year-btn:after {
content: '«';
}
.ant-calendar-header .ant-calendar-next-century-btn,
.ant-calendar-header .ant-calendar-next-decade-btn,
.ant-calendar-header .ant-calendar-next-year-btn {
right: 7px;
}
.ant-calendar-header .ant-calendar-next-century-btn:after,
.ant-calendar-header .ant-calendar-next-decade-btn:after,
.ant-calendar-header .ant-calendar-next-year-btn:after {
content: '»';
}
.ant-calendar-header .ant-calendar-prev-month-btn {
left: 29px;
}
.ant-calendar-header .ant-calendar-prev-month-btn:after {
content: '‹';
}
.ant-calendar-header .ant-calendar-next-month-btn {
right: 29px;
}
.ant-calendar-header .ant-calendar-next-month-btn:after {
content: '›';
}
.ant-calendar-body {
padding: 4px 8px;
}
.ant-calendar table {
border-collapse: collapse;
max-width: 100%;
background-color: transparent;
width: 100%;
}
.ant-calendar table,
.ant-calendar th,
.ant-calendar td {
border: 0;
}
.ant-calendar-calendar-table {
border-spacing: 0;
margin-bottom: 0;
}
.ant-calendar-column-header {
line-height: 18px;
width: 33px;
padding: 6px 0;
text-align: center;
}
.ant-calendar-column-header .ant-calendar-column-header-inner {
display: block;
font-weight: normal;
}
.ant-calendar-week-number-header .ant-calendar-column-header-inner {
display: none;
}
.ant-calendar-cell {
padding: 4px 0;
}
.ant-calendar-date {
display: block;
margin: 0 auto;
color: rgba(0, 0, 0, 0.65);
border-radius: 2px;
width: 20px;
height: 20px;
line-height: 18px;
border: 1px solid transparent;
padding: 0;
background: transparent;
text-align: center;
transition: background 0.3s ease;
}
.ant-calendar-date-panel {
position: relative;
}
.ant-calendar-date:hover {
background: #ecf6fd;
cursor: pointer;
}
.ant-calendar-date:active {
color: #fff;
background: #49a9ee;
}
.ant-calendar-today .ant-calendar-date {
border-color: #108ee9;
font-weight: bold;
color: #108ee9;
}
.ant-calendar-last-month-cell .ant-calendar-date,
.ant-calendar-next-month-btn-day .ant-calendar-date {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-selected-day .ant-calendar-date {
background: #108ee9;
color: #fff;
border: 1px solid transparent;
}
.ant-calendar-selected-day .ant-calendar-date:hover {
background: #108ee9;
}
.ant-calendar-disabled-cell .ant-calendar-date {
cursor: not-allowed;
color: #bcbcbc;
background: #f7f7f7;
border-radius: 0;
width: auto;
border: 1px solid transparent;
}
.ant-calendar-disabled-cell .ant-calendar-date:hover {
background: #f7f7f7;
}
.ant-calendar-disabled-cell.ant-calendar-today .ant-calendar-date {
position: relative;
margin-right: 5px;
padding-left: 5px;
}
.ant-calendar-disabled-cell.ant-calendar-today .ant-calendar-date:before {
content: " ";
position: absolute;
top: -1px;
left: 5px;
width: 20px;
height: 20px;
border: 1px solid #bcbcbc;
border-radius: 4px;
}
.ant-calendar-disabled-cell-first-of-row .ant-calendar-date {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.ant-calendar-disabled-cell-last-of-row .ant-calendar-date {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.ant-calendar-footer {
border-top: 1px solid #e9e9e9;
line-height: 38px;
padding: 0 12px;
}
.ant-calendar-footer:empty {
border-top: 0;
}
.ant-calendar-footer-btn {
text-align: center;
display: block;
}
.ant-calendar-footer-extra + .ant-calendar-footer-btn {
border-top: 1px solid #e9e9e9;
margin: 0 -12px;
padding: 0 12px;
}
.ant-calendar .ant-calendar-today-btn,
.ant-calendar .ant-calendar-clear-btn {
display: inline-block;
text-align: center;
margin: 0 0 0 8px;
}
.ant-calendar .ant-calendar-today-btn-disabled,
.ant-calendar .ant-calendar-clear-btn-disabled {
color: rgba(0, 0, 0, 0.25);
cursor: not-allowed;
}
.ant-calendar .ant-calendar-today-btn:only-child,
.ant-calendar .ant-calendar-clear-btn:only-child {
margin: 0;
}
.ant-calendar .ant-calendar-clear-btn {
display: none;
position: absolute;
right: 5px;
text-indent: -76px;
overflow: hidden;
width: 20px;
height: 20px;
text-align: center;
line-height: 20px;
top: 7px;
margin: 0;
}
.ant-calendar .ant-calendar-clear-btn:after {
font-family: 'anticon';
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\e62e";
font-size: 12px;
color: rgba(0, 0, 0, 0.25);
display: inline-block;
line-height: 1;
width: 20px;
text-indent: 43px;
transition: color 0.3s ease;
}
.ant-calendar .ant-calendar-clear-btn:hover:after {
color: rgba(0, 0, 0, 0.43);
}
.ant-calendar .ant-calendar-ok-btn {
display: inline-block;
margin-bottom: 0;
font-weight: 500;
text-align: center;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
white-space: nowrap;
line-height: 1.15;
padding: 0 15px;
height: 28px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
position: relative;
color: #fff;
background-color: #108ee9;
border-color: #108ee9;
padding: 0 7px;
font-size: 12px;
border-radius: 4px;
height: 22px;
line-height: 20px;
}
.ant-calendar .ant-calendar-ok-btn > .anticon {
line-height: 1;
}
.ant-calendar .ant-calendar-ok-btn,
.ant-calendar .ant-calendar-ok-btn:active,
.ant-calendar .ant-calendar-ok-btn:focus {
outline: 0;
}
.ant-calendar .ant-calendar-ok-btn:not([disabled]):hover {
text-decoration: none;
}
.ant-calendar .ant-calendar-ok-btn:not([disabled]):active {
outline: 0;
transition: none;
}
.ant-calendar .ant-calendar-ok-btn.disabled,
.ant-calendar .ant-calendar-ok-btn[disabled] {
cursor: not-allowed;
}
.ant-calendar .ant-calendar-ok-btn.disabled > *,
.ant-calendar .ant-calendar-ok-btn[disabled] > * {
pointer-events: none;
}
.ant-calendar .ant-calendar-ok-btn-lg {
padding: 0 15px;
font-size: 14px;
border-radius: 4px;
height: 32px;
}
.ant-calendar .ant-calendar-ok-btn-sm {
padding: 0 7px;
font-size: 12px;
border-radius: 4px;
height: 22px;
}
.ant-calendar .ant-calendar-ok-btn > a:only-child {
color: currentColor;
}
.ant-calendar .ant-calendar-ok-btn > a:only-child:after {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: transparent;
}
.ant-calendar .ant-calendar-ok-btn:hover,
.ant-calendar .ant-calendar-ok-btn:focus {
color: #fff;
background-color: #49a9ee;
border-color: #49a9ee;
}
.ant-calendar .ant-calendar-ok-btn:hover > a:only-child,
.ant-calendar .ant-calendar-ok-btn:focus > a:only-child {
color: currentColor;
}
.ant-calendar .ant-calendar-ok-btn:hover > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn:focus > a:only-child:after {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: transparent;
}
.ant-calendar .ant-calendar-ok-btn:active,
.ant-calendar .ant-calendar-ok-btn.active {
color: #fff;
background-color: #0e77ca;
border-color: #0e77ca;
}
.ant-calendar .ant-calendar-ok-btn:active > a:only-child,
.ant-calendar .ant-calendar-ok-btn.active > a:only-child {
color: currentColor;
}
.ant-calendar .ant-calendar-ok-btn:active > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn.active > a:only-child:after {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: transparent;
}
.ant-calendar .ant-calendar-ok-btn.disabled,
.ant-calendar .ant-calendar-ok-btn[disabled],
.ant-calendar .ant-calendar-ok-btn.disabled:hover,
.ant-calendar .ant-calendar-ok-btn[disabled]:hover,
.ant-calendar .ant-calendar-ok-btn.disabled:focus,
.ant-calendar .ant-calendar-ok-btn[disabled]:focus,
.ant-calendar .ant-calendar-ok-btn.disabled:active,
.ant-calendar .ant-calendar-ok-btn[disabled]:active,
.ant-calendar .ant-calendar-ok-btn.disabled.active,
.ant-calendar .ant-calendar-ok-btn[disabled].active {
color: rgba(0, 0, 0, 0.25);
background-color: #f7f7f7;
border-color: #d9d9d9;
}
.ant-calendar .ant-calendar-ok-btn.disabled > a:only-child,
.ant-calendar .ant-calendar-ok-btn[disabled] > a:only-child,
.ant-calendar .ant-calendar-ok-btn.disabled:hover > a:only-child,
.ant-calendar .ant-calendar-ok-btn[disabled]:hover > a:only-child,
.ant-calendar .ant-calendar-ok-btn.disabled:focus > a:only-child,
.ant-calendar .ant-calendar-ok-btn[disabled]:focus > a:only-child,
.ant-calendar .ant-calendar-ok-btn.disabled:active > a:only-child,
.ant-calendar .ant-calendar-ok-btn[disabled]:active > a:only-child,
.ant-calendar .ant-calendar-ok-btn.disabled.active > a:only-child,
.ant-calendar .ant-calendar-ok-btn[disabled].active > a:only-child {
color: currentColor;
}
.ant-calendar .ant-calendar-ok-btn.disabled > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn[disabled] > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn.disabled:hover > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn[disabled]:hover > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn.disabled:focus > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn[disabled]:focus > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn.disabled:active > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn[disabled]:active > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn.disabled.active > a:only-child:after,
.ant-calendar .ant-calendar-ok-btn[disabled].active > a:only-child:after {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: transparent;
}
.ant-calendar .ant-calendar-ok-btn-disabled {
color: rgba(0, 0, 0, 0.25);
background-color: #f7f7f7;
border-color: #d9d9d9;
cursor: not-allowed;
}
.ant-calendar .ant-calendar-ok-btn-disabled > a:only-child {
color: currentColor;
}
.ant-calendar .ant-calendar-ok-btn-disabled > a:only-child:after {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: transparent;
}
.ant-calendar .ant-calendar-ok-btn-disabled:hover {
color: rgba(0, 0, 0, 0.25);
background-color: #f7f7f7;
border-color: #d9d9d9;
}
.ant-calendar .ant-calendar-ok-btn-disabled:hover > a:only-child {
color: currentColor;
}
.ant-calendar .ant-calendar-ok-btn-disabled:hover > a:only-child:after {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: transparent;
}
.ant-calendar-range-picker-input {
background-color: transparent;
border: 0;
height: 99%;
outline: 0;
width: 43%;
text-align: center;
vertical-align: top;
}
.ant-calendar-range-picker-input::-moz-placeholder {
color: rgba(0, 0, 0, 0.25);
opacity: 1;
}
.ant-calendar-range-picker-input:-ms-input-placeholder {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-range-picker-input::-webkit-input-placeholder {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-range-picker-input[disabled] {
cursor: not-allowed;
}
.ant-calendar-range-picker-separator {
color: rgba(0, 0, 0, 0.43);
position: absolute;
top: 50%;
margin-top: -10px;
line-height: 20px;
height: 20px;
}
.ant-calendar-range {
width: 470px;
overflow: hidden;
}
.ant-calendar-range .ant-calendar-date-panel::after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.ant-calendar-range-part {
width: 50%;
position: relative;
}
.ant-calendar-range-left {
float: left;
}
.ant-calendar-range-left .ant-calendar-time-picker-inner {
border-right: 2px solid #e9e9e9;
}
.ant-calendar-range-right {
float: right;
}
.ant-calendar-range-right .ant-calendar-time-picker-inner {
border-left: 2px solid #e9e9e9;
}
.ant-calendar-range-middle {
position: absolute;
left: 50%;
width: 20px;
margin-left: -132px;
text-align: center;
height: 34px;
line-height: 34px;
color: rgba(0, 0, 0, 0.43);
}
.ant-calendar-range-right .ant-calendar-date-input-wrap {
margin-left: -118px;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-range-middle {
margin-left: -12px;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-range-right .ant-calendar-date-input-wrap {
margin-left: 0;
}
.ant-calendar-range .ant-calendar-input-wrap {
position: relative;
height: 34px;
}
.ant-calendar-range .ant-calendar-input,
.ant-calendar-range .ant-calendar-time-picker-input {
position: relative;
display: inline-block;
padding: 4px 7px;
width: 100%;
height: 28px;
cursor: text;
font-size: 12px;
line-height: 1.5;
color: rgba(0, 0, 0, 0.65);
background-color: #fff;
background-image: none;
border: 1px solid #d9d9d9;
border-radius: 4px;
transition: all .3s;
height: 22px;
border: 0;
box-shadow: none;
}
.ant-calendar-range .ant-calendar-input::-moz-placeholder,
.ant-calendar-range .ant-calendar-time-picker-input::-moz-placeholder {
color: rgba(0, 0, 0, 0.25);
opacity: 1;
}
.ant-calendar-range .ant-calendar-input:-ms-input-placeholder,
.ant-calendar-range .ant-calendar-time-picker-input:-ms-input-placeholder {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-range .ant-calendar-input::-webkit-input-placeholder,
.ant-calendar-range .ant-calendar-time-picker-input::-webkit-input-placeholder {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-range .ant-calendar-input:hover,
.ant-calendar-range .ant-calendar-time-picker-input:hover {
border-color: #49a9ee;
}
.ant-calendar-range .ant-calendar-input:focus,
.ant-calendar-range .ant-calendar-time-picker-input:focus {
border-color: #49a9ee;
outline: 0;
box-shadow: 0 0 0 2px rgba(16, 142, 233, 0.2);
}
.ant-calendar-range .ant-calendar-input-disabled,
.ant-calendar-range .ant-calendar-time-picker-input-disabled {
background-color: #f7f7f7;
opacity: 1;
cursor: not-allowed;
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-range .ant-calendar-input-disabled:hover,
.ant-calendar-range .ant-calendar-time-picker-input-disabled:hover {
border-color: #e2e2e2;
}
textarea.ant-calendar-range .ant-calendar-input,
textarea.ant-calendar-range .ant-calendar-time-picker-input {
max-width: 100%;
height: auto;
vertical-align: bottom;
}
.ant-calendar-range .ant-calendar-input-lg,
.ant-calendar-range .ant-calendar-time-picker-input-lg {
padding: 6px 7px;
height: 32px;
}
.ant-calendar-range .ant-calendar-input-sm,
.ant-calendar-range .ant-calendar-time-picker-input-sm {
padding: 1px 7px;
height: 22px;
}
.ant-calendar-range .ant-calendar-input:focus,
.ant-calendar-range .ant-calendar-time-picker-input:focus {
box-shadow: none;
}
.ant-calendar-range .ant-calendar-time-picker-icon {
display: none;
}
.ant-calendar-range.ant-calendar-week-number {
width: 574px;
}
.ant-calendar-range.ant-calendar-week-number .ant-calendar-range-part {
width: 286px;
}
.ant-calendar-range .ant-calendar-year-panel,
.ant-calendar-range .ant-calendar-month-panel {
top: 34px;
}
.ant-calendar-range .ant-calendar-month-panel .ant-calendar-year-panel {
top: 0;
}
.ant-calendar-range .ant-calendar-decade-panel-table,
.ant-calendar-range .ant-calendar-year-panel-table,
.ant-calendar-range .ant-calendar-month-panel-table {
height: 208px;
}
.ant-calendar-range .ant-calendar-in-range-cell {
border-radius: 0;
position: relative;
}
.ant-calendar-range .ant-calendar-in-range-cell > div {
position: relative;
z-index: 1;
}
.ant-calendar-range .ant-calendar-in-range-cell:before {
content: '';
display: block;
background: #ecf6fd;
border-radius: 0;
border: 0;
position: absolute;
top: 4px;
bottom: 4px;
left: 0;
right: 0;
}
div.ant-calendar-range-quick-selector {
text-align: left;
}
div.ant-calendar-range-quick-selector > a {
margin-right: 8px;
}
.ant-calendar-range .ant-calendar-header,
.ant-calendar-range .ant-calendar-month-panel-header,
.ant-calendar-range .ant-calendar-year-panel-header {
border-bottom: 0;
}
.ant-calendar-range .ant-calendar-body,
.ant-calendar-range .ant-calendar-month-panel-body,
.ant-calendar-range .ant-calendar-year-panel-body {
border-top: 1px solid #e9e9e9;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-time-picker {
height: 207px;
width: 100%;
top: 68px;
z-index: 2;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-time-picker-panel {
height: 241px;
margin-top: -34px;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-time-picker-inner {
padding-top: 34px;
height: 100%;
background: none;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-time-picker-combobox {
display: inline-block;
height: 100%;
background-color: #fff;
border-top: 1px solid #e9e9e9;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-time-picker-select {
height: 100%;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-time-picker-select ul {
max-height: 100%;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-footer .ant-calendar-time-picker-btn {
margin-right: 8px;
}
.ant-calendar-range.ant-calendar-time .ant-calendar-today-btn {
margin: 8px 12px;
height: 22px;
line-height: 22px;
}
.ant-calendar-range-with-ranges.ant-calendar-time .ant-calendar-time-picker {
height: 247px;
}
.ant-calendar-range-with-ranges.ant-calendar-time .ant-calendar-time-picker-panel {
height: 281px;
}
.ant-calendar-range.ant-calendar-show-time-picker .ant-calendar-body {
border-top-color: transparent;
}
.ant-calendar-time-picker {
position: absolute;
width: 100%;
top: 34px;
background-color: #fff;
}
.ant-calendar-time-picker-panel {
z-index: 1050;
position: absolute;
width: 100%;
}
.ant-calendar-time-picker-inner {
display: inline-block;
position: relative;
outline: none;
list-style: none;
font-size: 12px;
text-align: left;
background-color: #fff;
background-clip: padding-box;
line-height: 1.5;
overflow: hidden;
width: 100%;
}
.ant-calendar-time-picker-combobox {
width: 100%;
}
.ant-calendar-time-picker-column-1,
.ant-calendar-time-picker-column-1 .ant-calendar-time-picker-select {
width: 100%;
}
.ant-calendar-time-picker-column-2 .ant-calendar-time-picker-select {
width: 50%;
}
.ant-calendar-time-picker-column-3 .ant-calendar-time-picker-select {
width: 33.33%;
}
.ant-calendar-time-picker-column-4 .ant-calendar-time-picker-select {
width: 25%;
}
.ant-calendar-time-picker-input-wrap {
display: none;
}
.ant-calendar-time-picker-select {
float: left;
font-size: 12px;
border-right: 1px solid #e9e9e9;
box-sizing: border-box;
overflow: hidden;
position: relative;
height: 206px;
}
.ant-calendar-time-picker-select:hover {
overflow-y: auto;
}
.ant-calendar-time-picker-select:first-child {
border-left: 0;
margin-left: 0;
}
.ant-calendar-time-picker-select:last-child {
border-right: 0;
}
.ant-calendar-time-picker-select ul {
list-style: none;
box-sizing: border-box;
margin: 0;
padding: 0;
width: 100%;
max-height: 206px;
}
.ant-calendar-time-picker-select li {
text-align: center;
list-style: none;
box-sizing: content-box;
margin: 0;
width: 100%;
height: 24px;
line-height: 24px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
transition: background 0.3s ease;
}
.ant-calendar-time-picker-select li:last-child:after {
content: '';
height: 182px;
display: block;
}
.ant-calendar-time-picker-select li:hover {
background: #ecf6fd;
}
li.ant-calendar-time-picker-select-option-selected {
background: #f7f7f7;
font-weight: bold;
}
li.ant-calendar-time-picker-select-option-disabled {
color: rgba(0, 0, 0, 0.25);
}
li.ant-calendar-time-picker-select-option-disabled:hover {
background: transparent;
cursor: not-allowed;
}
.ant-calendar-time .ant-calendar-day-select {
padding: 0 2px;
font-weight: bold;
display: inline-block;
color: rgba(0, 0, 0, 0.65);
line-height: 34px;
}
.ant-calendar-time .ant-calendar-footer {
position: relative;
height: auto;
line-height: auto;
}
.ant-calendar-time .ant-calendar-footer-btn {
text-align: right;
}
.ant-calendar-time .ant-calendar-footer .ant-calendar-today-btn {
float: left;
margin: 0;
}
.ant-calendar-time .ant-calendar-footer .ant-calendar-time-picker-btn {
display: inline-block;
margin-right: 8px;
}
.ant-calendar-time .ant-calendar-footer .ant-calendar-time-picker-btn-disabled {
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-month-panel {
position: absolute;
top: 1px;
right: 0;
bottom: 0;
left: 0;
z-index: 10;
border-radius: 4px;
background: #fff;
outline: none;
}
.ant-calendar-month-panel > div {
height: 100%;
}
.ant-calendar-month-panel-hidden {
display: none;
}
.ant-calendar-month-panel-header {
height: 34px;
line-height: 34px;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
border-bottom: 1px solid #e9e9e9;
}
.ant-calendar-month-panel-header a:hover {
color: #49a9ee;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-century-select,
.ant-calendar-month-panel-header .ant-calendar-month-panel-decade-select,
.ant-calendar-month-panel-header .ant-calendar-month-panel-year-select,
.ant-calendar-month-panel-header .ant-calendar-month-panel-month-select {
padding: 0 2px;
font-weight: bold;
display: inline-block;
color: rgba(0, 0, 0, 0.65);
line-height: 34px;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-century-select-arrow,
.ant-calendar-month-panel-header .ant-calendar-month-panel-decade-select-arrow,
.ant-calendar-month-panel-header .ant-calendar-month-panel-year-select-arrow,
.ant-calendar-month-panel-header .ant-calendar-month-panel-month-select-arrow {
display: none;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-century-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-century-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-decade-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-decade-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-month-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-month-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-year-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-year-btn {
position: absolute;
top: 0;
color: rgba(0, 0, 0, 0.43);
font-family: Arial, "Hiragino Sans GB", "Microsoft Yahei", "Microsoft Sans Serif", sans-serif;
padding: 0 5px;
font-size: 16px;
display: inline-block;
line-height: 34px;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-century-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-decade-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-year-btn {
left: 7px;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-century-btn:after,
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-decade-btn:after,
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-year-btn:after {
content: '«';
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-century-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-decade-btn,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-year-btn {
right: 7px;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-century-btn:after,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-decade-btn:after,
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-year-btn:after {
content: '»';
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-month-btn {
left: 29px;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-prev-month-btn:after {
content: '‹';
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-month-btn {
right: 29px;
}
.ant-calendar-month-panel-header .ant-calendar-month-panel-next-month-btn:after {
content: '›';
}
.ant-calendar-month-panel-body {
height: calc(100% - 34px);
}
.ant-calendar-month-panel-table {
table-layout: fixed;
width: 100%;
height: 100%;
border-collapse: separate;
}
.ant-calendar-month-panel-selected-cell .ant-calendar-month-panel-month {
background: #108ee9;
color: #fff;
}
.ant-calendar-month-panel-selected-cell .ant-calendar-month-panel-month:hover {
background: #108ee9;
color: #fff;
}
.ant-calendar-month-panel-cell {
text-align: center;
}
.ant-calendar-month-panel-cell-disabled .ant-calendar-month-panel-month,
.ant-calendar-month-panel-cell-disabled .ant-calendar-month-panel-month:hover {
cursor: not-allowed;
color: #bcbcbc;
background: #f7f7f7;
}
.ant-calendar-month-panel-month {
display: inline-block;
margin: 0 auto;
color: rgba(0, 0, 0, 0.65);
background: transparent;
text-align: center;
height: 24px;
line-height: 24px;
padding: 0 6px;
border-radius: 4px;
transition: background 0.3s ease;
}
.ant-calendar-month-panel-month:hover {
background: #ecf6fd;
cursor: pointer;
}
.ant-calendar-year-panel {
position: absolute;
top: 1px;
right: 0;
bottom: 0;
left: 0;
z-index: 10;
border-radius: 4px;
background: #fff;
outline: none;
}
.ant-calendar-year-panel > div {
height: 100%;
}
.ant-calendar-year-panel-hidden {
display: none;
}
.ant-calendar-year-panel-header {
height: 34px;
line-height: 34px;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
border-bottom: 1px solid #e9e9e9;
}
.ant-calendar-year-panel-header a:hover {
color: #49a9ee;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-century-select,
.ant-calendar-year-panel-header .ant-calendar-year-panel-decade-select,
.ant-calendar-year-panel-header .ant-calendar-year-panel-year-select,
.ant-calendar-year-panel-header .ant-calendar-year-panel-month-select {
padding: 0 2px;
font-weight: bold;
display: inline-block;
color: rgba(0, 0, 0, 0.65);
line-height: 34px;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-century-select-arrow,
.ant-calendar-year-panel-header .ant-calendar-year-panel-decade-select-arrow,
.ant-calendar-year-panel-header .ant-calendar-year-panel-year-select-arrow,
.ant-calendar-year-panel-header .ant-calendar-year-panel-month-select-arrow {
display: none;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-century-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-century-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-decade-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-decade-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-month-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-month-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-year-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-year-btn {
position: absolute;
top: 0;
color: rgba(0, 0, 0, 0.43);
font-family: Arial, "Hiragino Sans GB", "Microsoft Yahei", "Microsoft Sans Serif", sans-serif;
padding: 0 5px;
font-size: 16px;
display: inline-block;
line-height: 34px;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-century-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-decade-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-year-btn {
left: 7px;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-century-btn:after,
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-decade-btn:after,
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-year-btn:after {
content: '«';
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-century-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-decade-btn,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-year-btn {
right: 7px;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-century-btn:after,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-decade-btn:after,
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-year-btn:after {
content: '»';
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-month-btn {
left: 29px;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-prev-month-btn:after {
content: '‹';
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-month-btn {
right: 29px;
}
.ant-calendar-year-panel-header .ant-calendar-year-panel-next-month-btn:after {
content: '›';
}
.ant-calendar-year-panel-body {
height: calc(100% - 34px);
}
.ant-calendar-year-panel-table {
table-layout: fixed;
width: 100%;
height: 100%;
border-collapse: separate;
}
.ant-calendar-year-panel-cell {
text-align: center;
}
.ant-calendar-year-panel-year {
display: inline-block;
margin: 0 auto;
color: rgba(0, 0, 0, 0.65);
background: transparent;
text-align: center;
height: 24px;
line-height: 24px;
padding: 0 6px;
border-radius: 4px;
transition: background 0.3s ease;
}
.ant-calendar-year-panel-year:hover {
background: #ecf6fd;
cursor: pointer;
}
.ant-calendar-year-panel-selected-cell .ant-calendar-year-panel-year {
background: #108ee9;
color: #fff;
}
.ant-calendar-year-panel-selected-cell .ant-calendar-year-panel-year:hover {
background: #108ee9;
color: #fff;
}
.ant-calendar-year-panel-last-decade-cell .ant-calendar-year-panel-year,
.ant-calendar-year-panel-next-decade-cell .ant-calendar-year-panel-year {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-decade-panel {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 10;
background: #fff;
border-radius: 4px;
outline: none;
}
.ant-calendar-decade-panel-hidden {
display: none;
}
.ant-calendar-decade-panel-header {
height: 34px;
line-height: 34px;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
border-bottom: 1px solid #e9e9e9;
}
.ant-calendar-decade-panel-header a:hover {
color: #49a9ee;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-century-select,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-decade-select,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-year-select,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-month-select {
padding: 0 2px;
font-weight: bold;
display: inline-block;
color: rgba(0, 0, 0, 0.65);
line-height: 34px;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-century-select-arrow,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-decade-select-arrow,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-year-select-arrow,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-month-select-arrow {
display: none;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-century-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-century-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-decade-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-decade-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-month-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-month-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-year-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-year-btn {
position: absolute;
top: 0;
color: rgba(0, 0, 0, 0.43);
font-family: Arial, "Hiragino Sans GB", "Microsoft Yahei", "Microsoft Sans Serif", sans-serif;
padding: 0 5px;
font-size: 16px;
display: inline-block;
line-height: 34px;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-century-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-decade-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-year-btn {
left: 7px;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-century-btn:after,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-decade-btn:after,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-year-btn:after {
content: '«';
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-century-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-decade-btn,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-year-btn {
right: 7px;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-century-btn:after,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-decade-btn:after,
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-year-btn:after {
content: '»';
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-month-btn {
left: 29px;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-prev-month-btn:after {
content: '‹';
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-month-btn {
right: 29px;
}
.ant-calendar-decade-panel-header .ant-calendar-decade-panel-next-month-btn:after {
content: '›';
}
.ant-calendar-decade-panel-body {
height: calc(100% - 34px);
}
.ant-calendar-decade-panel-table {
table-layout: fixed;
width: 100%;
height: 100%;
border-collapse: separate;
}
.ant-calendar-decade-panel-cell {
text-align: center;
white-space: nowrap;
}
.ant-calendar-decade-panel-decade {
display: inline-block;
margin: 0 auto;
color: rgba(0, 0, 0, 0.65);
background: transparent;
text-align: center;
height: 24px;
line-height: 24px;
padding: 0 6px;
border-radius: 4px;
transition: background 0.3s ease;
}
.ant-calendar-decade-panel-decade:hover {
background: #ecf6fd;
cursor: pointer;
}
.ant-calendar-decade-panel-selected-cell .ant-calendar-decade-panel-decade {
background: #108ee9;
color: #fff;
}
.ant-calendar-decade-panel-selected-cell .ant-calendar-decade-panel-decade:hover {
background: #108ee9;
color: #fff;
}
.ant-calendar-decade-panel-last-century-cell .ant-calendar-decade-panel-decade,
.ant-calendar-decade-panel-next-century-cell .ant-calendar-decade-panel-decade {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
color: rgba(0, 0, 0, 0.25);
}
.ant-calendar-month .ant-calendar-month-panel,
.ant-calendar-month .ant-calendar-year-panel {
top: 0;
height: 248px;
}
| {
"content_hash": "d9d8703a3025ebd4cd27db4648f11a8b",
"timestamp": "",
"source": "github",
"line_count": 1379,
"max_line_length": 123,
"avg_line_length": 29.30891950688905,
"alnum_prop": 0.7175198555063463,
"repo_name": "yhx0634/foodshopfront",
"id": "eb574754120e56feb0ea679456a6b5ec53086f34",
"size": "40441",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/antd/es/date-picker/style/index.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4313"
},
{
"name": "HTML",
"bytes": "1197"
},
{
"name": "JavaScript",
"bytes": "4684025"
}
],
"symlink_target": ""
} |
<?php
namespace Doctrine\Search\Event;
use Doctrine\Search\SearchManager;
use Doctrine\Common\EventArgs;
/**
* Provides event arguments for the postFlush event.
*
* @link www.doctrine-project.org
* @since 2.0
* @author Daniel Freudenberger <df@rebuy.de>
*/
class PostFlushEventArgs extends EventArgs
{
/**
* @var SearchManager
*/
private $sm;
/**
* Constructor.
*
* @param SearchManager $sm
*/
public function __construct(SearchManager $sm)
{
$this->sm = $sm;
}
/**
* Retrieve associated SearchManager.
*
* @return SearchManager
*/
public function getSearchManager()
{
return $this->sm;
}
}
| {
"content_hash": "64f2d588e429a1c020006a87b2947fce",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 52,
"avg_line_length": 17.30952380952381,
"alnum_prop": 0.5887207702888583,
"repo_name": "revinate/search",
"id": "b0bf05af8419fd23d769b3e33cc9e0f578fc01df",
"size": "1708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Doctrine/Search/Event/PostFlushEventArgs.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "204721"
}
],
"symlink_target": ""
} |
//========================================================================
//Copyright 2012 David Yu
//------------------------------------------------------------------------
//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.dyuproject.protostuff.runtime;
import com.dyuproject.protostuff.AbstractTest;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
/**
* Tests for {@link RuntimeView}.
*
* @author David Yu
* @created Nov 9, 2012
*/
public class RuntimeViewTest extends AbstractTest
{
// id name timestamp
static final Baz BAZ = newBaz( 128, "baz", 0);
static final int EXPECT_BAZ_LEN = 1+2 + 1+1+3 + 1+1;
static final int ID_LEN = 3;
static final int NAME_LEN = 5;
static final int TIMESTAMP_LEN = 2;
static final int WITHOUT_ID_LEN = EXPECT_BAZ_LEN - ID_LEN;
static final int WITHOUT_NAME_LEN = EXPECT_BAZ_LEN - NAME_LEN;
static final int WITHOUT_TIMESTAMP_LEN = EXPECT_BAZ_LEN - TIMESTAMP_LEN;
static final String STR_FN_ID = "1";
static final String STR_FN_NAME = "2";
static final String STR_FN_TIMESTAMP = "3";
static Baz newBaz(int id, String name, long timestamp)
{
Baz message = new Baz();
message.setId(id);
message.setName(name);
message.setTimestamp(timestamp);
return message;
}
static byte[] ser(Schema<Baz> schema)
{
return ProtostuffIOUtil.toByteArray(BAZ, schema, buf());
}
static int len(Schema<Baz> schema)
{
return ser(schema).length;
}
static RuntimeSchema<Baz> rs()
{
return (RuntimeSchema<Baz>)RuntimeSchema.getSchema(Baz.class);
}
static Schema<Baz> ex1(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.EXCLUDE,
null, args);
}
static Schema<Baz> ex2(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.EXCLUDE_OPTIMIZED_FOR_MERGE_ONLY,
null, args);
}
static Schema<Baz> in1(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.INCLUDE,
null, args);
}
static Schema<Baz> in2(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.INCLUDE_OPTIMIZED_FOR_MERGE_ONLY,
null, args);
}
static Schema<Baz> EQ(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.PREDICATE,
Predicate.Factories.EQ, args);
}
static Schema<Baz> NOTEQ(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.PREDICATE,
Predicate.Factories.NOTEQ, args);
}
static Schema<Baz> GT(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.PREDICATE,
Predicate.Factories.GT, args);
}
static Schema<Baz> LT(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.PREDICATE,
Predicate.Factories.LT, args);
}
static Schema<Baz> RANGE(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.PREDICATE,
Predicate.Factories.RANGE, args);
}
static Schema<Baz> NOTRANGE(String ... args)
{
return RuntimeView.createFrom(rs(),
RuntimeView.Factories.PREDICATE,
Predicate.Factories.NOTRANGE, args);
}
// tests
public void testLen()
{
assertEquals(EXPECT_BAZ_LEN, len(rs()));
}
public void testExcludeBazId()
{
assertEquals(WITHOUT_ID_LEN, len(ex1("id")));
assertEquals(WITHOUT_ID_LEN, len(ex2("id")));
assertEquals(WITHOUT_ID_LEN, len(in1("name", "timestamp")));
assertEquals(WITHOUT_ID_LEN, len(in2("name", "timestamp")));
assertEquals(WITHOUT_ID_LEN, len(NOTEQ(STR_FN_ID)));
assertEquals(WITHOUT_ID_LEN, len(GT(STR_FN_ID)));
assertEquals(WITHOUT_ID_LEN, len(RANGE(STR_FN_NAME, STR_FN_TIMESTAMP)));
}
public void testExcludeBazName()
{
assertEquals(WITHOUT_NAME_LEN, len(ex1("name")));
assertEquals(WITHOUT_NAME_LEN, len(ex2("name")));
assertEquals(WITHOUT_NAME_LEN, len(in1("id", "timestamp")));
assertEquals(WITHOUT_NAME_LEN, len(in2("id", "timestamp")));
assertEquals(WITHOUT_NAME_LEN, len(NOTEQ(STR_FN_NAME)));
assertEquals(WITHOUT_NAME_LEN, len(NOTRANGE(STR_FN_NAME, STR_FN_NAME)));
}
public void testExcludeBazTimestamp()
{
assertEquals(WITHOUT_TIMESTAMP_LEN, len(ex1("timestamp")));
assertEquals(WITHOUT_TIMESTAMP_LEN, len(ex2("timestamp")));
assertEquals(WITHOUT_TIMESTAMP_LEN, len(in1("id", "name")));
assertEquals(WITHOUT_TIMESTAMP_LEN, len(in2("id", "name")));
assertEquals(WITHOUT_TIMESTAMP_LEN, len(NOTEQ(STR_FN_TIMESTAMP)));
assertEquals(WITHOUT_TIMESTAMP_LEN, len(LT(STR_FN_TIMESTAMP)));
assertEquals(WITHOUT_TIMESTAMP_LEN, len(RANGE(STR_FN_ID, STR_FN_NAME)));
}
public void testIncludeOnlyBazId()
{
assertEquals(ID_LEN, len(ex1("name", "timestamp")));
assertEquals(ID_LEN, len(ex2("name", "timestamp")));
assertEquals(ID_LEN, len(in1("id")));
assertEquals(ID_LEN, len(in2("id")));
assertEquals(ID_LEN, len(EQ(STR_FN_ID)));
assertEquals(ID_LEN, len(LT(STR_FN_NAME)));
assertEquals(ID_LEN, len(RANGE(STR_FN_ID, STR_FN_ID)));
}
public void testIncludeOnlyBazName()
{
assertEquals(NAME_LEN, len(ex1("id", "timestamp")));
assertEquals(NAME_LEN, len(ex2("id", "timestamp")));
assertEquals(NAME_LEN, len(in1("name")));
assertEquals(NAME_LEN, len(in2("name")));
assertEquals(NAME_LEN, len(EQ(STR_FN_NAME)));
assertEquals(NAME_LEN, len(RANGE(STR_FN_NAME, STR_FN_NAME)));
}
public void testIncludeOnlyBazTimestamp()
{
assertEquals(TIMESTAMP_LEN, len(ex1("id", "name")));
assertEquals(TIMESTAMP_LEN, len(ex2("id", "name")));
assertEquals(TIMESTAMP_LEN, len(in1("timestamp")));
assertEquals(TIMESTAMP_LEN, len(in2("timestamp")));
assertEquals(TIMESTAMP_LEN, len(EQ(STR_FN_TIMESTAMP)));
assertEquals(TIMESTAMP_LEN, len(GT(STR_FN_NAME)));
assertEquals(TIMESTAMP_LEN, len(RANGE(STR_FN_TIMESTAMP, STR_FN_TIMESTAMP)));
}
}
| {
"content_hash": "5437a5d0b8d9844b66fd09b07f7b0e1e",
"timestamp": "",
"source": "github",
"line_count": 224,
"max_line_length": 84,
"avg_line_length": 33.392857142857146,
"alnum_prop": 0.5767379679144385,
"repo_name": "zhupan/protostuff",
"id": "445750538f4f039f70915a4a2ffcd72b46ef1b78",
"size": "7480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protostuff-runtime-view/src/test/java/com/dyuproject/protostuff/runtime/RuntimeViewTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1212"
},
{
"name": "Java",
"bytes": "4102947"
},
{
"name": "JavaScript",
"bytes": "34694"
}
],
"symlink_target": ""
} |
FROM rhel7:latest
# Pause indefinitely if asked to do so.
ARG OO_PAUSE_ON_BUILD
RUN test "$OO_PAUSE_ON_BUILD" = "true" && while sleep 10; do true; done || :
ADD usr_local_bin/* /usr/local/bin/
# setup yum repos
RUN /usr/local/bin/setup-yum.sh
RUN yum repolist --disablerepo=* && \
yum-config-manager --disable \* > /dev/null && \
yum-config-manager --enable rhel-7-server-rpms rhel-7-server-extras-rpms
# creature comforts (make it feel like a normal linux environment)
ENV LANG en_US.UTF-8
ENV CONTAINER docker
ENV USER root
ENV HOME /root
ENV TERM xterm
WORKDIR /root
ADD root/bashrc /root/.bashrc
ADD root/pdbrc /root/.pdbrc
# Make working in Python nice
ADD root/pythonrc /root/.pythonrc
ENV PYTHONSTARTUP=/root/.pythonrc
# setup epel repo
RUN rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
RUN yum clean metadata && \
yum -y update && \
yum-install-check.sh -y wget iputils cronie ansible vim procps less ack tar psmisc python-scandir lsof && \
yum clean all
# Setup locales. It comes broken (probably a size issue) by default in the docker image.
RUN yum -y reinstall glibc-common && \
yum clean all && \
mv -f /usr/lib/locale/locale-archive /usr/lib/locale/locale-archive.tmpl && \
/usr/sbin/build-locale-archive
# Setup Cron
ADD pamd.crond /etc/pam.d/crond
# Setup Ansible
ADD ansible.cfg /etc/ansible/ansible.cfg
RUN echo -e '[local]\nlocalhost ansible_connection=local\n' > /etc/ansible/hosts
# Make the container work more consistently in and out of openshift
# BE CAREFUL!!! If you change these, you may bloat the image! Use 'docker history' to see the size!
RUN chmod -R g+rwX /root/
| {
"content_hash": "b3ac1d00f265c0150629a5567e15aecb",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 111,
"avg_line_length": 31.77358490566038,
"alnum_prop": 0.7191211401425178,
"repo_name": "themurph/openshift-tools",
"id": "b181c18ef647c4bc3261742f0fbbd8b1f3c2b63c",
"size": "2073",
"binary": false,
"copies": "1",
"ref": "refs/heads/prod",
"path": "docker/oso-ops-base/rhel7/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "108987"
},
{
"name": "CSS",
"bytes": "588"
},
{
"name": "Groovy",
"bytes": "6322"
},
{
"name": "HTML",
"bytes": "43950"
},
{
"name": "JavaScript",
"bytes": "229"
},
{
"name": "PHP",
"bytes": "35793"
},
{
"name": "Python",
"bytes": "11349806"
},
{
"name": "Shell",
"bytes": "752773"
},
{
"name": "Vim script",
"bytes": "1836"
}
],
"symlink_target": ""
} |
layout: default
---
{% include nav.html %}
<article class="px2 mb4" itemprop="blogPost" itemscope itemtype="http://schema.org/BlogPosting">
<header class="center mb4 uppercase col-12 md-col-10 mx-auto">
<h1 itemprop="name" class="post-header">{{ page.title }}</h1>
<div class="mb2">–</div>
<time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">{{ page.date | date: "%b %-d, %Y" }}</time>
</header>
<section itemprop="articleBody" class="col-12 md-col-6 mx-auto">
{{ content }}
</section>
</article>
{% if page.previous.url %}
<section class="col-12 px2 md-col-8 mx-auto py4 border-top center">
<a href="{{page.previous.url | prepend: site.baseurl }}" class="btn btn-primary">
Read Next: {{page.previous.title}}
</a>
</section>
{% endif %}
| {
"content_hash": "571d7b1e1380eab8a0aaea68cd14f1b0",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 125,
"avg_line_length": 33.708333333333336,
"alnum_prop": 0.6353522867737948,
"repo_name": "borisrorsvort/simple-portfolio",
"id": "b3c20cc97f4d54b9ce37df544c83d0046dff21d6",
"size": "815",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_layouts/post.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22989"
},
{
"name": "HTML",
"bytes": "20200"
},
{
"name": "Ruby",
"bytes": "2589"
}
],
"symlink_target": ""
} |
<?php
namespace app\models;
use Yii;
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
/**
* This is the model class for table "tbl_ref_acara".
*
* @property integer $id
* @property integer $ref_sukan_id
* @property string $desc
* @property integer $aktif
* @property integer $created_by
* @property integer $updated_by
* @property string $created
* @property string $updated
*/
class RefAcara extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_ref_acara';
}
public function behaviors()
{
return [
'bedezign\yii2\audit\AuditTrailBehavior',
[
'class' => \yii\behaviors\BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
[
'class' => \yii\behaviors\TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => 'updated',
'value' => new \yii\db\Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['ref_sukan_id', 'desc', 'aktif'], 'required', 'message' => GeneralMessage::yii_validation_required],
[['ref_sukan_id', 'aktif', 'created_by', 'updated_by'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
[['created', 'updated'], 'safe'],
[['desc'], 'string', 'max' => 255, 'tooLong' => GeneralMessage::yii_validation_string_max],
[['discipline'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
[['desc', 'discipline'], function ($attribute, $params) {
if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
$this->addError($attribute, GeneralMessage::yii_validation_xss);
}
}],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => GeneralLabel::id,
'ref_sukan_id' => GeneralLabel::ref_sukan_id,
'desc' => GeneralLabel::desc,
'aktif' => GeneralLabel::aktif,
'created_by' => GeneralLabel::created_by,
'updated_by' => GeneralLabel::updated_by,
'created' => GeneralLabel::created,
'updated' => GeneralLabel::updated,
];
}
public function getDisciplineAcara(){
$returnValue = "";
if($this->discipline != ""){
$returnValue = $this->discipline . ' - ' . $this->desc;
} else {
$returnValue = $this->desc;
}
return $returnValue;
}
public function getRefSukan() {
return $this->hasOne(RefSukan::className(), ['id' => 'ref_sukan_id']);
}
}
| {
"content_hash": "389a29f270cbf3f22e922bbb516e8364",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 132,
"avg_line_length": 29.50980392156863,
"alnum_prop": 0.5299003322259136,
"repo_name": "hung101/kbs",
"id": "168140952e52c0ef377df1e72c8356e86637624a",
"size": "3010",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frontend/models/RefAcara.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "113"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "4999813"
},
{
"name": "HTML",
"bytes": "32884422"
},
{
"name": "JavaScript",
"bytes": "38543640"
},
{
"name": "PHP",
"bytes": "30558998"
},
{
"name": "PowerShell",
"bytes": "936"
},
{
"name": "Shell",
"bytes": "5561"
}
],
"symlink_target": ""
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/gaming/v1/game_server_clusters.proto
namespace Google\Cloud\Gaming\V1;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* Response message for
* GameServerClustersService.PreviewCreateGameServerCluster.
*
* Generated from protobuf message <code>google.cloud.gaming.v1.PreviewCreateGameServerClusterResponse</code>
*/
class PreviewCreateGameServerClusterResponse extends \Google\Protobuf\Internal\Message
{
/**
* The ETag of the game server cluster.
*
* Generated from protobuf field <code>string etag = 2;</code>
*/
private $etag = '';
/**
* The target state.
*
* Generated from protobuf field <code>.google.cloud.gaming.v1.TargetState target_state = 3;</code>
*/
private $target_state = null;
/**
* Output only. The state of the Kubernetes cluster in preview, this will be available if
* 'view' is set to `FULL` in the relevant List/Get/Preview request.
*
* Generated from protobuf field <code>.google.cloud.gaming.v1.KubernetesClusterState cluster_state = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
private $cluster_state = null;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $etag
* The ETag of the game server cluster.
* @type \Google\Cloud\Gaming\V1\TargetState $target_state
* The target state.
* @type \Google\Cloud\Gaming\V1\KubernetesClusterState $cluster_state
* Output only. The state of the Kubernetes cluster in preview, this will be available if
* 'view' is set to `FULL` in the relevant List/Get/Preview request.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Cloud\Gaming\V1\GameServerClusters::initOnce();
parent::__construct($data);
}
/**
* The ETag of the game server cluster.
*
* Generated from protobuf field <code>string etag = 2;</code>
* @return string
*/
public function getEtag()
{
return $this->etag;
}
/**
* The ETag of the game server cluster.
*
* Generated from protobuf field <code>string etag = 2;</code>
* @param string $var
* @return $this
*/
public function setEtag($var)
{
GPBUtil::checkString($var, True);
$this->etag = $var;
return $this;
}
/**
* The target state.
*
* Generated from protobuf field <code>.google.cloud.gaming.v1.TargetState target_state = 3;</code>
* @return \Google\Cloud\Gaming\V1\TargetState|null
*/
public function getTargetState()
{
return $this->target_state;
}
public function hasTargetState()
{
return isset($this->target_state);
}
public function clearTargetState()
{
unset($this->target_state);
}
/**
* The target state.
*
* Generated from protobuf field <code>.google.cloud.gaming.v1.TargetState target_state = 3;</code>
* @param \Google\Cloud\Gaming\V1\TargetState $var
* @return $this
*/
public function setTargetState($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Gaming\V1\TargetState::class);
$this->target_state = $var;
return $this;
}
/**
* Output only. The state of the Kubernetes cluster in preview, this will be available if
* 'view' is set to `FULL` in the relevant List/Get/Preview request.
*
* Generated from protobuf field <code>.google.cloud.gaming.v1.KubernetesClusterState cluster_state = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return \Google\Cloud\Gaming\V1\KubernetesClusterState|null
*/
public function getClusterState()
{
return $this->cluster_state;
}
public function hasClusterState()
{
return isset($this->cluster_state);
}
public function clearClusterState()
{
unset($this->cluster_state);
}
/**
* Output only. The state of the Kubernetes cluster in preview, this will be available if
* 'view' is set to `FULL` in the relevant List/Get/Preview request.
*
* Generated from protobuf field <code>.google.cloud.gaming.v1.KubernetesClusterState cluster_state = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param \Google\Cloud\Gaming\V1\KubernetesClusterState $var
* @return $this
*/
public function setClusterState($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Gaming\V1\KubernetesClusterState::class);
$this->cluster_state = $var;
return $this;
}
}
| {
"content_hash": "9ad25bb88520f8f8d29f10277bb92735",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 160,
"avg_line_length": 30.36875,
"alnum_prop": 0.6342868903066474,
"repo_name": "googleapis/google-cloud-php-game-servers",
"id": "90035c358bec50981ee546a2dbf2b2d117bc862c",
"size": "4859",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "src/V1/PreviewCreateGameServerClusterResponse.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "338038"
},
{
"name": "Python",
"bytes": "2760"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4d22c98cd8a3c4c4cd3de41b2a578e38",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "02d0189aeea1fe42d2a5d0343fb46266ddb5995e",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Chlorophyta/Bryopsidophyceae/Bryopsidales/Codiaceae/Codium/Codium globosum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
# babel-plugin-import-directory
  
Are you sick and tired of writing an `index.js` file, just to import/export all the other files in a directory?
Don't seek more :)
Just use `babel-plugin-import-directory` for that!






## Installation
```sh
$ npm i babel-plugin-import-directory
```
or with `yarn`
```sh
$ yarn babel-plugin-import-directory
```
Don't forget to save it in your project (use `--save-dev` or `-D` flag)
```sh
$ npm i -D babel-plugin-import-directory
```
or with `yarn`
```sh
$ yarn add -D babel-plugin-import-directory
```
## Example
With the following folder structure:
```
|- index.js
|- actions
|- action.a.js
|- action_b.js
|- sub_dir
|- actionC.js
```
and with the following JS:
```javascript
import actions from './actions';
```
will be compiled to:
```javascript
const _dirImport = {};
import * as _actionA from "./actions/action.a";
import * as _actionB from "./actions/action_b";
_dirImport.actionA = _actionA;
_dirImport.actionB = _actionB;
const actions = _dirImport;
```
---
You can also import files recursively using double `asterisk` like this:
```javascript
import actions from './actions/**';
```
will be compiled to:
```javascript
const _dirImport = {};
import * as _actionA from "./actions/action.a";
import * as _actionB from "./actions/action_b";
import * as _actionC from "./actions/sub_dir/actionC";
_dirImport.actionA = _actionA;
_dirImport.actionB = _actionB;
_dirImport.actionC = _actionC;
const actions = _dirImport;
```
---
You can also import all the methods directly, using a single `asterisk`.
the following JS:
```javascript
import actions from './actions/*';
```
will be compiled to:
```javascript
const _dirImport = {};
import * as _actionA from "./actions/action.a";
import * as _actionB from "./actions/action_b";
for (let key in _actionA) {
_dirImport[key === 'default' ? 'actionA' : key] = _actionA[key];
}
for (let key in _actionB) {
_dirImport[key === 'default' ? 'actionB' : key] = _actionB[key];
}
const actions = _dirImport;
```
---
And you can use both, double and single `asterisk`, like this:
```javascript
import actions from './actions/**/*';
```
will be compiled to:
```javascript
const _dirImport = {};
import * as _actionA from "./actions/action.a";
import * as _actionB from "./actions/action_b";
import * as _actionC from "./actions/sub_dir/actionC";
for (let key in _actionA) {
_dirImport[key === 'default' ? 'actionA' : key] = _actionA[key];
}
for (let key in _actionB) {
_dirImport[key === 'default' ? 'actionB' : key] = _actionB[key];
}
for (let key in _actionC) {
_dirImport[key === 'default' ? 'actionC' : key] = _actionC[key];
}
const actions = _dirImport;
```
## Usage
Just add it to your **.babelrc** file
```json
{
"plugins": ["import-directory"]
}
```
And don't write the `index.js` ;)
### Options
### `exts`
By default, the files with the following extensions: `["js", "es6", "es", "jsx"]`, will be imported. You can change this using:
```json
{
"plugins": [
["wildcard", {
"exts": ["js", "es6", "es", "jsx", "javascript"]
}]
]
}
```
### `snakeCase`
By default, the variables name would be in camelCase. You can change this using:
```json
{
"plugins": [
["wildcard", {
"snakeCase": true
}]
]
}
```
** result: `action_a`, `action_b` and `action_c` **
## Scripts
- **npm run readme** : `node-readme`
- **npm run test** : `nyc ava`
- **npm run test:watch** : `yarn test -- --watch`
- **npm run report** : `nyc report --reporter=html`
- **npm run build** : `babel -d ./lib ./src`
- **npm run prepublish** : `babel -d ./lib ./src --minified`
## Dependencies
Package | Version | Dev
--- |:---:|:---:
[babel-template](https://www.npmjs.com/package/babel-template) | ^6.26.0 | ✖
[ava](https://www.npmjs.com/package/ava) | ^0.22.0 | ✔
[babel](https://www.npmjs.com/package/babel) | ^6.5.2 | ✔
[babel-cli](https://www.npmjs.com/package/babel-cli) | ^6.18.0 | ✔
[babel-preset-es2015](https://www.npmjs.com/package/babel-preset-es2015) | ^6.18.0 | ✔
[node-readme](https://www.npmjs.com/package/node-readme) | ^0.1.9 | ✔
[nyc](https://www.npmjs.com/package/nyc) | ^11.2.1 | ✔
## Contributing
Contributions welcome; Please submit all pull requests the against master branch. If your pull request contains JavaScript patches or features, you should include relevant unit tests. Please check the [Contributing Guidelines](contributng.md) for more details. Thanks!
## Author
Anmo <btavares26@gmail.com>
## License
- **MIT** : http://opensource.org/licenses/MIT
| {
"content_hash": "eff03f977ce0310bd50396f479f7e41f",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 268,
"avg_line_length": 24.612903225806452,
"alnum_prop": 0.6594270735817263,
"repo_name": "Anmo/babel-plugin-import-directory",
"id": "0dd7038ee7ff8fbe59c3d8d5a33729f17cba9fa9",
"size": "5355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "9164"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE193.label.xml
Template File: sources-sink-81a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sinks: cpy
* BadSink : Copy string to data using strcpy()
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81.h"
namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81
{
#ifndef OMITBAD
void bad()
{
char * data;
data = NULL;
/* FLAW: Did not leave space for a null terminator */
data = (char *)malloc(10*sizeof(char));
const CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81_base& baseObject = CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81_bad();
baseObject.action(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
data = NULL;
/* FIX: Allocate space for a null terminator */
data = (char *)malloc((10+1)*sizeof(char));
const CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81_base& baseObject = CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81_goodG2B();
baseObject.action(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "bd440d0498ee2c68037b0e1b0d99f0ae",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 151,
"avg_line_length": 29.38372093023256,
"alnum_prop": 0.6723387415908192,
"repo_name": "maurer/tiamat",
"id": "ccd059abcf2ea5b8bdc6c2a85f2e00a9f9360396",
"size": "2527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s06/CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_cpy_81a.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.apache.river.qa.harness;
import java.io.IOException;
import org.apache.river.api.io.AtomicSerial;
import org.apache.river.api.io.AtomicSerial.GetArg;
/**
* A <code>SlaveRequest</code> to start a service.
*/
@AtomicSerial
class StartClassServerRequest implements SlaveRequest {
/** the service name */
private String serviceName;
/**
* Construct the request.
*
* @param serviceName the service name
*/
StartClassServerRequest(String serviceName) {
this.serviceName = serviceName;
}
StartClassServerRequest(GetArg arg) throws IOException, ClassNotFoundException{
this(arg.get("serviceName", null, String.class));
}
/**
* Called by the <code>SlaveTest</code> after unmarshalling this object.
* The <code>AdminManager</code> is retrieved from the slave test,
* an admin is retrieved from the manager, and the admins <code>start</code>
* method is called. The <code>serviceName</code> should be the name
* of a class server, although no check is performed to verify this.
* <code>null</code> is returned since the class server 'proxy' is
* a local reference which is not serializable.
*
* @param slaveTest a reference to the <code>SlaveTest</code>
* @return null
* @throws Exception if an error occurs starting the service
*/
public Object doSlaveRequest(SlaveTest slaveTest) throws Exception {
Admin admin = slaveTest.getAdminManager().getAdmin(serviceName, 0);
admin.start();
return null;
}
}
| {
"content_hash": "b5c673be9e357e8908214d5483f9beca",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 83,
"avg_line_length": 30.84,
"alnum_prop": 0.6997405966277561,
"repo_name": "pfirmstone/JGDMS",
"id": "a3b045552d463c60e16a71ee886187f964b8043b",
"size": "2348",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "qa/src/org/apache/river/qa/harness/StartClassServerRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "38260"
},
{
"name": "Groovy",
"bytes": "30510"
},
{
"name": "HTML",
"bytes": "107806458"
},
{
"name": "Java",
"bytes": "24863323"
},
{
"name": "JavaScript",
"bytes": "1702"
},
{
"name": "Makefile",
"bytes": "3032"
},
{
"name": "Roff",
"bytes": "863"
},
{
"name": "Shell",
"bytes": "68247"
}
],
"symlink_target": ""
} |
@implementation NSInvocationOperation (TFEasyCoder)
//superclass pros NSOperation
-(NSInvocationOperation *(^)(long long queuePriority))set_queuePriority{
__weak typeof(self) weakSelf = self;
return ^(long long queuePriority){
weakSelf.queuePriority = queuePriority;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(double threadPriority))set_threadPriority{
__weak typeof(self) weakSelf = self;
return ^(double threadPriority){
weakSelf.threadPriority = threadPriority;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(long long qualityOfService))set_qualityOfService{
__weak typeof(self) weakSelf = self;
return ^(long long qualityOfService){
weakSelf.qualityOfService = qualityOfService;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(NSString * name))set_name{
__weak typeof(self) weakSelf = self;
return ^(NSString * name){
weakSelf.name = name;
return weakSelf;
};
}
//superclass pros NSObject
-(NSInvocationOperation *(^)(NSArray * accessibilityElements))set_accessibilityElements{
__weak typeof(self) weakSelf = self;
return ^(NSArray * accessibilityElements){
weakSelf.accessibilityElements = accessibilityElements;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(NSArray * accessibilityCustomActions))set_accessibilityCustomActions{
__weak typeof(self) weakSelf = self;
return ^(NSArray * accessibilityCustomActions){
weakSelf.accessibilityCustomActions = accessibilityCustomActions;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(BOOL isAccessibilityElement))set_isAccessibilityElement{
__weak typeof(self) weakSelf = self;
return ^(BOOL isAccessibilityElement){
weakSelf.isAccessibilityElement = isAccessibilityElement;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(NSString * accessibilityLabel))set_accessibilityLabel{
__weak typeof(self) weakSelf = self;
return ^(NSString * accessibilityLabel){
weakSelf.accessibilityLabel = accessibilityLabel;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(NSString * accessibilityHint))set_accessibilityHint{
__weak typeof(self) weakSelf = self;
return ^(NSString * accessibilityHint){
weakSelf.accessibilityHint = accessibilityHint;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(NSString * accessibilityValue))set_accessibilityValue{
__weak typeof(self) weakSelf = self;
return ^(NSString * accessibilityValue){
weakSelf.accessibilityValue = accessibilityValue;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(unsigned long long accessibilityTraits))set_accessibilityTraits{
__weak typeof(self) weakSelf = self;
return ^(unsigned long long accessibilityTraits){
weakSelf.accessibilityTraits = accessibilityTraits;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(UIBezierPath * accessibilityPath))set_accessibilityPath{
__weak typeof(self) weakSelf = self;
return ^(UIBezierPath * accessibilityPath){
weakSelf.accessibilityPath = accessibilityPath;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(CGPoint accessibilityActivationPoint))set_accessibilityActivationPoint{
__weak typeof(self) weakSelf = self;
return ^(CGPoint accessibilityActivationPoint){
weakSelf.accessibilityActivationPoint = accessibilityActivationPoint;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(NSString * accessibilityLanguage))set_accessibilityLanguage{
__weak typeof(self) weakSelf = self;
return ^(NSString * accessibilityLanguage){
weakSelf.accessibilityLanguage = accessibilityLanguage;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(BOOL accessibilityElementsHidden))set_accessibilityElementsHidden{
__weak typeof(self) weakSelf = self;
return ^(BOOL accessibilityElementsHidden){
weakSelf.accessibilityElementsHidden = accessibilityElementsHidden;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(BOOL accessibilityViewIsModal))set_accessibilityViewIsModal{
__weak typeof(self) weakSelf = self;
return ^(BOOL accessibilityViewIsModal){
weakSelf.accessibilityViewIsModal = accessibilityViewIsModal;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(BOOL shouldGroupAccessibilityChildren))set_shouldGroupAccessibilityChildren{
__weak typeof(self) weakSelf = self;
return ^(BOOL shouldGroupAccessibilityChildren){
weakSelf.shouldGroupAccessibilityChildren = shouldGroupAccessibilityChildren;
return weakSelf;
};
}
-(NSInvocationOperation *(^)(long long accessibilityNavigationStyle))set_accessibilityNavigationStyle{
__weak typeof(self) weakSelf = self;
return ^(long long accessibilityNavigationStyle){
weakSelf.accessibilityNavigationStyle = accessibilityNavigationStyle;
return weakSelf;
};
}
@end | {
"content_hash": "5e1b1383586acf6a2f950dcfd67b115b",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 107,
"avg_line_length": 30.757575757575758,
"alnum_prop": 0.7083743842364532,
"repo_name": "shmxybfq/TFDemos",
"id": "3d5a210baca19d641d6b1f63014de69c0286a13b",
"size": "5272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo-导航栏背景渐变(简单版)/demo-导航栏背景渐变(简单版)/TFEasyCoder/foundation/NSInvocationOperation+TFEasyCoder.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "22671932"
}
],
"symlink_target": ""
} |
import {ClassC} from "./module-c";
export class ClassE {
private c: ClassC = new ClassC();
doSomething() {
this.c.doSomething();
}
}
| {
"content_hash": "4567327090ce30ca6ef9a1263175443f",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 37,
"avg_line_length": 17.22222222222222,
"alnum_prop": 0.5806451612903226,
"repo_name": "rfruesmer/module-structure",
"id": "7cb06ac53221c082adf39d801dd2a4270925591d",
"size": "155",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/resources/ts/circular-module-dependency-02/module-e.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "329"
},
{
"name": "HTML",
"bytes": "218"
},
{
"name": "JavaScript",
"bytes": "78472"
},
{
"name": "TypeScript",
"bytes": "112075"
}
],
"symlink_target": ""
} |
module GuidesStyle18F
class GeneratedNodes
# Params:
# url_to_nav: Mapping from original document URL to "nav item" objects,
# i.e. { 'text' => '...', 'url' => '...', 'internal' => true }
# nav_data: Array of nav item objects contained in `url_to_nav` after
# applying updates, possibly containing "orphan" items marked with an
# `:orphan_url` property
#
# Returns:
# nav_data with orphans properly nested within automatically-generated
# parent nodes marked with `'generated' => true`
def self.create_homes_for_orphans(url_to_nav, nav_data)
orphans = nav_data.select { |nav| nav[:orphan_url] }
orphans.each { |nav| create_home_for_orphan(nav, nav_data, url_to_nav) }
nav_data.reject! { |nav| nav[:orphan_url] }
prune_childless_parents(nav_data)
end
def self.create_home_for_orphan(nav, nav_data, url_to_nav)
parents = nav[:orphan_url].split('/')[1..-1]
nav['url'] = parents.pop + '/'
child_url = '/'
immediate_parent = parents.reduce(nil) do |parent, child|
child_url = child_url + child + '/'
find_or_create_node(nav_data, child_url, parent, child, url_to_nav)
end
assign_orphan_to_home(nav, immediate_parent, url_to_nav)
end
def self.find_or_create_node(nav_data, child_url, parent, child, url_to_nav)
child_nav = url_to_nav[child_url]
if child_nav.nil?
child_nav = generated_node(child)
url_to_nav[child_url] = child_nav
(parent.nil? ? nav_data : (parent['children'] ||= [])) << child_nav
end
child_nav
end
def self.generated_node(parent_slug)
{ 'text' => parent_slug.split('-').join(' ').capitalize,
'url' => parent_slug + '/',
'internal' => true,
'generated' => true,
}
end
def self.assign_orphan_to_home(nav, immediate_parent, url_to_nav)
nav_copy = {}.merge(nav)
url_to_nav[nav_copy.delete(:orphan_url)] = nav_copy
(immediate_parent['children'] ||= []) << nav_copy
end
def self.prune_childless_parents(nav_data)
(nav_data || []).reject! do |nav|
children = (nav['children'] || [])
prune_childless_parents(children)
nav['generated'] && children.empty?
end
end
end
end
| {
"content_hash": "df50b1f601a47f40c054c51ea1b68b27",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 80,
"avg_line_length": 36.63492063492063,
"alnum_prop": 0.5922876949740035,
"repo_name": "ajkamel/solidus-guides",
"id": "c4473e7447d55c6faadee0fce1681a4303cd65cd",
"size": "2308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_plugins/lib/guides_style_18f/generated_nodes.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "14563"
},
{
"name": "HTML",
"bytes": "6173"
},
{
"name": "JavaScript",
"bytes": "11121"
},
{
"name": "Ruby",
"bytes": "28227"
}
],
"symlink_target": ""
} |
// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using StsServer.Attributes;
using StsServer.Constants.Net;
using Framework.Cryptography;
using Framework.Cryptography.BNet;
using Framework.Database;
using Framework.Database.Auth;
using Framework.Misc;
using Lappa_ORM;
namespace StsServer.Network.Packets.Handlers
{
class StsHandler
{
[StsMessage(StsMessage.LoginStart)]
public static void HandleAuthLoginStart(StsPacket packet, StsSession session)
{
// Can be an email or user name.
var loginName = packet["LoginName"].ToString();
session.Account = DB.Auth.Single<Account>(a => a.Email == loginName);
// Support for email only.
if (loginName != null && session.Account != null)
{
session.SecureRemotePassword = new SRP6a(session.Account.Salt, loginName, session.Account.PasswordVerifier);
session.SecureRemotePassword.CalculateB();
var keyData = new BinaryWriter(new MemoryStream());
keyData.Write(session.SecureRemotePassword.S.Length);
keyData.Write(session.SecureRemotePassword.S);
keyData.Write(session.SecureRemotePassword.B.Length);
keyData.Write(session.SecureRemotePassword.B);
var reply = new StsPacket(StsReason.OK, packet.Header.Sequence);
var xmlData = new XmlData();
xmlData.WriteElementRoot("Reply");
xmlData.WriteElement("KeyData", Convert.ToBase64String(keyData.ToArray()));
reply.WriteXmlData(xmlData);
session.Send(reply);
}
else
{
// Let's use ErrBadPasswd instead of ErrAccountNotFound.
var reply = new StsPacket(StsReason.ErrBadPasswd, packet.Header.Sequence);
reply.WriteString("<Error code=\"11\" server=\"0\" module=\"0\" line=\"0\"/>\n");
session.Send(reply);
}
}
[StsMessage(StsMessage.KeyData)]
public static void HandleAuthKeyData(StsPacket packet, StsSession session)
{
var keyData = new BinaryReader(new MemoryStream(Convert.FromBase64String(packet["KeyData"].ToString())));
var a = keyData.ReadBytes(keyData.ReadInt32());
var m = keyData.ReadBytes(keyData.ReadInt32());
session.SecureRemotePassword.CalculateU(a);
session.SecureRemotePassword.CalculateClientM(a);
if (session.SecureRemotePassword.ClientM.Compare(m))
{
session.SecureRemotePassword.CalculateServerM(m, a);
session.ClientCrypt = new SARC4();
session.ClientCrypt.PrepareKey(session.SecureRemotePassword.SessionKey);
session.State = 1;
var SKeyData = new BinaryWriter(new MemoryStream());
SKeyData.Write(session.SecureRemotePassword.ServerM.Length);
SKeyData.Write(session.SecureRemotePassword.ServerM);
var reply = new StsPacket(StsReason.OK, packet.Header.Sequence);
var xmlData = new XmlData();
xmlData.WriteElementRoot("Reply");
xmlData.WriteElement("KeyData", Convert.ToBase64String(SKeyData.ToArray()));
reply.WriteXmlData(xmlData);
session.Send(reply);
}
else
{
session.Account = null;
var reply = new StsPacket(StsReason.ErrBadPasswd, packet.Header.Sequence);
reply.WriteString("<Error code=\"11\" server=\"0\" module=\"0\" line=\"0\"/>\n");
session.Send(reply);
}
}
[StsMessage(StsMessage.LoginFinish)]
public static void HandleAuthLoginFinish(StsPacket packet, StsSession session)
{
// Server packets are encrypted now.
session.ServerCrypt = new SARC4();
session.ServerCrypt.PrepareKey(session.SecureRemotePassword.SessionKey);
var reply = new StsPacket(StsReason.OK, packet.Header.Sequence);
var xmlData = new XmlData();
xmlData.WriteElementRoot("Reply");
xmlData.WriteElement("LocationId", "");
xmlData.WriteElement("UserId", session.Account.Id.ToString());
xmlData.WriteElement("UserCenter", "");
xmlData.WriteElement("UserName", session.Account.LoginName);
xmlData.WriteElement("AccessMask", "");
xmlData.WriteElement("Roles", "");
xmlData.WriteElement("Status", "");
reply.WriteXmlData(xmlData);
session.Send(reply);
}
[StsMessage(StsMessage.RequestGameToken)]
public static void HandleAuthRequestGameToken(StsPacket packet, StsSession session)
{
if (DB.Auth.Update<Account>(a => a.Id == session.Account.Id, a => a.Online.Set(true)))
{
var reply = new StsPacket(StsReason.OK, packet.Header.Sequence);
var xmlData = new XmlData();
xmlData.WriteElementRoot("Reply");
xmlData.WriteElement("Token", "");
reply.WriteXmlData(xmlData);
session.Send(reply);
}
else
session.Dispose();
}
}
}
| {
"content_hash": "7ecee1685bc8eff2ae9cfe0e75d5096f",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 124,
"avg_line_length": 36.30263157894737,
"alnum_prop": 0.5953243928959768,
"repo_name": "Captain-Ice/Project-WildStar",
"id": "42d00ea6527e73da99060db1751bfa105ce28db2",
"size": "5520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Projects/StsServer/Network/Packets/Handlers/StsHandler.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "102063"
}
],
"symlink_target": ""
} |
package allsimplebridges;
import static com.google.j2cl.integration.testing.Asserts.assertTrue;
public class Tester897 {
@SuppressWarnings("unchecked")
static class C1 {
C1() {}
@SuppressWarnings("MissingOverride")
public String get(Object value) {
return "C1.get";
}
@SuppressWarnings("MissingOverride")
public String get(String value) {
return "C1.get";
}
}
@SuppressWarnings("unchecked")
public static void test() {
C1 s = new C1();
assertTrue(s.get(new Object()).equals("C1.get"));
assertTrue(s.get("").equals("C1.get"));
}
}
| {
"content_hash": "73fdebd90d27988805a3d7d3d7bb21d1",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 69,
"avg_line_length": 22.185185185185187,
"alnum_prop": 0.6527545909849749,
"repo_name": "google/j2cl",
"id": "84a450086b01a502ed1edeb5b1051fef7395e50d",
"size": "1194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "transpiler/javatests/com/google/j2cl/integration/java/allsimplebridges/Tester897.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9170080"
},
{
"name": "JavaScript",
"bytes": "133627"
},
{
"name": "Kotlin",
"bytes": "152617"
},
{
"name": "Python",
"bytes": "29340"
},
{
"name": "Shell",
"bytes": "7548"
},
{
"name": "Starlark",
"bytes": "352448"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "9eee895e1959465419b3529c42f0ed17",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "6c5cea4358b27f22094ed259270165ba84fe85b6",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Zingiberaceae/Amomum/Amomum maximum/ Syn. Amomum dealbatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Krifollk\CodeGenerator\Model\Generator;
use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
use Krifollk\CodeGenerator\Model\CodeTemplate\Engine;
use Krifollk\CodeGenerator\Model\MethodInjector;
use Krifollk\CodeGenerator\Model\ModuleNameEntity;
/**
* Class PluginGenerator
*
* @package Krifollk\CodeGenerator\Model\Generator
*/
class PluginGenerator extends AbstractGenerator
{
const DEFAULT_CLASS_NAME_PATTERN = '\%s\Plugin\%s';
/** @var \Krifollk\CodeGenerator\Model\MethodInjector */
private $methodInjector;
/** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
private $codeTemplateEngine;
/**
* PluginGenerator constructor.
*
* @param \Krifollk\CodeGenerator\Model\MethodInjector $methodInjector
* @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
*/
public function __construct(MethodInjector $methodInjector, Engine $codeTemplateEngine)
{
$this->methodInjector = $methodInjector;
$this->codeTemplateEngine = $codeTemplateEngine;
}
/**
* @param \Krifollk\CodeGenerator\Model\ModuleNameEntity $moduleNameEntity
* @param string $interceptedClassName
*
* @return string
*/
public static function generateDefaultPluginName(
ModuleNameEntity $moduleNameEntity,
string $interceptedClassName
): string {
return sprintf(
self::DEFAULT_CLASS_NAME_PATTERN,
$moduleNameEntity->asPartOfNamespace(),
trim($interceptedClassName, '\\')
);
}
/**
* @inheritdoc
*/
protected function requiredArguments(): array
{
return ['methods', 'interceptedClassName'];
}
/**
* @inheritdoc
* @throws \RuntimeException
* @throws \ReflectionException
*/
protected function internalGenerate(
ModuleNameEntity $moduleNameEntity,
array $additionalArguments = []
): GeneratorResultInterface {
/** @var \Krifollk\CodeGenerator\Model\Command\Plugin\Method[] $methods */
$methods = $additionalArguments['methods'];
$pluginClass = $additionalArguments['pluginClass'];
$interceptedClassName = $additionalArguments['interceptedClassName'];
$pluginFullClassName = $this->generatePluginFullClassName(
$moduleNameEntity,
$pluginClass,
$interceptedClassName
);
$interceptors = '';
$reflectionClass = new \ReflectionClass($interceptedClassName);
foreach ($methods as $method) {
$methodName = ucfirst($method->getMethodName());
$methodParameters = $reflectionClass->getMethod($method->getMethodName())->getParameters();
$parameters = '';
foreach ($methodParameters as $parameter) {
if ($parameter->getType() === null) {
$parameters .= sprintf(
', $%s%s',
$parameter->getName(),
$this->prepareDefaultParameterValue($parameter, $interceptedClassName)
);
continue;
}
$parameters .= sprintf(
', %s%s $%s%s',
$parameter->getType()->isBuiltin() ? '' : '\\',//Add back slash to class
$parameter->getType(),
$parameter->getName(),
$this->prepareDefaultParameterValue($parameter, $interceptedClassName)
);
}
if ($method->isRequireBeforeInterceptor()) {
$interceptors .= $this->codeTemplateEngine->render('plugin/before_method', [
'methodName' => $methodName,
'subject' => $interceptedClassName,
'arguments' => count($methodParameters) > 0 ? $parameters : ''
]);
$interceptors .= "\n";
}
if ($method->isRequireAroundInterceptor()) {
$interceptors .= $this->codeTemplateEngine->render('plugin/around_method', [
'methodName' => $methodName,
'subject' => $interceptedClassName,
'arguments' => count($methodParameters) > 0 ? $parameters : ''
]);
$interceptors .= "\n";
}
if ($method->isRequireAfterInterceptor()) {
$interceptors .= $this->codeTemplateEngine->render('plugin/after_method', [
'methodName' => $methodName,
'subject' => $interceptedClassName,
'arguments' => ''//TODO in magento 2.2 we can pass arguments to after interceptor
]);
$interceptors .= "\n";
}
}
list($shortClassName, $namespace) = $this->extractShortClassNameAndNamespace($pluginFullClassName);
$content = $this->generatePluginContent($namespace, $shortClassName, $interceptors, $pluginFullClassName);
$destinationFile = sprintf('%s.php', str_replace('\\', '/', trim($pluginFullClassName, '\\')));
return new \Krifollk\CodeGenerator\Model\GeneratorResult(
$content,
$destinationFile,
$pluginFullClassName
);
}
private function generatePluginFullClassName(
ModuleNameEntity $moduleNameEntity,
string $pluginClass,
string $interceptedClassName
): string {
if ($pluginClass === '') {
return self::generateDefaultPluginName($moduleNameEntity, $interceptedClassName);
}
return sprintf('\%s\%s', $moduleNameEntity->asPartOfNamespace(), $pluginClass);
}
/**
* @throws \ReflectionException
* @throws \RuntimeException
*/
private function generatePluginContent(
string $namespace,
string $shortClassName,
string $interceptors,
string $pluginFullClassName
): string {
if (class_exists($pluginFullClassName)) {
$pluginReflectionClass = new \ReflectionClass($pluginFullClassName);
$content = file_get_contents($pluginReflectionClass->getFileName());
$content = $this->methodInjector->inject($content, $interceptors);
return $content;
}
$content = $this->codeTemplateEngine->render('plugin/class', [
'namespace' => $namespace,
'className' => $shortClassName,
'interceptors' => $interceptors
]);
return $content;
}
private function prepareDefaultParameterValue(\ReflectionParameter $parameter, string $interceptedClass): string
{
$value = '';
if (!$parameter->isDefaultValueAvailable()) {
return $value;
}
$pattern = ' = %s';
if ($parameter->isDefaultValueConstant()) {
if (strpos($parameter->getDefaultValueConstantName(), 'self::') !== false) {
return sprintf(
$pattern,
str_replace('self::', $interceptedClass . '::', $parameter->getDefaultValueConstantName())
);
}
return sprintf($pattern, '\\' . $parameter->getDefaultValueConstantName());
}
return sprintf($pattern, var_export($parameter->getDefaultValue(), true));
}
private function extractShortClassNameAndNamespace(string $pluginFullClassName): array
{
$explodedClassName = explode('\\', $pluginFullClassName);
$shortClassName = array_pop($explodedClassName);
$namespace = trim(implode('\\', $explodedClassName), '\\');
return [$shortClassName, $namespace];
}
}
| {
"content_hash": "6594943345a76d6a9b5fa0966655866d",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 116,
"avg_line_length": 35.211711711711715,
"alnum_prop": 0.5818088780862223,
"repo_name": "Krifollk/magento-code-generator",
"id": "56de53a8361d8fdfd36bfb951ebb2a4cb48aea11",
"size": "8058",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "Model/Generator/PluginGenerator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "139927"
}
],
"symlink_target": ""
} |
Ao abrir um pull request nesse repositório, você concorda em fornecer seu trabalho sob a [licença do projeto](LICENSE).
## Inclusão e exclusão de eventos
> Se você não estiver familiarizado com o GitHub, este [guia de fluxo (flow guide)](https://guides.github.com/introduction/flow/) pode ser útil.
Os eventos atualmente estão listados no arquivo [javascripts/events.js](javascripts/events.js).
A estrutura de um evento é a seguinte:
```javascript
{
titulo : "como o evento vai aparecer no Saia de Casa!",
dataInicio : "no formato -> 2015-09-22",
dataFim : "no formato -> 2015-09-22",
local : "nome do local onde o evento acontece",
endereco : "endereço de onde o evento acontece, tente ser o mais completo possível",
embed_link : "link do mapa do Google Maps, ajuda aqui: http://goo.gl/PxxQHo",
localizacao : { latitude: -25.2218113 , longitude: -54.3462431 },
link : "link da página do evento"
},
```
Fora as erratas (que encorajamos que você nos encaminhe logo que perceber um problema), as duas contribuições padrão que o projeto espera receber são as seguintes:
- inclusão de novos eventos
- exclusão de eventos passados
E aqui a regra de ouro para a sua contribuição:
- cada inclusão de evento **DEVE** ser colocada em um Pull Request (PR) exclusivo
- todas as exclusões **PODEM** ser colocadas juntas em um único Pull Request
Isso facilita a análise e posterior aceitação de seus Pull Requests, ok?
## Grandes Reescritas
Abra uma issue para discussão antes de começar. Assim, podemos escutar o que você tem a dizer, e podemos fornecer um encaminhamento se valerá a pena mudar grandes partes do projeto.
| {
"content_hash": "ac1edcaac7e3623d1cbc9157dcae150d",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 182,
"avg_line_length": 43.15384615384615,
"alnum_prop": 0.7302436125965538,
"repo_name": "renanmpimentel/saiadecasa.github.io",
"id": "dfc233d5318cc325570e28e474a37da47fc9b9cc",
"size": "1765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CONTRIBUTING.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "15419"
},
{
"name": "HTML",
"bytes": "5333"
},
{
"name": "JavaScript",
"bytes": "10155"
}
],
"symlink_target": ""
} |
package com.google.cloud;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.MoreObjects;
import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* This class represents options for methods that wait for changes in the status of a resource.
*/
public abstract class WaitForOption implements Serializable {
private static final long serialVersionUID = 8443451708032349243L;
private final OptionType optionType;
enum OptionType {
CHECKING_PERIOD,
TIMEOUT
}
private WaitForOption(OptionType optionType) {
this.optionType = optionType;
}
/**
* This class represents an option to set how frequently the resource status should be checked.
* Objects of this class keep the actual period and related time unit for the checking period.
*/
public static final class CheckingPeriod extends WaitForOption {
private static final long serialVersionUID = -2481062893220539210L;
private static final CheckingPeriod DEFAULT = new CheckingPeriod(500, TimeUnit.MILLISECONDS);
private final long period;
private final TimeUnit unit;
private CheckingPeriod(long period, TimeUnit unit) {
super(OptionType.CHECKING_PERIOD);
this.period = period;
this.unit = unit;
}
/**
* Returns the checking period.
*/
public long period() {
return period;
}
/**
* Returns the time unit for {@link #period()}.
*/
public TimeUnit unit() {
return unit;
}
/**
* Blocks the current thread for the amount of time specified by this object.
*
* @throws InterruptedException if the current thread was interrupted
*/
public void sleep() throws InterruptedException {
unit.sleep(period);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || !(obj instanceof CheckingPeriod)) {
return false;
}
CheckingPeriod other = (CheckingPeriod) obj;
return baseEquals(other)
&& Objects.equals(period, other.period)
&& Objects.equals(unit, other.unit);
}
@Override
public int hashCode() {
return Objects.hash(baseHashCode(), period, unit);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("period", period)
.add("unit", unit)
.toString();
}
/**
* Returns the {@code CheckingPeriod} option specified in {@code options}. If no
* {@code CheckingPeriod} could be found among {@code options}, the default checking period (500
* milliseconds) is used.
*/
public static CheckingPeriod getOrDefault(WaitForOption... options) {
return getOrDefaultInternal(OptionType.CHECKING_PERIOD, DEFAULT, options);
}
}
/**
* This class represents an option to set the maximum time to wait for the resource's status to
* reach the desired state.
*/
public static final class Timeout extends WaitForOption {
private static final long serialVersionUID = -7120401111985321932L;
private static final Timeout DEFAULT = new Timeout(-1);
private final long timeoutMillis;
private Timeout(long timeoutMillis) {
super(OptionType.TIMEOUT);
this.timeoutMillis = timeoutMillis;
}
/**
* Returns the timeout in milliseconds.
*/
public long timeoutMillis() {
return timeoutMillis;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || !(obj instanceof Timeout)) {
return false;
}
Timeout other = (Timeout) obj;
return baseEquals(other) && Objects.equals(timeoutMillis, other.timeoutMillis);
}
@Override
public int hashCode() {
return Objects.hash(baseHashCode(), timeoutMillis);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("timeoutMillis", timeoutMillis)
.toString();
}
/**
* Returns the {@code Timeout} option specified in {@code options}. If no {@code Timeout} could
* be found among {@code options}, no timeout will be used.
*/
public static Timeout getOrDefault(WaitForOption... options) {
return getOrDefaultInternal(OptionType.TIMEOUT, DEFAULT, options);
}
}
OptionType optionType() {
return optionType;
}
final boolean baseEquals(WaitForOption option) {
return Objects.equals(option.optionType, option.optionType);
}
final int baseHashCode() {
return Objects.hash(optionType);
}
@SuppressWarnings("unchecked")
private static <T extends WaitForOption> T getOrDefaultInternal(OptionType optionType,
T defaultValue, WaitForOption... options) {
T foundOption = null;
for (WaitForOption option : options) {
if (option.optionType.equals(optionType)) {
checkArgument(foundOption == null, "Duplicate option %s", option);
foundOption = (T) option;
}
}
return foundOption != null ? foundOption : defaultValue;
}
/**
* Returns an option to set how frequently the resource status should be checked.
*
* @param checkEvery the checking period
* @param unit the time unit of the checking period
*/
public static CheckingPeriod checkEvery(long checkEvery, TimeUnit unit) {
checkArgument(checkEvery >= 0, "checkEvery must be >= 0");
return new CheckingPeriod(checkEvery, unit);
}
/**
* Returns an option to set the maximum time to wait.
*
* @param timeout the maximum time to wait, expressed in {@code unit}
* @param unit the time unit of the timeout
*/
public static Timeout timeout(long timeout, TimeUnit unit) {
checkArgument(timeout >= 0, "timeout must be >= 0");
return new Timeout(unit.toMillis(timeout));
}
}
| {
"content_hash": "e959c4211ecb2697790c9ca8632eae2f",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 100,
"avg_line_length": 28.10900473933649,
"alnum_prop": 0.6661608497723824,
"repo_name": "tangiel/google-cloud-java",
"id": "8af7a074ab4db6b2209ca55bc2fec6e7b2c75e02",
"size": "6548",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "google-cloud-core/src/main/java/com/google/cloud/WaitForOption.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "23036"
},
{
"name": "HTML",
"bytes": "13784"
},
{
"name": "Java",
"bytes": "6416496"
},
{
"name": "JavaScript",
"bytes": "989"
},
{
"name": "Python",
"bytes": "14898"
},
{
"name": "Shell",
"bytes": "8124"
}
],
"symlink_target": ""
} |
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Renderer/Public/Resource/Material/MaterialProperties.h"
#include <algorithm>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
const MaterialProperty* MaterialProperties::getPropertyById(MaterialPropertyId materialPropertyId) const
{
SortedPropertyVector::const_iterator iterator = std::lower_bound(mSortedPropertyVector.cbegin(), mSortedPropertyVector.cend(), materialPropertyId, detail::OrderByMaterialPropertyId());
return (iterator != mSortedPropertyVector.end() && iterator->getMaterialPropertyId() == materialPropertyId) ? &(*iterator) : nullptr;
}
MaterialProperty* MaterialProperties::setPropertyById(MaterialPropertyId materialPropertyId, const MaterialPropertyValue& materialPropertyValue, MaterialProperty::Usage materialPropertyUsage, bool changeOverwrittenState)
{
// Check whether or not this is a new property or a property value change
SortedPropertyVector::iterator iterator = std::lower_bound(mSortedPropertyVector.begin(), mSortedPropertyVector.end(), materialPropertyId, detail::OrderByMaterialPropertyId());
if (iterator == mSortedPropertyVector.end() || iterator->getMaterialPropertyId() != materialPropertyId)
{
// Add new material property
iterator = mSortedPropertyVector.insert(iterator, MaterialProperty(materialPropertyId, materialPropertyUsage, materialPropertyValue));
if (changeOverwrittenState)
{
MaterialProperty* materialProperty = &*iterator;
materialProperty->mOverwritten = true;
return materialProperty;
}
if (MaterialProperty::Usage::SHADER_COMBINATION == materialPropertyUsage)
{
++mShaderCombinationGenerationCounter;
}
return &*iterator;
}
// Update the material property value, in case there's a material property value change
else if (*iterator != materialPropertyValue)
{
// Sanity checks
ASSERT(iterator->getValueType() == materialPropertyValue.getValueType(), "Invalid value type")
ASSERT(MaterialProperty::Usage::UNKNOWN == materialPropertyUsage || materialPropertyUsage == iterator->getUsage(), "Invalid usage")
// Update the material property value
materialPropertyUsage = iterator->getUsage();
*iterator = MaterialProperty(materialPropertyId, materialPropertyUsage, materialPropertyValue);
if (MaterialProperty::Usage::SHADER_COMBINATION == materialPropertyUsage)
{
++mShaderCombinationGenerationCounter;
}
// Material property change detected
if (changeOverwrittenState)
{
MaterialProperty* materialProperty = &*iterator;
materialProperty->mOverwritten = true;
return materialProperty;
}
else
{
return &*iterator;
}
}
// No material property change detected
return nullptr;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
| {
"content_hash": "663024763cf91f48e03aa46541384f7a",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 221,
"avg_line_length": 40.04705882352941,
"alnum_prop": 0.6154524089306698,
"repo_name": "cofenberg/unrimp",
"id": "f9fec446f84e7824202ed657b9f4041bad51c3d9",
"size": "4632",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Renderer/Public/Resource/Material/MaterialProperties.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "520140"
},
{
"name": "C++",
"bytes": "9009630"
},
{
"name": "CMake",
"bytes": "106241"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("KwazyThreeDee.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KwazyThreeDee.Droid")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// 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")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| {
"content_hash": "86bced1bfe688e57bfcc39ad1544e131",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 84,
"avg_line_length": 37.794117647058826,
"alnum_prop": 0.7571984435797665,
"repo_name": "charlespetzold/xamarin-forms-samples",
"id": "c0019b6921dc48d13584462fce71042461b76871",
"size": "1288",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "KwazyThreeDee/KwazyThreeDee/KwazyThreeDee.Droid/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "484312"
},
{
"name": "F#",
"bytes": "44295"
}
],
"symlink_target": ""
} |
apetools.watchers.fileexpressionwatcher.BaseFileexpressionwatcher.connection
============================================================================
.. currentmodule:: apetools.watchers.fileexpressionwatcher
.. autoattribute:: BaseFileexpressionwatcher.connection | {
"content_hash": "b1528f131c6886d634431df8037cfc0c",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 76,
"avg_line_length": 45,
"alnum_prop": 0.6296296296296297,
"repo_name": "rsnakamura/oldape",
"id": "befd8696b1f2f9c694d750c18643acda5ec4e6f8",
"size": "270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apetools/watchers/api/apetools.watchers.fileexpressionwatcher.BaseFileexpressionwatcher.connection.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "5832"
},
{
"name": "Python",
"bytes": "1076570"
},
{
"name": "Shell",
"bytes": "47671"
}
],
"symlink_target": ""
} |
<!--
{% comment %}
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.
{% endcomment %}
-->
[](https://travis-ci.org/apache/calcite)
[](https://ci.appveyor.com/project/ApacheSoftwareFoundation/calcite)
# Apache Calcite
Apache Calcite is a dynamic data management framework.
For more details, see the [home page](http://calcite.apache.org).
| {
"content_hash": "2017ad0b275e0d6c2a9b53b9c6f994ca",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 182,
"avg_line_length": 47.46153846153846,
"alnum_prop": 0.7852512155591572,
"repo_name": "dindin5258/calcite",
"id": "67d27bf59e0f020f2982289c1763e45daacb2dd5",
"size": "1234",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3037"
},
{
"name": "CSS",
"bytes": "36560"
},
{
"name": "FreeMarker",
"bytes": "16065"
},
{
"name": "HTML",
"bytes": "28465"
},
{
"name": "Java",
"bytes": "15811546"
},
{
"name": "Kotlin",
"bytes": "1157"
},
{
"name": "Python",
"bytes": "1610"
},
{
"name": "Ruby",
"bytes": "1807"
},
{
"name": "Shell",
"bytes": "5326"
}
],
"symlink_target": ""
} |
namespace gw6cmessaging
{
// --------------------------------------------------------------------------
// Function : ServerMsgSender constructor
//
// Description:
// Will initialize a new ServerMsgSender object.
//
// Arguments: (none)
//
// Return values: (N/A)
//
// --------------------------------------------------------------------------
ServerMsgSender::ServerMsgSender( void )
{
}
// --------------------------------------------------------------------------
// Function : ServerMsgSender destructor
//
// Description:
// Will clean-up space allocated during object lifetime.
//
// Arguments: (none)
//
// Return values: (N/A)
//
// --------------------------------------------------------------------------
ServerMsgSender::~ServerMsgSender( void )
{
}
// --------------------------------------------------------------------------
// Function : Send_StatusInfo
//
// Description:
// Will send information on the status of the Gateway6 Client.
// A message is created with the information and posted to the send queue.
//
// Arguments:
// aStatusInfo: Gw6cStatusInfo* [in], The current state of the gateway6
// client.
//
// Return values: (none)
//
// --------------------------------------------------------------------------
void ServerMsgSender::Send_StatusInfo( const Gw6cStatusInfo* aStatusInfo )
{
Message* pMsg;
uint8_t pData[MSG_MAX_USERDATA];
unsigned int nDataLen = 0;
assert( aStatusInfo != NULL );
// Write client status to data buffer.
memcpy( pData, (void*)&(aStatusInfo->eStatus), sizeof(Gw6cCliStatus) );
nDataLen += sizeof(Gw6cCliStatus);
// Append status code to nStatus.
memcpy( pData + nDataLen, (void*)&(aStatusInfo->nStatus), sizeof(aStatusInfo->nStatus) );
nDataLen += sizeof(aStatusInfo->nStatus);
assert( nDataLen <= MSG_MAX_USERDATA ); // Buffer overflow has occured.
// Create Message
pMsg = Message::CreateMessage( MESSAGEID_STATUSINFO, nDataLen, pData );
assert( pMsg != NULL );
// Post the message.
PostMessage( pMsg );
}
// --------------------------------------------------------------------------
// Function : Send_TunnelInfo
//
// Description:
// Will send information on the established tunnel of the Gateway6 Client.
// A message is created with the information and posted to the send queue.
//
// Arguments: (none)
//
// Return values: (none)
//
// --------------------------------------------------------------------------
void ServerMsgSender::Send_TunnelInfo( const Gw6cTunnelInfo* aTunnelInfo )
{
Message* pMsg;
uint8_t pData[MSG_MAX_USERDATA];
uint16_t nDataLen = 0;
assert( aTunnelInfo != NULL );
// Append broker name to data buffer.
if( aTunnelInfo->szBrokerName ) {
memcpy( pData + nDataLen, aTunnelInfo->szBrokerName, strlen(aTunnelInfo->szBrokerName) + 1 );
nDataLen += (uint16_t)strlen(aTunnelInfo->szBrokerName) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append tunnel type to data buffer.
memcpy( pData + nDataLen, (void*)&(aTunnelInfo->eTunnelType), sizeof(Gw6cTunnelType) );
nDataLen += sizeof(Gw6cTunnelType);
// Append Local tunnel endpoint IPv4 address to data buffer.
if( aTunnelInfo->szIPV4AddrLocalEndpoint ) {
memcpy( pData + nDataLen, aTunnelInfo->szIPV4AddrLocalEndpoint, strlen(aTunnelInfo->szIPV4AddrLocalEndpoint) + 1 );
nDataLen += (uint16_t)strlen(aTunnelInfo->szIPV4AddrLocalEndpoint) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append Local tunnel endpoint IPv6 address to data buffer.
if( aTunnelInfo->szIPV6AddrLocalEndpoint ) {
memcpy( pData + nDataLen, aTunnelInfo->szIPV6AddrLocalEndpoint, strlen(aTunnelInfo->szIPV6AddrLocalEndpoint) + 1 );
nDataLen += (uint16_t)strlen(aTunnelInfo->szIPV6AddrLocalEndpoint) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append Remote tunnel endpoint IPv4 address to data buffer.
if( aTunnelInfo->szIPV4AddrRemoteEndpoint ) {
memcpy( pData + nDataLen, aTunnelInfo->szIPV4AddrRemoteEndpoint, strlen(aTunnelInfo->szIPV4AddrRemoteEndpoint) + 1 );
nDataLen += (uint16_t)strlen(aTunnelInfo->szIPV4AddrRemoteEndpoint) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append Remote tunnel endpoint IPv6 address to data buffer.
if( aTunnelInfo->szIPV6AddrRemoteEndpoint ) {
memcpy( pData + nDataLen, aTunnelInfo->szIPV6AddrRemoteEndpoint, strlen(aTunnelInfo->szIPV6AddrRemoteEndpoint) + 1 );
nDataLen += (uint16_t)strlen(aTunnelInfo->szIPV6AddrRemoteEndpoint) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append The delegated prefix to data buffer.
if( aTunnelInfo->szDelegatedPrefix ) {
memcpy( pData + nDataLen, aTunnelInfo->szDelegatedPrefix, strlen(aTunnelInfo->szDelegatedPrefix) + 1 );
nDataLen += (uint16_t)strlen(aTunnelInfo->szDelegatedPrefix) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append The delegated user domain to data buffer.
if( aTunnelInfo->szUserDomain ) {
memcpy( pData + nDataLen, aTunnelInfo->szUserDomain, strlen(aTunnelInfo->szUserDomain) + 1 );
nDataLen += (uint16_t)strlen(aTunnelInfo->szUserDomain) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append tunnel uptime to data buffer.
memcpy( pData + nDataLen, (void*)&(aTunnelInfo->tunnelUpTime), sizeof(time_t) );
nDataLen += sizeof(time_t);
assert( nDataLen <= MSG_MAX_USERDATA ); // Buffer overflow has occured.
// Create Message.
pMsg = Message::CreateMessage( MESSAGEID_TUNNELINFO, nDataLen, pData );
assert( pMsg != NULL );
// Post the message.
PostMessage( pMsg );
}
// --------------------------------------------------------------------------
// Function : Send_BrokerList
//
// Description:
// Will send a list of brokers.
// A message is created with the information and posted to the send queue.
//
// Arguments:
// aBrokerList: Gw6cBrokerList* [IN], The list of broker names.
//
// Return values: (none)
//
// --------------------------------------------------------------------------
void ServerMsgSender::Send_BrokerList( const Gw6cBrokerList* aBrokerList )
{
Message* pMsg;
uint8_t pData[MSG_MAX_USERDATA];
Gw6cBrokerList* list = (Gw6cBrokerList*)aBrokerList;
unsigned int nDataLen = 0;
assert( aBrokerList != NULL );
// Loop until the list is empty.
do
{
// Append broker name to data buffer.
if( list->szAddress ) {
memcpy( pData + nDataLen, list->szAddress, strlen(list->szAddress) + 1 );
nDataLen += (uint16_t)strlen(list->szAddress) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append distance
memcpy( pData + nDataLen, (void*)&(list->nDistance), sizeof(int) );
nDataLen += sizeof(int);
assert( nDataLen <= MSG_MAX_USERDATA ); // Buffer overflow occured.
} while( (list = list->next) != NULL );
// Create Message.
pMsg = Message::CreateMessage( MESSAGEID_BROKERLIST, nDataLen, pData );
assert( pMsg != NULL );
// Post the message.
PostMessage( pMsg );
}
// --------------------------------------------------------------------------
// Function : Send_HAP6StatusInfo
//
// Description:
// Will send the HAP6 Status Info.
// A message is created with the information and posted to the send queue.
//
// Arguments:
// aHAP6StatusInfo: HAP6StatusInfo* [IN], The HAP6 Status info.
//
// Return values: (none)
//
// --------------------------------------------------------------------------
void ServerMsgSender::Send_HAP6StatusInfo( const HAP6StatusInfo* aHAP6StatusInfo )
{
Message* pMsg;
uint8_t pData[MSG_MAX_USERDATA];
PMAPPING_STATUS list = aHAP6StatusInfo->hap6_devmap_statuses;
unsigned int nDataLen = 0;
assert( aHAP6StatusInfo != NULL );
// Insert HAP6 features statuses (web, proxy, DMM).
// Append HAP6 proxying status
memcpy( pData + nDataLen, (void*)&(aHAP6StatusInfo->hap6_proxy_status), sizeof(HAP6FeatStts) );
nDataLen += sizeof(HAP6FeatStts);
// Append HAP6 web service status
memcpy( pData + nDataLen, (void*)&(aHAP6StatusInfo->hap6_web_status), sizeof(HAP6FeatStts) );
nDataLen += sizeof(HAP6FeatStts);
// Append Device Mapping Module status
memcpy( pData + nDataLen, (void*)&(aHAP6StatusInfo->hap6_devmapmod_status), sizeof(HAP6FeatStts) );
nDataLen += sizeof(HAP6FeatStts);
// Append the device mapping statuses.
if( list != NULL )
{
do
{
// Append device name to data buffer.
if( list->device_name ) {
memcpy( pData + nDataLen, list->device_name, strlen(list->device_name) + 1 );
nDataLen += (uint16_t)strlen(list->device_name) + 1;
}
else {
memset( pData + nDataLen, 0x00, 1 );
++nDataLen;
}
// Append mapping status
memcpy( pData + nDataLen, (void*)&(list->mapping_status), sizeof(HAP6DevMapStts) );
nDataLen += sizeof(HAP6DevMapStts);
assert( nDataLen <= MSG_MAX_USERDATA ); // Buffer overflow occured.
} while( (list = list->next) != NULL );
}
// Create Message.
pMsg = Message::CreateMessage( MESSAGEID_HAP6STATUSINFO, nDataLen, pData );
assert( pMsg != NULL );
// Post the message.
PostMessage( pMsg );
}
} // namespace
| {
"content_hash": "ca62d135a059245b63143364841cb5ff",
"timestamp": "",
"source": "github",
"line_count": 323,
"max_line_length": 121,
"avg_line_length": 28.928792569659443,
"alnum_prop": 0.606806506849315,
"repo_name": "h4ck3rm1k3/gw6c-debian",
"id": "3386c60792028294047bd8bacebdb7d04f8b12a2",
"size": "9962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gw6c-messaging/src/servermsgsender.cc",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "519228"
},
{
"name": "C++",
"bytes": "265702"
},
{
"name": "Shell",
"bytes": "56372"
}
],
"symlink_target": ""
} |
Project in DH2642 built in React Native. By Johan Kasperi and Daniel Lindström
| {
"content_hash": "03ba1e8c9468ed6fd5fe9a78afc1eb2e",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 78,
"avg_line_length": 79,
"alnum_prop": 0.8227848101265823,
"repo_name": "johankasperi/VilkenUppgang",
"id": "cbc553ea7d3c48d661122db4b09d6bfb138bf5aa",
"size": "96",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1289"
},
{
"name": "JavaScript",
"bytes": "57761"
},
{
"name": "Objective-C",
"bytes": "5141"
}
],
"symlink_target": ""
} |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using HETSAPI;
using HETSAPI.Models;
using System.Reflection;
namespace HETSAPI.Test
{
/// <summary>
/// Class for testing the model TimeRecord
/// </summary>
public class TimeRecordModelTests
{
private readonly TimeRecord instance;
/// <summary>
/// Setup the test.
/// </summary>
public TimeRecordModelTests()
{
instance = new TimeRecord();
}
/// <summary>
/// Test an instance of TimeRecord
/// </summary>
[Fact]
public void TimeRecordInstanceTest()
{
Assert.IsType<TimeRecord>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
Assert.IsType<int>(instance.Id);
}
/// <summary>
/// Test the property 'RentalAgreement'
/// </summary>
[Fact]
public void RentalAgreementTest()
{
// TODO unit test for the property 'RentalAgreement'
Assert.True(true);
}
/// <summary>
/// Test the property 'WorkedDate'
/// </summary>
[Fact]
public void WorkedDateTest()
{
// TODO unit test for the property 'WorkedDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'EnteredDate'
/// </summary>
[Fact]
public void EnteredDateTest()
{
// TODO unit test for the property 'EnteredDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'Hours'
/// </summary>
[Fact]
public void HoursTest()
{
// TODO unit test for the property 'Hours'
Assert.True(true);
}
/// <summary>
/// Test the property 'Rate'
/// </summary>
[Fact]
public void RateTest()
{
// TODO unit test for the property 'Rate'
Assert.True(true);
}
/// <summary>
/// Test the property 'Hours2'
/// </summary>
[Fact]
public void Hours2Test()
{
// TODO unit test for the property 'Hours2'
Assert.True(true);
}
/// <summary>
/// Test the property 'Rate2'
/// </summary>
[Fact]
public void Rate2Test()
{
// TODO unit test for the property 'Rate2'
Assert.True(true);
}
/// <summary>
/// Test the property 'Hours3'
/// </summary>
[Fact]
public void Hours3Test()
{
// TODO unit test for the property 'Hours3'
Assert.True(true);
}
/// <summary>
/// Test the property 'Rate3'
/// </summary>
[Fact]
public void Rate3Test()
{
// TODO unit test for the property 'Rate3'
Assert.True(true);
}
}
}
| {
"content_hash": "83b548ac73fe0568a6cd8fd17795c2b5",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 467,
"avg_line_length": 25.979166666666668,
"alnum_prop": 0.5388933440256616,
"repo_name": "swcurran/hets",
"id": "0871c886c3c6f26f28f03d9bec075eaba9c68e83",
"size": "3741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Server/test/Models/TimeRecordTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9606"
},
{
"name": "C#",
"bytes": "4385863"
},
{
"name": "CSS",
"bytes": "66260"
},
{
"name": "Groovy",
"bytes": "25186"
},
{
"name": "HTML",
"bytes": "980461"
},
{
"name": "JavaScript",
"bytes": "649052"
},
{
"name": "PLpgSQL",
"bytes": "51570"
},
{
"name": "Python",
"bytes": "4784"
},
{
"name": "Shell",
"bytes": "18040"
}
],
"symlink_target": ""
} |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "ET002:Namespace does not match file path or default namespace", Justification = "It should be visible globally without unecessary includes", Scope = "namespace", Target = "~N:QueryBuilder")]
| {
"content_hash": "3e579e1d9f4b5ee49698de2256820d3e",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 260,
"avg_line_length": 64.125,
"alnum_prop": 0.7738791423001949,
"repo_name": "Machet/SqlQueryBuilder",
"id": "a44485b0793eb1c9f56d81e2edc5365028642511",
"size": "515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SqlQueryBuilder/GlobalSuppressions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "84904"
}
],
"symlink_target": ""
} |
// Consider both sides of branches
/*
{
"env.diffuseColor": "color",
"env.diffuseColor2": "color",
"env.specularColor1": "color",
"env.specularColor2": "color",
"env.normal": "normal"
}
*/
function shade(env) {
var diffuseColor = env.diffuseColor || env.diffuseColor2;
var specularColor;
if (env.bool) {
specularColor = env.specularColor1;
} else {
specularColor = env.specularColor2;
}
var normal = env.normal || new Vec3(1);
return new Shade().diffuse(diffuseColor, env.normal).phong(specularColor, normal);
}
| {
"content_hash": "80201f8e07bf7f63005f8e41098a63fb",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 86,
"avg_line_length": 27.476190476190474,
"alnum_prop": 0.6412478336221837,
"repo_name": "xml3d/shade.js",
"id": "496e071310d28b4f62595c48367bb5b2b9ccabae",
"size": "577",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "test/data/semantics/branches.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1041187"
}
],
"symlink_target": ""
} |
<?php
/**
* Zend_Http_Client
*/
require_once 'Zend/Http/Client.php';
/**
* @category Zend
* @package Zend_Service
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Service_Abstract
{
/**
* HTTP Client used to query all web services
*
* @var Zend_Http_Client
*/
protected static $_httpClient = null;
/**
* Sets the HTTP client object to use for retrieving the feeds. If none
* is set, the default Zend_Http_Client will be used.
*
* @param Zend_Http_Client $httpClient
*/
final public static function setHttpClient(Zend_Http_Client $httpClient)
{
self::$_httpClient = $httpClient;
}
/**
* Gets the HTTP client object.
*
* @return Zend_Http_Client
*/
final public static function getHttpClient()
{
if (!self::$_httpClient instanceof Zend_Http_Client) {
self::$_httpClient = new Zend_Http_Client();
}
return self::$_httpClient;
}
}
| {
"content_hash": "35ace0231927a0bbdd4cc62fa8d01459",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 87,
"avg_line_length": 21.452830188679247,
"alnum_prop": 0.6024626209322779,
"repo_name": "jodier/tmpdddf",
"id": "30a82a69fd43da61f21730f4189f58b1320c81ec",
"size": "1894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/private/tine20/library/Zend/Service/Abstract.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "44010"
},
{
"name": "Perl",
"bytes": "794"
},
{
"name": "Shell",
"bytes": "286"
}
],
"symlink_target": ""
} |
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide a memory manager that manages an external buffer.
//
//@CLASSES:
// bdlma::BufferManager: memory manager that manages an external buffer
//
//@SEE_ALSO: bdlma_bufferimputil, bdlma_bufferedsequentialallocator
//
//@DESCRIPTION: This component provides a memory manager ("buffer manager"),
// 'bdlma::BufferManager', that dispenses heterogeneous memory blocks (of
// varying, user-specified sizes) from an external buffer. A 'BufferManager'
// has a similar interface to a sequential pool in that the two methods
// 'allocate' and 'release' are provided.
//
// In addition to the 'allocate' method, a less safe but faster variation,
// 'allocateRaw', is provided to support memory allocation: If there is
// insufficient memory remaining in the buffer to satisfy an allocation
// request, 'allocate' will return 0 while 'allocateRaw' will result in
// undefined behavior.
//
// The behavior of 'allocate' and 'allocateRaw' illustrates the main difference
// between this buffer manager and a sequential pool. Once the external buffer
// runs out of memory, the buffer manager does not self-replenish, whereas a
// sequential pool will do so.
//
// The 'release' method resets the buffer manager such that the memory within
// the entire external buffer will be made available for subsequent
// allocations. Note that individually allocated memory blocks cannot be
// separately deallocated.
//
// 'bdlma::BufferManager' is typically used for fast and efficient memory
// allocation, when the user knows in advance the maximum amount of memory
// needed.
//
///Usage
///-----
// Suppose that we need to detect whether there are at least 'n' duplicates
// within an array of integers. Furthermore, suppose that speed is a concern
// and we need the fastest possible implementation. A natural solution will be
// to use a hash table. To further optimize for speed, we can use a custom
// memory manager, such as 'bdlma::BufferManager', to speed up memory
// allocations.
//
// First, let's define the structure of a node inside our custom hash table
// structure:
//..
// struct my_Node {
// // This struct represents a node within a hash table.
//
// // DATA
// int d_value; // integer value this node holds
// int d_count; // number of occurrences of this integer value
// my_Node *d_next_p; // pointer to the next node
//
// // CREATORS
// my_Node(int value, my_Node *next);
// // Create a node having the specified 'value' that refers to the
// // specified 'next' node.
// };
//
// // CREATORS
// my_Node::my_Node(int value, my_Node *next)
// : d_value(value)
// , d_count(1)
// , d_next_p(next)
// {
// }
//..
// Note that 'sizeof(my_Node) == 12' when compiled in 32-bit mode, and
// 'sizeof(my_Node) == 16' when compiled in 64-bit mode. This difference
// affects the amount of memory used under different alignment strategies (see
// 'bsls_alignment' for more details on alignment strategies).
//
// We can then define the structure of our specialized hash table used for
// integer counting:
//..
// class my_IntegerCountingHashTable {
// // This class represents a hash table that is used to keep track of the
// // number of occurrences of various integers. Note that this is a
// // highly specialized class that uses a 'bdlma::BufferManager' with
// // sufficient memory for memory allocations.
//
// // DATA
// my_Node **d_nodeArray; // array of 'my_Node' pointers
//
// int d_size; // size of the node array
//
// bdlma::BufferManager *d_buffer; // buffer manager (held, not
// // owned)
//
// public:
// // CLASS METHODS
// static int calculateBufferSize(int tableLength, int numNodes);
// // Return the memory required by a 'my_IntegerCountingHashTable'
// // that has the specified 'tableLength' and 'numNodes'.
//
// // CREATORS
// my_IntegerCountingHashTable(int size, bdlma::BufferManager *buffer);
// // Create a hash table of the specified 'size', using the specified
// // 'buffer' to supply memory. The behavior is undefined unless
// // '0 < size', 'buffer' is non-zero, and 'buffer' has sufficient
// // memory to support all memory allocations required.
//
// // ...
//
// // MANIPULATORS
// int insert(int value);
// // Insert the specified 'value' with a count of 1 into this hash
// // table if 'value' does not currently exist in the hash table, and
// // increment the count for 'value' otherwise. Return the number of
// // occurrences of 'value' in this hash table.
//
// // ...
// };
//..
// The implementation of the rest of 'my_IntegerCountingHashTable' is elided as
// the class method 'calculateBufferSize', constructor, and the 'insert' method
// alone are sufficient to illustrate the use of 'bdlma::BufferManager':
//..
// // CLASS METHODS
// int my_IntegerCountingHashTable::calculateBufferSize(int tableLength,
// int numNodes)
// {
// return static_cast<int>(tableLength * sizeof(my_Node *)
// + numNodes * sizeof(my_Node)
// + bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT);
// }
//..
// Note that, in case the allocated buffer is not aligned, the size calculation
// includes a "fudge" factor equivalent to the maximum alignment requirement of
// the platform.
//..
// // CREATORS
// my_IntegerCountingHashTable::my_IntegerCountingHashTable(
// int size,
// bdlma::BufferManager *buffer)
// : d_size(size)
// , d_buffer(buffer)
// {
// // 'd_buffer' must have sufficient memory to satisfy the allocation
// // request (as specified by the constructor's contract).
//
// d_nodeArray = static_cast<my_Node **>(
// d_buffer->allocate(d_size * sizeof(my_Node *)));
//
// bsl::memset(d_nodeArray, 0, d_size * sizeof(my_Node *));
// }
//
// // MANIPULATORS
// int my_IntegerCountingHashTable::insert(int value)
// {
// // Naive hash function using only mod.
//
// const int hashValue = value % d_size;
// my_Node **tmp = &d_nodeArray[hashValue];
//
// while (*tmp) {
// if ((*tmp)->d_value != value) {
// tmp = &((*tmp)->d_next_p);
// }
// else {
// return ++((*tmp)->d_count); // RETURN
// }
// }
//
// // 'allocate' does not trigger dynamic memory allocation. Therefore,
// // we don't have to worry about exceptions and can use placement 'new'
// // directly with 'allocate'. 'd_buffer' must have sufficient memory to
// // satisfy the allocation request (as specified by the constructor's
// // contract).
//
// *tmp = new(d_buffer->allocate(sizeof(my_Node))) my_Node(value, *tmp);
//
// return 1;
// }
//..
// Note that 'bdlma::BufferManager' is used to allocate memory blocks of
// heterogeneous sizes. In the constructor, memory is allocated for the node
// array. In 'insert', memory is allocated for the nodes.
//
// Finally, in the following 'detectNOccurrences' function, we can use the hash
// table class to detect whether any integer value occurs at least 'n' times
// within a specified array:
//..
// bool detectNOccurrences(int n, const int *array, int length)
// // Return 'true' if any integer value in the specified 'array' having
// // the specified 'length' appears at least the specified 'n' times, and
// // 'false' otherwise.
// {
// const int MAX_SIZE = my_IntegerCountingHashTable::
// calculateBufferSize(length, length);
//..
// We then allocate an external buffer to be used by 'bdlma::BufferManager'.
// Normally, this buffer will be created on the program stack if we know the
// length in advance (for example, if we specify in the contract of this
// function that we only handle arrays having a length of up to 10,000
// integers). However, to make this function more general, we decide to
// allocate the memory dynamically. This approach is still much more efficient
// than using the default allocator, say, to allocate memory for individual
// nodes within 'insert', since we need only a single dynamic allocation,
// versus separate dynamic allocations for every single node:
//..
// bslma::Allocator *allocator = bslma::Default::defaultAllocator();
// char *buffer = static_cast<char *>(allocator->allocate(MAX_SIZE));
//..
// We use a 'bslma::DeallocatorGuard' to automatically deallocate the buffer
// when the function ends:
//..
// bslma::DeallocatorGuard<bslma::Allocator> guard(buffer, allocator);
//
// bdlma::BufferManager bufferManager(buffer, MAX_SIZE);
// my_IntegerCountingHashTable table(length, &bufferManager);
//
// while (--length >= 0) {
// if (n == table.insert(array[length])) {
// return true; // RETURN
// }
// }
//
// return false;
// }
//..
// Note that the calculation of 'MAX_SIZE' assumes natural alignment. If
// maximum alignment is used instead, a larger buffer is needed since each node
// object will then be maximally aligned, which takes up 16 bytes each instead
// of 12 bytes on a 32-bit architecture. On a 64-bit architecture, there will
// be no savings using natural alignment since the size of a node will be 16
// bytes regardless.
#ifndef INCLUDED_BDLSCM_VERSION
#include <bdlscm_version.h>
#endif
#ifndef INCLUDED_BSLS_ALIGNMENT
#include <bsls_alignment.h>
#endif
#ifndef INCLUDED_BSLS_ALIGNMENTUTIL
#include <bsls_alignmentutil.h>
#endif
#ifndef INCLUDED_BSLS_ASSERT
#include <bsls_assert.h>
#endif
#ifndef INCLUDED_BSLS_PERFORMANCEHINT
#include <bsls_performancehint.h>
#endif
#ifndef INCLUDED_BSLS_PLATFORM
#include <bsls_platform.h>
#endif
#ifndef INCLUDED_BSLS_TYPES
#include <bsls_types.h>
#endif
namespace BloombergLP {
namespace bdlma {
// ===================
// class BufferManager
// ===================
class BufferManager {
// This class implements a buffer manager that dispenses heterogeneous
// blocks of memory (of varying, user-specified sizes) from an external
// buffer whose address and size are optionally supplied at construction.
// If an allocation request exceeds the remaining free memory space in the
// external buffer, the allocation request returns 0 if 'allocate' is used,
// or results in undefined behavior if 'allocateRaw' is used. Note that in
// no event will the buffer manager attempt to deallocate the external
// buffer.
// DATA
char *d_buffer_p; // external buffer (held, not
// owned)
bsls::Types::size_type d_bufferSize; // size (in bytes) of external
// buffer
bsls::Types::IntPtr d_cursor; // offset to next available
// byte in buffer
bsls::Types::size_type d_alignmentAndMask; // a mask used during the
// alignment calculation
bsls::Types::size_type d_alignmentOrMask; // a mask used during the
// alignment calculation
private:
// NOT IMPLEMENTED
BufferManager(const BufferManager&);
BufferManager& operator=(const BufferManager&);
public:
// CREATORS
explicit
BufferManager(
bsls::Alignment::Strategy strategy = bsls::Alignment::BSLS_NATURAL);
// Create a buffer manager for allocating memory blocks. Optionally
// specify an alignment 'strategy' used to align allocated memory
// blocks. If 'strategy' is not specified, natural alignment is used.
// A default constructed buffer manager is unable to allocate any
// memory until an external buffer is provided by calling the
// 'replaceBuffer' method.
BufferManager(
char *buffer,
bsls::Types::size_type bufferSize,
bsls::Alignment::Strategy strategy = bsls::Alignment::BSLS_NATURAL);
// Create a buffer manager for allocating memory blocks from the
// specified external 'buffer' having the specified 'bufferSize' (in
// bytes). Optionally specify an alignment 'strategy' used to align
// allocated memory blocks. If 'strategy' is not specified, natural
// alignment is used. The behavior is undefined unless
// '0 < bufferSize' and 'buffer' has at least 'bufferSize' bytes.
~BufferManager();
// Destroy this buffer manager.
// MANIPULATORS
void *allocate(bsls::Types::size_type size);
// Return the address of a contiguous block of memory of the specified
// 'size' (in bytes) on success, according to the alignment strategy
// specified at construction. If 'size' is 0 or the allocation request
// exceeds the remaining free memory space in the external buffer, no
// memory is allocated and 0 is returned.
void *allocateRaw(bsls::Types::size_type size);
// Return the address of a contiguous block of memory of the specified
// 'size' (in bytes) according to the alignment strategy specified at
// construction. The behavior is undefined unless the allocation
// request does not exceed the remaining free memory space in the
// external buffer, '0 < size', and this object is currently managing a
// buffer.
template <class TYPE>
void deleteObjectRaw(const TYPE *object);
// Destroy the specified 'object'. Note that memory associated with
// 'object' is not deallocated because there is no 'deallocate' method
// in 'BufferManager'.
template <class TYPE>
void deleteObject(const TYPE *object);
// Destroy the specified 'object'. Note that this method has the same
// effect as the 'deleteObjectRaw' method (since no deallocation is
// involved), and exists for consistency with a pool interface.
bsls::Types::size_type expand(void *address, bsls::Types::size_type size);
// Increase the amount of memory allocated at the specified 'address'
// from the original 'size' (in bytes) to also include the maximum
// amount remaining in the buffer. Return the amount of memory
// available at 'address' after expanding, or 'size' if the memory at
// 'address' cannot be expanded. This method can only 'expand' the
// memory block returned by the most recent 'allocate' or 'allocateRaw'
// request from this buffer manager, and otherwise has no effect. The
// behavior is undefined unless the memory at 'address' was originally
// allocated by this buffer manager, the size of the memory at
// 'address' is 'size', and 'release' was not called after allocating
// the memory at 'address'.
char *replaceBuffer(char *newBuffer, bsls::Types::size_type newBufferSize);
// Replace the buffer currently managed by this object with the
// specified 'newBuffer' of the specified 'newBufferSize' (in bytes);
// return the address of the previously held buffer, or 0 if this
// object currently manages no buffer. The replaced buffer (if any) is
// removed from the management of this object with no effect on the
// outstanding allocated memory blocks. Subsequent allocations will
// allocate memory from the beginning of the new external buffer. The
// behavior is undefined unless '0 < newBufferSize' and 'newBuffer' has
// at least 'newBufferSize' bytes.
void release();
// Release all memory currently allocated through this buffer manager.
// After this call, the external buffer managed by this object is
// retained. Subsequent allocations will allocate memory from the
// beginning of the external buffer (if any).
void reset();
// Reset this buffer manager to its default constructed state, except
// retain the alignment strategy in effect at the time of construction.
// The currently managed buffer (if any) is removed from the management
// of this object with no effect on the outstanding allocated memory
// blocks.
bsls::Types::size_type truncate(void *address,
bsls::Types::size_type originalSize,
bsls::Types::size_type newSize);
// Reduce the amount of memory allocated at the specified 'address' of
// the specified 'originalSize' (in bytes) to the specified 'newSize'
// (in bytes). Return 'newSize' after truncating, or 'originalSize' if
// the memory at 'address' cannot be truncated. This method can only
// 'truncate' the memory block returned by the most recent 'allocate'
// or 'allocateRaw' request from this object, and otherwise has no
// effect. The behavior is undefined unless the memory at 'address'
// was originally allocated by this buffer manager, the size of the
// memory at 'address' is 'originalSize', 'newSize <= originalSize',
// '0 <= newSize', and 'release' was not called after allocating the
// memory at 'address'.
// ACCESSORS
char *buffer() const;
// Return an address providing modifiable access to the buffer
// currently managed by this object, or 0 if this object currently
// manages no buffer.
bsls::Types::size_type bufferSize() const;
// Return the size (in bytes) of the buffer currently managed by this
// object, or 0 if this object currently manages no buffer.
int calculateAlignmentOffsetFromSize(const void *address,
bsls::Types::size_type size) const;
// Return the minimum non-negative integer that, when added to the
// numerical value of the specified 'address', yields the alignment as
// per the 'alignmentStrategy' provided at construction for an
// allocation of the specified 'size'. Note that if '0 == size' and
// natural alignment was provided at construction, the result of this
// method is identical to the result for '0 == size' and maximal
// alignment.
bool hasSufficientCapacity(bsls::Types::size_type size) const;
// Return 'true' if there is sufficient memory space in the buffer to
// allocate a contiguous memory block of the specified 'size' (in
// bytes) after taking the alignment strategy into consideration, and
// 'false' otherwise. The behavior is undefined unless '0 < size', and
// this object is currently managing a buffer.
};
// ============================================================================
// INLINE DEFINITIONS
// ============================================================================
// ------------
// class Buffer
// ------------
// CREATORS
inline
BufferManager::BufferManager(bsls::Alignment::Strategy strategy)
: d_buffer_p(0)
, d_bufferSize(0)
, d_cursor(0)
, d_alignmentAndMask( strategy != bsls::Alignment::BSLS_MAXIMUM
? bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT - 1
: 0)
, d_alignmentOrMask( strategy != bsls::Alignment::BSLS_BYTEALIGNED
? bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT
: 1)
{
}
inline
BufferManager::BufferManager(char *buffer,
bsls::Types::size_type bufferSize,
bsls::Alignment::Strategy strategy)
: d_buffer_p(buffer)
, d_bufferSize(bufferSize)
, d_cursor(0)
, d_alignmentAndMask( strategy != bsls::Alignment::BSLS_MAXIMUM
? bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT - 1
: 0)
, d_alignmentOrMask( strategy != bsls::Alignment::BSLS_BYTEALIGNED
? bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT
: 1)
{
BSLS_ASSERT_SAFE(buffer);
BSLS_ASSERT_SAFE(0 < bufferSize);
}
inline
BufferManager::~BufferManager()
{
BSLS_ASSERT_SAFE(0 <= d_cursor);
BSLS_ASSERT_SAFE(static_cast<bsls::Types::size_type>(d_cursor)
<= d_bufferSize);
BSLS_ASSERT_SAFE( (0 != d_buffer_p && 0 < d_bufferSize)
|| (0 == d_buffer_p && 0 == d_bufferSize));
}
// MANIPULATORS
inline
void *BufferManager::allocate(bsls::Types::size_type size)
{
BSLS_ASSERT_SAFE(0 <= d_cursor);
BSLS_ASSERT_SAFE(static_cast<bsls::Types::size_type>(d_cursor)
<= d_bufferSize);
char *address = d_buffer_p + d_cursor;
int offset = calculateAlignmentOffsetFromSize(address, size);
bsls::Types::IntPtr cursor = d_cursor + offset + size;
if ( BSLS_PERFORMANCEHINT_PREDICT_LIKELY(
static_cast<bsls::Types::size_type>(cursor) <= d_bufferSize)
&& BSLS_PERFORMANCEHINT_PREDICT_LIKELY(0 < size)) {
d_cursor = cursor;
return address + offset;
}
return 0;
}
inline
void *BufferManager::allocateRaw(bsls::Types::size_type size)
{
BSLS_ASSERT_SAFE(0 < size);
BSLS_ASSERT_SAFE(0 <= d_cursor);
BSLS_ASSERT_SAFE(static_cast<bsls::Types::size_type>(d_cursor)
<= d_bufferSize);
BSLS_ASSERT_SAFE(d_buffer_p);
char *address = d_buffer_p + d_cursor;
int offset = calculateAlignmentOffsetFromSize(address, size);
d_cursor = d_cursor + offset + size;
return address + offset;
}
template <class TYPE>
inline
void BufferManager::deleteObjectRaw(const TYPE *object)
{
if (0 != object) {
#ifndef BSLS_PLATFORM_CMP_SUN
object->~TYPE();
#else
const_cast<TYPE *>(object)->~TYPE();
#endif
}
}
template <class TYPE>
inline
void BufferManager::deleteObject(const TYPE *object)
{
deleteObjectRaw(object);
}
inline
char *BufferManager::replaceBuffer(char *newBuffer,
bsls::Types::size_type newBufferSize)
{
BSLS_ASSERT_SAFE(newBuffer);
BSLS_ASSERT_SAFE(0 < newBufferSize);
char *oldBuffer = d_buffer_p;
d_buffer_p = newBuffer;
d_bufferSize = newBufferSize;
d_cursor = 0;
return oldBuffer;
}
inline
void BufferManager::release()
{
d_cursor = 0;
}
inline
void BufferManager::reset()
{
d_buffer_p = 0;
d_bufferSize = 0;
d_cursor = 0;
}
// ACCESSORS
inline
char *BufferManager::buffer() const
{
return d_buffer_p;
}
inline
bsls::Types::size_type BufferManager::bufferSize() const
{
return d_bufferSize;
}
inline
int BufferManager::calculateAlignmentOffsetFromSize(
const void *address,
bsls::Types::size_type size) const
{
bsls::Types::size_type alignment = (size & d_alignmentAndMask)
| d_alignmentOrMask;
alignment &= -alignment; // clear all but lowest order set bit
return static_cast<int>(
(alignment - reinterpret_cast<bsls::Types::size_type>(address))
& (alignment - 1));
}
inline
bool BufferManager::hasSufficientCapacity(bsls::Types::size_type size) const
{
BSLS_ASSERT_SAFE(0 < size);
BSLS_ASSERT_SAFE(d_buffer_p);
BSLS_ASSERT_SAFE(0 <= d_cursor);
BSLS_ASSERT_SAFE(static_cast<bsls::Types::size_type>(d_cursor)
<= d_bufferSize);
char *address = d_buffer_p + d_cursor;
int offset = calculateAlignmentOffsetFromSize(address, size);
return d_cursor + offset + size <= d_bufferSize;
}
} // close package namespace
} // close enterprise namespace
#endif
// ----------------------------------------------------------------------------
// Copyright 2016 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| {
"content_hash": "5270c3577c8506eae539947d9608a80c",
"timestamp": "",
"source": "github",
"line_count": 634,
"max_line_length": 79,
"avg_line_length": 40.02208201892744,
"alnum_prop": 0.6167336643808623,
"repo_name": "bowlofstew/bde",
"id": "a85f9112815e5e106647a364893361b544b401c1",
"size": "25929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "groups/bdl/bdlma/bdlma_buffermanager.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "147162"
},
{
"name": "C++",
"bytes": "80424920"
},
{
"name": "Objective-C",
"bytes": "86496"
},
{
"name": "Perl",
"bytes": "2008"
},
{
"name": "Python",
"bytes": "890"
}
],
"symlink_target": ""
} |
import { INotice } from '../notice';
import { Filter } from './filter';
export function makeDebounceFilter(): Filter {
let lastNoticeJSON: string;
let timeout;
return (notice: INotice): INotice | null => {
let s = JSON.stringify(notice.errors);
if (s === lastNoticeJSON) {
return null;
}
if (timeout) {
clearTimeout(timeout);
}
lastNoticeJSON = s;
timeout = setTimeout(() => {
lastNoticeJSON = '';
}, 1000);
return notice;
};
}
| {
"content_hash": "5477e6268dd45e0d9e1450cd23b85244",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 47,
"avg_line_length": 19.8,
"alnum_prop": 0.5898989898989899,
"repo_name": "airbrake/airbrake-js",
"id": "0b8936c1adfa42a74682794f2a69ad401a50ab97",
"size": "495",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/browser/src/filter/debounce.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1220"
},
{
"name": "HTML",
"bytes": "474"
},
{
"name": "JavaScript",
"bytes": "51295"
},
{
"name": "TypeScript",
"bytes": "75214"
}
],
"symlink_target": ""
} |
package com.tle.web.quickcontributeandversion;
import com.tle.beans.entity.itemdef.ItemDefinition;
import com.tle.beans.item.VersionSelection;
import com.tle.common.Check;
import com.tle.common.Format;
import com.tle.common.NameValue;
import com.tle.common.settings.standard.QuickContributeAndVersionSettings;
import com.tle.core.collection.service.ItemDefinitionService;
import com.tle.core.i18n.BundleCache;
import com.tle.core.i18n.BundleNameValue;
import com.tle.core.settings.service.ConfigurationService;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.annotations.EventFactory;
import com.tle.web.sections.annotations.EventHandlerMethod;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.equella.layout.OneColumnLayout;
import com.tle.web.sections.equella.receipt.ReceiptService;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.events.js.EventGenerator;
import com.tle.web.sections.render.GenericTemplateResult;
import com.tle.web.sections.render.Label;
import com.tle.web.sections.render.TemplateResult;
import com.tle.web.sections.standard.Button;
import com.tle.web.sections.standard.Checkbox;
import com.tle.web.sections.standard.SingleSelectionList;
import com.tle.web.sections.standard.annotations.Component;
import com.tle.web.sections.standard.model.DynamicHtmlListModel;
import com.tle.web.sections.standard.model.SimpleHtmlListModel;
import com.tle.web.settings.menu.SettingsUtils;
import com.tle.web.template.Breadcrumbs;
import com.tle.web.template.Decorations;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
/** @author larry */
@SuppressWarnings("nls")
public class RootQuickContributeAndVersionSettingsSection
extends OneColumnLayout<
RootQuickContributeAndVersionSettingsSection.QuickContributeAndVersionSettingsModel> {
@PlugKey("quickcontributeandversionsettings.title")
private static Label TITLE_LABEL;
@PlugKey("quickcontribute.settings.save.receipt")
private static Label SAVE_RECEIPT_LABEL;
@PlugKey("quickcontributeandversionsettings.none")
private static String NO_COLLECTION_KEY;
@PlugKey("quickcontributeandversionsettings.forcecurrent")
private static String FORCE_CURRENT_KEY;
@PlugKey("quickcontributeandversionsettings.forcelatest")
private static String FORCE_LATEST_KEY;
@PlugKey("quickcontributeandversionsettings.defaultcurrent")
private static String DEFAULT_CURRENT_KEY;
@PlugKey("quickcontributeandversionsettings.defaultlatest")
private static String DEFAULT_LATEST_KEY;
@Component(name = "fins")
private SingleSelectionList<NameValue> collectionSelector;
@Component private SingleSelectionList<NameValue> versionViewOptions;
@Component(name = "e", stateful = false)
@PlugKey("selectionsettings.disablebutton.label")
private Checkbox disable;
@Component
@PlugKey("settings.save.button")
private Button saveButton;
@EventFactory private EventGenerator events;
@Inject private QuickContributeAndVersionSettingsPrivilegeTreeProvider securityProvider;
@Inject private ConfigurationService configService;
@Inject private ItemDefinitionService itemDefinitionService;
@Inject private BundleCache bundleCache;
@Inject private ReceiptService receiptService;
@Override
protected TemplateResult setupTemplate(RenderEventContext info) {
securityProvider.checkAuthorised();
// Get the currently store one click collection, if any
QuickContributeAndVersionSettings settings =
configService.getProperties(new QuickContributeAndVersionSettings());
String existingSelectedUuid = settings.getOneClickCollection();
collectionSelector.setSelectedStringValue(info, existingSelectedUuid);
VersionSelection currentVersionSelection = settings.getVersionSelection();
if (currentVersionSelection != null) {
versionViewOptions.setSelectedStringValue(info, currentVersionSelection.toString());
}
disable.setChecked(info, settings.isButtonDisable());
return new GenericTemplateResult(
viewFactory.createNamedResult(BODY, "quickcontributeandversionsettings.ftl", this));
}
@Override
public void registered(String id, SectionTree tree) {
super.registered(id, tree);
collectionSelector.setListModel(
new DynamicHtmlListModel<NameValue>() {
@Override
protected Iterable<NameValue> populateModel(SectionInfo info) {
final List<NameValue> populateMe = new ArrayList<NameValue>();
List<ItemDefinition> allCollections = itemDefinitionService.enumerate();
for (ItemDefinition itemDef : allCollections) {
populateMe.add(
new BundleNameValue(itemDef.getName(), itemDef.getUuid(), bundleCache));
}
Collections.sort(populateMe, Format.NAME_VALUE_COMPARATOR);
populateMe.add(0, new BundleNameValue(NO_COLLECTION_KEY, null));
collectionSelector.getState(info).setDisallowMultiple(true);
return populateMe;
}
});
SimpleHtmlListModel<NameValue> versionOptions =
new SimpleHtmlListModel<NameValue>(
new BundleNameValue(FORCE_CURRENT_KEY, VersionSelection.FORCE_CURRENT.toString()),
new BundleNameValue(FORCE_LATEST_KEY, VersionSelection.FORCE_LATEST.toString()),
new BundleNameValue(
DEFAULT_CURRENT_KEY, VersionSelection.DEFAULT_TO_CURRENT.toString()),
new BundleNameValue(DEFAULT_LATEST_KEY, VersionSelection.DEFAULT_TO_LATEST.toString()));
versionViewOptions.setListModel(versionOptions);
versionViewOptions.setAlwaysSelect(true);
saveButton.setClickHandler(events.getNamedHandler("save"));
}
@Override
protected void addBreadcrumbsAndTitle(
SectionInfo info, Decorations decorations, Breadcrumbs crumbs) {
decorations.setTitle(TITLE_LABEL);
crumbs.addToStart(SettingsUtils.getBreadcrumb(info));
}
public SingleSelectionList<NameValue> getCollectionSelector() {
return collectionSelector;
}
@EventHandlerMethod
public void save(SectionInfo info) {
boolean altered = false;
QuickContributeAndVersionSettings settings =
configService.getProperties(new QuickContributeAndVersionSettings());
String existingSelectedUuid = settings.getOneClickCollection();
NameValue selectedNV = collectionSelector.getSelectedValue(info);
String selectedNVUuid = selectedNV != null ? selectedNV.getValue() : null;
if (!(Check.isEmpty(existingSelectedUuid) && Check.isEmpty(selectedNVUuid))) {
if (existingSelectedUuid == null) {
existingSelectedUuid = "";
}
if (!existingSelectedUuid.equals(selectedNVUuid)) {
altered |= true;
settings.setOneClickCollection(selectedNVUuid);
}
}
NameValue selectedVersionSelectionNV = versionViewOptions.getSelectedValue(info);
VersionSelection oldVersionSelection = settings.getVersionSelection();
String oldVersionSelectAsString =
oldVersionSelection != null ? oldVersionSelection.toString() : "";
String newVersionSelectAsString =
selectedVersionSelectionNV != null && !Check.isEmpty(selectedVersionSelectionNV.getValue())
? selectedVersionSelectionNV.getValue()
: "";
if (!oldVersionSelectAsString.equals(newVersionSelectAsString)) {
altered |= true;
settings.setVersionSelection(VersionSelection.valueOf(newVersionSelectAsString));
}
boolean buttonDisable = settings.isButtonDisable();
if (!disable.isChecked(info) == buttonDisable) {
altered |= true;
settings.setButtonDisable(disable.isChecked(info));
}
if (altered) {
configService.setProperties(settings);
receiptService.setReceipt(SAVE_RECEIPT_LABEL);
}
}
public SingleSelectionList<NameValue> getVersionViewOptions() {
return versionViewOptions;
}
/** @return the saveButton */
public Button getSaveButton() {
return saveButton;
}
@Override
public Class<QuickContributeAndVersionSettingsModel> getModelClass() {
return QuickContributeAndVersionSettingsModel.class;
}
public Checkbox getDisable() {
return disable;
}
public static class QuickContributeAndVersionSettingsModel
extends OneColumnLayout.OneColumnLayoutModel {
// Token implementation
}
}
| {
"content_hash": "d0547a5f7f57c55efe5bb33ae4b1a59e",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 100,
"avg_line_length": 38.61187214611872,
"alnum_prop": 0.7638363292336803,
"repo_name": "equella/Equella",
"id": "24767c7d2cb11666f09d7418883622b9eddab094",
"size": "9259",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Source/Plugins/Core/com.equella.core/src/com/tle/web/quickcontributeandversion/RootQuickContributeAndVersionSettingsSection.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "402"
},
{
"name": "Batchfile",
"bytes": "38432"
},
{
"name": "CSS",
"bytes": "648823"
},
{
"name": "Dockerfile",
"bytes": "2055"
},
{
"name": "FreeMarker",
"bytes": "370046"
},
{
"name": "HTML",
"bytes": "865667"
},
{
"name": "Java",
"bytes": "27081020"
},
{
"name": "JavaScript",
"bytes": "1673995"
},
{
"name": "PHP",
"bytes": "821"
},
{
"name": "PLpgSQL",
"bytes": "1363"
},
{
"name": "PureScript",
"bytes": "307610"
},
{
"name": "Python",
"bytes": "79871"
},
{
"name": "Scala",
"bytes": "765981"
},
{
"name": "Shell",
"bytes": "64170"
},
{
"name": "TypeScript",
"bytes": "146564"
},
{
"name": "XSLT",
"bytes": "510113"
}
],
"symlink_target": ""
} |
% Test file for trigtech/isnan.m
function pass = test_isnan(pref)
% Get preferences.
if ( nargin < 1 )
pref = trigtech.techPref();
end
testclass = trigtech();
% Test a scalar-valued function.
f = testclass.make(@(x) cos(pi*x), [], pref);
pass(1) = ~isnan(f);
% Test an array-valued function.
f = testclass.make(@(x) [cos(pi*x), cos(pi*x).^2], [], pref);
pass(2) = ~isnan(f);
% Artificially construct and test a NaN-valued function.
f = testclass.make(NaN);
pass(3) = isnan(f);
% Test a NaN scalar-valued function.
try
f = testclass.make(@(x) cos(pi*x) + NaN);
pass(4) = isnan(f);
catch ME
pass(4) = strcmpi(ME.message, 'Cannot handle functions that evaluate to Inf or NaN.');
end
% Test a NaN array-valued function.
try
f = testclass.make(@(x) [cos(pi*x) + NaN, cos(pi*x)]);
pass(5) = isnan(f);
catch ME
pass(5) = strcmpi(ME.message, 'Cannot handle functions that evaluate to Inf or NaN.');
end
end
| {
"content_hash": "802548ff0e2a814f8ec1c9a23e9b0f5b",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 90,
"avg_line_length": 23.4,
"alnum_prop": 0.6452991452991453,
"repo_name": "alshedivat/chebfun",
"id": "a54e389e97bf15c0ab3ecb21ea7a2f6dfdf59218",
"size": "936",
"binary": false,
"copies": "5",
"ref": "refs/heads/development",
"path": "tests/trigtech/test_isnan.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "M",
"bytes": "4938"
},
{
"name": "Matlab",
"bytes": "6012627"
},
{
"name": "Objective-C",
"bytes": "977"
}
],
"symlink_target": ""
} |
{% extends "caffeine_oauth2/mail_body_base.html" %}{% load i18n %}
{% block title %}[{{ site.name }}]
{% blocktrans with appname=application.name %}A new API client {{ appname }}
has been requested{% endblocktrans %}{% endblock %}
{% block content_start %}{% trans "Hello Team," %}{% endblock %}
{% block content %}
{% blocktrans with appname=application.name appdescription=application.description appwebsite=application.website user=application.user user_url=application.user.get_absolute_url sitename=site.name %}
<p>a new API client <b>{{ appname }}</b> for <b>{{ sitename }}</b> has
been requested by
<a href="{{ site_url }}{{ user_url }}">{{ user }}</a>,
with these details:</p>
<dl>
<dt>Description:</dt>
<dd>{{ appdescription }}</dd>
<dt>Website:</dt>
<dd><a href="{{ appwebsite }}">{{ appwebsite }}</a></dd>
</dl>
<p>Please visit the <a href="{{ approval_url }}">application's approval
page</a> to approve or reject the application.</p>
{% endblocktrans %}
{% endblock %} | {
"content_hash": "818a45f1671b6503d26b991b6e505e64",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 204,
"avg_line_length": 53.714285714285715,
"alnum_prop": 0.5851063829787234,
"repo_name": "coffeestats/coffeestats-django",
"id": "b546ce8226fc6082640e4a14848f17478aac7547",
"size": "1128",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "coffeestats/templates/caffeine_oauth2/mail_registered_body.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "62461"
},
{
"name": "Dockerfile",
"bytes": "881"
},
{
"name": "HTML",
"bytes": "106689"
},
{
"name": "JavaScript",
"bytes": "45668"
},
{
"name": "Python",
"bytes": "279433"
},
{
"name": "Shell",
"bytes": "1210"
}
],
"symlink_target": ""
} |
<?php
interface IEMBIconProvider
{
public function registerClientScript();
public function dropDownList($model,$attribute,$htmlOptions=array());
public static function getIconLabel($icon,$label);
}
| {
"content_hash": "87aa58a346a1c3705a6c1f110c382bd5",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 73,
"avg_line_length": 24.555555555555557,
"alnum_prop": 0.7194570135746606,
"repo_name": "yii-joblo/menubuilder",
"id": "af8cf440d8a7435fc84c314eff18a2cd406a88a6",
"size": "580",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "components/IEMBIconProvider.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "52055"
},
{
"name": "JavaScript",
"bytes": "143016"
},
{
"name": "PHP",
"bytes": "404149"
},
{
"name": "Shell",
"bytes": "1468"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/temples/kirtland-ohio#kirtland-temple-766535" xml:lang="eng" locale="eng" status="publish">
<search-meta>
<uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">kirtland-temple-766535</uri-title>
<source>kirtland-temple-766535</source>
<publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
<media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
<publication value="ldsorg">LDS.org</publication>
<publication-date value="2012-04-09">2012-04-09</publication-date>
<title/>
<description/>
<collections>
<collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
<collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
<collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
</collections>
<subjects>
<subject>temples</subject>
<subject>kirtland temple</subject>
<subject>kirtland</subject>
<subject>ohio</subject>
<subject>house of the lord</subject>
</subjects>
</search-meta>
<no-search>
<path>http://media.ldscdn.org/images/media-library/temples/kirtland-ohio/kirtland-temple-766535-gallery.jpg</path>
<images>
<small its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">http://media.ldscdn.org/images/media-library/temples/kirtland-ohio/kirtland-temple-766535-thumbnail.jpg</small>
</images>
<download-urls>
<download-url>
<label>Mobile</label>
<size>95 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/kirtland-ohio/kirtland-temple-766535-mobile.jpg</path>
</download-url>
<download-url>
<label>Tablet</label>
<size>130 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/kirtland-ohio/kirtland-temple-766535-tablet.jpg</path>
</download-url>
<download-url>
<label>Print</label>
<size>296 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/kirtland-ohio/kirtland-temple-766535-print.jpg</path>
</download-url>
<download-url>
<label>Wallpaper</label>
<size>501 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/kirtland-ohio/kirtland-temple-766535-wallpaper.jpg</path>
</download-url>
</download-urls>
</no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="kirtland-temple-766535" locale="eng" uri="/media-library/images/temples/kirtland-ohio#kirtland-temple-766535" status="publish" site="ldsorg" source="chq" words="128" tgp="0.4476"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:12.550235-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>
| {
"content_hash": "a81df977bf2893ae20ae01cb6c1ca466",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 452,
"avg_line_length": 62.15094339622642,
"alnum_prop": 0.6287188828172434,
"repo_name": "freshie/ml-taxonomies",
"id": "58caf64cba064ccf5cc98b022aeafd64961e72fa",
"size": "3294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "roxy/data/gospel-topical-explorer-v2/content/images/kirtland-temple-766535.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4422"
},
{
"name": "CSS",
"bytes": "38665"
},
{
"name": "HTML",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "411651"
},
{
"name": "Ruby",
"bytes": "259121"
},
{
"name": "Shell",
"bytes": "7329"
},
{
"name": "XQuery",
"bytes": "857170"
},
{
"name": "XSLT",
"bytes": "13753"
}
],
"symlink_target": ""
} |
import React from 'react';
import DayPicker from 'react-day-picker';
import { isSameDay } from './DateUtils';
import '../../style/DayPicker.scss';
import '../../style/SelectableDayExample.scss';
class datePicker extends React.Component{
constructor(props) {
super(props);
this.handleDayClick = this.handleDayClick.bind(this);
this.state = {
selectedDay: new Date()
};
}
handleDayClick(e, day) {
this.setState({
selectedDay: day
});
this.props.handleChange(day.toLocaleDateString());
}
render() {
let { selectedDay } = this.state;
let modifiers = {
'selected': (day) => isSameDay(selectedDay, day)
};
return (
<div className="SelectableDayExample">
<DayPicker
numberOfMonths={1}
enableOutsideDays={true}
modifiers={ modifiers }
onDayClick={this.handleDayClick}
/>
<p>
Selected: { selectedDay.toLocaleDateString() }
</p>
</div>
);
}
}
export default datePicker;
datePicker.propTypes = {
handleChange: React.PropTypes.any
};
| {
"content_hash": "beee074ce4cef616f6405ee83b89b954",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 56,
"avg_line_length": 21.826923076923077,
"alnum_prop": 0.5955947136563877,
"repo_name": "robhogfeldt-fron15/ReactiveDogs",
"id": "6839ca72093d485c9de6ad51d75d43bb182898d8",
"size": "1135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/components/common/datePicker.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19252"
},
{
"name": "HTML",
"bytes": "1563"
},
{
"name": "JavaScript",
"bytes": "118361"
},
{
"name": "PHP",
"bytes": "1097"
}
],
"symlink_target": ""
} |
from pox.core import core
from pox.lib.addresses import IPAddr,EthAddr,parse_cidr
from pox.lib.revent import EventContinue,EventHalt
import pox.openflow.libopenflow_01 as of
from pox.lib.util import dpidToStr
import sys
log = core.getLogger()
############## Global constants #############
virtual_ip = IPAddr("10.0.0.5")
virtual_mac = EthAddr("00:00:00:00:00:05")
server = {}
server[0] = {'ip':IPAddr("10.0.0.2"), 'mac':EthAddr("00:00:00:00:00:02"), 'outport': 2}
server[1] = {'ip':IPAddr("10.0.0.3"), 'mac':EthAddr("00:00:00:00:00:03"), 'outport': 3}
server[2] = {'ip':IPAddr("10.0.0.4"), 'mac':EthAddr("00:00:00:00:00:04"), 'outport': 4}
total_servers = len(server)
server_index = 0
################ Handlers ###################
def _handle_PacketIn (event):
global server_index
packet = event.parsed
# Only handle IPv4 flows
if (not event.parsed.find("ipv4")):
return EventContinue
msg = of.ofp_flow_mod()
msg.match = of.ofp_match.from_packet(packet)
# Only handle traffic destined to virtual IP
if (msg.match.nw_dst != virtual_ip):
return EventContinue
# Round robin selection of servers
index = server_index % total_servers
print index
selected_server_ip = server[index]['ip']
selected_server_mac = server[index]['mac']
selected_server_outport = server[index]['outport']
server_index += 1
# Setup route to server
msg.buffer_id = event.ofp.buffer_id
msg.in_port = event.port
msg.actions.append(of.ofp_action_dl_addr(of.OFPAT_SET_DL_DST, selected_server_mac))
msg.actions.append(of.ofp_action_nw_addr(of.OFPAT_SET_NW_DST, selected_server_ip))
msg.actions.append(of.ofp_action_output(port = selected_server_outport))
event.connection.send(msg)
# Setup reverse route from server
reverse_msg = of.ofp_flow_mod()
reverse_msg.buffer_id = None
reverse_msg.in_port = selected_server_outport
reverse_msg.match = of.ofp_match()
reverse_msg.match.dl_src = selected_server_mac
reverse_msg.match.nw_src = selected_server_ip
reverse_msg.match.tp_src = msg.match.tp_dst
reverse_msg.match.dl_dst = msg.match.dl_src
reverse_msg.match.nw_dst = msg.match.nw_src
reverse_msg.match.tp_dst = msg.match.tp_src
reverse_msg.actions.append(of.ofp_action_dl_addr(of.OFPAT_SET_DL_SRC, virtual_mac))
reverse_msg.actions.append(of.ofp_action_nw_addr(of.OFPAT_SET_NW_SRC, virtual_ip))
reverse_msg.actions.append(of.ofp_action_output(port = msg.in_port))
event.connection.send(reverse_msg)
return EventHalt
def launch ():
# To intercept packets before the learning switch
core.openflow.addListenerByName("PacketIn", _handle_PacketIn, priority=2)
log.info("Stateless LB running.")
| {
"content_hash": "5810eec5878c03e4bb1ce05bf2c7acb6",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 87,
"avg_line_length": 33.58536585365854,
"alnum_prop": 0.6735657225853304,
"repo_name": "ddurando/my_pox",
"id": "742715076b06a216040347a93839b8b96cc3e030",
"size": "3221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pox/forwarding/tutorial_stateless_lb.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7899"
},
{
"name": "C++",
"bytes": "18894"
},
{
"name": "HTML",
"bytes": "999"
},
{
"name": "JavaScript",
"bytes": "9048"
},
{
"name": "Python",
"bytes": "1266832"
},
{
"name": "Shell",
"bytes": "24491"
},
{
"name": "TeX",
"bytes": "19188"
}
],
"symlink_target": ""
} |
declare var ADALFrameworkVersionNumber: number;
declare var ADALFrameworkVersionString: interop.Reference<number>;
declare const enum ADAL_LOG_LEVEL {
EVEL_NO_LOG = 0,
EVEL_ERROR = 1,
EVEL_WARN = 2,
EVEL_INFO = 3,
EVEL_VERBOSE = 4,
AST = 4
}
declare const enum ADAssertionType {
D_SAML1_1 = 0,
D_SAML2 = 1
}
declare class ADAuthenticationContext extends NSObject {
static alloc(): ADAuthenticationContext; // inherited from NSObject
static authenticationContextWithAuthorityError(authority: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): ADAuthenticationContext;
static authenticationContextWithAuthoritySharedGroupError(authority: string, sharedGroup: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): ADAuthenticationContext;
static authenticationContextWithAuthorityValidateAuthorityError(authority: string, validate: boolean, error: interop.Pointer | interop.Reference<ADAuthenticationError>): ADAuthenticationContext;
static authenticationContextWithAuthorityValidateAuthoritySharedGroupError(authority: string, validate: boolean, sharedGroup: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): ADAuthenticationContext;
static handleBrokerResponse(response: NSURL): boolean;
static isResponseFromBrokerResponse(sourceApplication: string, response: NSURL): boolean;
static new(): ADAuthenticationContext; // inherited from NSObject
readonly authority: string;
correlationId: NSUUID;
credentialsType: ADCredentialsType;
extendedLifetimeEnabled: boolean;
logComponent: string;
parentController: UIViewController;
validateAuthority: boolean;
webView: UIWebView;
constructor(o: { authority: string; validateAuthority: boolean; error: interop.Pointer | interop.Reference<ADAuthenticationError>; });
constructor(o: { authority: string; validateAuthority: boolean; sharedGroup: string; error: interop.Pointer | interop.Reference<ADAuthenticationError>; });
acquireTokenForAssertionAssertionTypeResourceClientIdUserIdCompletionBlock(assertion: string, assertionType: ADAssertionType, resource: string, clientId: string, userId: string, completionBlock: (p1: ADAuthenticationResult) => void): void;
acquireTokenSilentWithResourceClientIdRedirectUriCompletionBlock(resource: string, clientId: string, redirectUri: NSURL, completionBlock: (p1: ADAuthenticationResult) => void): void;
acquireTokenSilentWithResourceClientIdRedirectUriUserIdCompletionBlock(resource: string, clientId: string, redirectUri: NSURL, userId: string, completionBlock: (p1: ADAuthenticationResult) => void): void;
acquireTokenWithResourceClientIdRedirectUriCompletionBlock(resource: string, clientId: string, redirectUri: NSURL, completionBlock: (p1: ADAuthenticationResult) => void): void;
acquireTokenWithResourceClientIdRedirectUriPromptBehaviorUserIdExtraQueryParametersCompletionBlock(resource: string, clientId: string, redirectUri: NSURL, promptBehavior: ADPromptBehavior, userId: string, queryParams: string, completionBlock: (p1: ADAuthenticationResult) => void): void;
acquireTokenWithResourceClientIdRedirectUriPromptBehaviorUserIdentifierExtraQueryParametersCompletionBlock(resource: string, clientId: string, redirectUri: NSURL, promptBehavior: ADPromptBehavior, userId: ADUserIdentifier, queryParams: string, completionBlock: (p1: ADAuthenticationResult) => void): void;
acquireTokenWithResourceClientIdRedirectUriUserIdCompletionBlock(resource: string, clientId: string, redirectUri: NSURL, userId: string, completionBlock: (p1: ADAuthenticationResult) => void): void;
acquireTokenWithResourceClientIdRedirectUriUserIdExtraQueryParametersCompletionBlock(resource: string, clientId: string, redirectUri: NSURL, userId: string, queryParams: string, completionBlock: (p1: ADAuthenticationResult) => void): void;
initWithAuthorityValidateAuthorityError(authority: string, validateAuthority: boolean, error: interop.Pointer | interop.Reference<ADAuthenticationError>): this;
initWithAuthorityValidateAuthoritySharedGroupError(authority: string, validateAuthority: boolean, sharedGroup: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): this;
}
declare class ADAuthenticationError extends NSError {
static alloc(): ADAuthenticationError; // inherited from NSObject
static errorWithDomainCodeUserInfo(domain: string, code: number, dict: NSDictionary<any, any>): ADAuthenticationError; // inherited from NSError
static new(): ADAuthenticationError; // inherited from NSObject
readonly errorDetails: string;
readonly protocolCode: string;
}
declare var ADAuthenticationErrorDomain: string;
declare class ADAuthenticationParameters extends NSObject {
static alloc(): ADAuthenticationParameters; // inherited from NSObject
static new(): ADAuthenticationParameters; // inherited from NSObject
static parametersFromResourceUrlCompletionBlock(resourceUrl: NSURL, completion: (p1: ADAuthenticationParameters, p2: ADAuthenticationError) => void): void;
static parametersFromResponseAuthenticateHeaderError(authenticateHeader: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): ADAuthenticationParameters;
static parametersFromResponseError(response: NSHTTPURLResponse, error: interop.Pointer | interop.Reference<ADAuthenticationError>): ADAuthenticationParameters;
readonly authority: string;
readonly extractedParameters: NSDictionary<any, any>;
readonly resource: string;
}
declare class ADAuthenticationResult extends NSObject {
static alloc(): ADAuthenticationResult; // inherited from NSObject
static new(): ADAuthenticationResult; // inherited from NSObject
readonly accessToken: string;
readonly correlationId: NSUUID;
readonly error: ADAuthenticationError;
readonly extendedLifeTimeToken: boolean;
readonly multiResourceRefreshToken: boolean;
readonly status: ADAuthenticationResultStatus;
readonly tokenCacheItem: ADTokenCacheItem;
}
declare const enum ADAuthenticationResultStatus {
D_SUCCEEDED = 0,
D_USER_CANCELLED = 1,
D_FAILED = 2
}
declare class ADAuthenticationSettings extends NSObject {
static alloc(): ADAuthenticationSettings; // inherited from NSObject
static new(): ADAuthenticationSettings; // inherited from NSObject
static sharedInstance(): ADAuthenticationSettings;
enableFullScreen: boolean;
expirationBuffer: number;
requestTimeOut: number;
defaultKeychainGroup(): string;
setDefaultKeychainGroup(keychainGroup: string): void;
}
declare var ADBrokerResponseErrorDomain: string;
declare const enum ADCredentialsType {
D_CREDENTIALS_AUTO = 0,
D_CREDENTIALS_EMBEDDED = 1
}
interface ADDispatcher extends NSObjectProtocol {
dispatchEvent(event: NSDictionary<string, string>): void;
}
declare var ADDispatcher: {
prototype: ADDispatcher;
};
declare const enum ADErrorCode {
D_ERROR_SUCCEEDED = 0,
D_ERROR_UNEXPECTED = -1,
D_ERROR_DEVELOPER_INVALID_ARGUMENT = 100,
D_ERROR_DEVELOPER_AUTHORITY_VALIDATION = 101,
D_ERROR_SERVER_USER_INPUT_NEEDED = 200,
D_ERROR_SERVER_WPJ_REQUIRED = 201,
D_ERROR_SERVER_OAUTH = 202,
D_ERROR_SERVER_REFRESH_TOKEN_REJECTED = 203,
D_ERROR_SERVER_WRONG_USER = 204,
D_ERROR_SERVER_NON_HTTPS_REDIRECT = 205,
D_ERROR_SERVER_INVALID_ID_TOKEN = 206,
D_ERROR_SERVER_MISSING_AUTHENTICATE_HEADER = 207,
D_ERROR_SERVER_AUTHENTICATE_HEADER_BAD_FORMAT = 208,
D_ERROR_SERVER_UNAUTHORIZED_CODE_EXPECTED = 209,
D_ERROR_SERVER_UNSUPPORTED_REQUEST = 210,
D_ERROR_SERVER_AUTHORIZATION_CODE = 211,
D_ERROR_CACHE_MULTIPLE_USERS = 300,
D_ERROR_CACHE_VERSION_MISMATCH = 301,
D_ERROR_CACHE_BAD_FORMAT = 302,
D_ERROR_CACHE_NO_REFRESH_TOKEN = 303,
D_ERROR_UI_MULTLIPLE_INTERACTIVE_REQUESTS = 400,
D_ERROR_UI_NO_MAIN_VIEW_CONTROLLER = 401,
D_ERROR_UI_NOT_SUPPORTED_IN_APP_EXTENSION = 402,
D_ERROR_UI_USER_CANCEL = 403,
D_ERROR_UI_NOT_ON_MAIN_THREAD = 404,
D_ERROR_TOKENBROKER_UNKNOWN = 500,
D_ERROR_TOKENBROKER_INVALID_REDIRECT_URI = 501,
D_ERROR_TOKENBROKER_RESPONSE_HASH_MISMATCH = 502,
D_ERROR_TOKENBROKER_RESPONSE_NOT_RECEIVED = 503,
D_ERROR_TOKENBROKER_FAILED_TO_CREATE_KEY = 504,
D_ERROR_TOKENBROKER_DECRYPTION_FAILED = 505,
D_ERROR_TOKENBROKER_NOT_A_BROKER_RESPONSE = 506,
D_ERROR_TOKENBROKER_NO_RESUME_STATE = 507,
D_ERROR_TOKENBROKER_BAD_RESUME_STATE = 508,
D_ERROR_TOKENBROKER_MISMATCHED_RESUME_STATE = 509,
D_ERROR_TOKENBROKER_HASH_MISSING = 510,
D_ERROR_TOKENBROKER_NOT_SUPPORTED_IN_EXTENSION = 511
}
declare var ADHTTPErrorCodeDomain: string;
declare var ADKeychainErrorDomain: string;
declare class ADKeychainTokenCache extends NSObject {
static alloc(): ADKeychainTokenCache; // inherited from NSObject
static defaultKeychainCache(): ADKeychainTokenCache;
static defaultKeychainGroup(): string;
static keychainCacheForGroup(group: string): ADKeychainTokenCache;
static new(): ADKeychainTokenCache; // inherited from NSObject
static setDefaultKeychainGroup(keychainGroup: string): void;
readonly sharedGroup: string;
constructor(o: { group: string; });
allItems(error: interop.Pointer | interop.Reference<ADAuthenticationError>): NSArray<ADTokenCacheItem>;
initWithGroup(sharedGroup: string): this;
removeAllForClientIdError(clientId: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): boolean;
removeAllForUserIdClientIdError(userId: string, clientId: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): boolean;
removeItemError(item: ADTokenCacheItem, error: interop.Pointer | interop.Reference<ADAuthenticationError>): boolean;
}
declare class ADLogger extends NSObject {
static alloc(): ADLogger; // inherited from NSObject
static getLevel(): ADAL_LOG_LEVEL;
static getNSLogging(): boolean;
static new(): ADLogger; // inherited from NSObject
static setLevel(logLevel: ADAL_LOG_LEVEL): void;
static setLogCallBack(callback: (p1: ADAL_LOG_LEVEL, p2: string, p3: string, p4: number, p5: NSDictionary<any, any>) => void): void;
static setNSLogging(nslogging: boolean): void;
}
declare var ADOAuthServerErrorDomain: string;
declare const enum ADPromptBehavior {
D_PROMPT_AUTO = 0,
D_PROMPT_ALWAYS = 1,
D_PROMPT_REFRESH_SESSION = 2,
D_FORCE_PROMPT = 3
}
declare class ADTelemetry extends NSObject {
static alloc(): ADTelemetry; // inherited from NSObject
static new(): ADTelemetry; // inherited from NSObject
static sharedInstance(): ADTelemetry;
addDispatcherAggregationRequired(dispatcher: ADDispatcher, aggregationRequired: boolean): void;
removeAllDispatchers(): void;
removeDispatcher(dispatcher: ADDispatcher): void;
}
declare class ADTokenCacheItem extends NSObject implements NSCopying, NSSecureCoding {
static alloc(): ADTokenCacheItem; // inherited from NSObject
static new(): ADTokenCacheItem; // inherited from NSObject
accessToken: string;
accessTokenType: string;
authority: string;
clientId: string;
expiresOn: Date;
familyId: string;
refreshToken: string;
resource: string;
sessionKey: NSData;
userInformation: ADUserInformation;
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(aCoder: NSCoder): void;
initWithCoder(aDecoder: NSCoder): this;
isEmptyUser(): boolean;
isExpired(): boolean;
isMultiResourceRefreshToken(): boolean;
isSameUser(other: ADTokenCacheItem): boolean;
tombstone(): NSDictionary<any, any>;
}
declare class ADUserIdentifier extends NSObject implements NSCopying {
static alloc(): ADUserIdentifier; // inherited from NSObject
static identifierMatchesInfo(identifier: ADUserIdentifier, info: ADUserInformation): boolean;
static identifierWithId(userId: string): ADUserIdentifier;
static identifierWithIdType(userId: string, type: ADUserIdentifierType): ADUserIdentifier;
static identifierWithIdTypeFromString(userId: string, type: string): ADUserIdentifier;
static new(): ADUserIdentifier; // inherited from NSObject
static stringForType(type: ADUserIdentifierType): string;
readonly type: ADUserIdentifierType;
readonly userId: string;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
isDisplayable(): boolean;
typeAsString(): string;
userIdMatchString(info: ADUserInformation): string;
}
declare const enum ADUserIdentifierType {
UniqueId = 0,
OptionalDisplayableId = 1,
RequiredDisplayableId = 2
}
declare class ADUserInformation extends NSObject implements NSCopying, NSSecureCoding {
static alloc(): ADUserInformation; // inherited from NSObject
static new(): ADUserInformation; // inherited from NSObject
static normalizeUserId(userId: string): string;
static userInformationWithIdTokenError(idToken: string, error: interop.Pointer | interop.Reference<ADAuthenticationError>): ADUserInformation;
readonly allClaims: NSDictionary<any, any>;
readonly eMail: string;
readonly familyName: string;
readonly givenName: string;
readonly guestId: string;
readonly identityProvider: string;
readonly rawIdToken: string;
readonly subject: string;
readonly tenantId: string;
readonly uniqueId: string;
readonly uniqueName: string;
readonly upn: string;
readonly userId: string;
readonly userIdDisplayable: boolean;
readonly userObjectId: string;
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(aCoder: NSCoder): void;
initWithCoder(aDecoder: NSCoder): this;
}
declare class ADWebAuthController extends NSObject {
static alloc(): ADWebAuthController; // inherited from NSObject
static cancelCurrentWebAuthSession(): void;
static new(): ADWebAuthController; // inherited from NSObject
static responseFromInterruptedBrokerSession(): ADAuthenticationResult;
}
declare var ADWebAuthDidCompleteNotification: string;
declare var ADWebAuthDidFailNotification: string;
declare var ADWebAuthDidFinishLoadNotification: string;
declare var ADWebAuthDidReceieveResponseFromBroker: string;
declare var ADWebAuthDidStartLoadNotification: string;
declare var ADWebAuthWillSwitchToBrokerApp: string;
declare const enum HTTPStatusCodes {
P_UNAUTHORIZED = 401
}
| {
"content_hash": "0c88c5a9a1d81c210c786c4feac499a3",
"timestamp": "",
"source": "github",
"line_count": 504,
"max_line_length": 307,
"avg_line_length": 28.938492063492063,
"alnum_prop": 0.7850531367843675,
"repo_name": "NavaraBV/nativescript-adal",
"id": "cbc2b858c15ef020e0e1ee5bd53ad2c2f4323729",
"size": "14586",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/platforms/ios/typings/adal-library.ios.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "42"
},
{
"name": "Shell",
"bytes": "1264"
},
{
"name": "TypeScript",
"bytes": "4403"
}
],
"symlink_target": ""
} |
var sentiment = require('sentiment')
var afinn = require('sentiment/build/AFINN.json')
module.exports = function analyzeSentiment(controller) {
var listeningFor = '^' + Object.keys(afinn).map(escapeStringRegexp).join('|') + '$';
controller.hears([listeningFor], ['ambient'], function(bot, message) {
var sentimentAnalysis = sentiment(message.text);
console.log({
sentimentAnalysis: sentimentAnalysis
});
if (COUNT_POSITIVE_SCORES == false && sentimentAnalysis.score > 0) {
return;
}
if (COUNT_NEGATIVE_SCORES == false && sentimentAnalysis.score < 0) {
return;
}
collection.findAndModify({
_id: message.user
}, [
['_id', 1]
], {
$inc: {
score: sentimentAnalysis.score
}
}, {
'new': true,
upsert: true
}, function(err, result) {
if (err) {
throw err;
}
// full doc is available in result object:
// console.log(result)
var shamed = false;
if (INSTANCE_PUBLIC_SHAMING &&
sentimentAnalysis.score <= INSTANCE_PUBLIC_SHAMING_THRESHOLD) {
shamed = true;
bot.startConversation(message, function(err, convo) {
if (err) {
throw err;
}
var publicShamingMessage = _.sample(INSTANCE_PUBLIC_SHAMING_MESSAGES);
console.log({
publicShamingMessage: publicShamingMessage
});
convo.say(publicShamingMessage);
});
}
if (!shamed && INSTANCE_PRIVATE_SHAMING &&
sentimentAnalysis.score <= INSTANCE_PRIVATE_SHAMING_THRESHOLD) {
bot.startPrivateConversation(message, function(err, dm) {
if (err) {
throw err;
}
var privateShamingMessage = _.sample(INSTANCE_PRIVATE_SHAMING_MESSAGES);
console.log({
privateShamingMessage: privateShamingMessage
});
dm.say(privateShamingMessage);
});
}
});
});
}
| {
"content_hash": "b862aade07ecff35a1f63bc2868b4c28",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 92,
"avg_line_length": 34.114285714285714,
"alnum_prop": 0.4815745393634841,
"repo_name": "esjay/nonbots-bot",
"id": "625aefceded27874b2bef42a51a63a85d85e6617",
"size": "2388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/sentiment.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "212"
},
{
"name": "JavaScript",
"bytes": "10354"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.