text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "SDWebImageOperation.h"
typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
SDWebImageDownloaderLowPriority = 1 << 0,
SDWebImageDownloaderProgressiveDownload = 1 << 1,
/**
* By default, request prevent the of NSURLCache. With this flag, NSURLCache
* is used with default policies.
*/
SDWebImageDownloaderUseNSURLCache = 1 << 2,
/**
* Call completion block with nil image/imageData if the image was read from NSURLCache
* (to be combined with `SDWebImageDownloaderUseNSURLCache`).
*/
SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
/**
* In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
* extra time in background to let the request finish. If the background task expires the operation will be cancelled.
*/
SDWebImageDownloaderContinueInBackground = 1 << 4,
/**
* Handles cookies stored in NSHTTPCookieStore by setting
* NSMutableURLRequest.HTTPShouldHandleCookies = YES;
*/
SDWebImageDownloaderHandleCookies = 1 << 5,
/**
* Enable to allow untrusted SSL ceriticates.
* Useful for testing purposes. Use with caution in production.
*/
SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
/**
* Put the image in the high priority queue.
*/
SDWebImageDownloaderHighPriority = 1 << 7,
};
typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
/**
* Default value. All download operations will execute in queue style (first-in-first-out).
*/
SDWebImageDownloaderFIFOExecutionOrder,
/**
* All download operations will execute in stack style (last-in-first-out).
*/
SDWebImageDownloaderLIFOExecutionOrder
};
extern NSString *const SDWebImageDownloadStartNotification;
extern NSString *const SDWebImageDownloadStopNotification;
typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize);
typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers);
/**
* Asynchronous downloader dedicated and optimized for image loading.
*/
@interface SDWebImageDownloader : NSObject
@property (assign, nonatomic) NSInteger maxConcurrentDownloads;
/**
* Shows the current amount of downloads that still need to be downloaded
*/
@property (readonly, nonatomic) NSUInteger currentDownloadCount;
/**
* The timeout value (in seconds) for the download operation. Default: 15.0.
*/
@property (assign, nonatomic) NSTimeInterval downloadTimeout;
/**
* Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`.
*/
@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder;
/**
* Singleton method, returns the shared instance
*
* @return global shared instance of downloader class
*/
+ (SDWebImageDownloader *)sharedDownloader;
/**
* Set username
*/
@property (strong, nonatomic) NSString *username;
/**
* Set password
*/
@property (strong, nonatomic) NSString *password;
/**
* Set filter to pick headers for downloading image HTTP request.
*
* This block will be invoked for each downloading image request, returned
* NSDictionary will be used as headers in corresponding HTTP request.
*/
@property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter;
/**
* Set a value for a HTTP header to be appended to each download HTTP request.
*
* @param value The value for the header field. Use `nil` value to remove the header.
* @param field The name of the header field to set.
*/
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
/**
* Returns the value of the specified HTTP header field.
*
* @return The value associated with the header field field, or `nil` if there is no corresponding header field.
*/
- (NSString *)valueForHTTPHeaderField:(NSString *)field;
/**
* Sets a subclass of `SDWebImageDownloaderOperation` as the default
* `NSOperation` to be used each time SDWebImage constructs a request
* operation to download an image.
*
* @param operationClass The subclass of `SDWebImageDownloaderOperation` to set
* as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`.
*/
- (void)setOperationClass:(Class)operationClass;
/**
* Creates a SDWebImageDownloader async downloader instance with a given URL
*
* The delegate will be informed when the image is finish downloaded or an error has happen.
*
* @see SDWebImageDownloaderDelegate
*
* @param url The URL to the image to download
* @param options The options to be used for this download
* @param progressBlock A block called repeatedly while the image is downloading
* @param completedBlock A block called once the download is completed.
* If the download succeeded, the image parameter is set, in case of error,
* error parameter is set with the error. The last parameter is always YES
* if SDWebImageDownloaderProgressiveDownload isn't use. With the
* SDWebImageDownloaderProgressiveDownload option, this block is called
* repeatedly with the partial image object and the finished argument set to NO
* before to be called a last time with the full image and finished argument
* set to YES. In case of error, the finished argument is always YES.
*
* @return A cancellable SDWebImageOperation
*/
- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
options:(SDWebImageDownloaderOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
/**
* Sets the download queue suspension state
*/
- (void)setSuspended:(BOOL)suspended;
@end
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-checkbox-input-directive-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.4/angular.min.js"></script>
</head>
<body ng-app="">
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</body>
</html> | {
"pile_set_name": "Github"
} |
101.678400 0.000000 0.000000 -0.000000 -0.000000 0.000000 -0.000000 1.000000
101.782100 -0.005101 -0.008405 0.182029 0.000078 0.000049 -0.000578 1.000000
101.885900 -0.009896 -0.010170 0.364250 0.000296 -0.000088 -0.000994 0.999999
| {
"pile_set_name": "Github"
} |
<div class="alerta-severity-{{ max }} alerta-div">
<table class="alerta-table">
<tbody>
{% if title %}
<tr><th class="" colspan="5">{{ title }}</th></tr>
{% endif %}
<tr>
<td class="{{ 'alerta-severity-critical' if counts['critical'] }}"><b>{{ counts['critical'] }}</b></td>
<td class="{{ 'alerta-severity-major' if counts['major'] }}"><b>{{ counts['major'] }}</b></td>
<td class="{{ 'alerta-severity-minor' if counts['minor'] }}"><b>{{ counts['minor'] }}</b></td>
<td class="{{ 'alerta-severity-warning' if counts['warning'] }}"><b>{{ counts['warning'] }}</b></td>
<td class="{{ 'alerta-severity-informational' if counts['informational'] }}"><b>{{ counts['informational'] }}</b></td>
</tr>
</tbody>
</table>
<style>
.alerta-severity-critical{background-color: red;}
.alerta-severity-major{background-color: orange;}
.alerta-severity-minor {background-color: yellow;}
.alerta-severity-warning {background-color: #1E90FF;}
.alerta-severity-informational, .severity-cleared, .severity-ok, .severity-informational {background-color: #00CC00;}
.alerta-severity-debug {background-color: #7554BF;}
</style>
</div>
| {
"pile_set_name": "Github"
} |
package com.bdc.ociney.view.textview;
import android.graphics.Paint;
import android.view.Gravity;
import android.widget.TextView;
/*!
*
* TextJustifyUtils.java
* @author Mathew Kurian
*
* From TextJustify-Android Library v1.0.2
* https://github.com/bluejamesbond/TextJustify-Android
*
* Please report any issues
* https://github.com/bluejamesbond/TextJustify-Android/issues
*
* Date: 12/13/2013 12:29:16 PM
*
*/
public class TextJustifyUtils
{
// Please use run(...) instead
public static void justify(TextView textView)
{
Paint paint = new Paint();
String [] blocks;
float spaceOffset = 0;
float textWrapWidth = 0;
int spacesToSpread;
float wrappedEdgeSpace;
String block;
String [] lineAsWords;
String wrappedLine;
String smb = "";
Object [] wrappedObj;
// Pull widget properties
paint.setColor(textView.getCurrentTextColor());
paint.setTypeface(textView.getTypeface());
paint.setTextSize(textView.getTextSize());
textWrapWidth = textView.getWidth();
spaceOffset = paint.measureText(" ");
blocks = textView.getText().toString().split("((?<=\n)|(?=\n))");
if(textWrapWidth < 20)
{
return;
}
for(int i = 0; i < blocks.length; i++)
{
block = blocks[i];
if(block.length() == 0)
{
continue;
}
else if(block.equals("\n"))
{
smb += block;
continue;
}
block = block.trim();
if(block.length() == 0) continue;
wrappedObj = TextJustifyUtils.createWrappedLine(block, paint, spaceOffset, textWrapWidth);
wrappedLine = ((String) wrappedObj[0]);
wrappedEdgeSpace = (Float) wrappedObj[1];
lineAsWords = wrappedLine.split(" ");
spacesToSpread = (int) (wrappedEdgeSpace != Float.MIN_VALUE ? wrappedEdgeSpace/spaceOffset : 0);
for(String word : lineAsWords)
{
smb += word + " ";
if(--spacesToSpread > 0)
{
smb += " ";
}
}
smb = smb.trim();
if(blocks[i].length() > 0)
{
blocks[i] = blocks[i].substring(wrappedLine.length());
if(blocks[i].length() > 0)
{
smb += "\n";
}
i--;
}
}
textView.setGravity(Gravity.LEFT);
textView.setText(smb);
}
protected static Object [] createWrappedLine(String block, Paint paint, float spaceOffset, float maxWidth)
{
float cacheWidth = maxWidth;
float origMaxWidth = maxWidth;
String line = "";
for(String word : block.split("\\s"))
{
cacheWidth = paint.measureText(word);
maxWidth -= cacheWidth;
if(maxWidth <= 0)
{
return new Object[] { line, maxWidth + cacheWidth + spaceOffset };
}
line += word + " ";
maxWidth -= spaceOffset;
}
if(paint.measureText(block) <= origMaxWidth)
{
return new Object[] { block, Float.MIN_VALUE };
}
return new Object[] { line, maxWidth };
}
final static String SYSTEM_NEWLINE = "\n";
final static float COMPLEXITY = 5.12f; //Reducing this will increase efficiency but will decrease effectiveness
final static Paint p = new Paint();
/* @author Mathew Kurian */
public static void run(final TextView tv, float origWidth) {
String s = tv.getText().toString();
p.setTypeface(tv.getTypeface());
String [] splits = s.split(SYSTEM_NEWLINE);
float width = origWidth - 5;
for(int x = 0; x<splits.length;x++)
if(p.measureText(splits[x])>width){
splits[x] = wrap(splits[x], width, p);
String [] microSplits = splits[x].split(SYSTEM_NEWLINE);
for(int y = 0; y<microSplits.length-1;y++)
microSplits[y] = justify(removeLast(microSplits[y], " "), width, p);
StringBuilder smb_internal = new StringBuilder();
for(int z = 0; z<microSplits.length;z++)
smb_internal.append(microSplits[z]+((z+1<microSplits.length) ? SYSTEM_NEWLINE : ""));
splits[x] = smb_internal.toString();
}
final StringBuilder smb = new StringBuilder();
for(String cleaned : splits)
smb.append(cleaned+SYSTEM_NEWLINE);
tv.setGravity(Gravity.LEFT);
tv.setText(smb);
}
private static String wrap(String s, float width, Paint p){
String [] str = s.split("\\s"); //regex
StringBuilder smb = new StringBuilder(); //save memory
smb.append(SYSTEM_NEWLINE);
for(int x = 0; x<str.length; x++){
float length = p.measureText(str[x]);
String [] pieces = smb.toString().split(SYSTEM_NEWLINE);
try{
if(p.measureText(pieces[pieces.length-1])+length>width)
smb.append(SYSTEM_NEWLINE);
}catch(Exception e){}
smb.append(str[x] + " ");
}
return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
}
private static String removeLast(String s, String g){
if(s.contains(g)){
int index = s.lastIndexOf(g);
int indexEnd = index + g.length();
if(index == 0) return s.substring(1);
else if(index == s.length()-1) return s.substring(0, index);
else
return s.substring(0, index) + s.substring(indexEnd);
}
return s;
}
private static String justifyOperation(String s, float width, Paint p){
float holder = (float) (COMPLEXITY*Math.random());
while(s.contains(Float.toString(holder)))
holder = (float) (COMPLEXITY*Math.random());
String holder_string = Float.toString(holder);
float lessThan = width;
int timeOut = 100;
int current = 0;
while(p.measureText(s)<lessThan&¤t<timeOut) {
s = s.replaceFirst(" ([^"+holder_string+"])", " "+holder_string+"$1");
lessThan = p.measureText(holder_string)+lessThan-p.measureText(" ");
current++;
}
String cleaned = s.replaceAll(holder_string, " ");
return cleaned;
}
private static String justify(String s, float width, Paint p){
while(p.measureText(s)<width){
s = justifyOperation(s,width, p);
}
return s;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2005-2010 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) Version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
/*
* rport.c Remote port implementation.
*/
#include "bfad_drv.h"
#include "bfad_im.h"
#include "bfa_fcs.h"
#include "bfa_fcbuild.h"
BFA_TRC_FILE(FCS, RPORT);
static u32
bfa_fcs_rport_del_timeout = BFA_FCS_RPORT_DEF_DEL_TIMEOUT * 1000;
/* In millisecs */
/*
* forward declarations
*/
static struct bfa_fcs_rport_s *bfa_fcs_rport_alloc(
struct bfa_fcs_lport_s *port, wwn_t pwwn, u32 rpid);
static void bfa_fcs_rport_free(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_hal_online(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_online_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_offline_action(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_update(struct bfa_fcs_rport_s *rport,
struct fc_logi_s *plogi);
static void bfa_fcs_rport_timeout(void *arg);
static void bfa_fcs_rport_send_plogi(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_send_plogiacc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_plogi_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_adisc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_adisc_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_nsdisc(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_gidpn_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_gpnid_response(void *fcsarg,
struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs);
static void bfa_fcs_rport_send_logo(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rport_send_logo_acc(void *rport_cbarg);
static void bfa_fcs_rport_process_prli(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len);
static void bfa_fcs_rport_send_ls_rjt(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u8 reason_code,
u8 reason_code_expl);
static void bfa_fcs_rport_process_adisc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len);
static void bfa_fcs_rport_send_prlo_acc(struct bfa_fcs_rport_s *rport);
static void bfa_fcs_rport_sm_uninit(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogiacc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_plogi(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hal_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_online(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsquery_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsquery(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_adisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_adisc(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_fc4_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_hcb_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_logo_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static void bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event);
static struct bfa_sm_table_s rport_sm_table[] = {
{BFA_SM(bfa_fcs_rport_sm_uninit), BFA_RPORT_UNINIT},
{BFA_SM(bfa_fcs_rport_sm_plogi_sending), BFA_RPORT_PLOGI},
{BFA_SM(bfa_fcs_rport_sm_plogiacc_sending), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_plogi_retry), BFA_RPORT_PLOGI_RETRY},
{BFA_SM(bfa_fcs_rport_sm_plogi), BFA_RPORT_PLOGI},
{BFA_SM(bfa_fcs_rport_sm_hal_online), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_online), BFA_RPORT_ONLINE},
{BFA_SM(bfa_fcs_rport_sm_nsquery_sending), BFA_RPORT_NSQUERY},
{BFA_SM(bfa_fcs_rport_sm_nsquery), BFA_RPORT_NSQUERY},
{BFA_SM(bfa_fcs_rport_sm_adisc_sending), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_adisc), BFA_RPORT_ADISC},
{BFA_SM(bfa_fcs_rport_sm_fc4_logorcv), BFA_RPORT_LOGORCV},
{BFA_SM(bfa_fcs_rport_sm_fc4_logosend), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_fc4_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_hcb_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_hcb_logorcv), BFA_RPORT_LOGORCV},
{BFA_SM(bfa_fcs_rport_sm_hcb_logosend), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_logo_sending), BFA_RPORT_LOGO},
{BFA_SM(bfa_fcs_rport_sm_offline), BFA_RPORT_OFFLINE},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_sending), BFA_RPORT_NSDISC},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_retry), BFA_RPORT_NSDISC},
{BFA_SM(bfa_fcs_rport_sm_nsdisc_sent), BFA_RPORT_NSDISC},
};
/*
* Beginning state.
*/
static void
bfa_fcs_rport_sm_uninit(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_PLOGI_SEND:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_ADDRESS_DISC:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is being sent.
*/
static void
bfa_fcs_rport_sm_plogi_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_SCN:
/* query the NS */
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is being sent.
*/
static void
bfa_fcs_rport_sm_plogiacc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_PLOGI_COMP:
case RPSM_EVENT_SCN:
/*
* Ignore, SCN is possibly online notification.
*/
break;
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_HCB_OFFLINE:
/*
* Ignore BFA callback, on a PLOGI receive we call bfa offline.
*/
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is sent.
*/
static void
bfa_fcs_rport_sm_plogi_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
bfa_fcs_rport_send_plogi(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_LOGO_RCVD:
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_SCN:
bfa_timer_stop(&rport->timer);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_stop(&rport->timer);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is sent.
*/
static void
bfa_fcs_rport_sm_plogi(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
rport->plogi_retries = 0;
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
/*
* !! fall through !!
*/
case RPSM_EVENT_PRLO_RCVD:
if (rport->prlo == BFA_TRUE)
bfa_fcs_rport_send_prlo_acc(rport);
bfa_fcxp_discard(rport->fcxp);
/*
* !! fall through !!
*/
case RPSM_EVENT_FAILED:
if (rport->plogi_retries < BFA_FCS_RPORT_MAX_RETRIES) {
rport->plogi_retries++;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_retry);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
BFA_FCS_RETRY_TIMEOUT);
} else {
bfa_stats(rport->port, rport_del_max_plogi_retry);
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_PLOGI_RETRY:
rport->plogi_retries = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_retry);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
(FC_RA_TOV * 1000));
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_SCN:
bfa_fcxp_discard(rport->fcxp);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* PLOGI is complete. Awaiting BFA rport online callback. FC-4s
* are offline.
*/
static void
bfa_fcs_rport_sm_hal_online(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_ONLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_online);
bfa_fcs_rport_online_action(rport);
break;
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_PLOGI_COMP:
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logorcv);
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
break;
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
break;
case RPSM_EVENT_PLOGI_RCVD:
rport->plogi_pending = BFA_TRUE;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logosend);
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
break;
case RPSM_EVENT_SCN:
/*
* @todo
* Ignore SCN - PLOGI just completed, FC-4 login should detect
* device failures.
*/
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is ONLINE. FC-4s active.
*/
static void
bfa_fcs_rport_sm_online(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_SCN:
if (bfa_fcs_fabric_is_switched(rport->port->fabric)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsquery_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc_sending);
bfa_fcs_rport_send_adisc(rport, NULL);
}
break;
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. NS query is being sent
* prior to ADISC authentication with rport. FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_nsquery_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsquery);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
/*
* ignore SCN, wait for response to query itself
*/
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. NS query is sent to rport.
* FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_nsquery(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc_sending);
bfa_fcs_rport_send_adisc(rport, NULL);
break;
case RPSM_EVENT_FAILED:
rport->ns_retries++;
if (rport->ns_retries < BFA_FCS_RPORT_MAX_RETRIES) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsquery_sending);
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_offline_action(rport);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
case RPSM_EVENT_ADDRESS_CHANGE:
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. ADISC is being sent for
* authenticating with rport. FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_adisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_adisc);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* An SCN event is received in ONLINE state. ADISC is to rport.
* FC-4s are paused.
*/
static void
bfa_fcs_rport_sm_adisc(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_online);
break;
case RPSM_EVENT_PLOGI_RCVD:
/*
* Too complex to cleanup FC-4 & rport and then acc to PLOGI.
* At least go offline when a PLOGI is received.
*/
bfa_fcxp_discard(rport->fcxp);
/*
* !!! fall through !!!
*/
case RPSM_EVENT_FAILED:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_SCN:
/*
* already processing RSCN
*/
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logorcv);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_offline_action(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport has sent LOGO. Awaiting FC-4 offline completion callback.
*/
static void
bfa_fcs_rport_sm_fc4_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logorcv);
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* LOGO needs to be sent to rport. Awaiting FC-4 offline completion
* callback.
*/
static void
bfa_fcs_rport_sm_fc4_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logosend);
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is going offline. Awaiting FC-4 offline completion callback.
*/
static void
bfa_fcs_rport_sm_fc4_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FC4_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_OFFLINE);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_LOGO_IMP:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
/*
* rport is already going offline.
* SCN - ignore and wait till transitioning to offline state
*/
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_fc4_logosend);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is offline. FC-4s are offline. Awaiting BFA rport offline
* callback.
*/
static void
bfa_fcs_rport_sm_hcb_offline(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
if (bfa_fcs_lport_is_online(rport->port) &&
(rport->plogi_pending)) {
rport->plogi_pending = BFA_FALSE;
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
}
/*
* !! fall through !!
*/
case RPSM_EVENT_ADDRESS_CHANGE:
if (bfa_fcs_lport_is_online(rport->port)) {
if (bfa_fcs_fabric_is_switched(rport->port->fabric)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
}
} else {
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_PLOGI_RCVD:
case RPSM_EVENT_LOGO_IMP:
/*
* Ignore, already offline.
*/
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is offline. FC-4s are offline. Awaiting BFA rport offline
* callback to send LOGO accept.
*/
static void
bfa_fcs_rport_sm_hcb_logorcv(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
case RPSM_EVENT_ADDRESS_CHANGE:
if (rport->pid && (rport->prlo == BFA_TRUE))
bfa_fcs_rport_send_prlo_acc(rport);
if (rport->pid && (rport->prlo == BFA_FALSE))
bfa_fcs_rport_send_logo_acc(rport);
/*
* If the lport is online and if the rport is not a well
* known address port,
* we try to re-discover the r-port.
*/
if (bfa_fcs_lport_is_online(rport->port) &&
(!BFA_FCS_PID_IS_WKA(rport->pid))) {
if (bfa_fcs_fabric_is_switched(rport->port->fabric)) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
/* For N2N Direct Attach, try to re-login */
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
}
} else {
/*
* if it is not a well known address, reset the
* pid to 0.
*/
if (!BFA_FCS_PID_IS_WKA(rport->pid))
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
}
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_logosend);
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hcb_offline);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
/*
* Ignore - already processing a LOGO.
*/
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is being deleted. FC-4s are offline.
* Awaiting BFA rport offline
* callback to send LOGO.
*/
static void
bfa_fcs_rport_sm_hcb_logosend(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_HCB_OFFLINE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_logo_sending);
bfa_fcs_rport_send_logo(rport, NULL);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is being deleted. FC-4s are offline. LOGO is being sent.
*/
static void
bfa_fcs_rport_sm_logo_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
/* Once LOGO is sent, we donot wait for the response */
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport is offline. FC-4s are offline. BFA rport is offline.
* Timer active to delete stale rport.
*/
static void
bfa_fcs_rport_sm_offline(struct bfa_fcs_rport_s *rport, enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_timer_stop(&rport->timer);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_LOGO_IMP:
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_hal_online(rport);
break;
case RPSM_EVENT_PLOGI_SEND:
bfa_timer_stop(&rport->timer);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
rport->plogi_retries = 0;
bfa_fcs_rport_send_plogi(rport, NULL);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport address has changed. Nameserver discovery request is being sent.
*/
static void
bfa_fcs_rport_sm_nsdisc_sending(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sent);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_LOGO_RCVD:
case RPSM_EVENT_PRLO_RCVD:
case RPSM_EVENT_PLOGI_SEND:
break;
case RPSM_EVENT_ADDRESS_CHANGE:
rport->ns_retries = 0; /* reset the retry count */
break;
case RPSM_EVENT_LOGO_IMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rport->fcxp_wqe);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Nameserver discovery failed. Waiting for timeout to retry.
*/
static void
bfa_fcs_rport_sm_nsdisc_retry(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_TIMEOUT:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_SCN:
case RPSM_EVENT_ADDRESS_CHANGE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_nsdisc_sending);
bfa_timer_stop(&rport->timer);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_stop(&rport->timer);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_LOGO_RCVD:
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_PRLO_RCVD:
bfa_fcs_rport_send_prlo_acc(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_timer_stop(&rport->timer);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Rport address has changed. Nameserver discovery request is sent.
*/
static void
bfa_fcs_rport_sm_nsdisc_sent(struct bfa_fcs_rport_s *rport,
enum rport_event event)
{
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPSM_EVENT_ACCEPTED:
case RPSM_EVENT_ADDRESS_CHANGE:
if (rport->pid) {
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogi_sending);
bfa_fcs_rport_send_plogi(rport, NULL);
} else {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
rport->ns_retries = 0;
bfa_fcs_rport_send_nsdisc(rport, NULL);
}
break;
case RPSM_EVENT_FAILED:
rport->ns_retries++;
if (rport->ns_retries < BFA_FCS_RPORT_MAX_RETRIES) {
bfa_sm_set_state(rport,
bfa_fcs_rport_sm_nsdisc_sending);
bfa_fcs_rport_send_nsdisc(rport, NULL);
} else {
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
};
break;
case RPSM_EVENT_DELETE:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_free(rport);
break;
case RPSM_EVENT_PLOGI_RCVD:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_plogiacc_sending);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_send_plogiacc(rport, NULL);
break;
case RPSM_EVENT_LOGO_IMP:
rport->pid = 0;
bfa_sm_set_state(rport, bfa_fcs_rport_sm_offline);
bfa_fcxp_discard(rport->fcxp);
bfa_timer_start(rport->fcs->bfa, &rport->timer,
bfa_fcs_rport_timeout, rport,
bfa_fcs_rport_del_timeout);
break;
case RPSM_EVENT_PRLO_RCVD:
bfa_fcs_rport_send_prlo_acc(rport);
break;
case RPSM_EVENT_SCN:
/*
* ignore, wait for NS query response
*/
break;
case RPSM_EVENT_LOGO_RCVD:
/*
* Not logged-in yet. Accept LOGO.
*/
bfa_fcs_rport_send_logo_acc(rport);
break;
case RPSM_EVENT_PLOGI_COMP:
bfa_sm_set_state(rport, bfa_fcs_rport_sm_hal_online);
bfa_fcxp_discard(rport->fcxp);
bfa_fcs_rport_hal_online(rport);
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* fcs_rport_private FCS RPORT provate functions
*/
static void
bfa_fcs_rport_send_plogi(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_plogi, rport);
return;
}
rport->fcxp = fcxp;
len = fc_plogi_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), 0,
port->port_cfg.pwwn, port->port_cfg.nwwn,
bfa_fcport_get_maxfrsize(port->fcs->bfa),
bfa_fcport_get_rx_bbcredit(port->fcs->bfa));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rport_plogi_response,
(void *)rport, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.plogis++;
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_plogi_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct fc_logi_s *plogi_rsp;
struct fc_ls_rjt_s *ls_rjt;
struct bfa_fcs_rport_s *twin;
struct list_head *qe;
bfa_trc(rport->fcs, rport->pwwn);
/*
* Sanity Checks
*/
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
rport->stats.plogi_failed++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
plogi_rsp = (struct fc_logi_s *) BFA_FCXP_RSP_PLD(fcxp);
/*
* Check for failure first.
*/
if (plogi_rsp->els_cmd.els_code != FC_ELS_ACC) {
ls_rjt = (struct fc_ls_rjt_s *) BFA_FCXP_RSP_PLD(fcxp);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
if ((ls_rjt->reason_code == FC_LS_RJT_RSN_UNABLE_TO_PERF_CMD) &&
(ls_rjt->reason_code_expl == FC_LS_RJT_EXP_INSUFF_RES)) {
rport->stats.rjt_insuff_res++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RETRY);
return;
}
rport->stats.plogi_rejects++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
/*
* PLOGI is complete. Make sure this device is not one of the known
* device with a new FC port address.
*/
list_for_each(qe, &rport->port->rport_q) {
twin = (struct bfa_fcs_rport_s *) qe;
if (twin == rport)
continue;
if (!rport->pwwn && (plogi_rsp->port_name == twin->pwwn)) {
bfa_trc(rport->fcs, twin->pid);
bfa_trc(rport->fcs, rport->pid);
/* Update plogi stats in twin */
twin->stats.plogis += rport->stats.plogis;
twin->stats.plogi_rejects +=
rport->stats.plogi_rejects;
twin->stats.plogi_timeouts +=
rport->stats.plogi_timeouts;
twin->stats.plogi_failed +=
rport->stats.plogi_failed;
twin->stats.plogi_rcvd += rport->stats.plogi_rcvd;
twin->stats.plogi_accs++;
bfa_sm_send_event(rport, RPSM_EVENT_DELETE);
bfa_fcs_rport_update(twin, plogi_rsp);
twin->pid = rsp_fchs->s_id;
bfa_sm_send_event(twin, RPSM_EVENT_PLOGI_COMP);
return;
}
}
/*
* Normal login path -- no evil twins.
*/
rport->stats.plogi_accs++;
bfa_fcs_rport_update(rport, plogi_rsp);
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
}
static void
bfa_fcs_rport_send_plogiacc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->reply_oxid);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_plogiacc, rport);
return;
}
rport->fcxp = fcxp;
len = fc_plogi_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rport->pid, bfa_fcs_lport_get_fcid(port),
rport->reply_oxid, port->port_cfg.pwwn,
port->port_cfg.nwwn,
bfa_fcport_get_maxfrsize(port->fcs->bfa),
bfa_fcport_get_rx_bbcredit(port->fcs->bfa));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_send_adisc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_adisc, rport);
return;
}
rport->fcxp = fcxp;
len = fc_adisc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), 0,
port->port_cfg.pwwn, port->port_cfg.nwwn);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rport_adisc_response,
rport, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.adisc_sent++;
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_adisc_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
void *pld = bfa_fcxp_get_rspbuf(fcxp);
struct fc_ls_rjt_s *ls_rjt;
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
rport->stats.adisc_failed++;
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
return;
}
if (fc_adisc_rsp_parse((struct fc_adisc_s *)pld, rsp_len, rport->pwwn,
rport->nwwn) == FC_PARSE_OK) {
rport->stats.adisc_accs++;
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
return;
}
rport->stats.adisc_rejects++;
ls_rjt = pld;
bfa_trc(rport->fcs, ls_rjt->els_cmd.els_code);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
}
static void
bfa_fcs_rport_send_nsdisc(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_cb_fcxp_send_t cbfn;
bfa_trc(rport->fcs, rport->pid);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_nsdisc, rport);
return;
}
rport->fcxp = fcxp;
if (rport->pwwn) {
len = fc_gidpn_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
bfa_fcs_lport_get_fcid(port), 0, rport->pwwn);
cbfn = bfa_fcs_rport_gidpn_response;
} else {
len = fc_gpnid_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
bfa_fcs_lport_get_fcid(port), 0, rport->pid);
cbfn = bfa_fcs_rport_gpnid_response;
}
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, cbfn,
(void *)rport, FC_MAX_PDUSZ, FC_FCCT_TOV);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rport_gidpn_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct ct_hdr_s *cthdr;
struct fcgs_gidpn_resp_s *gidpn_rsp;
struct bfa_fcs_rport_s *twin;
struct list_head *qe;
bfa_trc(rport->fcs, rport->pwwn);
cthdr = (struct ct_hdr_s *) BFA_FCXP_RSP_PLD(fcxp);
cthdr->cmd_rsp_code = be16_to_cpu(cthdr->cmd_rsp_code);
if (cthdr->cmd_rsp_code == CT_RSP_ACCEPT) {
/* Check if the pid is the same as before. */
gidpn_rsp = (struct fcgs_gidpn_resp_s *) (cthdr + 1);
if (gidpn_rsp->dap == rport->pid) {
/* Device is online */
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
} else {
/*
* Device's PID has changed. We need to cleanup
* and re-login. If there is another device with
* the the newly discovered pid, send an scn notice
* so that its new pid can be discovered.
*/
list_for_each(qe, &rport->port->rport_q) {
twin = (struct bfa_fcs_rport_s *) qe;
if (twin == rport)
continue;
if (gidpn_rsp->dap == twin->pid) {
bfa_trc(rport->fcs, twin->pid);
bfa_trc(rport->fcs, rport->pid);
twin->pid = 0;
bfa_sm_send_event(twin,
RPSM_EVENT_ADDRESS_CHANGE);
}
}
rport->pid = gidpn_rsp->dap;
bfa_sm_send_event(rport, RPSM_EVENT_ADDRESS_CHANGE);
}
return;
}
/*
* Reject Response
*/
switch (cthdr->reason_code) {
case CT_RSN_LOGICAL_BUSY:
/*
* Need to retry
*/
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
break;
case CT_RSN_UNABLE_TO_PERF:
/*
* device doesn't exist : Start timer to cleanup this later.
*/
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
default:
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
}
}
static void
bfa_fcs_rport_gpnid_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct ct_hdr_s *cthdr;
bfa_trc(rport->fcs, rport->pwwn);
cthdr = (struct ct_hdr_s *) BFA_FCXP_RSP_PLD(fcxp);
cthdr->cmd_rsp_code = be16_to_cpu(cthdr->cmd_rsp_code);
if (cthdr->cmd_rsp_code == CT_RSP_ACCEPT) {
bfa_sm_send_event(rport, RPSM_EVENT_ACCEPTED);
return;
}
/*
* Reject Response
*/
switch (cthdr->reason_code) {
case CT_RSN_LOGICAL_BUSY:
/*
* Need to retry
*/
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
break;
case CT_RSN_UNABLE_TO_PERF:
/*
* device doesn't exist : Start timer to cleanup this later.
*/
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
default:
bfa_sm_send_event(rport, RPSM_EVENT_FAILED);
break;
}
}
/*
* Called to send a logout to the rport.
*/
static void
bfa_fcs_rport_send_logo(void *rport_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
u16 len;
bfa_trc(rport->fcs, rport->pid);
port = rport->port;
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rport->fcxp_wqe,
bfa_fcs_rport_send_logo, rport);
return;
}
rport->fcxp = fcxp;
len = fc_logo_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), 0,
bfa_fcs_lport_get_pwwn(port));
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL,
rport, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.logos++;
bfa_fcxp_discard(rport->fcxp);
bfa_sm_send_event(rport, RPSM_EVENT_FCXP_SENT);
}
/*
* Send ACC for a LOGO received.
*/
static void
bfa_fcs_rport_send_logo_acc(void *rport_cbarg)
{
struct bfa_fcs_rport_s *rport = rport_cbarg;
struct bfa_fcs_lport_s *port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
u16 len;
bfa_trc(rport->fcs, rport->pid);
port = rport->port;
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
rport->stats.logo_rcvd++;
len = fc_logo_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rport->pid, bfa_fcs_lport_get_fcid(port),
rport->reply_oxid);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
/*
* brief
* This routine will be called by bfa_timer on timer timeouts.
*
* param[in] rport - pointer to bfa_fcs_lport_ns_t.
* param[out] rport_status - pointer to return vport status in
*
* return
* void
*
* Special Considerations:
*
* note
*/
static void
bfa_fcs_rport_timeout(void *arg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) arg;
rport->stats.plogi_timeouts++;
bfa_stats(rport->port, rport_plogi_timeouts);
bfa_sm_send_event(rport, RPSM_EVENT_TIMEOUT);
}
static void
bfa_fcs_rport_process_prli(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_lport_s *port = rport->port;
struct fc_prli_s *prli;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.prli_rcvd++;
/*
* We are in Initiator Mode
*/
prli = (struct fc_prli_s *) (rx_fchs + 1);
if (prli->parampage.servparams.target) {
/*
* PRLI from a target ?
* Send the Acc.
* PRLI sent by us will be used to transition the IT nexus,
* once the response is received from the target.
*/
bfa_trc(port->fcs, rx_fchs->s_id);
rport->scsi_function = BFA_RPORT_TARGET;
} else {
bfa_trc(rport->fcs, prli->parampage.type);
rport->scsi_function = BFA_RPORT_INITIATOR;
bfa_fcs_itnim_is_initiator(rport->itnim);
}
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
len = fc_prli_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, port->port_cfg.roles);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
static void
bfa_fcs_rport_process_rpsc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_lport_s *port = rport->port;
struct fc_rpsc_speed_info_s speeds;
struct bfa_port_attr_s pport_attr;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.rpsc_rcvd++;
speeds.port_speed_cap =
RPSC_SPEED_CAP_1G | RPSC_SPEED_CAP_2G | RPSC_SPEED_CAP_4G |
RPSC_SPEED_CAP_8G;
/*
* get curent speed from pport attributes from BFA
*/
bfa_fcport_get_attr(port->fcs->bfa, &pport_attr);
speeds.port_op_speed = fc_bfa_speed_to_rpsc_operspeed(pport_attr.speed);
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
len = fc_rpsc_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, &speeds);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, NULL, NULL, FC_MAX_PDUSZ, 0);
}
static void
bfa_fcs_rport_process_adisc(struct bfa_fcs_rport_s *rport,
struct fchs_s *rx_fchs, u16 len)
{
struct bfa_fcxp_s *fcxp;
struct fchs_s fchs;
struct bfa_fcs_lport_s *port = rport->port;
struct fc_adisc_s *adisc;
bfa_trc(port->fcs, rx_fchs->s_id);
bfa_trc(port->fcs, rx_fchs->d_id);
rport->stats.adisc_rcvd++;
adisc = (struct fc_adisc_s *) (rx_fchs + 1);
/*
* Accept if the itnim for this rport is online.
* Else reject the ADISC.
*/
if (bfa_fcs_itnim_get_online_state(rport->itnim) == BFA_STATUS_OK) {
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
len = fc_adisc_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, port->port_cfg.pwwn,
port->port_cfg.nwwn);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag,
BFA_FALSE, FC_CLASS_3, len, &fchs, NULL, NULL,
FC_MAX_PDUSZ, 0);
} else {
rport->stats.adisc_rejected++;
bfa_fcs_rport_send_ls_rjt(rport, rx_fchs,
FC_LS_RJT_RSN_UNABLE_TO_PERF_CMD,
FC_LS_RJT_EXP_LOGIN_REQUIRED);
}
}
static void
bfa_fcs_rport_hal_online(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfa_rport_info_s rport_info;
rport_info.pid = rport->pid;
rport_info.local_pid = port->pid;
rport_info.lp_tag = port->lp_tag;
rport_info.vf_id = port->fabric->vf_id;
rport_info.vf_en = port->fabric->is_vf;
rport_info.fc_class = rport->fc_cos;
rport_info.cisc = rport->cisc;
rport_info.max_frmsz = rport->maxfrsize;
bfa_rport_online(rport->bfa_rport, &rport_info);
}
static struct bfa_fcs_rport_s *
bfa_fcs_rport_alloc(struct bfa_fcs_lport_s *port, wwn_t pwwn, u32 rpid)
{
struct bfa_fcs_s *fcs = port->fcs;
struct bfa_fcs_rport_s *rport;
struct bfad_rport_s *rport_drv;
/*
* allocate rport
*/
if (bfa_fcb_rport_alloc(fcs->bfad, &rport, &rport_drv)
!= BFA_STATUS_OK) {
bfa_trc(fcs, rpid);
return NULL;
}
/*
* Initialize r-port
*/
rport->port = port;
rport->fcs = fcs;
rport->rp_drv = rport_drv;
rport->pid = rpid;
rport->pwwn = pwwn;
/*
* allocate BFA rport
*/
rport->bfa_rport = bfa_rport_create(port->fcs->bfa, rport);
if (!rport->bfa_rport) {
bfa_trc(fcs, rpid);
kfree(rport_drv);
return NULL;
}
/*
* allocate FC-4s
*/
WARN_ON(!bfa_fcs_lport_is_initiator(port));
if (bfa_fcs_lport_is_initiator(port)) {
rport->itnim = bfa_fcs_itnim_create(rport);
if (!rport->itnim) {
bfa_trc(fcs, rpid);
bfa_sm_send_event(rport->bfa_rport,
BFA_RPORT_SM_DELETE);
kfree(rport_drv);
return NULL;
}
}
bfa_fcs_lport_add_rport(port, rport);
bfa_sm_set_state(rport, bfa_fcs_rport_sm_uninit);
/* Initialize the Rport Features(RPF) Sub Module */
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_init(rport);
return rport;
}
static void
bfa_fcs_rport_free(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
/*
* - delete FC-4s
* - delete BFA rport
* - remove from queue of rports
*/
if (bfa_fcs_lport_is_initiator(port)) {
bfa_fcs_itnim_delete(rport->itnim);
if (rport->pid != 0 && !BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_offline(rport);
}
bfa_sm_send_event(rport->bfa_rport, BFA_RPORT_SM_DELETE);
bfa_fcs_lport_del_rport(port, rport);
kfree(rport->rp_drv);
}
static void
bfa_fcs_rport_aen_post(struct bfa_fcs_rport_s *rport,
enum bfa_rport_aen_event event,
struct bfa_rport_aen_data_s *data)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfad_s *bfad = (struct bfad_s *)port->fcs->bfad;
struct bfa_aen_entry_s *aen_entry;
bfad_get_aen_entry(bfad, aen_entry);
if (!aen_entry)
return;
if (event == BFA_RPORT_AEN_QOS_PRIO)
aen_entry->aen_data.rport.priv.qos = data->priv.qos;
else if (event == BFA_RPORT_AEN_QOS_FLOWID)
aen_entry->aen_data.rport.priv.qos = data->priv.qos;
aen_entry->aen_data.rport.vf_id = rport->port->fabric->vf_id;
aen_entry->aen_data.rport.ppwwn = bfa_fcs_lport_get_pwwn(
bfa_fcs_get_base_port(rport->fcs));
aen_entry->aen_data.rport.lpwwn = bfa_fcs_lport_get_pwwn(rport->port);
aen_entry->aen_data.rport.rpwwn = rport->pwwn;
/* Send the AEN notification */
bfad_im_post_vendor_event(aen_entry, bfad, ++rport->fcs->fcs_aen_seq,
BFA_AEN_CAT_RPORT, event);
}
static void
bfa_fcs_rport_online_action(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfad_s *bfad = (struct bfad_s *)port->fcs->bfad;
char lpwwn_buf[BFA_STRING_32];
char rpwwn_buf[BFA_STRING_32];
rport->stats.onlines++;
if ((!rport->pid) || (!rport->pwwn)) {
bfa_trc(rport->fcs, rport->pid);
bfa_sm_fault(rport->fcs, rport->pid);
}
if (bfa_fcs_lport_is_initiator(port)) {
bfa_fcs_itnim_rport_online(rport->itnim);
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_online(rport);
};
wwn2str(lpwwn_buf, bfa_fcs_lport_get_pwwn(port));
wwn2str(rpwwn_buf, rport->pwwn);
if (!BFA_FCS_PID_IS_WKA(rport->pid)) {
BFA_LOG(KERN_INFO, bfad, bfa_log_level,
"Remote port (WWN = %s) online for logical port (WWN = %s)\n",
rpwwn_buf, lpwwn_buf);
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_ONLINE, NULL);
}
}
static void
bfa_fcs_rport_offline_action(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct bfad_s *bfad = (struct bfad_s *)port->fcs->bfad;
char lpwwn_buf[BFA_STRING_32];
char rpwwn_buf[BFA_STRING_32];
rport->stats.offlines++;
rport->plogi_pending = BFA_FALSE;
wwn2str(lpwwn_buf, bfa_fcs_lport_get_pwwn(port));
wwn2str(rpwwn_buf, rport->pwwn);
if (!BFA_FCS_PID_IS_WKA(rport->pid)) {
if (bfa_fcs_lport_is_online(rport->port) == BFA_TRUE) {
BFA_LOG(KERN_ERR, bfad, bfa_log_level,
"Remote port (WWN = %s) connectivity lost for "
"logical port (WWN = %s)\n",
rpwwn_buf, lpwwn_buf);
bfa_fcs_rport_aen_post(rport,
BFA_RPORT_AEN_DISCONNECT, NULL);
} else {
BFA_LOG(KERN_INFO, bfad, bfa_log_level,
"Remote port (WWN = %s) offlined by "
"logical port (WWN = %s)\n",
rpwwn_buf, lpwwn_buf);
bfa_fcs_rport_aen_post(rport,
BFA_RPORT_AEN_OFFLINE, NULL);
}
}
if (bfa_fcs_lport_is_initiator(port)) {
bfa_fcs_itnim_rport_offline(rport->itnim);
if (!BFA_FCS_PID_IS_WKA(rport->pid))
bfa_fcs_rpf_rport_offline(rport);
}
}
/*
* Update rport parameters from PLOGI or PLOGI accept.
*/
static void
bfa_fcs_rport_update(struct bfa_fcs_rport_s *rport, struct fc_logi_s *plogi)
{
bfa_fcs_lport_t *port = rport->port;
/*
* - port name
* - node name
*/
rport->pwwn = plogi->port_name;
rport->nwwn = plogi->node_name;
/*
* - class of service
*/
rport->fc_cos = 0;
if (plogi->class3.class_valid)
rport->fc_cos = FC_CLASS_3;
if (plogi->class2.class_valid)
rport->fc_cos |= FC_CLASS_2;
/*
* - CISC
* - MAX receive frame size
*/
rport->cisc = plogi->csp.cisc;
if (be16_to_cpu(plogi->class3.rxsz) < be16_to_cpu(plogi->csp.rxsz))
rport->maxfrsize = be16_to_cpu(plogi->class3.rxsz);
else
rport->maxfrsize = be16_to_cpu(plogi->csp.rxsz);
bfa_trc(port->fcs, be16_to_cpu(plogi->csp.bbcred));
bfa_trc(port->fcs, port->fabric->bb_credit);
/*
* Direct Attach P2P mode :
* This is to handle a bug (233476) in IBM targets in Direct Attach
* Mode. Basically, in FLOGI Accept the target would have
* erroneously set the BB Credit to the value used in the FLOGI
* sent by the HBA. It uses the correct value (its own BB credit)
* in PLOGI.
*/
if ((!bfa_fcs_fabric_is_switched(port->fabric)) &&
(be16_to_cpu(plogi->csp.bbcred) < port->fabric->bb_credit)) {
bfa_trc(port->fcs, be16_to_cpu(plogi->csp.bbcred));
bfa_trc(port->fcs, port->fabric->bb_credit);
port->fabric->bb_credit = be16_to_cpu(plogi->csp.bbcred);
bfa_fcport_set_tx_bbcredit(port->fcs->bfa,
port->fabric->bb_credit, 0);
}
}
/*
* Called to handle LOGO received from an existing remote port.
*/
static void
bfa_fcs_rport_process_logo(struct bfa_fcs_rport_s *rport, struct fchs_s *fchs)
{
rport->reply_oxid = fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->prlo = BFA_FALSE;
rport->stats.logo_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_LOGO_RCVD);
}
/*
* fcs_rport_public FCS rport public interfaces
*/
/*
* Called by bport/vport to create a remote port instance for a discovered
* remote device.
*
* @param[in] port - base port or vport
* @param[in] rpid - remote port ID
*
* @return None
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_create(struct bfa_fcs_lport_s *port, u32 rpid)
{
struct bfa_fcs_rport_s *rport;
bfa_trc(port->fcs, rpid);
rport = bfa_fcs_rport_alloc(port, WWN_NULL, rpid);
if (!rport)
return NULL;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_SEND);
return rport;
}
/*
* Called to create a rport for which only the wwn is known.
*
* @param[in] port - base port
* @param[in] rpwwn - remote port wwn
*
* @return None
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_create_by_wwn(struct bfa_fcs_lport_s *port, wwn_t rpwwn)
{
struct bfa_fcs_rport_s *rport;
bfa_trc(port->fcs, rpwwn);
rport = bfa_fcs_rport_alloc(port, rpwwn, 0);
if (!rport)
return NULL;
bfa_sm_send_event(rport, RPSM_EVENT_ADDRESS_DISC);
return rport;
}
/*
* Called by bport in private loop topology to indicate that a
* rport has been discovered and plogi has been completed.
*
* @param[in] port - base port or vport
* @param[in] rpid - remote port ID
*/
void
bfa_fcs_rport_start(struct bfa_fcs_lport_s *port, struct fchs_s *fchs,
struct fc_logi_s *plogi)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_rport_alloc(port, WWN_NULL, fchs->s_id);
if (!rport)
return;
bfa_fcs_rport_update(rport, plogi);
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_COMP);
}
/*
* Called by bport/vport to handle PLOGI received from a new remote port.
* If an existing rport does a plogi, it will be handled separately.
*/
void
bfa_fcs_rport_plogi_create(struct bfa_fcs_lport_s *port, struct fchs_s *fchs,
struct fc_logi_s *plogi)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_rport_alloc(port, plogi->port_name, fchs->s_id);
if (!rport)
return;
bfa_fcs_rport_update(rport, plogi);
rport->reply_oxid = fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->stats.plogi_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RCVD);
}
/*
* Called by bport/vport to handle PLOGI received from an existing
* remote port.
*/
void
bfa_fcs_rport_plogi(struct bfa_fcs_rport_s *rport, struct fchs_s *rx_fchs,
struct fc_logi_s *plogi)
{
/*
* @todo Handle P2P and initiator-initiator.
*/
bfa_fcs_rport_update(rport, plogi);
rport->reply_oxid = rx_fchs->ox_id;
bfa_trc(rport->fcs, rport->reply_oxid);
rport->pid = rx_fchs->s_id;
bfa_trc(rport->fcs, rport->pid);
rport->stats.plogi_rcvd++;
bfa_sm_send_event(rport, RPSM_EVENT_PLOGI_RCVD);
}
/*
* Called by bport/vport to notify SCN for the remote port
*/
void
bfa_fcs_rport_scn(struct bfa_fcs_rport_s *rport)
{
rport->stats.rscns++;
bfa_sm_send_event(rport, RPSM_EVENT_SCN);
}
/*
* brief
* This routine BFA callback for bfa_rport_online() call.
*
* param[in] cb_arg - rport struct.
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_online(void *cbarg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
bfa_trc(rport->fcs, rport->pwwn);
bfa_sm_send_event(rport, RPSM_EVENT_HCB_ONLINE);
}
/*
* brief
* This routine BFA callback for bfa_rport_offline() call.
*
* param[in] rport -
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_offline(void *cbarg)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
bfa_trc(rport->fcs, rport->pwwn);
bfa_sm_send_event(rport, RPSM_EVENT_HCB_OFFLINE);
}
/*
* brief
* This routine is a static BFA callback when there is a QoS flow_id
* change notification
*
* param[in] rport -
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_qos_scn_flowid(void *cbarg,
struct bfa_rport_qos_attr_s old_qos_attr,
struct bfa_rport_qos_attr_s new_qos_attr)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct bfa_rport_aen_data_s aen_data;
bfa_trc(rport->fcs, rport->pwwn);
aen_data.priv.qos = new_qos_attr;
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_QOS_FLOWID, &aen_data);
}
/*
* brief
* This routine is a static BFA callback when there is a QoS priority
* change notification
*
* param[in] rport -
*
* return
* void
*
* Special Considerations:
*
* note
*/
void
bfa_cb_rport_qos_scn_prio(void *cbarg,
struct bfa_rport_qos_attr_s old_qos_attr,
struct bfa_rport_qos_attr_s new_qos_attr)
{
struct bfa_fcs_rport_s *rport = (struct bfa_fcs_rport_s *) cbarg;
struct bfa_rport_aen_data_s aen_data;
bfa_trc(rport->fcs, rport->pwwn);
aen_data.priv.qos = new_qos_attr;
bfa_fcs_rport_aen_post(rport, BFA_RPORT_AEN_QOS_PRIO, &aen_data);
}
/*
* Called to process any unsolicted frames from this remote port
*/
void
bfa_fcs_rport_uf_recv(struct bfa_fcs_rport_s *rport,
struct fchs_s *fchs, u16 len)
{
struct bfa_fcs_lport_s *port = rport->port;
struct fc_els_cmd_s *els_cmd;
bfa_trc(rport->fcs, fchs->s_id);
bfa_trc(rport->fcs, fchs->d_id);
bfa_trc(rport->fcs, fchs->type);
if (fchs->type != FC_TYPE_ELS)
return;
els_cmd = (struct fc_els_cmd_s *) (fchs + 1);
bfa_trc(rport->fcs, els_cmd->els_code);
switch (els_cmd->els_code) {
case FC_ELS_LOGO:
bfa_stats(port, plogi_rcvd);
bfa_fcs_rport_process_logo(rport, fchs);
break;
case FC_ELS_ADISC:
bfa_stats(port, adisc_rcvd);
bfa_fcs_rport_process_adisc(rport, fchs, len);
break;
case FC_ELS_PRLO:
bfa_stats(port, prlo_rcvd);
if (bfa_fcs_lport_is_initiator(port))
bfa_fcs_fcpim_uf_recv(rport->itnim, fchs, len);
break;
case FC_ELS_PRLI:
bfa_stats(port, prli_rcvd);
bfa_fcs_rport_process_prli(rport, fchs, len);
break;
case FC_ELS_RPSC:
bfa_stats(port, rpsc_rcvd);
bfa_fcs_rport_process_rpsc(rport, fchs, len);
break;
default:
bfa_stats(port, un_handled_els_rcvd);
bfa_fcs_rport_send_ls_rjt(rport, fchs,
FC_LS_RJT_RSN_CMD_NOT_SUPP,
FC_LS_RJT_EXP_NO_ADDL_INFO);
break;
}
}
/* send best case acc to prlo */
static void
bfa_fcs_rport_send_prlo_acc(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_trc(rport->fcs, rport->pid);
fcxp = bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp)
return;
len = fc_prlo_acc_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rport->pid, bfa_fcs_lport_get_fcid(port),
rport->reply_oxid, 0);
bfa_fcxp_send(fcxp, rport->bfa_rport, port->fabric->vf_id,
port->lp_tag, BFA_FALSE, FC_CLASS_3, len, &fchs,
NULL, NULL, FC_MAX_PDUSZ, 0);
}
/*
* Send a LS reject
*/
static void
bfa_fcs_rport_send_ls_rjt(struct bfa_fcs_rport_s *rport, struct fchs_s *rx_fchs,
u8 reason_code, u8 reason_code_expl)
{
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
struct bfa_fcxp_s *fcxp;
int len;
bfa_trc(rport->fcs, rx_fchs->s_id);
fcxp = bfa_fcs_fcxp_alloc(rport->fcs);
if (!fcxp)
return;
len = fc_ls_rjt_build(&fchs, bfa_fcxp_get_reqbuf(fcxp),
rx_fchs->s_id, bfa_fcs_lport_get_fcid(port),
rx_fchs->ox_id, reason_code, reason_code_expl);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag,
BFA_FALSE, FC_CLASS_3, len, &fchs, NULL, NULL,
FC_MAX_PDUSZ, 0);
}
/*
* Return state of rport.
*/
int
bfa_fcs_rport_get_state(struct bfa_fcs_rport_s *rport)
{
return bfa_sm_to_state(rport_sm_table, rport->sm);
}
/*
* brief
* Called by the Driver to set rport delete/ageout timeout
*
* param[in] rport timeout value in seconds.
*
* return None
*/
void
bfa_fcs_rport_set_del_timeout(u8 rport_tmo)
{
/* convert to Millisecs */
if (rport_tmo > 0)
bfa_fcs_rport_del_timeout = rport_tmo * 1000;
}
void
bfa_fcs_rport_prlo(struct bfa_fcs_rport_s *rport, __be16 ox_id)
{
bfa_trc(rport->fcs, rport->pid);
rport->prlo = BFA_TRUE;
rport->reply_oxid = ox_id;
bfa_sm_send_event(rport, RPSM_EVENT_PRLO_RCVD);
}
void
bfa_fcs_rport_get_attr(struct bfa_fcs_rport_s *rport,
struct bfa_rport_attr_s *rport_attr)
{
struct bfa_rport_qos_attr_s qos_attr;
struct bfa_fcs_lport_s *port = rport->port;
bfa_port_speed_t rport_speed = rport->rpf.rpsc_speed;
memset(rport_attr, 0, sizeof(struct bfa_rport_attr_s));
memset(&qos_attr, 0, sizeof(struct bfa_rport_qos_attr_s));
rport_attr->pid = rport->pid;
rport_attr->pwwn = rport->pwwn;
rport_attr->nwwn = rport->nwwn;
rport_attr->cos_supported = rport->fc_cos;
rport_attr->df_sz = rport->maxfrsize;
rport_attr->state = bfa_fcs_rport_get_state(rport);
rport_attr->fc_cos = rport->fc_cos;
rport_attr->cisc = rport->cisc;
rport_attr->scsi_function = rport->scsi_function;
rport_attr->curr_speed = rport->rpf.rpsc_speed;
rport_attr->assigned_speed = rport->rpf.assigned_speed;
qos_attr.qos_priority = rport->bfa_rport->qos_attr.qos_priority;
qos_attr.qos_flow_id =
cpu_to_be32(rport->bfa_rport->qos_attr.qos_flow_id);
rport_attr->qos_attr = qos_attr;
rport_attr->trl_enforced = BFA_FALSE;
if (bfa_fcport_is_ratelim(port->fcs->bfa) &&
(rport->scsi_function == BFA_RPORT_TARGET)) {
if (rport_speed == BFA_PORT_SPEED_UNKNOWN)
rport_speed =
bfa_fcport_get_ratelim_speed(rport->fcs->bfa);
if (rport_speed < bfa_fcs_lport_get_rport_max_speed(port))
rport_attr->trl_enforced = BFA_TRUE;
}
}
/*
* Remote port implementation.
*/
/*
* fcs_rport_api FCS rport API.
*/
struct bfa_fcs_rport_s *
bfa_fcs_rport_lookup(struct bfa_fcs_lport_s *port, wwn_t rpwwn)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_lport_get_rport_by_pwwn(port, rpwwn);
if (rport == NULL) {
/*
* TBD Error handling
*/
}
return rport;
}
struct bfa_fcs_rport_s *
bfa_fcs_rport_lookup_by_nwwn(struct bfa_fcs_lport_s *port, wwn_t rnwwn)
{
struct bfa_fcs_rport_s *rport;
rport = bfa_fcs_lport_get_rport_by_nwwn(port, rnwwn);
if (rport == NULL) {
/*
* TBD Error handling
*/
}
return rport;
}
/*
* Remote port features (RPF) implementation.
*/
#define BFA_FCS_RPF_RETRIES (3)
#define BFA_FCS_RPF_RETRY_TIMEOUT (1000) /* 1 sec (In millisecs) */
static void bfa_fcs_rpf_send_rpsc2(void *rport_cbarg,
struct bfa_fcxp_s *fcxp_alloced);
static void bfa_fcs_rpf_rpsc2_response(void *fcsarg,
struct bfa_fcxp_s *fcxp,
void *cbarg,
bfa_status_t req_status,
u32 rsp_len,
u32 resid_len,
struct fchs_s *rsp_fchs);
static void bfa_fcs_rpf_timeout(void *arg);
/*
* fcs_rport_ftrs_sm FCS rport state machine events
*/
enum rpf_event {
RPFSM_EVENT_RPORT_OFFLINE = 1, /* Rport offline */
RPFSM_EVENT_RPORT_ONLINE = 2, /* Rport online */
RPFSM_EVENT_FCXP_SENT = 3, /* Frame from has been sent */
RPFSM_EVENT_TIMEOUT = 4, /* Rport SM timeout event */
RPFSM_EVENT_RPSC_COMP = 5,
RPFSM_EVENT_RPSC_FAIL = 6,
RPFSM_EVENT_RPSC_ERROR = 7,
};
static void bfa_fcs_rpf_sm_uninit(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_rpsc_sending(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_rpsc(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_rpsc_retry(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_offline(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void bfa_fcs_rpf_sm_online(struct bfa_fcs_rpf_s *rpf,
enum rpf_event event);
static void
bfa_fcs_rpf_sm_uninit(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
struct bfa_fcs_fabric_s *fabric = &rport->fcs->fabric;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPORT_ONLINE:
/* Send RPSC2 to a Brocade fabric only. */
if ((!BFA_FCS_PID_IS_WKA(rport->pid)) &&
((rport->port->fabric->lps->brcd_switch) ||
(bfa_fcs_fabric_get_switch_oui(fabric) ==
BFA_FCS_BRCD_SWITCH_OUI))) {
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_sending);
rpf->rpsc_retries = 0;
bfa_fcs_rpf_send_rpsc2(rpf, NULL);
}
break;
case RPFSM_EVENT_RPORT_OFFLINE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_rpsc_sending(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_FCXP_SENT:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc);
break;
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
bfa_fcxp_walloc_cancel(rport->fcs->bfa, &rpf->fcxp_wqe);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_rpsc(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPSC_COMP:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_online);
/* Update speed info in f/w via BFA */
if (rpf->rpsc_speed != BFA_PORT_SPEED_UNKNOWN)
bfa_rport_speed(rport->bfa_rport, rpf->rpsc_speed);
else if (rpf->assigned_speed != BFA_PORT_SPEED_UNKNOWN)
bfa_rport_speed(rport->bfa_rport, rpf->assigned_speed);
break;
case RPFSM_EVENT_RPSC_FAIL:
/* RPSC not supported by rport */
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_online);
break;
case RPFSM_EVENT_RPSC_ERROR:
/* need to retry...delayed a bit. */
if (rpf->rpsc_retries++ < BFA_FCS_RPF_RETRIES) {
bfa_timer_start(rport->fcs->bfa, &rpf->timer,
bfa_fcs_rpf_timeout, rpf,
BFA_FCS_RPF_RETRY_TIMEOUT);
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_retry);
} else {
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_online);
}
break;
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
bfa_fcxp_discard(rpf->fcxp);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_rpsc_retry(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_TIMEOUT:
/* re-send the RPSC */
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_sending);
bfa_fcs_rpf_send_rpsc2(rpf, NULL);
break;
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_timer_stop(&rpf->timer);
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_online(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPORT_OFFLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_offline);
rpf->rpsc_retries = 0;
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
static void
bfa_fcs_rpf_sm_offline(struct bfa_fcs_rpf_s *rpf, enum rpf_event event)
{
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pwwn);
bfa_trc(rport->fcs, rport->pid);
bfa_trc(rport->fcs, event);
switch (event) {
case RPFSM_EVENT_RPORT_ONLINE:
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_rpsc_sending);
bfa_fcs_rpf_send_rpsc2(rpf, NULL);
break;
case RPFSM_EVENT_RPORT_OFFLINE:
break;
default:
bfa_sm_fault(rport->fcs, event);
}
}
/*
* Called when Rport is created.
*/
void
bfa_fcs_rpf_init(struct bfa_fcs_rport_s *rport)
{
struct bfa_fcs_rpf_s *rpf = &rport->rpf;
bfa_trc(rport->fcs, rport->pid);
rpf->rport = rport;
bfa_sm_set_state(rpf, bfa_fcs_rpf_sm_uninit);
}
/*
* Called when Rport becomes online
*/
void
bfa_fcs_rpf_rport_online(struct bfa_fcs_rport_s *rport)
{
bfa_trc(rport->fcs, rport->pid);
if (__fcs_min_cfg(rport->port->fcs))
return;
if (bfa_fcs_fabric_is_switched(rport->port->fabric))
bfa_sm_send_event(&rport->rpf, RPFSM_EVENT_RPORT_ONLINE);
}
/*
* Called when Rport becomes offline
*/
void
bfa_fcs_rpf_rport_offline(struct bfa_fcs_rport_s *rport)
{
bfa_trc(rport->fcs, rport->pid);
if (__fcs_min_cfg(rport->port->fcs))
return;
rport->rpf.rpsc_speed = 0;
bfa_sm_send_event(&rport->rpf, RPFSM_EVENT_RPORT_OFFLINE);
}
static void
bfa_fcs_rpf_timeout(void *arg)
{
struct bfa_fcs_rpf_s *rpf = (struct bfa_fcs_rpf_s *) arg;
struct bfa_fcs_rport_s *rport = rpf->rport;
bfa_trc(rport->fcs, rport->pid);
bfa_sm_send_event(rpf, RPFSM_EVENT_TIMEOUT);
}
static void
bfa_fcs_rpf_send_rpsc2(void *rpf_cbarg, struct bfa_fcxp_s *fcxp_alloced)
{
struct bfa_fcs_rpf_s *rpf = (struct bfa_fcs_rpf_s *)rpf_cbarg;
struct bfa_fcs_rport_s *rport = rpf->rport;
struct bfa_fcs_lport_s *port = rport->port;
struct fchs_s fchs;
int len;
struct bfa_fcxp_s *fcxp;
bfa_trc(rport->fcs, rport->pwwn);
fcxp = fcxp_alloced ? fcxp_alloced : bfa_fcs_fcxp_alloc(port->fcs);
if (!fcxp) {
bfa_fcs_fcxp_alloc_wait(port->fcs->bfa, &rpf->fcxp_wqe,
bfa_fcs_rpf_send_rpsc2, rpf);
return;
}
rpf->fcxp = fcxp;
len = fc_rpsc2_build(&fchs, bfa_fcxp_get_reqbuf(fcxp), rport->pid,
bfa_fcs_lport_get_fcid(port), &rport->pid, 1);
bfa_fcxp_send(fcxp, NULL, port->fabric->vf_id, port->lp_tag, BFA_FALSE,
FC_CLASS_3, len, &fchs, bfa_fcs_rpf_rpsc2_response,
rpf, FC_MAX_PDUSZ, FC_ELS_TOV);
rport->stats.rpsc_sent++;
bfa_sm_send_event(rpf, RPFSM_EVENT_FCXP_SENT);
}
static void
bfa_fcs_rpf_rpsc2_response(void *fcsarg, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len,
u32 resid_len, struct fchs_s *rsp_fchs)
{
struct bfa_fcs_rpf_s *rpf = (struct bfa_fcs_rpf_s *) cbarg;
struct bfa_fcs_rport_s *rport = rpf->rport;
struct fc_ls_rjt_s *ls_rjt;
struct fc_rpsc2_acc_s *rpsc2_acc;
u16 num_ents;
bfa_trc(rport->fcs, req_status);
if (req_status != BFA_STATUS_OK) {
bfa_trc(rport->fcs, req_status);
if (req_status == BFA_STATUS_ETIMER)
rport->stats.rpsc_failed++;
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_ERROR);
return;
}
rpsc2_acc = (struct fc_rpsc2_acc_s *) BFA_FCXP_RSP_PLD(fcxp);
if (rpsc2_acc->els_cmd == FC_ELS_ACC) {
rport->stats.rpsc_accs++;
num_ents = be16_to_cpu(rpsc2_acc->num_pids);
bfa_trc(rport->fcs, num_ents);
if (num_ents > 0) {
WARN_ON(rpsc2_acc->port_info[0].pid == rport->pid);
bfa_trc(rport->fcs,
be16_to_cpu(rpsc2_acc->port_info[0].pid));
bfa_trc(rport->fcs,
be16_to_cpu(rpsc2_acc->port_info[0].speed));
bfa_trc(rport->fcs,
be16_to_cpu(rpsc2_acc->port_info[0].index));
bfa_trc(rport->fcs,
rpsc2_acc->port_info[0].type);
if (rpsc2_acc->port_info[0].speed == 0) {
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_ERROR);
return;
}
rpf->rpsc_speed = fc_rpsc_operspeed_to_bfa_speed(
be16_to_cpu(rpsc2_acc->port_info[0].speed));
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_COMP);
}
} else {
ls_rjt = (struct fc_ls_rjt_s *) BFA_FCXP_RSP_PLD(fcxp);
bfa_trc(rport->fcs, ls_rjt->reason_code);
bfa_trc(rport->fcs, ls_rjt->reason_code_expl);
rport->stats.rpsc_rejects++;
if (ls_rjt->reason_code == FC_LS_RJT_RSN_CMD_NOT_SUPP)
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_FAIL);
else
bfa_sm_send_event(rpf, RPFSM_EVENT_RPSC_ERROR);
}
}
| {
"pile_set_name": "Github"
} |
/**
* 64-bit integer encodded as Hex String.
*/
type IdNumber = string;
/**
* Dictionary type, so baiscally just a Map from string to T.
*/
interface IDictionary<T> {
[x: string]: T;
}
/**
* Type to pass functions around without allowing them being called.
*/
type UncallableFunction = (this: never) => any;
// DTO type which is guaranteed to be serializable correctly via toJSON
type DTOtype = string | number | boolean | GenericDTO | DTOArray;
// tslint:disable-next-line
interface DTOArray extends Array<DTOtype> { }
// tslint:disable-next-line
interface GenericDTO { [k: string]: DTOtype }
/**
* DTO which is only allowed to have the same properties as T.
* Useful to avoid typos, unfortunately doesn't work for private members.
*/
type DTO<T> = {[k in keyof T]?: DTOtype};
/**
* Configuration provided by the environment.
*/
interface IAgentConfiguration {
eumManagementServer: string;
activeAgentModules: string;
relevancyThreshold: number;
allowListenerInstrumentation: boolean;
respectDNT: boolean;
domEventSelectors?: Array<[string, string, string, boolean, number]>;
traceid?: IdNumber;
}
const SETTINGS: IAgentConfiguration = (window as any).inspectIT_settings;
// remove the settigns from the global object to avoid modification
delete (window as any).inspectIT_settings;
// add inspectIt to the Window interface
interface InspectIT {
init?: () => void;
}
// tslint:disable-next-line
interface Window {
inspectIT: InspectIT;
}
| {
"pile_set_name": "Github"
} |
{frontmatter}
00-foreword/00-introduction.md
00-foreword/01-about-the-author.md
00-foreword/02-requirements.md
00-foreword/03-faq.md
00-foreword/04-how-to-read-the-book.md
00-foreword/05-challenge.md
{mainmatter}
01-graphql/index.md
02-apollo/index.md
03-graphql-setup/index.md
04-graphql-fundamentals/index.md
05-graphql-react/index.md
06-apollo-client/index.md
07-apollo-react/index.md
08-apollo-server/index.md
{backmatter}
99-end/00-learning-paths.md
99-end/01-keep-learning.md
99-end/02-thanks.md
| {
"pile_set_name": "Github"
} |
name: "FSRCNN"
input: "data"
input_dim: 1
input_dim: 1
input_dim: 7
input_dim: 7
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
convolution_param {
num_output: 56
kernel_size: 5
stride: 1
pad: 2
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prelu1"
type: "PReLU"
bottom: "conv1"
top: "conv1"
}
layer {
name: "conv2"
type: "Convolution"
bottom: "conv1"
top: "conv2"
convolution_param {
num_output: 12
kernel_size: 1
stride: 1
pad: 0
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prelu2"
type: "PReLU"
bottom: "conv2"
top: "conv2"
}
layer {
name: "conv3"
type: "Convolution"
bottom: "conv2"
top: "conv3"
convolution_param {
num_output: 12
kernel_size: 3
stride: 1
pad: 1
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prelu3"
type: "PReLU"
bottom: "conv3"
top: "conv3"
}
layer {
name: "conv4"
type: "Convolution"
bottom: "conv3"
top: "conv4"
convolution_param {
num_output: 12
kernel_size: 3
stride: 1
pad: 1
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prelu4"
type: "PReLU"
bottom: "conv4"
top: "conv4"
}
layer {
name: "conv5"
type: "Convolution"
bottom: "conv4"
top: "conv5"
convolution_param {
num_output: 12
kernel_size: 3
stride: 1
pad: 1
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prelu5"
type: "PReLU"
bottom: "conv5"
top: "conv5"
}
layer {
name: "conv6"
type: "Convolution"
bottom: "conv5"
top: "conv6"
convolution_param {
num_output: 12
kernel_size: 3
stride: 1
pad: 1
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prelu6"
type: "PReLU"
bottom: "conv6"
top: "conv6"
}
layer {
name: "conv7"
type: "Convolution"
bottom: "conv6"
top: "conv7"
convolution_param {
num_output: 56
kernel_size: 1
stride: 1
pad: 0
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prelu7"
type: "PReLU"
bottom: "conv7"
top: "conv7"
}
layer {
name: "deconv"
type: "Deconvolution"
bottom: "conv7"
top: "deconv"
convolution_param {
num_output: 1
kernel_size: 9
stride: 3
pad: 4
weight_filler {
type: "gaussian"
std: 0.001
}
bias_filler {
type: "constant"
}
}
} | {
"pile_set_name": "Github"
} |
#Lesson 2: Create and Test Alerts [](slides/june-DSO-bootcamp-week-four-lesson-two.pdf)[](https://speakerdeck.com/devsecops/devsecops-bootcamp-week-4-lesson-2)
##
```
* Important Fields within Data
* Field Extractions
* Statistics
* Dashboards
```
## Lab #2 [](labs/LAB-2.md)
```
* Search for Invalid SSH Login Attempts
* Splunk Field Extraction
* Splunk Statistics
* Create a Splunk Alert
```
## Resources
* [Splunk](http://splunk.com)
| {
"pile_set_name": "Github"
} |
using Cim.Eap.Tx;
using Secs4Net;
namespace Eap.Driver.MWN {
partial class Driver {
void EQP_UnloadComplete(SecsMessage msg) {
EAP.Report(new UnloadCompleteReport {
PortID = GetPortID((byte)msg.SecsItem.Items[2].Items[0].Items[1].Items[0])
});
}
}
} | {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/. */
var EXPORTED_SYMBOLS = ['findCallerFrame'];
/**
* @namespace Defines utility methods for handling stack frames
*/
/**
* Find the frame to use for logging the test result. If a start frame has
* been specified, we walk down the stack until a frame with the same filename
* as the start frame has been found. The next file in the stack will be the
* frame to use for logging the result.
*
* @memberOf stack
* @param {Object} [aStartFrame=Components.stack] Frame to start from walking up the stack.
* @returns {Object} Frame of the stack to use for logging the result.
*/
function findCallerFrame(aStartFrame) {
let frame = Components.stack;
let filename = frame.filename.replace(/(.*)-> /, "");
// If a start frame has been specified, walk up the stack until we have
// found the corresponding file
if (aStartFrame) {
filename = aStartFrame.filename.replace(/(.*)-> /, "");
while (frame.caller &&
frame.filename && (frame.filename.indexOf(filename) == -1)) {
frame = frame.caller;
}
}
// Walk even up more until the next file has been found
while (frame.caller &&
(!frame.filename || (frame.filename.indexOf(filename) != -1)))
frame = frame.caller;
return frame;
}
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#import <Foundation/Foundation.h>
@class GPBMessage;
@class GPBExtensionRegistry;
NS_ASSUME_NONNULL_BEGIN
CF_EXTERN_C_BEGIN
/**
* @c GPBCodedInputStream exception name. Exceptions raised from
* @c GPBCodedInputStream contain an underlying error in the userInfo dictionary
* under the GPBCodedInputStreamUnderlyingErrorKey key.
**/
extern NSString *const GPBCodedInputStreamException;
/** The key under which the underlying NSError from the exception is stored. */
extern NSString *const GPBCodedInputStreamUnderlyingErrorKey;
/** NSError domain used for @c GPBCodedInputStream errors. */
extern NSString *const GPBCodedInputStreamErrorDomain;
/**
* Error code for NSError with @c GPBCodedInputStreamErrorDomain.
**/
typedef NS_ENUM(NSInteger, GPBCodedInputStreamErrorCode) {
/** The size does not fit in the remaining bytes to be read. */
GPBCodedInputStreamErrorInvalidSize = -100,
/** Attempted to read beyond the subsection limit. */
GPBCodedInputStreamErrorSubsectionLimitReached = -101,
/** The requested subsection limit is invalid. */
GPBCodedInputStreamErrorInvalidSubsectionLimit = -102,
/** Invalid tag read. */
GPBCodedInputStreamErrorInvalidTag = -103,
/** Invalid UTF-8 character in a string. */
GPBCodedInputStreamErrorInvalidUTF8 = -104,
/** Invalid VarInt read. */
GPBCodedInputStreamErrorInvalidVarInt = -105,
/** The maximum recursion depth of messages was exceeded. */
GPBCodedInputStreamErrorRecursionDepthExceeded = -106,
};
CF_EXTERN_C_END
/**
* Reads and decodes protocol message fields.
*
* The common uses of protocol buffers shouldn't need to use this class.
* @c GPBMessage's provide a @c +parseFromData:error: and
* @c +parseFromData:extensionRegistry:error: method that will decode a
* message for you.
*
* @note Subclassing of @c GPBCodedInputStream is NOT supported.
**/
@interface GPBCodedInputStream : NSObject
/**
* Creates a new stream wrapping some data.
*
* @param data The data to wrap inside the stream.
*
* @return A newly instanced GPBCodedInputStream.
**/
+ (instancetype)streamWithData:(NSData *)data;
/**
* Initializes a stream wrapping some data.
*
* @param data The data to wrap inside the stream.
*
* @return A newly initialized GPBCodedInputStream.
**/
- (instancetype)initWithData:(NSData *)data;
/**
* Attempts to read a field tag, returning zero if we have reached EOF.
* Protocol message parsers use this to read tags, since a protocol message
* may legally end wherever a tag occurs, and zero is not a valid tag number.
*
* @return The field tag, or zero if EOF was reached.
**/
- (int32_t)readTag;
/**
* @return A double read from the stream.
**/
- (double)readDouble;
/**
* @return A float read from the stream.
**/
- (float)readFloat;
/**
* @return A uint64 read from the stream.
**/
- (uint64_t)readUInt64;
/**
* @return A uint32 read from the stream.
**/
- (uint32_t)readUInt32;
/**
* @return An int64 read from the stream.
**/
- (int64_t)readInt64;
/**
* @return An int32 read from the stream.
**/
- (int32_t)readInt32;
/**
* @return A fixed64 read from the stream.
**/
- (uint64_t)readFixed64;
/**
* @return A fixed32 read from the stream.
**/
- (uint32_t)readFixed32;
/**
* @return An enum read from the stream.
**/
- (int32_t)readEnum;
/**
* @return A sfixed32 read from the stream.
**/
- (int32_t)readSFixed32;
/**
* @return A fixed64 read from the stream.
**/
- (int64_t)readSFixed64;
/**
* @return A sint32 read from the stream.
**/
- (int32_t)readSInt32;
/**
* @return A sint64 read from the stream.
**/
- (int64_t)readSInt64;
/**
* @return A boolean read from the stream.
**/
- (BOOL)readBool;
/**
* @return A string read from the stream.
**/
- (NSString *)readString;
/**
* @return Data read from the stream.
**/
- (NSData *)readBytes;
/**
* Read an embedded message field value from the stream.
*
* @param message The message to set fields on as they are read.
* @param extensionRegistry An optional extension registry to use to lookup
* extensions for message.
**/
- (void)readMessage:(GPBMessage *)message
extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry;
/**
* Reads and discards a single field, given its tag value.
*
* @param tag The tag number of the field to skip.
*
* @return NO if the tag is an endgroup tag (in which case nothing is skipped),
* YES in all other cases.
**/
- (BOOL)skipField:(int32_t)tag;
/**
* Reads and discards an entire message. This will read either until EOF or
* until an endgroup tag, whichever comes first.
**/
- (void)skipMessage;
/**
* Check to see if the logical end of the stream has been reached.
*
* @note This can return NO when there is no more data, but the current parsing
* expected more data.
*
* @return YES if the logical end of the stream has been reached, NO otherwise.
**/
- (BOOL)isAtEnd;
/**
* @return The offset into the stream.
**/
- (size_t)position;
/**
* Moves the limit to the given byte offset starting at the current location.
*
* @exception GPBCodedInputStreamException If the requested bytes exceeed the
* current limit.
*
* @param byteLimit The number of bytes to move the limit, offset to the current
* location.
*
* @return The limit offset before moving the new limit.
*/
- (size_t)pushLimit:(size_t)byteLimit;
/**
* Moves the limit back to the offset as it was before calling pushLimit:.
*
* @param oldLimit The number of bytes to move the current limit. Usually this
* is the value returned by the pushLimit: method.
*/
- (void)popLimit:(size_t)oldLimit;
/**
* Verifies that the last call to -readTag returned the given tag value. This
* is used to verify that a nested group ended with the correct end tag.
*
* @exception NSParseErrorException If the value does not match the last tag.
*
* @param expected The tag that was expected.
**/
- (void)checkLastTagWas:(int32_t)expected;
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
#include <libmarkup/Markup.h>
#include <libsystem/utils/BufferBuilder.h>
struct MarkupPrettifyState
{
BufferBuilder *builder;
int depth;
bool color;
bool first_line;
};
static const char *depth_color[] = {
"\e[91m",
"\e[92m",
"\e[93m",
"\e[94m",
"\e[95m",
"\e[96m",
};
static void markup_prettify_ident(MarkupPrettifyState *state)
{
if (!state->first_line)
buffer_builder_append_chr(state->builder, '\n');
else
state->first_line = false;
for (int i = 0; i < state->depth; i++)
{
buffer_builder_append_str(state->builder, " ");
}
}
static void markup_prettify_internal(MarkupPrettifyState *state, MarkupNode *node)
{
markup_prettify_ident(state);
buffer_builder_append_chr(state->builder, '<');
if (state->color)
{
buffer_builder_append_str(state->builder, depth_color[state->depth % 6]);
}
buffer_builder_append_str(state->builder, node->type);
if (state->color)
{
buffer_builder_append_str(state->builder, "\e[m");
}
list_foreach(MarkupAttribute, attribute, node->attributes)
{
buffer_builder_append_chr(state->builder, ' ');
buffer_builder_append_str(state->builder, attribute->name);
if (attribute->value)
{
buffer_builder_append_chr(state->builder, '=');
buffer_builder_append_chr(state->builder, '"');
buffer_builder_append_str(state->builder, attribute->value);
buffer_builder_append_chr(state->builder, '"');
}
}
if (node->childs->empty())
{
buffer_builder_append_str(state->builder, "/>");
return;
}
else
{
buffer_builder_append_chr(state->builder, '>');
}
list_foreach(MarkupNode, child, node->childs)
{
state->depth++;
markup_prettify_internal(state, child);
state->depth--;
}
markup_prettify_ident(state);
buffer_builder_append_str(state->builder, "</");
if (state->color)
{
buffer_builder_append_str(state->builder, depth_color[state->depth % 6]);
}
buffer_builder_append_str(state->builder, node->type);
if (state->color)
{
buffer_builder_append_str(state->builder, "\e[m");
}
buffer_builder_append_chr(state->builder, '>');
}
char *markup_prettify(MarkupNode *root)
{
BufferBuilder *builder = buffer_builder_create(128);
MarkupPrettifyState state = {builder, 0, true, true};
markup_prettify_internal(&state, root);
return buffer_builder_finalize(builder);
}
| {
"pile_set_name": "Github"
} |
parameters:
nelmio_security.external_redirects.whitelist: ~
services:
nelmio_security.external_redirect_listener:
class: Nelmio\SecurityBundle\EventListener\ExternalRedirectListener
arguments:
- '%nelmio_security.external_redirects.abort%'
- '%nelmio_security.external_redirects.override%'
- '%nelmio_security.external_redirects.forward_as%'
- '@?nelmio_security.external_redirect.target_validator'
- '@?logger'
- '@?router'
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
- { name: monolog.logger, channel: security }
nelmio_security.external_redirect.target_validator:
alias: nelmio_security.external_redirect.target_validator.whitelist
nelmio_security.external_redirect.target_validator.whitelist:
public: false
class: Nelmio\SecurityBundle\ExternalRedirect\WhitelistBasedTargetValidator
arguments:
- '%nelmio_security.external_redirects.whitelist%'
| {
"pile_set_name": "Github"
} |
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Power Management Controller
namespace PmcLvdsc1{ ///<Low Voltage Detect Status and Control 1 Register
using Addr = Register::Address<0x4007d000,0xffffff0c,0x00000000,unsigned char>;
///Low-Voltage Detect Voltage Select
enum class LvdvVal {
v00=0x00000000, ///<Low trip point selected (V LVD = V LVDL )
v01=0x00000001, ///<High trip point selected (V LVD = V LVDH )
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,LvdvVal> lvdv{};
namespace LvdvValC{
constexpr Register::FieldValue<decltype(lvdv)::Type,LvdvVal::v00> v00{};
constexpr Register::FieldValue<decltype(lvdv)::Type,LvdvVal::v01> v01{};
}
///Low-Voltage Detect Reset Enable
enum class LvdreVal {
v0=0x00000000, ///<LVDF does not generate hardware resets
v1=0x00000001, ///<Force an MCU reset when LVDF = 1
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,LvdreVal> lvdre{};
namespace LvdreValC{
constexpr Register::FieldValue<decltype(lvdre)::Type,LvdreVal::v0> v0{};
constexpr Register::FieldValue<decltype(lvdre)::Type,LvdreVal::v1> v1{};
}
///Low-Voltage Detect Interrupt Enable
enum class LvdieVal {
v0=0x00000000, ///<Hardware interrupt disabled (use polling)
v1=0x00000001, ///<Request a hardware interrupt when LVDF = 1.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,LvdieVal> lvdie{};
namespace LvdieValC{
constexpr Register::FieldValue<decltype(lvdie)::Type,LvdieVal::v0> v0{};
constexpr Register::FieldValue<decltype(lvdie)::Type,LvdieVal::v1> v1{};
}
///Low-Voltage Detect Acknowledge
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lvdack{};
///Low-Voltage Detect Flag
enum class LvdfVal {
v0=0x00000000, ///<Low-voltage event not detected
v1=0x00000001, ///<Low-voltage event detected
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,LvdfVal> lvdf{};
namespace LvdfValC{
constexpr Register::FieldValue<decltype(lvdf)::Type,LvdfVal::v0> v0{};
constexpr Register::FieldValue<decltype(lvdf)::Type,LvdfVal::v1> v1{};
}
}
namespace PmcLvdsc2{ ///<Low Voltage Detect Status and Control 2 Register
using Addr = Register::Address<0x4007d001,0xffffff1c,0x00000000,unsigned char>;
///Low-Voltage Warning Voltage Select
enum class LvwvVal {
v00=0x00000000, ///<Low trip point selected (V LVW = V LVW1 )
v01=0x00000001, ///<Mid 1 trip point selected (V LVW = V LVW2 )
v10=0x00000002, ///<Mid 2 trip point selected (V LVW = V LVW3 )
v11=0x00000003, ///<High trip point selected (V LVW = V LVW4 )
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,LvwvVal> lvwv{};
namespace LvwvValC{
constexpr Register::FieldValue<decltype(lvwv)::Type,LvwvVal::v00> v00{};
constexpr Register::FieldValue<decltype(lvwv)::Type,LvwvVal::v01> v01{};
constexpr Register::FieldValue<decltype(lvwv)::Type,LvwvVal::v10> v10{};
constexpr Register::FieldValue<decltype(lvwv)::Type,LvwvVal::v11> v11{};
}
///Low-Voltage Warning Interrupt Enable
enum class LvwieVal {
v0=0x00000000, ///<Hardware interrupt disabled (use polling)
v1=0x00000001, ///<Request a hardware interrupt when LVWF = 1.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,LvwieVal> lvwie{};
namespace LvwieValC{
constexpr Register::FieldValue<decltype(lvwie)::Type,LvwieVal::v0> v0{};
constexpr Register::FieldValue<decltype(lvwie)::Type,LvwieVal::v1> v1{};
}
///Low-Voltage Warning Acknowledge
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lvwack{};
///Low-Voltage Warning Flag
enum class LvwfVal {
v0=0x00000000, ///<Low-voltage warning event not detected
v1=0x00000001, ///<Low-voltage warning event detected
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,LvwfVal> lvwf{};
namespace LvwfValC{
constexpr Register::FieldValue<decltype(lvwf)::Type,LvwfVal::v0> v0{};
constexpr Register::FieldValue<decltype(lvwf)::Type,LvwfVal::v1> v1{};
}
}
namespace PmcRegsc{ ///<Regulator Status and Control Register
using Addr = Register::Address<0x4007d002,0xfffffff2,0x00000000,unsigned char>;
///Bandgap Buffer Enable
enum class BgbeVal {
v0=0x00000000, ///<Bandgap buffer not enabled
v1=0x00000001, ///<Bandgap buffer enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,BgbeVal> bgbe{};
namespace BgbeValC{
constexpr Register::FieldValue<decltype(bgbe)::Type,BgbeVal::v0> v0{};
constexpr Register::FieldValue<decltype(bgbe)::Type,BgbeVal::v1> v1{};
}
///Regulator in Run Regulation Status
enum class RegonsVal {
v0=0x00000000, ///<Regulator is in stop regulation or in transition to/from it
v1=0x00000001, ///<Regulator is in run regulation
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,RegonsVal> regons{};
namespace RegonsValC{
constexpr Register::FieldValue<decltype(regons)::Type,RegonsVal::v0> v0{};
constexpr Register::FieldValue<decltype(regons)::Type,RegonsVal::v1> v1{};
}
///Acknowledge Isolation
enum class AckisoVal {
v0=0x00000000, ///<Peripherals and I/O pads are in normal run state
v1=0x00000001, ///<Certain peripherals and I/O pads are in an isolated and latched state
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,AckisoVal> ackiso{};
namespace AckisoValC{
constexpr Register::FieldValue<decltype(ackiso)::Type,AckisoVal::v0> v0{};
constexpr Register::FieldValue<decltype(ackiso)::Type,AckisoVal::v1> v1{};
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisperv5
import (
"bytes"
mrand "math/rand"
"testing"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
)
func generateMessageParams() (*MessageParams, error) {
// set all the parameters except p.Dst and p.Padding
buf := make([]byte, 4)
mrand.Read(buf)
sz := mrand.Intn(400)
var p MessageParams
p.PoW = 0.01
p.WorkTime = 1
p.TTL = uint32(mrand.Intn(1024))
p.Payload = make([]byte, sz)
p.KeySym = make([]byte, aesKeyLength)
mrand.Read(p.Payload)
mrand.Read(p.KeySym)
p.Topic = BytesToTopic(buf)
var err error
p.Src, err = crypto.GenerateKey()
if err != nil {
return nil, err
}
return &p, nil
}
func singleMessageTest(t *testing.T, symmetric bool) {
params, err := generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
key, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
}
if !symmetric {
params.KeySym = nil
params.Dst = &key.PublicKey
}
text := make([]byte, 0, 512)
text = append(text, params.Payload...)
msg, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
env, err := msg.Wrap(params)
if err != nil {
t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
}
var decrypted *ReceivedMessage
if symmetric {
decrypted, err = env.OpenSymmetric(params.KeySym)
} else {
decrypted, err = env.OpenAsymmetric(key)
}
if err != nil {
t.Fatalf("failed to encrypt with seed %d: %s.", seed, err)
}
if !decrypted.Validate() {
t.Fatalf("failed to validate with seed %d.", seed)
}
if !bytes.Equal(text, decrypted.Payload) {
t.Fatalf("failed with seed %d: compare payload.", seed)
}
if !isMessageSigned(decrypted.Raw[0]) {
t.Fatalf("failed with seed %d: unsigned.", seed)
}
if len(decrypted.Signature) != signatureLength {
t.Fatalf("failed with seed %d: signature len %d.", seed, len(decrypted.Signature))
}
if !IsPubKeyEqual(decrypted.Src, ¶ms.Src.PublicKey) {
t.Fatalf("failed with seed %d: signature mismatch.", seed)
}
}
func TestMessageEncryption(t *testing.T) {
InitSingleTest()
var symmetric bool
for i := 0; i < 256; i++ {
singleMessageTest(t, symmetric)
symmetric = !symmetric
}
}
func TestMessageWrap(t *testing.T) {
seed = int64(1777444222)
mrand.Seed(seed)
target := 128.0
params, err := generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
params.TTL = 1
params.WorkTime = 12
params.PoW = target
env, err := msg.Wrap(params)
if err != nil {
t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
}
pow := env.PoW()
if pow < target {
t.Fatalf("failed Wrap with seed %d: pow < target (%f vs. %f).", seed, pow, target)
}
// set PoW target too high, expect error
msg2, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
params.TTL = 1000000
params.WorkTime = 1
params.PoW = 10000000.0
_, err = msg2.Wrap(params)
if err == nil {
t.Fatalf("unexpectedly reached the PoW target with seed %d.", seed)
}
}
func TestMessageSeal(t *testing.T) {
// this test depends on deterministic choice of seed (1976726903)
seed = int64(1976726903)
mrand.Seed(seed)
params, err := generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
params.TTL = 1
aesnonce := make([]byte, 12)
mrand.Read(aesnonce)
env := NewEnvelope(params.TTL, params.Topic, aesnonce, msg)
if err != nil {
t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
}
env.Expiry = uint32(seed) // make it deterministic
target := 32.0
params.WorkTime = 4
params.PoW = target
env.Seal(params)
env.calculatePoW(0)
pow := env.PoW()
if pow < target {
t.Fatalf("failed Wrap with seed %d: pow < target (%f vs. %f).", seed, pow, target)
}
params.WorkTime = 1
params.PoW = 1000000000.0
env.Seal(params)
env.calculatePoW(0)
pow = env.PoW()
if pow < 2*target {
t.Fatalf("failed Wrap with seed %d: pow too small %f.", seed, pow)
}
}
func TestEnvelopeOpen(t *testing.T) {
InitSingleTest()
var symmetric bool
for i := 0; i < 256; i++ {
singleEnvelopeOpenTest(t, symmetric)
symmetric = !symmetric
}
}
func singleEnvelopeOpenTest(t *testing.T, symmetric bool) {
params, err := generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
key, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
}
if !symmetric {
params.KeySym = nil
params.Dst = &key.PublicKey
}
text := make([]byte, 0, 512)
text = append(text, params.Payload...)
msg, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
env, err := msg.Wrap(params)
if err != nil {
t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
}
f := Filter{KeyAsym: key, KeySym: params.KeySym}
decrypted := env.Open(&f)
if decrypted == nil {
t.Fatalf("failed to open with seed %d.", seed)
}
if !bytes.Equal(text, decrypted.Payload) {
t.Fatalf("failed with seed %d: compare payload.", seed)
}
if !isMessageSigned(decrypted.Raw[0]) {
t.Fatalf("failed with seed %d: unsigned.", seed)
}
if len(decrypted.Signature) != signatureLength {
t.Fatalf("failed with seed %d: signature len %d.", seed, len(decrypted.Signature))
}
if !IsPubKeyEqual(decrypted.Src, ¶ms.Src.PublicKey) {
t.Fatalf("failed with seed %d: signature mismatch.", seed)
}
if decrypted.isAsymmetricEncryption() == symmetric {
t.Fatalf("failed with seed %d: asymmetric %v vs. %v.", seed, decrypted.isAsymmetricEncryption(), symmetric)
}
if decrypted.isSymmetricEncryption() != symmetric {
t.Fatalf("failed with seed %d: symmetric %v vs. %v.", seed, decrypted.isSymmetricEncryption(), symmetric)
}
if !symmetric {
if decrypted.Dst == nil {
t.Fatalf("failed with seed %d: dst is nil.", seed)
}
if !IsPubKeyEqual(decrypted.Dst, &key.PublicKey) {
t.Fatalf("failed with seed %d: Dst.", seed)
}
}
}
func TestEncryptWithZeroKey(t *testing.T) {
InitSingleTest()
params, err := generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
params.KeySym = make([]byte, aesKeyLength)
_, err = msg.Wrap(params)
if err == nil {
t.Fatalf("wrapped with zero key, seed: %d.", seed)
}
params, err = generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err = NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
params.KeySym = make([]byte, 0)
_, err = msg.Wrap(params)
if err == nil {
t.Fatalf("wrapped with empty key, seed: %d.", seed)
}
params, err = generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err = NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
params.KeySym = nil
_, err = msg.Wrap(params)
if err == nil {
t.Fatalf("wrapped with nil key, seed: %d.", seed)
}
}
func TestRlpEncode(t *testing.T) {
InitSingleTest()
params, err := generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
env, err := msg.Wrap(params)
if err != nil {
t.Fatalf("wrapped with zero key, seed: %d.", seed)
}
raw, err := rlp.EncodeToBytes(env)
if err != nil {
t.Fatalf("RLP encode failed: %s.", err)
}
var decoded Envelope
rlp.DecodeBytes(raw, &decoded)
if err != nil {
t.Fatalf("RLP decode failed: %s.", err)
}
he := env.Hash()
hd := decoded.Hash()
if he != hd {
t.Fatalf("Hashes are not equal: %x vs. %x", he, hd)
}
}
func singlePaddingTest(t *testing.T, padSize int) {
params, err := generateMessageParams()
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d and sz=%d: %s.", seed, padSize, err)
}
params.Padding = make([]byte, padSize)
params.PoW = 0.0000000001
pad := make([]byte, padSize)
_, err = mrand.Read(pad)
if err != nil {
t.Fatalf("padding is not generated (seed %d): %s", seed, err)
}
n := copy(params.Padding, pad)
if n != padSize {
t.Fatalf("padding is not copied (seed %d): %s", seed, err)
}
msg, err := NewSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
env, err := msg.Wrap(params)
if err != nil {
t.Fatalf("failed to wrap, seed: %d and sz=%d.", seed, padSize)
}
f := Filter{KeySym: params.KeySym}
decrypted := env.Open(&f)
if decrypted == nil {
t.Fatalf("failed to open, seed and sz=%d: %d.", seed, padSize)
}
if !bytes.Equal(pad, decrypted.Padding) {
t.Fatalf("padding is not retireved as expected with seed %d and sz=%d:\n[%x]\n[%x].", seed, padSize, pad, decrypted.Padding)
}
}
func TestPadding(t *testing.T) {
InitSingleTest()
for i := 1; i < 260; i++ {
singlePaddingTest(t, i)
}
lim := 256 * 256
for i := lim - 5; i < lim+2; i++ {
singlePaddingTest(t, i)
}
for i := 0; i < 256; i++ {
n := mrand.Intn(256*254) + 256
singlePaddingTest(t, n)
}
for i := 0; i < 256; i++ {
n := mrand.Intn(256*1024) + 256*256
singlePaddingTest(t, n)
}
}
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: PaintBrush_Mat
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _MASKMAP _METALLICGLOSSMAP _NORMALMAP _NORMALMAP_TANGENT_SPACE
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: 2000
stringTagMap: {}
disabledShaderPasses:
- DistortionVectors
- TransparentDepthPrepass
- TransparentDepthPostpass
- TransparentBackface
- MOTIONVECTORS
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _AnisotropyMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BaseColorMap:
m_Texture: {fileID: 2800000, guid: 4675081b0baf66345adc734388155502, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BentNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BentNormalMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 2800000, guid: 249536348ff8b3d45adf54396f0e4034, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _CoatMaskMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DistortionVectorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissiveColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _HeightMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _IridescenceMaskMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _IridescenceThicknessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 4675081b0baf66345adc734388155502, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MaskMap:
m_Texture: {fileID: 2800000, guid: 888916a5e87c05948b1a97b3c0d42556, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 2800000, guid: ea55e91b49907b948b3f1f9f68f61778, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMap:
m_Texture: {fileID: 2800000, guid: 09e745bf0b8ff6a4bb5785d14168289a, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 2800000, guid: ea55e91b49907b948b3f1f9f68f61778, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecularColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubsurfaceMaskMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TransmittanceColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AORemapMax: 1
- _AORemapMin: 0
- _ATDistance: 1
- _AlbedoAffectEmissive: 0
- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 0
- _AlphaCutoffPostpass: 0.5
- _AlphaCutoffPrepass: 0.5
- _Anisotropy: 0
- _BlendMode: 0
- _BumpScale: 1
- _CoatMask: 0
- _CullMode: 2
- _CullModeForward: 2
- _Cutoff: 0.5
- _DepthOffsetEnable: 0
- _DetailAlbedoScale: 1
- _DetailNormalMapScale: 1
- _DetailNormalScale: 1
- _DetailSmoothnessScale: 1
- _DiffusionProfile: 0
- _DisplacementLockObjectScale: 1
- _DisplacementLockTilingScale: 1
- _DisplacementMode: 0
- _DistortionBlendMode: 0
- _DistortionBlurBlendMode: 0
- _DistortionBlurDstBlend: 1
- _DistortionBlurRemapMax: 1
- _DistortionBlurRemapMin: 0
- _DistortionBlurScale: 1
- _DistortionBlurSrcBlend: 1
- _DistortionDepthTest: 1
- _DistortionDstBlend: 1
- _DistortionEnable: 0
- _DistortionScale: 1
- _DistortionSrcBlend: 1
- _DistortionVectorBias: -1
- _DistortionVectorScale: 2
- _DoubleSidedEnable: 0
- _DoubleSidedNormalMode: 1
- _Drag: 1
- _DstBlend: 0
- _EmissiveColorMode: 1
- _EmissiveIntensity: 0
- _EnableBlendModePreserveSpecularLighting: 1
- _EnableFogOnTransparent: 1
- _EnableMotionVectorForVertexAnimation: 0
- _EnableSpecularOcclusion: 0
- _EnableWind: 0
- _EnergyConservingSpecularColor: 1
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _HeightAmplitude: 0.02
- _HeightCenter: 0.5
- _HeightMapParametrization: 0
- _HeightMax: 1
- _HeightMin: -1
- _HeightOffset: 0
- _HeightPoMAmplitude: 2
- _HeightTessAmplitude: 2
- _HeightTessCenter: 0.5
- _InitialBend: 1
- _InvTilingScale: 1
- _Ior: 1
- _IridescenceMask: 1
- _IridescenceThickness: 1
- _LinkDetailsWithBase: 1
- _MaterialID: 1
- _Metallic: 1
- _Mode: 0
- _NormalMapSpace: 0
- _NormalScale: 1
- _OcclusionStrength: 1
- _PPDLodThreshold: 5
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _PPDPrimitiveLength: 1
- _PPDPrimitiveWidth: 1
- _Parallax: 0.02
- _PreRefractionPass: 0
- _RefractionMode: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2
- _Smoothness: 0.5
- _SmoothnessRemapMax: 1
- _SmoothnessRemapMin: 0
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _StencilRef: 2
- _StencilRefMV: 128
- _StencilWriteMask: 7
- _StencilWriteMaskMV: 128
- _Stiffness: 1
- _SubsurfaceMask: 1
- _SupportDBuffer: 1
- _SurfaceType: 0
- _TexWorldScale: 1
- _TexWorldScaleEmissive: 1
- _Thickness: 1
- _ThicknessMultiplier: 1
- _TransmissionEnable: 1
- _TransparentBackfaceEnable: 0
- _TransparentDepthPostpassEnable: 0
- _TransparentDepthPrepassEnable: 0
- _TransparentSortPriority: 0
- _UVBase: 0
- _UVDetail: 0
- _UVEmissive: 0
- _UVSec: 0
- _ZTestDepthEqualForOpaque: 3
- _ZTestModeDistortion: 4
- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _DoubleSidedConstants: {r: 1, g: 1, b: -1, a: 0}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
- _IridescenceThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
- _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}
| {
"pile_set_name": "Github"
} |
// declare the namespace for this example
var example = {};
/**
*
* The **GraphicalEditor** is responsible for layout and dialog handling.
*
* @author Andreas Herz
* @extends draw2d.ui.parts.GraphicalEditor
*/
var defaultRouterClassName = "draw2d.layout.connection.ManhattanConnectionRouter";
var defaultRouter = new draw2d.layout.connection.ManhattanConnectionRouter();
example.Application = Class.extend(
{
NAME : "example.Application",
/**
* @constructor
*
* @param {String} canvasId the id of the DOM element to use as paint container
*/
init : function()
{
this.view = new draw2d.Canvas("canvas");
// Override the default connection type. This is used during drag&drop operations of ports.
this.view.installEditPolicy( new draw2d.policy.connection.DragConnectionCreatePolicy({
createConnection: this.createConnection
}));
this.toolbar = new example.Toolbar("toolbar", this, this.view );
this.view.setScrollArea("#canvas");
var layout = {
north: {
resizable:false,
closable:false,
spacing_open:0,
spacing_closed:0,
size:50,
paneSelector: "#toolbar"
},
center: {
resizable:true,
closable:false,
spacing_open:0,
spacing_closed:0,
paneSelector: "#canvas"
}
};
if(showJSON===true){
layout.east={
size:250,
resizable:true,
closable:false,
paneSelector: "#json"
};
}
// layout FIRST the body
this.appLayout = $('#container').layout(layout);
},
/**
* Load the JSON data into the view/canvas
*/
load: function(jsonDocument){
this.view.clear();
// unmarshal the JSON document into the canvas
// (load)
var reader = new draw2d.io.json.Reader();
reader.unmarshal(this.view, jsonDocument);
},
setDefaultRouterClassName: function( defaultRouterClassName){
defaultRouterClassName= defaultRouterClassName;
defaultRouter = eval("new "+defaultRouterClassName+"()");
},
createConnection: function(){
var conn = new draw2d.Connection();
conn.setRouter(defaultRouter);
conn.setOutlineStroke(1);
conn.setOutlineColor("#303030");
conn.setStroke(3);
conn.setRadius(5);
conn.setColor('#00A8F0');
return conn;
}
});
| {
"pile_set_name": "Github"
} |
/* vim:tw=110:ts=4: */
#ifndef DHF_H
#define DHF_H
/**************************************************************************************************************
*
* FILE : DHF.H
*
* DATE : $Date: 2004/07/19 08:16:14 $ $Revision: 1.2 $
* Original : 2004/05/17 07:33:13 Revision: 1.25 Tag: hcf7_t20040602_01
* Original : 2004/05/11 06:03:14 Revision: 1.24 Tag: hcf7_t7_20040513_01
* Original : 2004/04/15 09:24:42 Revision: 1.22 Tag: hcf7_t7_20040415_01
* Original : 2004/04/09 14:35:52 Revision: 1.21 Tag: t7_20040413_01
* Original : 2004/04/01 15:32:55 Revision: 1.18 Tag: t7_20040401_01
* Original : 2004/03/10 15:39:28 Revision: 1.15 Tag: t20040310_01
* Original : 2004/03/04 11:03:38 Revision: 1.13 Tag: t20040304_01
* Original : 2004/02/25 14:14:37 Revision: 1.11 Tag: t20040302_03
* Original : 2004/02/24 13:00:28 Revision: 1.10 Tag: t20040224_01
* Original : 2004/02/19 10:57:28 Revision: 1.8 Tag: t20040219_01
*
* AUTHOR : John Meertens
* Nico Valster
*
* SPECIFICATION: .........
*
* DESC : structure definitions and function prototypes for unit DHF.
*
* Customizable via HCFCFG.H, which is included indirectly via HCF.H
*
***************************************************************************************************************
*
*
* SOFTWARE LICENSE
*
* This software is provided subject to the following terms and conditions,
* which you should read carefully before using the software. Using this
* software indicates your acceptance of these terms and conditions. If you do
* not agree with these terms and conditions, do not use the software.
*
* COPYRIGHT (C) 1994 - 1995 by AT&T. All Rights Reserved
* COPYRIGHT (C) 1999 - 2000 by Lucent Technologies. All Rights Reserved
* COPYRIGHT (C) 2001 - 2004 by Agere Systems Inc. All Rights Reserved
* All rights reserved.
*
* Redistribution and use in source or binary forms, with or without
* modifications, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following Disclaimer as comments in the code as
* well as in the documentation and/or other materials provided with the
* distribution.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following Disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name of Agere Systems Inc. nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Disclaimer
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY
* USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN
* RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*
**************************************************************************************************************/
#ifdef _WIN32_WCE
#include <windef.h>
#endif
#include "hcf.h" /* includes HCFCFG.H too */
#ifdef DHF_UIL
#define GET_INFO(pp) uil_get_info((LTVP)pp)
#define PUT_INFO(pp) uil_put_info((LTVP)pp)
#else
#define GET_INFO(pp) hcf_get_info(ifbp, (LTVP)pp)
#define PUT_INFO(pp) hcf_put_info(ifbp, (LTVP)pp)
#endif
/*---- Defines --------------------------------------------------------------*/
#define CODEMASK 0x0000FFFFL /* Codemask for plug records */
/*---- Error numbers --------------------------------------------------------*/
#define DHF_ERR_INCOMP_FW 0x40 /* Image not compatible with NIC */
/*---- Type definitions -----------------------------------------------------*/
/* needed by dhf_wrap.c */
typedef struct {
LTVP ltvp;
hcf_16 len;
} LTV_INFO_STRUCT , *LTV_INFO_STRUCT_PTR;
/*
* Type: plugrecord
*
* Abstract: This structure represents a Plug Data Record.
*
* Description:
* This structure is used to overlay the plug records in the firmware memory image.
*/
typedef struct {
hcf_32 code; /* Code to plug */
hcf_32 addr; /* Address within the memory image to plug it in */
hcf_32 len; /* The # of bytes which are available to store it */
} plugrecord;
/*
* Type: stringrecord
*
* Abstract: This structure represents a Firmware debug/assert string
*
* Description:
* This structure is used to get assert and debug outputs in the driver and/or utility to be
* able to get more visability of the FW.
*/
#define MAX_DEBUGSTRINGS 1024
#define MAX_DEBUGSTRING_LEN 82
typedef struct {
hcf_32 id;
char str[MAX_DEBUGSTRING_LEN];
} stringrecord;
/*
* Type: exportrecord
*
* Abstract: This structure represents a Firmware export of a variable
*
* Description:
* This structure is used to get the address and name of a FW variable.
*/
#define MAX_DEBUGEXPORTS 2048
#define MAX_DEBUGEXPORT_LEN 12
typedef struct {
hcf_32 id;
char str[MAX_DEBUGEXPORT_LEN];
} exportrecord;
/* Offsets in memimage array p[] */
#define FWSTRINGS_FUNCTION 0
#define FWEXPORTS_FUNCTION 1
/*
* Type: memimage
*
* Abstract: The "root" description of a complete memory image
*
* Description:
* This type represents an entire memory image. The image is built up of several
* segments. These segments need not be contiguous areas in memory, in other words
* the image may contain 'holes'.
*
* The 'codep' field points to an array of segment_descriptor structures.
* The end of the array is indicated by a segment_descriptor of which all fields are zero.
* The 'execution' field is a 32-bit address representing the execution address
* of the firmware within the memory image. This address is zero in case of non-volatile
* memory download.
* The 'compat' field points to an array of TODO
* The end of the array is indicated by a plug record of which all fields are zero.
* The 'identity' field points to an array of TODO
* The end of the array is indicated by a plug record of which all fields are zero.
* The Hermes-I specific 'pdaplug' field points to an array of Production Data Plug record structures.
* The end of the array is indicated by a plug record of which all fields are zero.
* The Hermes-I specific 'priplug' field points to an array of Primary Information Plug record structures.
* The end of the array is indicated by a plug record of which all fields are zero.
*/
typedef struct {
char signature[14+1+1]; /* signature (see DHF.C) + C/LE-Bin/BE-Bin-flag + format version */
CFG_PROG_STRCT FAR *codep; /* */
hcf_32 execution; /* Execution address of the firmware */
void FAR *place_holder_1;
void FAR *place_holder_2;
CFG_RANGE20_STRCT FAR *compat; /* Pointer to the compatibility info records */
CFG_IDENTITY_STRCT FAR *identity; /* Pointer to the identity info records */
void FAR *p[2]; /* (Up to 9) pointers for (future) expansion
* currently in use:
* - F/W printf information
*/
} memimage;
/*-----------------------------------------------------------------------------
*
* DHF function prototypes
*
*---------------------------------------------------------------------------*/
EXTERN_C int dhf_download_fw(void *ifbp, memimage *fw); /* ifbp, ignored when using the UIL */
EXTERN_C int dhf_download_binary(memimage *fw);
/*-----------------------------------------------------------------------------
*
* Functions to be provided by the user of the DHF module.
*
*---------------------------------------------------------------------------*/
/* defined in DHF.C; see there for comments */
EXTERN_C hcf_16 *find_record_in_pda(hcf_16 *pdap, hcf_16 code);
#endif /* DHF_H */
| {
"pile_set_name": "Github"
} |
<resources>
<string name="app_name">Library</string>
</resources>
| {
"pile_set_name": "Github"
} |
# Find the native NANOFLANN headers and libraries.
#
# NANOFLANN_INCLUDE_DIRS - where to find nana/nana.h, etc.
# NANOFLANN_FOUND - True if nana found.
# Look for the header file.
FIND_PATH(NANOFLANN_INCLUDE_DIR NAMES nanoflann/nanoflann.hpp
PATHS
${CMAKE_SOURCE_DIR}/include
${CMAKE_SOURCE_DIR}/../include
${CMAKE_INSTALL_PREFIX}/include
${KDE4_INCLUDE_DIR}
PATH_SUFFIXES NANOFLANN
)
MARK_AS_ADVANCED(NANOFLANN_INCLUDE_DIR)
# handle the QUIETLY and REQUIRED arguments and set NANOFLANN_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(NANOFLANN DEFAULT_MSG NANOFLANN_INCLUDE_DIR)
IF(NANOFLANN_FOUND)
SET(NANOFLANN_INCLUDE_DIRS ${NANOFLANN_INCLUDE_DIR})
ELSE(NANOFLANN_FOUND)
SET(NANOFLANN_INCLUDE_DIRS)
ENDIF(NANOFLANN_FOUND)
| {
"pile_set_name": "Github"
} |
{
"stackLimitGas_1025" : {
"_info" : {
"comment" : "",
"filledwith" : "testeth 1.6.0-alpha.0-11+commit.978e68d2",
"lllcversion" : "Version: 0.5.0-develop.2018.11.9+commit.9709dfe0.Linux.g++",
"source" : "src/GeneralStateTestsFiller/stMemoryTest/stackLimitGas_1025Filler.json",
"sourceHash" : "306f8a733f16349f27cc22f9fcb086c412f75b018b1ac9ae2cb7a344bd3a98fd"
},
"env" : {
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "0x20000",
"currentGasLimit" : "0x0a00000000",
"currentNumber" : "0x01",
"currentTimestamp" : "0x03e8",
"previousHash" : "0x5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"post" : {
"Byzantium" : [
{
"hash" : "0x0bf698140781a243586d4b8a3b5af5e3d9196a961215295e15d4a21fb9405983",
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
],
"Constantinople" : [
{
"hash" : "0x0bf698140781a243586d4b8a3b5af5e3d9196a961215295e15d4a21fb9405983",
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
],
"ConstantinopleFix" : [
{
"hash" : "0x0bf698140781a243586d4b8a3b5af5e3d9196a961215295e15d4a21fb9405983",
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
],
"EIP150" : [
{
"hash" : "0x0bf698140781a243586d4b8a3b5af5e3d9196a961215295e15d4a21fb9405983",
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
],
"EIP158" : [
{
"hash" : "0x0bf698140781a243586d4b8a3b5af5e3d9196a961215295e15d4a21fb9405983",
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
],
"Frontier" : [
{
"hash" : "0x0bf698140781a243586d4b8a3b5af5e3d9196a961215295e15d4a21fb9405983",
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
],
"Homestead" : [
{
"hash" : "0x0bf698140781a243586d4b8a3b5af5e3d9196a961215295e15d4a21fb9405983",
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
]
},
"pre" : {
"0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
"balance" : "0x0de0b6b3a7640000",
"code" : "0x6103ff6000525b5a60016000510360005260005160065700",
"nonce" : "0x00",
"storage" : {
}
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x6400000000",
"code" : "",
"nonce" : "0x00",
"storage" : {
}
}
},
"transaction" : {
"data" : [
"0x"
],
"gasLimit" : [
"0x0186a0"
],
"gasPrice" : "0x01",
"nonce" : "0x00",
"secretKey" : "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
"value" : [
"0x0a"
]
}
}
}
| {
"pile_set_name": "Github"
} |
QUOTE Q289 12 0 12 3 " Smooth ! "
QUOTE Q290 13 0 13 8 " As smooth as an automobile salesman . "
QUOTE Q293 30 0 30 15 " Well , I 'd like to know what 's the matter with it ! "
QUOTE Q294 32 0 32 4 " All right , "
QUOTE Q295 33 0 34 5 " I 'll tell you . It 's too young . "
QUOTE Q296 35 0 35 3 " Young ! "
QUOTE Q297 37 0 37 7 " What d'you mean -- young ? "
QUOTE Q298 40 0 44 31 " I know that you look like a man on a magazine cover in it . But Norfolk suits spell tennis , and seashore , and elegant leisure . And you 're going out this morning , Son , to interview business men . You 're going to try to impress the advertising world with the fact that it needs your expert services . You walk into a business office in a Norfolk suit , and everybody from the office boy to the president of the company will ask you what your score is . "
QUOTE Q299 46 0 46 9 " I 'll wear the black and white , "
QUOTE Q300 47 11 49 13 " For that matter , they 're looking for young men . Everybody 's young . Why , the biggest men in the advertising game are just kids . "
QUOTE Q301 54 16 54 24 " Well , you asked my advice , "
QUOTE Q302 54 46 58 15 " and I gave it . Wear a white duck sailor suit with blue anchors and carry a red tin pail and a shovel , if you want to look young . Only get into it in a jiffy , Son , because breakfast will be ready in ten minutes . I can tell by the way Annie 's crashing the cups . So step lively if you want to pay your lovely mother 's subway fare . "
QUOTE Q303 71 0 71 10 " I want to write the kind of ad , "
QUOTE Q304 71 16 72 25 " that you see 'em staring at in the subways , and street cars and L-trains . I want to sit across the aisle and watch their up-turned faces staring at that oblong , and reading it aloud to each other . "
QUOTE Q305 73 0 73 14 " Is n't that an awfully obvious necktie you 're wearing , Jock ? "
QUOTE Q306 74 0 76 8 " This ? You ought to see some of them . This is a Quaker stock in comparison . "
QUOTE Q307 79 0 79 41 " And the first thing you know , Mrs. McChesney , ma'am , we 'll have a motor truck backing up at the door once a month and six strong men carrying my salary to the freight elevator in sacks . "
QUOTE Q308 80 15 80 35 " Had n't you better qualify for the trial heats , Jock , before you jump into the finals ? "
QUOTE Q309 81 0 81 4 " Trial heats ! "
QUOTE Q287 82 0 91 3 " They 're poky . I want real money . Now ! It is n't enough to be just well-to-do in these days . It needs money . I want to be rich ! Not just prosperous , but rich ! So rich that I can let the bath soap float around in the water without any pricks of conscience . So successful that they 'll say , ' And he 's a mere boy , too . Imagine ! ' "
QUOTE Q288 92 2 92 6 " Jock dear , "
QUOTE Q291 92 11 94 29 " you 've still to learn that plans and ambitions are like soap bubbles . The harder you blow and the more you inflate them , the quicker they burst . Plans and ambitions are things to be kept locked away in your heart , Son , with no one but yourself to take an occasional peep at them . "
QUOTE Q292 96 0 96 7 " You 're a jealous blonde , "
QUOTE Q310 97 0 97 29 " Because I 'm going to be a captain of finance -- an advertising wizard ; you 're afraid I 'll grab the glory all away from you . "
QUOTE Q311 100 0 100 6 " I 'm not afraid , "
QUOTE Q312 101 0 103 7 " You see , they 'll only regard your feats and say , ' H 'm , no wonder . He ought to be able to sell ice to an Eskimo . His mother was Emma McChesney . ' "
QUOTE Q313 106 0 109 9 " Lamb chops to-night , eh , Annie ? And sweet potatoes . Jock loves 'em . And corn au gratin and some head lettuce . "
QUOTE Q314 111 7 112 17 " just give us one of your peach cobblers , will you ? You see he -- he 's going to be awfully -- tired when he gets home . "
QUOTE Q315 111 0 111 3 " Annie , "
ATTRIB Q289 our-4
ATTRIB Q290 our-4
ATTRIB Q293 Jock_McChesney-22
ATTRIB Q294 his_mother-24
ATTRIB Q295 his_mother-24
ATTRIB Q296 Jock_McChesney-22
ATTRIB Q297 Jock_McChesney-22
ATTRIB Q298 his_mother-24
ATTRIB Q299 Jock_McChesney-22
ATTRIB Q300 Jock_McChesney-22
ATTRIB Q301 his_mother-24
ATTRIB Q302 his_mother-24
ATTRIB Q303 Jock_McChesney-22
ATTRIB Q304 Jock_McChesney-22
ATTRIB Q305 his_mother-24
ATTRIB Q306 Jock_McChesney-22
ATTRIB Q307 Jock_McChesney-22
ATTRIB Q308 his_mother-24
ATTRIB Q309 Jock_McChesney-22
ATTRIB Q287 Jock_McChesney-22
ATTRIB Q288 his_mother-24
ATTRIB Q291 his_mother-24
ATTRIB Q292 Jock_McChesney-22
ATTRIB Q310 Jock_McChesney-22
ATTRIB Q311 his_mother-24
ATTRIB Q312 his_mother-24
ATTRIB Q313 his_mother-24
ATTRIB Q314 his_mother-24
ATTRIB Q315 his_mother-24
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2014 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace objectivec {
namespace {
TEST(ObjCHelper, TextFormatDecodeData_DecodeDataForString_RawStrings) {
string input_for_decode("abcdefghIJ");
string desired_output_for_decode;
string expected;
string result;
// Different data, can't transform.
desired_output_for_decode = "zbcdefghIJ";
expected = string("\0zbcdefghIJ\0", 12);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
desired_output_for_decode = "abcdezghIJ";
expected = string("\0abcdezghIJ\0", 12);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
// Shortened data, can't transform.
desired_output_for_decode = "abcdefghI";
expected = string("\0abcdefghI\0", 11);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
// Extra data, can't transform.
desired_output_for_decode = "abcdefghIJz";
expected = string("\0abcdefghIJz\0", 13);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
}
TEST(ObjCHelper, TextFormatDecodeData_DecodeDataForString_ByteCodes) {
string input_for_decode("abcdefghIJ");
string desired_output_for_decode;
string expected;
string result;
desired_output_for_decode = "abcdefghIJ";
expected = string("\x0A\x0", 2);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
desired_output_for_decode = "_AbcdefghIJ";
expected = string("\xCA\x0", 2);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
desired_output_for_decode = "ABCD__EfghI_j";
expected = string("\x64\x80\xC5\xA1\x0", 5);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
// Long name so multiple decode ops are needed.
input_for_decode =
"longFieldNameIsLooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong1000";
desired_output_for_decode =
"long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000";
expected = string("\x04\xA5\xA4\xA2\xBF\x1F\x0E\x84\x0", 9);
result = TextFormatDecodeData::DecodeDataForString(input_for_decode,
desired_output_for_decode);
EXPECT_EQ(expected, result);
}
// Death tests do not work on Windows as of yet.
#ifdef PROTOBUF_HAS_DEATH_TEST
TEST(ObjCHelperDeathTest, TextFormatDecodeData_DecodeDataForString_Failures) {
// Empty inputs.
EXPECT_EXIT(TextFormatDecodeData::DecodeDataForString("", ""),
::testing::KilledBySignal(SIGABRT),
"error: got empty string for making TextFormat data, input:");
EXPECT_EXIT(TextFormatDecodeData::DecodeDataForString("a", ""),
::testing::KilledBySignal(SIGABRT),
"error: got empty string for making TextFormat data, input:");
EXPECT_EXIT(TextFormatDecodeData::DecodeDataForString("", "a"),
::testing::KilledBySignal(SIGABRT),
"error: got empty string for making TextFormat data, input:");
// Null char in the string.
string str_with_null_char("ab\0c", 4);
EXPECT_EXIT(
TextFormatDecodeData::DecodeDataForString(str_with_null_char, "def"),
::testing::KilledBySignal(SIGABRT),
"error: got a null char in a string for making TextFormat data, input:");
EXPECT_EXIT(
TextFormatDecodeData::DecodeDataForString("def", str_with_null_char),
::testing::KilledBySignal(SIGABRT),
"error: got a null char in a string for making TextFormat data, input:");
}
#endif // PROTOBUF_HAS_DEATH_TEST
TEST(ObjCHelper, TextFormatDecodeData_RawStrings) {
TextFormatDecodeData decode_data;
// Different data, can't transform.
decode_data.AddString(1, "abcdefghIJ", "zbcdefghIJ");
decode_data.AddString(3, "abcdefghIJ", "abcdezghIJ");
// Shortened data, can't transform.
decode_data.AddString(2, "abcdefghIJ", "abcdefghI");
// Extra data, can't transform.
decode_data.AddString(4, "abcdefghIJ", "abcdefghIJz");
EXPECT_EQ(4, decode_data.num_entries());
uint8 expected_data[] = {
0x4,
0x1, 0x0, 'z', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'J', 0x0,
0x3, 0x0, 'a', 'b', 'c', 'd', 'e', 'z', 'g', 'h', 'I', 'J', 0x0,
0x2, 0x0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 0x0,
0x4, 0x0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'J', 'z', 0x0,
};
string expected((const char*)expected_data, sizeof(expected_data));
EXPECT_EQ(expected, decode_data.Data());
}
TEST(ObjCHelper, TextFormatDecodeData_ByteCodes) {
TextFormatDecodeData decode_data;
decode_data.AddString(1, "abcdefghIJ", "abcdefghIJ");
decode_data.AddString(3, "abcdefghIJ", "_AbcdefghIJ");
decode_data.AddString(2, "abcdefghIJ", "Abcd_EfghIJ");
decode_data.AddString(4, "abcdefghIJ", "ABCD__EfghI_j");
decode_data.AddString(1000,
"longFieldNameIsLooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong1000",
"long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000");
EXPECT_EQ(5, decode_data.num_entries());
uint8 expected_data[] = {
0x5,
// All as is (00 op)
0x1, 0x0A, 0x0,
// Underscore, upper + 9 (10 op)
0x3, 0xCA, 0x0,
// Upper + 3 (10 op), underscore, upper + 5 (10 op)
0x2, 0x44, 0xC6, 0x0,
// All Upper for 4 (11 op), underscore, underscore, upper + 5 (10 op),
// underscore, lower + 0 (01 op)
0x4, 0x64, 0x80, 0xC5, 0xA1, 0x0,
// 2 byte key: as is + 3 (00 op), underscore, lower + 4 (01 op),
// underscore, lower + 3 (01 op), underscore, lower + 1 (01 op),
// underscore, lower + 30 (01 op), as is + 30 (00 op), as is + 13 (00
// op),
// underscore, as is + 3 (00 op)
0xE8, 0x07, 0x04, 0xA5, 0xA4, 0xA2, 0xBF, 0x1F, 0x0E, 0x84, 0x0,
};
string expected((const char*)expected_data, sizeof(expected_data));
EXPECT_EQ(expected, decode_data.Data());
}
// Death tests do not work on Windows as of yet.
#ifdef PROTOBUF_HAS_DEATH_TEST
TEST(ObjCHelperDeathTest, TextFormatDecodeData_Failures) {
TextFormatDecodeData decode_data;
// Empty inputs.
EXPECT_EXIT(decode_data.AddString(1, "", ""),
::testing::KilledBySignal(SIGABRT),
"error: got empty string for making TextFormat data, input:");
EXPECT_EXIT(decode_data.AddString(1, "a", ""),
::testing::KilledBySignal(SIGABRT),
"error: got empty string for making TextFormat data, input:");
EXPECT_EXIT(decode_data.AddString(1, "", "a"),
::testing::KilledBySignal(SIGABRT),
"error: got empty string for making TextFormat data, input:");
// Null char in the string.
string str_with_null_char("ab\0c", 4);
EXPECT_EXIT(
decode_data.AddString(1, str_with_null_char, "def"),
::testing::KilledBySignal(SIGABRT),
"error: got a null char in a string for making TextFormat data, input:");
EXPECT_EXIT(
decode_data.AddString(1, "def", str_with_null_char),
::testing::KilledBySignal(SIGABRT),
"error: got a null char in a string for making TextFormat data, input:");
// Duplicate keys
decode_data.AddString(1, "abcdefghIJ", "abcdefghIJ");
decode_data.AddString(3, "abcdefghIJ", "_AbcdefghIJ");
decode_data.AddString(2, "abcdefghIJ", "Abcd_EfghIJ");
EXPECT_EXIT(decode_data.AddString(2, "xyz", "x_yz"),
::testing::KilledBySignal(SIGABRT),
"error: duplicate key \\(2\\) making TextFormat data, input:");
}
#endif // PROTOBUF_HAS_DEATH_TEST
// TODO(thomasvl): Should probably add some unittests for all the special cases
// of name mangling (class name, field name, enum names). Rather than doing
// this with an ObjC test in the objectivec directory, we should be able to
// use src/google/protobuf/compiler/importer* (like other tests) to support a
// virtual file system to feed in protos, once we have the Descriptor tree, the
// tests could use the helper methods for generating names and validate the
// right things are happening.
} // namespace
} // namespace objectivec
} // namespace compiler
} // namespace protobuf
} // namespace google
| {
"pile_set_name": "Github"
} |
// -----------------------------------------------------------------------------------
// NKDBarcode.h
// -----------------------------------------------------------------------------------
// Created by Jeff LaMarche on Wed May 01 2002.
// Copyright (c) 2002 Naked Software. All rights reserved.
// -----------------------------------------------------------------------------------
// THIS SOURCE CODE IS PROVIDED AS-IS WITH NO WARRANTY OF ANY KIND
// -----------------------------------------------------------------------------------
// You may use and redistribute this source code without limitation
// -----------------------------------------------------------------------------------
/*!
@header NKDBarcode.h
NKDBarcode is a quasi-abstract class that contains state and actions common to generating many
different types of barcodes. It encapsulates much of the common behavior of the concrete subclasses that
implement varoius one dimensional (linear) barcodes. Subclasses will respond to a barcode message by
returning an NSString of 1s and 0s, assuming that a value of '1' represents a bar of the narrowest size needed
by this encoding scheme, and that '0' represents a gap of the same size.
If a subclass modifies this behavior, it should be well documented, and NKDBarcodeOffscreenView will possibly
have to be modified to accommodate the change.
Although most barcode specifications allow narrow bar widths as small as 7.5 mils, I am using a default
size of 13 mils for all barcodes that don't have strict bar-width requirements in their specification (e.g. PostNet)
because this is an acceptable bar width for most barcodes and many inkjet and laser printers have insufficient resolution
to produce a readable code on plain paper at bar widths smaller than this size.
The framework currently contains subclasses for Code 3 of 9, Extended Code 3 of 9, Interleaved Code
2 of 5, Modified Plessey and Modified Plessey Hex (not compliant with specs, untested), PostNet,
UPC-A, Code 128, Industrial 2 of 5, and EAN-13, Codabar, EAN-8 and UPC-E. In some cases, I do not have the complete
or official specifications. I also, unfortunately, do not have equipment to test some types of barcode, so I welcome
any help debugging, testing, and validating the encoding schemes of the provided subclasses. No guarantee is made concerning
the creation of readable code for any given hardware - I've done the best job that I could armed only with my PowerBook,
a Cue Cat and the specifications I could find.
If you have complete specifications or information about any dimensional linear barcodes or (for that matter) and other feedback,
please send it to me at <code>jeff_lamarche@mac.com</code> and I will try to respond. Support for 2-dimensional (matrix)
barcodes is not currently planned as part of this framework, but if there's an interest, I'll consider adding it.
*/
#import <Foundation/Foundation.h>
/*!
@defined kScreenResolution
@discussion This value is used to determine the drawing location of various bars. Though many
devices have different resolution, drawing in Cocoa seems to based on 72 pixels per inch
*/
#define kScreenResolution 163.00
/*!
@class NKDBarcode
@abstract Superclass of concrete barcode classes.
@discussion The Naked Barcode Framework is designed to allow rapid creation and easy maintenance of
a set of classes for generating resolution independent one-dimensional linear barcodes. NKDBarcode is the root class
of the NKDBarcode framework.
*/
@interface NKDBarcode : NSObject <NSCopying, NSCoding>
{
NSString *content;
float height;
float width;
char checkDigit;
float barWidth; // bar width in mils (thousands of an inch)
BOOL printsCaption;
float fontSize;
float captionHeight;
}
/*!
@method initWithContent:
@abstract Initializes new barcode object to encode provided data.
@param inContent A string containing the data to be encoded; should use only <B>ASCII-8</B> characters
(those that can be encoded using a single char in UTF-8)
@result Returns initialized NKDBarcode class
*/
-(id)initWithContent: (NSString *)inContent;
/*!
@method initWithContent:printsCaption
@abstract Initializes new barcode object with provided data and specifies whether a caption should be printed
below the barcode.
@param inContent A string containing the data to be encoded; should use only <B>ASCII-8</B> characters
(those that can be encoded using a single char in UTF-8)
@param inPrints YES if caption should print.
@result Returns initialized NKDBarcode class
*/
-(id)initWithContent: (NSString *)inContent
printsCaption: (BOOL)inPrints;
/*!
@method initWithContent:printsCaption:andBarWidth:andHeight:andFontSize:andCheckDigit:
@abstract Designated initializer for abstract barcode object.
@param inContent A string containing the data to be encoded; should use only <B>ASCII-8</B> characters
(those that can be encoded using a single char in UTF-8)
@param inPrints YES if caption should print.
@param inBarWidth Width of the smallest bar or gap to be used, in base units (points)
@param inHeight Height of the bar (excluding caption) in base units
@param inFontSize Size of the font to use for the caption
@param inDigit Check Digit either provided or calculated, -1 if not used or not yet calculated
@result Returns initialized NKDBarcode class
*/
-(id)initWithContent: (NSString *)inContent
printsCaption: (BOOL)inPrints
andBarWidth: (float)inBarWidth
andHeight: (float)inHeight
andFontSize: (float)inFontSize
andCheckDigit: (char)inDigit;
/*!
@method setContent:
@abstract Sets the content to provided NSString.
@param inContent A string containing the data to be encoded; should use only <B>ASCII-8</B> characters
(those that can be encoded using a single char in UTF-8)
*/
-(void)setContent:(NSString *)inContent;
/*!
@method setHeight:
@abstract Sets the barcode height to the provided value.
@param inHeight Value to set the height to.
*/
-(void)setHeight:(float)inHeight;
/*!
@method setWidth:
@abstract Sets the barcode width to the provided value.
@param inWidth Value to set the width to.
*/
-(void)setWidth:(float)inWidth;
/*!
@method setFontSize:
@abstract Sets the size of the font to use
@param inSize The size (as a float) of the font to use
*/
-(void)setFontSize:(float)inSize;
/*!
@method setCaptionHeight:
@abstract: Set amount of space to leave under barcode for the caption
@param inHeight: Floating point amount of space to set (in inches)
*/
-(void)setCaptionHeight:(float)inHeight;
/*!
@method captionHeight
@abstract Returns the amount of space to leave under the barcode for the caption
@result Floating point value representing the amount of space to leave (in inches)
*/
-(float)captionHeight;
/*!
@method calculateWidth
@abstract Calculates the correct width for the barcode based on the encoding scheme and the specified bar width.
*/
-(void)calculateWidth;
/*!
@method setCheckDigit:
@abstract Sets the check digit to the provided character.
@param inCheckDigit Character (char, not unichar) to set the check digit to.
*/
-(void)setCheckDigit:(char)inCheckDigit;
/*!
@method setPrintsCaption:
@abstract Sets whether this barcode should print the content below the code.
@param inPrints Boolean value to specify whether the caption should print.
*/
-(void)setPrintsCaption:(BOOL)inPrints;
/*!
@method setBarWidth:
@abstract Sets the width of a single bar (represented by a single 1 in the barcode string).
@param inBarWidth The value to use for the width of a single bar.
*/
-(void)setBarWidth:(float)inBarWidth;
/*!
@method content
@abstract Accessor method for the data being encoded by this barcode.
@result Pointer to the NSString that stores the barcode's data.
*/
-(NSString *)content;
/*!
@method height
@abstract Accessor method for the height of this barcode.
@result The current height of the barcode in inches.
*/
-(float)height;
/*!
@method width
@abstract Accessor method for the width of this barcode.
@result The current width of this barcode in inches.
*/
-(float)width;
/*!
@method checkDigit
@abstract Accessor method for the checkDigit for this barcode.
@discussion Many barcodes offer and some require a check digit that is calculated based on the rest of the content. This
value shouldn't print as part of the caption and will need to be recalculated if the content changes, so
it makes sense to store it separately
@result The check digit character (ASCII-8 char, not unichar)
*/
-(char)checkDigit;
/*!
@method printsCaption
@abstract Accessor method for printsCaption.
@result YES if the content should be printed below the barcode.
*/
-(BOOL)printsCaption;
/*!
@method barWidth
@abstract Accessor method for the current width of a single bar in inches
@result The current width in inches of a single bar or gap.
*/
-(float)barWidth;
/*!
@method fontSize
@abstract returns the size of the font to use for the caption
@result Floating point value representing the size of the font (in points) to use for the caption
*/
-(float) fontSize;
/*!
@method isSizeValid
@abstract (Deprecated) Returns true if the supplied image size provides sufficient
space to create a valid (open) barcode using this encoding scheme.
@discussion The first version of this barcode framework allowed the user to specify
the size of the barcode when it was instantiated. This method was
implemented as a check to make sure that the barcode that was created
didn't result in a barWidth less than the barcode's specification allowed
(usually 7.5 mils)
@result YES if the bar width at these settings is okay according to the specifications.
*/
-(BOOL)isSizeValid;
/*!
@method generateChecksum
@abstract Generates the check digit or checksum for this barcode encoding scheme.
@discussion This can be overridden by objects implementing encoding schemes that
have a checksum algorithm. You can either require the entire, correct
number be passed in the constructor including the check digit (parsing
it out as appropriate, or you can accept the number without the checksum
and modify the content accordingly here.
*/
-(void)generateChecksum;
/*!
@method isContentValid
@abstract Validates that this barcode supports the data it is encoding.
@discussion This method checks the actual content string to make sure that this encoding
scheme can encode the data it contains. For example, numeric-only schemes
should return false if a string with one or more letters is passed. If there
is a checksum used for the content. that can also be checked here. Don't
override if validation isn't desired or required.
*/
-(BOOL) isContentValid;
/*!
@method initiator
@abstract Returns the encoded initiator or alignment bar(s)
@discussion Returns encoded string representing the left most character. While some barcodes
do not use this, many do have a required character of sequence of bars or gaps
that are used for calibration. Sublasses only need to override if such a character
is needed.
@result String of 0s and 1s representing the first (non-content) character or alignment bar(s).
*/
-(NSString *)initiator;
/*!
@method terminator
@abstract Returns the encoded terminator or alignment bar(s)
@discussion Returns encoded string representing the right-most characte. While some barcodes
do not use this, many do have a required character of sequence of bars or gaps
that are used for calibration. Sublasses only need to override if such a character
is needed.
@result String of 0s and 1s representing the last (non-content) character or alignment bar(s).
*/
-(NSString *)terminator;
/*!
@method _encodeChar
@abstract Private method to turn a single character into a string of 1s and 0s.
@discussion This routine returns an NSString representing a single character. This private method
is used by the default getBarcode function, which is responsible for ordering the
characters (if necessary and returning the entire encoded string, excluding the
terminator and initiator.
@result String of 0s and 1s representing inChar encoded for this barcode.
*/
-(NSString *)_encodeChar:(char)inChar;
/*!
@method barcode:
@abstract Returns string of 0s and 1s representing the content for this type of barcode.
@discussion This method returns a string representing the entire barcode, excluding the initiator
and terminator.
@result String of 0s and 1s representing the content.
*/
-(NSString *)barcode;
/*!
@method completeBarcode
@abstract Method to get the entire barcode as a string of 0s and 1s
@discussion Returns a string representing the entire barcode, including terminator and initiator.
@result String of 0s and 1s representing the entire barcode
*/
-(NSString *)completeBarcode;
/*!
@method digitsToLeft
@abstract Returns number of digits to print to the left of the first bar.
@discussion For encoders with intruding captions such as UPC and EAN barcodes, this method
tells how many of the digits of the content should be printed to the left of the barcode,
rather than intruding on the barcode or printing below the barcode. This only needs to be
overridden if you need a value other than 0
@result The number of characters to print to the left.
*/
-(int)digitsToLeft;
/*!
@method digitsToRight
@abstract Returns number of digits to print to the right of the last bar.
@discussion For encoders with intruding captions such as UPC and EAN barcodes, this method
tells how many of the digits of the content should be printed to the right of the barcode,
rather than intruding on the barcode or printing below the barcode. This only needs to be
overridden if you need a value other than 0
@result The number of characters to print to the right.
*/
-(int)digitsToRight;
/*!
@method leftCaption
@abstract Returns string representing the characters to print to the left of the first bar
@discussion Returns string representing the portion of the caption that goes to the left of the barcode.
@result A string with the data to print to the left.
*/
-(NSString *)leftCaption;
/*!
@method rightCaption
@abstract Returns string representing the characters to print to the right of the last bar
@discussion Returns string representing the portion of the caption that goes to the right of the barcode.
@result A string with the data to print to the right.
*/
-(NSString *)rightCaption;
/*!
@method caption
@abstract Returns content to print below the barcode.
@result String representing the portion of the caption that goes under (or intrudes upon) the barcode.
*/
-(NSString *)caption;
/*!
@method barBottom:
@abstract Designates the bottom of the bar within the barcode for the bar at a given index.
@discussion Given an index which corresponds to the bar / gap number (counting from left), where should
the bottom of the bar be. For most barcodes this value will always be the bottom of the barcode
excluding the caption, but some, like UPC and EAN have different bar bottoms for some bars.
Assumes that origin (0,0) is in lower left.
@param index The bar (from the left, 0-indexed) to specify the bottom position for.
@result The bottom of the bar in inches from the bottom of the barcode.
*/
-(float)barBottom:(int)index;
/*!
@method barTop:
@abstract Designates the top of the bar within the barcode for the bar at a given index.
@discussion Given an index which corresponds to the bar/gap number (counting from left, 0-indexed),
this method will tell where the top of the bar should be. For most barcodes this value will
always be the top of the barcode excluding the caption, since most barcodes have a uniform top, but
some, like PostNet use different bar tops as part of the encoding scheme.
@param index The bar (from the left, 0 indexed) to specify the top position for.
@result The top of the bar in inches from the bottom of the barcode.
*/
-(float)barTop:(int)index;
/*!
@method firstBar
@abstract Returns the position, from the left, specified in inches where the first bar prints
@discussion Returns the the horizontal position of the left edge of the first bar or gap. Typically, this is 0,
but some code, like EAN/UPC require some digits to print to the left and/or right of the code, meaning
that we need allocate some white space by skipping some pixels before drawing the first bar
@result The x-position in inches where the first bar prints
*/
-(float)firstBar;
/*!
@method lastBar
@abstract Returns the position, from the left, specified in inches where the last bar ends
@discussion Returns the the horizontal position of the right edge of the last bar or gap. Typically, this is the
same as [barcode width] but some codes, like EAN/UPC require some digits to print to the left and/or
right of the code, meaning that we need allocate some white space by ending the codes before the end
of the barcode. This is generally the right edge of the last barcode less one barwidth
@result The x-position in inches where the last bar ends
*/
-(float)lastBar;
@end
| {
"pile_set_name": "Github"
} |
int foo()
{
return 10;
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
# Contest Management System - http://cms-dev.github.io/
# Copyright © 2018 Stefano Maggiolo <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Tests for the DumpImporter script"""
import json
import os
import unittest
# Needs to be first to allow for monkey patching the DB connection string.
from cmstestsuite.unit_tests.databasemixin import DatabaseMixin
from cms.db import Contest, FSObject, Session, version
from cmscommon.digest import bytes_digest
from cmscontrib.DumpImporter import DumpImporter
from cmstestsuite.unit_tests.filesystemmixin import FileSystemMixin
class TestDumpImporter(DatabaseMixin, FileSystemMixin, unittest.TestCase):
GENERATED_FILE_CONTENT = b"content"
NON_GENERATED_FILE_CONTENT = b"source"
GENERATED_FILE_DIGEST = bytes_digest(GENERATED_FILE_CONTENT)
NON_GENERATED_FILE_DIGEST = bytes_digest(NON_GENERATED_FILE_CONTENT)
FILES = {
GENERATED_FILE_DIGEST: ("desc", GENERATED_FILE_CONTENT),
NON_GENERATED_FILE_DIGEST: ("subsource", NON_GENERATED_FILE_CONTENT),
}
DUMP = {
"contest_key": {
"_class": "Contest",
"name": "contestname",
"description": "contest description 你好",
"tasks": ["task_key"],
"participations": ["part_key"],
},
"task_key": {
"_class": "Task",
"name": "taskname",
"title": "task title",
"num": 0,
"contest": "contest_key",
"submission_format": ["source"],
"attachments": {},
"datasets": ["dataset_key"],
"active_dataset": "dataset_key",
"submissions": ["sub_key"],
},
"dataset_key": {
"_class": "Dataset",
"task_type": "Batch",
"task_type_parameters": "[]",
"score_type": "Sum",
"score_type_parameters": "[]",
"time_limit": 1.0,
"memory_limit": 512 * 1024 * 1024,
"description": "dataset description",
"task": "task_key",
"managers": {},
},
"user_key": {
"_class": "User",
"username": "username",
"first_name": "First Name",
"last_name": "Last Name",
"password": "pwd",
"participations": ["part_key"],
},
"part_key": {
"_class": "Participation",
"user": "user_key",
"contest": "contest_key",
"submissions": ["sub_key"],
},
"sub_key": {
"_class": "Submission",
"timestamp": 1_234_567_890.123,
"participation": "part_key",
"task": "task_key",
"files": {"source": "file_key"},
"results": ["sr_key"],
},
"file_key": {
"_class": "File",
"submission": "sub_key",
"filename": "source",
"digest": NON_GENERATED_FILE_DIGEST,
},
"sr_key": {
"_class": "SubmissionResult",
"submission": "sub_key",
"dataset": "dataset_key",
"executables": {"exe": "exe_key"},
},
"exe_key": {
"_class": "Executable",
"submission_result": "sr_key",
"filename": "exe",
"dataset": "dataset_key",
"digest": GENERATED_FILE_DIGEST,
},
"_version": version,
"_objects": ["contest_key", "user_key"],
}
def setUp(self):
super().setUp()
# Another contest, to make sure it's not wiped on import.
self.other_contest = self.add_contest()
self.session.commit()
self.other_contest_name = self.other_contest.name
self.other_contest_description = self.other_contest.description
def tearDown(self):
self.delete_data()
super().tearDown()
def do_import(self, drop=False, load_files=True,
skip_generated=False, skip_submissions=False):
"""Create an importer and call do_import in a convenient way"""
return DumpImporter(
drop,
self.base_dir,
load_files=load_files,
load_model=True,
skip_generated=skip_generated,
skip_submissions=skip_submissions,
skip_user_tests=False,
skip_print_jobs=False).do_import()
def write_dump(self, dump):
destination = self.get_path("contest.json")
with open(destination, "wt", encoding="utf-8") as f:
json.dump(dump, f, indent=4, sort_keys=True)
def write_files(self, data):
"""Write files and descriptions on the filesystem.
data ({str: (str, bytes)}): dictionary mapping digest to description
and content.
"""
f_path = self.makedirs("files")
d_path = self.makedirs("descriptions")
for digest, (desc, content) in data.items():
with open(
os.path.join(d_path, digest), "wt", encoding="utf-8") as f:
f.write(desc)
with open(os.path.join(f_path, digest), "wb") as f:
f.write(content)
def assertContestInDb(self, name, description, task_names_and_titles,
usernames_and_last_names):
"""Assert that the contest with the given data is in the DB
The query is done by contest name, and to avoid caching, we query from
a brand new session.
"""
db_contests = self.session.query(Contest)\
.filter(Contest.name == name).all()
self.assertEqual(len(db_contests), 1)
c = db_contests[0]
self.assertEqual(c.name, name)
self.assertEqual(c.description, description)
self.assertCountEqual([(t.name, t.title) for t in c.tasks],
task_names_and_titles)
self.assertCountEqual([(u.user.username, u.user.last_name)
for u in c.participations],
usernames_and_last_names)
def assertContestNotInDb(self, name):
"""Assert that the contest with the given name is not in the DB."""
db_contests = self.session.query(Contest)\
.filter(Contest.name == name).all()
self.assertEqual(len(db_contests), 0)
def assertFileInDb(self, digest, description, content):
"""Assert that the file with the given data is in the DB."""
fsos = self.session.query(FSObject)\
.filter(FSObject.digest == digest).all()
self.assertEqual(len(fsos), 1)
fso = fsos[0]
self.assertEqual(fso.digest, digest)
self.assertEqual(fso.description, description)
self.assertEqual(fso.get_lobject().read(), content)
def assertFileNotInDb(self, digest):
"""Assert that the file with the given digest is not in the DB."""
fsos = self.session.query(FSObject)\
.filter(FSObject.digest == digest).all()
self.assertEqual(len(fsos), 0)
def test_import(self):
"""Test importing everything, while keeping the existing contest."""
self.write_dump(TestDumpImporter.DUMP)
self.write_files(TestDumpImporter.FILES)
self.assertTrue(self.do_import())
self.assertContestInDb("contestname", "contest description 你好",
[("taskname", "task title")],
[("username", "Last Name")])
self.assertContestInDb(
self.other_contest_name, self.other_contest_description, [], [])
self.assertFileInDb(
TestDumpImporter.GENERATED_FILE_DIGEST, "desc", b"content")
self.assertFileInDb(
TestDumpImporter.NON_GENERATED_FILE_DIGEST, "subsource", b"source")
def test_import_with_drop(self):
"""Test importing everything, but dropping existing data."""
self.write_dump(TestDumpImporter.DUMP)
self.write_files(TestDumpImporter.FILES)
# Need to close the session and reopen it, otherwise the drop hangs.
self.session.close()
self.assertTrue(self.do_import(drop=True))
self.session = Session()
self.assertContestInDb("contestname", "contest description 你好",
[("taskname", "task title")],
[("username", "Last Name")])
self.assertContestNotInDb(self.other_contest_name)
self.assertFileInDb(
TestDumpImporter.GENERATED_FILE_DIGEST, "desc", b"content")
self.assertFileInDb(
TestDumpImporter.NON_GENERATED_FILE_DIGEST, "subsource", b"source")
def test_import_skip_generated(self):
"""Test importing everything but the generated data."""
self.write_dump(TestDumpImporter.DUMP)
self.write_files(TestDumpImporter.FILES)
self.assertTrue(self.do_import(skip_generated=True))
self.assertContestInDb("contestname", "contest description 你好",
[("taskname", "task title")],
[("username", "Last Name")])
self.assertContestInDb(
self.other_contest_name, self.other_contest_description, [], [])
self.assertFileNotInDb(TestDumpImporter.GENERATED_FILE_DIGEST)
self.assertFileInDb(
TestDumpImporter.NON_GENERATED_FILE_DIGEST, "subsource", b"source")
def test_import_skip_files(self):
"""Test importing the json but not the files."""
self.write_dump(TestDumpImporter.DUMP)
self.write_files(TestDumpImporter.FILES)
self.assertTrue(self.do_import(load_files=False))
self.assertContestInDb("contestname", "contest description 你好",
[("taskname", "task title")],
[("username", "Last Name")])
self.assertContestInDb(
self.other_contest_name, self.other_contest_description, [], [])
self.assertFileNotInDb(TestDumpImporter.GENERATED_FILE_DIGEST)
self.assertFileNotInDb(TestDumpImporter.NON_GENERATED_FILE_DIGEST)
def test_import_old(self):
"""Test importing an old dump.
This does not pretend to be exhaustive, just makes sure the happy
path of the updaters run successfully.
"""
self.write_dump({
"contest_key": {
"_class": "Contest",
"name": "contestname",
"description": "contest description",
"start": 1_234_567_890.000,
"stop": 1_324_567_890.000,
"token_initial": 2,
"token_gen_number": 1,
"token_gen_time": 10,
"token_total": 100,
"token_max": 100,
"tasks": ["task_key"],
},
"task_key": {
"_class": "Task",
"name": "taskname",
"title": "task title",
"num": 0,
"primary_statements": "[\"en\", \"ja\"]",
"token_initial": None,
"token_gen_number": 0,
"token_gen_time": 0,
"token_total": None,
"token_max": None,
"task_type": "Batch",
"task_type_parameters": "[]",
"score_type": "Sum",
"score_type_parameters": "[]",
"time_limit": 0.0,
"memory_limit": None,
"contest": "contest_key",
"attachments": {},
"managers": {},
"testcases": {},
"submissions": ["sub1_key", "sub2_key"],
"user_tests": [],
},
"user_key": {
"_class": "User",
"username": "username",
"first_name": "First Name",
"last_name": "Last Name",
"password": "pwd",
"email": "",
"ip": "0.0.0.0",
"preferred_languages": "[\"en\", \"it_IT\"]",
"contest": "contest_key",
"submissions": ["sub1_key", "sub2_key"],
},
"sub1_key": {
"_class": "Submission",
"timestamp": 1_234_567_890.123,
"language": "c",
"user": "user_key",
"task": "task_key",
"compilation_text": "OK [1.234 - 20]",
"files": {},
"executables": {"exe": "exe_key"},
"evaluations": [],
},
"sub2_key": {
"_class": "Submission",
"timestamp": 1_234_567_900.123,
"language": "c",
"user": "user_key",
"task": "task_key",
"compilation_text": "Killed with signal 11 [0.123 - 10]\n",
"files": {},
"executables": {},
"evaluations": [],
},
"exe_key": {
"_class": "Executable",
"submission": "sub1_key",
"filename": "exe",
"digest": TestDumpImporter.GENERATED_FILE_DIGEST,
},
"_version": 1,
"_objects": ["contest_key", "user_key"],
})
self.write_files(TestDumpImporter.FILES)
self.assertTrue(self.do_import(skip_generated=True))
self.assertContestInDb("contestname", "contest description",
[("taskname", "task title")],
[("username", "Last Name")])
self.assertContestInDb(
self.other_contest_name, self.other_contest_description, [], [])
self.assertFileNotInDb("040f06fd774092478d450774f5ba30c5da78acc8")
if __name__ == "__main__":
unittest.main()
| {
"pile_set_name": "Github"
} |
# /* Copyright (C) 2001
# * Housemarque Oy
# * http://www.housemarque.com
# *
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# */
#
# /* Revised by Paul Mensonides (2002) */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_ARITHMETIC_INC_HPP
# define BOOST_PREPROCESSOR_ARITHMETIC_INC_HPP
#
# include <boost/preprocessor/config/config.hpp>
#
# /* BOOST_PP_INC */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC()
# define BOOST_PP_INC(x) BOOST_PP_INC_I(x)
# else
# define BOOST_PP_INC(x) BOOST_PP_INC_OO((x))
# define BOOST_PP_INC_OO(par) BOOST_PP_INC_I ## par
# endif
#
# define BOOST_PP_INC_I(x) BOOST_PP_INC_ ## x
#
# define BOOST_PP_INC_0 1
# define BOOST_PP_INC_1 2
# define BOOST_PP_INC_2 3
# define BOOST_PP_INC_3 4
# define BOOST_PP_INC_4 5
# define BOOST_PP_INC_5 6
# define BOOST_PP_INC_6 7
# define BOOST_PP_INC_7 8
# define BOOST_PP_INC_8 9
# define BOOST_PP_INC_9 10
# define BOOST_PP_INC_10 11
# define BOOST_PP_INC_11 12
# define BOOST_PP_INC_12 13
# define BOOST_PP_INC_13 14
# define BOOST_PP_INC_14 15
# define BOOST_PP_INC_15 16
# define BOOST_PP_INC_16 17
# define BOOST_PP_INC_17 18
# define BOOST_PP_INC_18 19
# define BOOST_PP_INC_19 20
# define BOOST_PP_INC_20 21
# define BOOST_PP_INC_21 22
# define BOOST_PP_INC_22 23
# define BOOST_PP_INC_23 24
# define BOOST_PP_INC_24 25
# define BOOST_PP_INC_25 26
# define BOOST_PP_INC_26 27
# define BOOST_PP_INC_27 28
# define BOOST_PP_INC_28 29
# define BOOST_PP_INC_29 30
# define BOOST_PP_INC_30 31
# define BOOST_PP_INC_31 32
# define BOOST_PP_INC_32 33
# define BOOST_PP_INC_33 34
# define BOOST_PP_INC_34 35
# define BOOST_PP_INC_35 36
# define BOOST_PP_INC_36 37
# define BOOST_PP_INC_37 38
# define BOOST_PP_INC_38 39
# define BOOST_PP_INC_39 40
# define BOOST_PP_INC_40 41
# define BOOST_PP_INC_41 42
# define BOOST_PP_INC_42 43
# define BOOST_PP_INC_43 44
# define BOOST_PP_INC_44 45
# define BOOST_PP_INC_45 46
# define BOOST_PP_INC_46 47
# define BOOST_PP_INC_47 48
# define BOOST_PP_INC_48 49
# define BOOST_PP_INC_49 50
# define BOOST_PP_INC_50 51
# define BOOST_PP_INC_51 52
# define BOOST_PP_INC_52 53
# define BOOST_PP_INC_53 54
# define BOOST_PP_INC_54 55
# define BOOST_PP_INC_55 56
# define BOOST_PP_INC_56 57
# define BOOST_PP_INC_57 58
# define BOOST_PP_INC_58 59
# define BOOST_PP_INC_59 60
# define BOOST_PP_INC_60 61
# define BOOST_PP_INC_61 62
# define BOOST_PP_INC_62 63
# define BOOST_PP_INC_63 64
# define BOOST_PP_INC_64 65
# define BOOST_PP_INC_65 66
# define BOOST_PP_INC_66 67
# define BOOST_PP_INC_67 68
# define BOOST_PP_INC_68 69
# define BOOST_PP_INC_69 70
# define BOOST_PP_INC_70 71
# define BOOST_PP_INC_71 72
# define BOOST_PP_INC_72 73
# define BOOST_PP_INC_73 74
# define BOOST_PP_INC_74 75
# define BOOST_PP_INC_75 76
# define BOOST_PP_INC_76 77
# define BOOST_PP_INC_77 78
# define BOOST_PP_INC_78 79
# define BOOST_PP_INC_79 80
# define BOOST_PP_INC_80 81
# define BOOST_PP_INC_81 82
# define BOOST_PP_INC_82 83
# define BOOST_PP_INC_83 84
# define BOOST_PP_INC_84 85
# define BOOST_PP_INC_85 86
# define BOOST_PP_INC_86 87
# define BOOST_PP_INC_87 88
# define BOOST_PP_INC_88 89
# define BOOST_PP_INC_89 90
# define BOOST_PP_INC_90 91
# define BOOST_PP_INC_91 92
# define BOOST_PP_INC_92 93
# define BOOST_PP_INC_93 94
# define BOOST_PP_INC_94 95
# define BOOST_PP_INC_95 96
# define BOOST_PP_INC_96 97
# define BOOST_PP_INC_97 98
# define BOOST_PP_INC_98 99
# define BOOST_PP_INC_99 100
# define BOOST_PP_INC_100 101
# define BOOST_PP_INC_101 102
# define BOOST_PP_INC_102 103
# define BOOST_PP_INC_103 104
# define BOOST_PP_INC_104 105
# define BOOST_PP_INC_105 106
# define BOOST_PP_INC_106 107
# define BOOST_PP_INC_107 108
# define BOOST_PP_INC_108 109
# define BOOST_PP_INC_109 110
# define BOOST_PP_INC_110 111
# define BOOST_PP_INC_111 112
# define BOOST_PP_INC_112 113
# define BOOST_PP_INC_113 114
# define BOOST_PP_INC_114 115
# define BOOST_PP_INC_115 116
# define BOOST_PP_INC_116 117
# define BOOST_PP_INC_117 118
# define BOOST_PP_INC_118 119
# define BOOST_PP_INC_119 120
# define BOOST_PP_INC_120 121
# define BOOST_PP_INC_121 122
# define BOOST_PP_INC_122 123
# define BOOST_PP_INC_123 124
# define BOOST_PP_INC_124 125
# define BOOST_PP_INC_125 126
# define BOOST_PP_INC_126 127
# define BOOST_PP_INC_127 128
# define BOOST_PP_INC_128 129
# define BOOST_PP_INC_129 130
# define BOOST_PP_INC_130 131
# define BOOST_PP_INC_131 132
# define BOOST_PP_INC_132 133
# define BOOST_PP_INC_133 134
# define BOOST_PP_INC_134 135
# define BOOST_PP_INC_135 136
# define BOOST_PP_INC_136 137
# define BOOST_PP_INC_137 138
# define BOOST_PP_INC_138 139
# define BOOST_PP_INC_139 140
# define BOOST_PP_INC_140 141
# define BOOST_PP_INC_141 142
# define BOOST_PP_INC_142 143
# define BOOST_PP_INC_143 144
# define BOOST_PP_INC_144 145
# define BOOST_PP_INC_145 146
# define BOOST_PP_INC_146 147
# define BOOST_PP_INC_147 148
# define BOOST_PP_INC_148 149
# define BOOST_PP_INC_149 150
# define BOOST_PP_INC_150 151
# define BOOST_PP_INC_151 152
# define BOOST_PP_INC_152 153
# define BOOST_PP_INC_153 154
# define BOOST_PP_INC_154 155
# define BOOST_PP_INC_155 156
# define BOOST_PP_INC_156 157
# define BOOST_PP_INC_157 158
# define BOOST_PP_INC_158 159
# define BOOST_PP_INC_159 160
# define BOOST_PP_INC_160 161
# define BOOST_PP_INC_161 162
# define BOOST_PP_INC_162 163
# define BOOST_PP_INC_163 164
# define BOOST_PP_INC_164 165
# define BOOST_PP_INC_165 166
# define BOOST_PP_INC_166 167
# define BOOST_PP_INC_167 168
# define BOOST_PP_INC_168 169
# define BOOST_PP_INC_169 170
# define BOOST_PP_INC_170 171
# define BOOST_PP_INC_171 172
# define BOOST_PP_INC_172 173
# define BOOST_PP_INC_173 174
# define BOOST_PP_INC_174 175
# define BOOST_PP_INC_175 176
# define BOOST_PP_INC_176 177
# define BOOST_PP_INC_177 178
# define BOOST_PP_INC_178 179
# define BOOST_PP_INC_179 180
# define BOOST_PP_INC_180 181
# define BOOST_PP_INC_181 182
# define BOOST_PP_INC_182 183
# define BOOST_PP_INC_183 184
# define BOOST_PP_INC_184 185
# define BOOST_PP_INC_185 186
# define BOOST_PP_INC_186 187
# define BOOST_PP_INC_187 188
# define BOOST_PP_INC_188 189
# define BOOST_PP_INC_189 190
# define BOOST_PP_INC_190 191
# define BOOST_PP_INC_191 192
# define BOOST_PP_INC_192 193
# define BOOST_PP_INC_193 194
# define BOOST_PP_INC_194 195
# define BOOST_PP_INC_195 196
# define BOOST_PP_INC_196 197
# define BOOST_PP_INC_197 198
# define BOOST_PP_INC_198 199
# define BOOST_PP_INC_199 200
# define BOOST_PP_INC_200 201
# define BOOST_PP_INC_201 202
# define BOOST_PP_INC_202 203
# define BOOST_PP_INC_203 204
# define BOOST_PP_INC_204 205
# define BOOST_PP_INC_205 206
# define BOOST_PP_INC_206 207
# define BOOST_PP_INC_207 208
# define BOOST_PP_INC_208 209
# define BOOST_PP_INC_209 210
# define BOOST_PP_INC_210 211
# define BOOST_PP_INC_211 212
# define BOOST_PP_INC_212 213
# define BOOST_PP_INC_213 214
# define BOOST_PP_INC_214 215
# define BOOST_PP_INC_215 216
# define BOOST_PP_INC_216 217
# define BOOST_PP_INC_217 218
# define BOOST_PP_INC_218 219
# define BOOST_PP_INC_219 220
# define BOOST_PP_INC_220 221
# define BOOST_PP_INC_221 222
# define BOOST_PP_INC_222 223
# define BOOST_PP_INC_223 224
# define BOOST_PP_INC_224 225
# define BOOST_PP_INC_225 226
# define BOOST_PP_INC_226 227
# define BOOST_PP_INC_227 228
# define BOOST_PP_INC_228 229
# define BOOST_PP_INC_229 230
# define BOOST_PP_INC_230 231
# define BOOST_PP_INC_231 232
# define BOOST_PP_INC_232 233
# define BOOST_PP_INC_233 234
# define BOOST_PP_INC_234 235
# define BOOST_PP_INC_235 236
# define BOOST_PP_INC_236 237
# define BOOST_PP_INC_237 238
# define BOOST_PP_INC_238 239
# define BOOST_PP_INC_239 240
# define BOOST_PP_INC_240 241
# define BOOST_PP_INC_241 242
# define BOOST_PP_INC_242 243
# define BOOST_PP_INC_243 244
# define BOOST_PP_INC_244 245
# define BOOST_PP_INC_245 246
# define BOOST_PP_INC_246 247
# define BOOST_PP_INC_247 248
# define BOOST_PP_INC_248 249
# define BOOST_PP_INC_249 250
# define BOOST_PP_INC_250 251
# define BOOST_PP_INC_251 252
# define BOOST_PP_INC_252 253
# define BOOST_PP_INC_253 254
# define BOOST_PP_INC_254 255
# define BOOST_PP_INC_255 256
# define BOOST_PP_INC_256 256
#
# endif
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zeppelin.utils;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
public class CorsUtils {
public static Boolean isValidOrigin(String sourceHost, ZeppelinConfiguration conf)
throws UnknownHostException, URISyntaxException {
String sourceUriHost = "";
if (sourceHost != null && !sourceHost.isEmpty()) {
sourceUriHost = new URI(sourceHost).getHost();
sourceUriHost = (sourceUriHost == null) ? "" : sourceUriHost.toLowerCase();
}
sourceUriHost = sourceUriHost.toLowerCase();
String currentHost = InetAddress.getLocalHost().getHostName().toLowerCase();
return conf.getAllowedOrigins().contains("*")
|| currentHost.equals(sourceUriHost)
|| "localhost".equals(sourceUriHost)
|| conf.getAllowedOrigins().contains(sourceHost);
}
}
| {
"pile_set_name": "Github"
} |
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`treeToSVG wraps whatever text you pass into it with an SVG schema 1`] = `
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\" ?>
<svg width=\\"1024\\" height=\\"768\\" xmlns=\\"http://www.w3.org/2000/svg\\" version=\\"1.1\\">
<rect type=\\"View\\" x=\\"2\\" y=\\"80\\" width=\\"200\\" height=\\"200\\" fill=\\"none\\"/>
</svg>
"
`;
| {
"pile_set_name": "Github"
} |
{
"id": "google_groupssettings",
"title": "Groups Settings",
"description": "Lets you manage permission levels and related settings of a group.",
"security": {
"google_groupssettings": {
"integration": "google_groupssettings",
"fields": {
"access_token": "An OAuth access token",
"refresh_token": "An OAuth refresh token (optional)",
"client_id": "An OAuth client ID (optional)",
"client_secret": "An OAuth client secret (optional)",
"redirect_uri": "The callback URL for your application"
},
"oauth": {
"authorizationUrl": "https://accounts.google.com/o/oauth2/auth",
"description": "Oauth 2.0 accessCode authentication",
"flow": "accessCode",
"scopes": {
"https://www.googleapis.com/auth/apps.groups.settings": "View and manage the settings of a G Suite group"
},
"tokenUrl": "https://accounts.google.com/o/oauth2/token",
"type": "oauth2"
}
}
},
"logo": {
"url": "https://s3-us-west-2.amazonaws.com/datafire-logos/google_groupssettings.png"
},
"actionCount": 5,
"definitions": {
"Groups": {
"description": "JSON template for Group resource",
"properties": {
"allowExternalMembers": {
"description": "Are external members allowed to join the group.",
"type": "string"
},
"allowGoogleCommunication": {
"description": "Is google allowed to contact admins.",
"type": "string"
},
"allowWebPosting": {
"description": "If posting from web is allowed.",
"type": "string"
},
"archiveOnly": {
"description": "If the group is archive only",
"type": "string"
},
"customFooterText": {
"description": "Custom footer text.",
"type": "string"
},
"customReplyTo": {
"description": "Default email to which reply to any message should go.",
"type": "string"
},
"defaultMessageDenyNotificationText": {
"description": "Default message deny notification message",
"type": "string"
},
"description": {
"description": "Description of the group",
"type": "string"
},
"email": {
"description": "Email id of the group",
"type": "string"
},
"includeCustomFooter": {
"description": "Whether to include custom footer.",
"type": "string"
},
"includeInGlobalAddressList": {
"description": "If this groups should be included in global address list or not.",
"type": "string"
},
"isArchived": {
"description": "If the contents of the group are archived.",
"type": "string"
},
"kind": {
"default": "groupsSettings#groups",
"description": "The type of the resource.",
"type": "string"
},
"maxMessageBytes": {
"description": "Maximum message size allowed.",
"format": "int32",
"type": "integer"
},
"membersCanPostAsTheGroup": {
"description": "Can members post using the group email address.",
"type": "string"
},
"messageDisplayFont": {
"description": "Default message display font. Possible values are: DEFAULT_FONT FIXED_WIDTH_FONT",
"type": "string"
},
"messageModerationLevel": {
"description": "Moderation level for messages. Possible values are: MODERATE_ALL_MESSAGES MODERATE_NON_MEMBERS MODERATE_NEW_MEMBERS MODERATE_NONE",
"type": "string"
},
"name": {
"description": "Name of the Group",
"type": "string"
},
"primaryLanguage": {
"description": "Primary language for the group.",
"type": "string"
},
"replyTo": {
"description": "Whome should the default reply to a message go to. Possible values are: REPLY_TO_CUSTOM REPLY_TO_SENDER REPLY_TO_LIST REPLY_TO_OWNER REPLY_TO_IGNORE REPLY_TO_MANAGERS",
"type": "string"
},
"sendMessageDenyNotification": {
"description": "Should the member be notified if his message is denied by owner.",
"type": "string"
},
"showInGroupDirectory": {
"description": "Is the group listed in groups directory",
"type": "string"
},
"spamModerationLevel": {
"description": "Moderation level for messages detected as spam. Possible values are: ALLOW MODERATE SILENTLY_MODERATE REJECT",
"type": "string"
},
"whoCanAdd": {
"description": "Permissions to add members. Possible values are: ALL_MANAGERS_CAN_ADD ALL_MEMBERS_CAN_ADD NONE_CAN_ADD",
"type": "string"
},
"whoCanContactOwner": {
"description": "Permission to contact owner of the group via web UI. Possible values are: ANYONE_CAN_CONTACT ALL_IN_DOMAIN_CAN_CONTACT ALL_MEMBERS_CAN_CONTACT ALL_MANAGERS_CAN_CONTACT",
"type": "string"
},
"whoCanInvite": {
"description": "Permissions to invite members. Possible values are: ALL_MEMBERS_CAN_INVITE ALL_MANAGERS_CAN_INVITE NONE_CAN_INVITE",
"type": "string"
},
"whoCanJoin": {
"description": "Permissions to join the group. Possible values are: ANYONE_CAN_JOIN ALL_IN_DOMAIN_CAN_JOIN INVITED_CAN_JOIN CAN_REQUEST_TO_JOIN",
"type": "string"
},
"whoCanLeaveGroup": {
"description": "Permission to leave the group. Possible values are: ALL_MANAGERS_CAN_LEAVE ALL_MEMBERS_CAN_LEAVE NONE_CAN_LEAVE",
"type": "string"
},
"whoCanPostMessage": {
"description": "Permissions to post messages to the group. Possible values are: NONE_CAN_POST ALL_MANAGERS_CAN_POST ALL_MEMBERS_CAN_POST ALL_IN_DOMAIN_CAN_POST ANYONE_CAN_POST",
"type": "string"
},
"whoCanViewGroup": {
"description": "Permissions to view group. Possible values are: ANYONE_CAN_VIEW ALL_IN_DOMAIN_CAN_VIEW ALL_MEMBERS_CAN_VIEW ALL_MANAGERS_CAN_VIEW",
"type": "string"
},
"whoCanViewMembership": {
"description": "Permissions to view membership. Possible values are: ALL_IN_DOMAIN_CAN_VIEW ALL_MEMBERS_CAN_VIEW ALL_MANAGERS_CAN_VIEW",
"type": "string"
}
},
"type": "object",
"title": "Groups"
}
},
"actions": [
{
"id": "oauthCallback",
"title": "",
"description": "Exchange the code passed to your redirect URI for an access_token",
"inputSchema": {
"type": "object",
"properties": {
"code": {
"title": "code",
"type": "string"
}
},
"required": [
"code"
]
},
"outputSchema": {
"properties": {
"access_token": {
"type": "string"
},
"refresh_token": {
"type": "string"
},
"token_type": {
"type": "string"
},
"scope": {
"type": "string"
},
"expiration": {
"type": "string"
}
}
},
"security": {
"google_groupssettings": {
"integration": "google_groupssettings"
}
}
},
{
"id": "oauthRefresh",
"title": "",
"description": "Exchange a refresh_token for an access_token",
"inputSchema": {},
"outputSchema": {
"properties": {
"access_token": {
"type": "string"
},
"refresh_token": {
"type": "string"
},
"token_type": {
"type": "string"
},
"scope": {
"type": "string"
},
"expiration": {
"type": "string"
}
}
},
"security": {
"google_groupssettings": {
"integration": "google_groupssettings"
}
}
},
{
"id": "groups.get",
"title": "groups.get",
"description": "Gets one resource by id.",
"inputSchema": {
"type": "object",
"properties": {
"groupUniqueId": {
"type": "string",
"description": "The resource ID"
},
"alt": {
"type": "string",
"description": "Data format for the response.",
"enum": [
"atom",
"json"
],
"default": "atom"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response."
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token."
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user."
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": true
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided."
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits."
}
},
"additionalProperties": false,
"required": [
"groupUniqueId"
]
},
"outputSchema": {
"$ref": "#/definitions/Groups"
},
"security": {
"google_groupssettings": {
"integration": "google_groupssettings"
}
}
},
{
"id": "groups.patch",
"title": "groups.patch",
"description": "Updates an existing resource. This method supports patch semantics.",
"inputSchema": {
"type": "object",
"properties": {
"groupUniqueId": {
"type": "string",
"description": "The resource ID"
},
"body": {
"$ref": "#/definitions/Groups"
},
"alt": {
"type": "string",
"description": "Data format for the response.",
"enum": [
"atom",
"json"
],
"default": "atom"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response."
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token."
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user."
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": true
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided."
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits."
}
},
"additionalProperties": false,
"required": [
"groupUniqueId"
]
},
"outputSchema": {
"$ref": "#/definitions/Groups"
},
"security": {
"google_groupssettings": {
"integration": "google_groupssettings"
}
}
},
{
"id": "groups.update",
"title": "groups.update",
"description": "Updates an existing resource.",
"inputSchema": {
"type": "object",
"properties": {
"groupUniqueId": {
"type": "string",
"description": "The resource ID"
},
"body": {
"$ref": "#/definitions/Groups"
},
"alt": {
"type": "string",
"description": "Data format for the response.",
"enum": [
"atom",
"json"
],
"default": "atom"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response."
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token."
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user."
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": true
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided."
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits."
}
},
"additionalProperties": false,
"required": [
"groupUniqueId"
]
},
"outputSchema": {
"$ref": "#/definitions/Groups"
},
"security": {
"google_groupssettings": {
"integration": "google_groupssettings"
}
}
}
],
"tags": [
"google"
]
} | {
"pile_set_name": "Github"
} |
/**********************************************************************
*These solidity codes have been obtained from Etherscan for extracting
*the smartcontract related info.
*The data will be used by MATRIX AI team as the reference basis for
*MATRIX model analysis,extraction of contract semantics,
*as well as AI based data analysis, etc.
**********************************************************************/
// Copyright New Alchemy Limited, 2017. All rights reserved.
pragma solidity >=0.4.10;
// from Zeppelin
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
require(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
require(c>=a && c>=b);
return c;
}
}
contract Owned {
address public owner;
address newOwner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
contract Pausable is Owned {
bool public paused;
function pause() onlyOwner {
paused = true;
}
function unpause() onlyOwner {
paused = false;
}
modifier notPaused() {
require(!paused);
_;
}
}
contract Finalizable is Owned {
bool public finalized;
function finalize() onlyOwner {
finalized = true;
}
modifier notFinalized() {
require(!finalized);
_;
}
}
contract IToken {
function transfer(address _to, uint _value) returns (bool);
function balanceOf(address owner) returns(uint);
}
// In case someone accidentally sends token to one of these contracts,
// add a way to get them back out.
contract TokenReceivable is Owned {
function claimTokens(address _token, address _to) onlyOwner returns (bool) {
IToken token = IToken(_token);
return token.transfer(_to, token.balanceOf(this));
}
}
contract EventDefinitions {
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Token is Finalizable, TokenReceivable, SafeMath, EventDefinitions, Pausable {
string constant public name = "Token Report";
uint8 constant public decimals = 8;
string constant public symbol = "DATA";
Controller public controller;
string public motd;
event Motd(string message);
// functions below this line are onlyOwner
// set "message of the day"
function setMotd(string _m) onlyOwner {
motd = _m;
Motd(_m);
}
function setController(address _c) onlyOwner notFinalized {
controller = Controller(_c);
}
// functions below this line are public
function balanceOf(address a) constant returns (uint) {
return controller.balanceOf(a);
}
function totalSupply() constant returns (uint) {
return controller.totalSupply();
}
function allowance(address _owner, address _spender) constant returns (uint) {
return controller.allowance(_owner, _spender);
}
function transfer(address _to, uint _value) onlyPayloadSize(2) notPaused returns (bool success) {
if (controller.transfer(msg.sender, _to, _value)) {
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3) notPaused returns (bool success) {
if (controller.transferFrom(msg.sender, _from, _to, _value)) {
Transfer(_from, _to, _value);
return true;
}
return false;
}
function approve(address _spender, uint _value) onlyPayloadSize(2) notPaused returns (bool success) {
// promote safe user behavior
if (controller.approve(msg.sender, _spender, _value)) {
Approval(msg.sender, _spender, _value);
return true;
}
return false;
}
function increaseApproval (address _spender, uint _addedValue) onlyPayloadSize(2) notPaused returns (bool success) {
if (controller.increaseApproval(msg.sender, _spender, _addedValue)) {
uint newval = controller.allowance(msg.sender, _spender);
Approval(msg.sender, _spender, newval);
return true;
}
return false;
}
function decreaseApproval (address _spender, uint _subtractedValue) onlyPayloadSize(2) notPaused returns (bool success) {
if (controller.decreaseApproval(msg.sender, _spender, _subtractedValue)) {
uint newval = controller.allowance(msg.sender, _spender);
Approval(msg.sender, _spender, newval);
return true;
}
return false;
}
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length >= numwords * 32 + 4);
_;
}
function burn(uint _amount) notPaused {
controller.burn(msg.sender, _amount);
Transfer(msg.sender, 0x0, _amount);
}
// functions below this line are onlyController
modifier onlyController() {
assert(msg.sender == address(controller));
_;
}
// In the future, when the controller supports multiple token
// heads, allow the controller to reconstitute the transfer and
// approval history.
function controllerTransfer(address _from, address _to, uint _value) onlyController {
Transfer(_from, _to, _value);
}
function controllerApprove(address _owner, address _spender, uint _value) onlyController {
Approval(_owner, _spender, _value);
}
}
contract Controller is Owned, Finalizable {
Ledger public ledger;
Token public token;
function Controller() {
}
// functions below this line are onlyOwner
function setToken(address _token) onlyOwner {
token = Token(_token);
}
function setLedger(address _ledger) onlyOwner {
ledger = Ledger(_ledger);
}
modifier onlyToken() {
require(msg.sender == address(token));
_;
}
modifier onlyLedger() {
require(msg.sender == address(ledger));
_;
}
// public functions
function totalSupply() constant returns (uint) {
return ledger.totalSupply();
}
function balanceOf(address _a) constant returns (uint) {
return ledger.balanceOf(_a);
}
function allowance(address _owner, address _spender) constant returns (uint) {
return ledger.allowance(_owner, _spender);
}
// functions below this line are onlyLedger
// let the ledger send transfer events (the most obvious case
// is when we mint directly to the ledger and need the Transfer()
// events to appear in the token)
function ledgerTransfer(address from, address to, uint val) onlyLedger {
token.controllerTransfer(from, to, val);
}
// functions below this line are onlyToken
function transfer(address _from, address _to, uint _value) onlyToken returns (bool success) {
return ledger.transfer(_from, _to, _value);
}
function transferFrom(address _spender, address _from, address _to, uint _value) onlyToken returns (bool success) {
return ledger.transferFrom(_spender, _from, _to, _value);
}
function approve(address _owner, address _spender, uint _value) onlyToken returns (bool success) {
return ledger.approve(_owner, _spender, _value);
}
function increaseApproval (address _owner, address _spender, uint _addedValue) onlyToken returns (bool success) {
return ledger.increaseApproval(_owner, _spender, _addedValue);
}
function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyToken returns (bool success) {
return ledger.decreaseApproval(_owner, _spender, _subtractedValue);
}
function burn(address _owner, uint _amount) onlyToken {
ledger.burn(_owner, _amount);
}
}
contract Ledger is Owned, SafeMath, Finalizable {
Controller public controller;
mapping(address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint public totalSupply;
uint public mintingNonce;
bool public mintingStopped;
// functions below this line are onlyOwner
function Ledger() {
}
function setController(address _controller) onlyOwner notFinalized {
controller = Controller(_controller);
}
function stopMinting() onlyOwner {
mintingStopped = true;
}
function multiMint(uint nonce, uint256[] bits) onlyOwner {
require(!mintingStopped);
if (nonce != mintingNonce) return;
mintingNonce += 1;
uint256 lomask = (1 << 96) - 1;
uint created = 0;
for (uint i=0; i<bits.length; i++) {
address a = address(bits[i]>>96);
uint value = bits[i]&lomask;
balanceOf[a] = balanceOf[a] + value;
controller.ledgerTransfer(0, a, value);
created += value;
}
totalSupply += created;
}
// functions below this line are onlyController
modifier onlyController() {
require(msg.sender == address(controller));
_;
}
function transfer(address _from, address _to, uint _value) onlyController returns (bool success) {
if (balanceOf[_from] < _value) return false;
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
return true;
}
function transferFrom(address _spender, address _from, address _to, uint _value) onlyController returns (bool success) {
if (balanceOf[_from] < _value) return false;
var allowed = allowance[_from][_spender];
if (allowed < _value) return false;
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
allowance[_from][_spender] = safeSub(allowed, _value);
return true;
}
function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) {
// require user to set to zero before resetting to nonzero
if ((_value != 0) && (allowance[_owner][_spender] != 0)) {
return false;
}
allowance[_owner][_spender] = _value;
return true;
}
function increaseApproval (address _owner, address _spender, uint _addedValue) onlyController returns (bool success) {
uint oldValue = allowance[_owner][_spender];
allowance[_owner][_spender] = safeAdd(oldValue, _addedValue);
return true;
}
function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyController returns (bool success) {
uint oldValue = allowance[_owner][_spender];
if (_subtractedValue > oldValue) {
allowance[_owner][_spender] = 0;
} else {
allowance[_owner][_spender] = safeSub(oldValue, _subtractedValue);
}
return true;
}
function burn(address _owner, uint _amount) onlyController {
balanceOf[_owner] = safeSub(balanceOf[_owner], _amount);
totalSupply = safeSub(totalSupply, _amount);
}
} | {
"pile_set_name": "Github"
} |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03
// UNSUPPORTED: windows
// ADDITIONAL_COMPILE_FLAGS: -D_LIBCPP_DEBUG=1
// Can't test the system lib because this test enables debug mode
// UNSUPPORTED: with_system_cxx_lib=macosx
// test array<T, 0>::front() raises a debug error.
#include <array>
#include "test_macros.h"
#include "debug_mode_helper.h"
int main(int, char**)
{
{
typedef std::array<int, 0> C;
C c = {};
C const& cc = c;
EXPECT_DEATH(c.front());
EXPECT_DEATH(cc.front());
}
{
typedef std::array<const int, 0> C;
C c = {{}};
C const& cc = c;
EXPECT_DEATH(c.front());
EXPECT_DEATH(cc.front());
}
return 0;
}
| {
"pile_set_name": "Github"
} |
@(metaData: model.PreferencesMetaData)(implicit request: RequestHeader, context: model.ApplicationContext)
@import conf.switches.Switches._
@import views.html.fragments.containers.facia_cards.containerScaffold
@if(HistoryTags.isSwitchedOn) {
@containerScaffold("recently visited links", "preferences") {
<div id="preferences-history-tags">Loading…</div>
}
}
| {
"pile_set_name": "Github"
} |
/*
* FriendRequestWidget.vala
*
* Copyright (C) 2018 Venom authors and contributors
*
* This file is part of Venom.
*
* Venom is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Venom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Venom. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Venom {
[GtkTemplate(ui = "/com/github/naxuroqa/venom/ui/friend_request_widget.ui")]
public class FriendRequestWidget : Gtk.ListBoxRow {
private Logger logger;
private FriendRequest friend_request;
private FriendRequestWidgetListener listener;
[GtkChild] private Gtk.Label contact_id;
[GtkChild] private Gtk.Label contact_message;
[GtkChild] private Gtk.Label contact_time;
[GtkChild] private Gtk.Image contact_image;
[GtkChild] private Gtk.Button accept;
[GtkChild] private Gtk.Button reject;
public FriendRequestWidget(Logger logger, FriendRequest friend_request, FriendRequestWidgetListener listener) {
logger.d("FriendRequestWidget created.");
this.logger = logger;
this.friend_request = friend_request;
this.listener = listener;
contact_id.label = friend_request.id;
contact_message.label = _("“%s”").printf(friend_request.message);
contact_time.label = TimeStamp.get_pretty_timestamp(friend_request.timestamp);
contact_time.tooltip_text = friend_request.timestamp.format("%c");
var pub_key = Tools.hexstring_to_bin(friend_request.id);
contact_image.pixbuf = round_corners(Identicon.generate_pixbuf(pub_key, 40));
accept.clicked.connect(on_accept_clicked);
reject.clicked.connect(on_reject_clicked);
}
private void on_accept_clicked() {
try {
listener.on_accept_friend_request(friend_request.id);
} catch (Error e) {
logger.i("Could not accept friend request: " + e.message);
}
}
private void on_reject_clicked() {
try {
listener.on_reject_friend_request(friend_request.id);
} catch (Error e) {
logger.i("Could not reject friend request: " + e.message);
}
}
~FriendRequestWidget() {
logger.d("FriendRequestWidget destroyed.");
}
}
public interface FriendRequestWidgetListener : GLib.Object {
public abstract void on_accept_friend_request(string id) throws Error;
public abstract void on_reject_friend_request(string id) throws Error;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AppGlobals;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.UriPermission;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceCategory;
import android.text.format.Formatter;
import android.util.Log;
import android.util.MutableInt;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.android.internal.logging.MetricsProto.MetricsEvent;
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settings.deviceinfo.StorageWizardMoveConfirm;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.applications.ApplicationsState.AppEntry;
import com.android.settingslib.applications.ApplicationsState.Callbacks;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import static android.content.pm.ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA;
import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
public class AppStorageSettings extends AppInfoWithHeader
implements OnClickListener, Callbacks, DialogInterface.OnClickListener {
private static final String TAG = AppStorageSettings.class.getSimpleName();
//internal constants used in Handler
private static final int OP_SUCCESSFUL = 1;
private static final int OP_FAILED = 2;
private static final int MSG_CLEAR_USER_DATA = 1;
private static final int MSG_CLEAR_CACHE = 3;
// invalid size value used initially and also when size retrieval through PackageManager
// fails for whatever reason
private static final int SIZE_INVALID = -1;
// Result code identifiers
public static final int REQUEST_MANAGE_SPACE = 2;
private static final int DLG_CLEAR_DATA = DLG_BASE + 1;
private static final int DLG_CANNOT_CLEAR_DATA = DLG_BASE + 2;
private static final String KEY_STORAGE_USED = "storage_used";
private static final String KEY_CHANGE_STORAGE = "change_storage_button";
private static final String KEY_STORAGE_SPACE = "storage_space";
private static final String KEY_STORAGE_CATEGORY = "storage_category";
private static final String KEY_TOTAL_SIZE = "total_size";
private static final String KEY_APP_SIZE = "app_size";
private static final String KEY_EXTERNAL_CODE_SIZE = "external_code_size";
private static final String KEY_DATA_SIZE = "data_size";
private static final String KEY_EXTERNAL_DATA_SIZE = "external_data_size";
private static final String KEY_CACHE_SIZE = "cache_size";
private static final String KEY_CLEAR_DATA = "clear_data_button";
private static final String KEY_CLEAR_CACHE = "clear_cache_button";
private static final String KEY_URI_CATEGORY = "uri_category";
private static final String KEY_CLEAR_URI = "clear_uri_button";
private Preference mTotalSize;
private Preference mAppSize;
private Preference mDataSize;
private Preference mExternalCodeSize;
private Preference mExternalDataSize;
// Views related to cache info
private Preference mCacheSize;
private Button mClearDataButton;
private Button mClearCacheButton;
private Preference mStorageUsed;
private Button mChangeStorageButton;
// Views related to URI permissions
private Button mClearUriButton;
private LayoutPreference mClearUri;
private PreferenceCategory mUri;
private boolean mCanClearData = true;
private boolean mHaveSizes = false;
private long mLastCodeSize = -1;
private long mLastDataSize = -1;
private long mLastExternalCodeSize = -1;
private long mLastExternalDataSize = -1;
private long mLastCacheSize = -1;
private long mLastTotalSize = -1;
private ClearCacheObserver mClearCacheObserver;
private ClearUserDataObserver mClearDataObserver;
// Resource strings
private CharSequence mInvalidSizeStr;
private CharSequence mComputingStr;
private VolumeInfo[] mCandidates;
private AlertDialog.Builder mDialogBuilder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.app_storage_settings);
setupViews();
initMoveDialog();
}
@Override
public void onResume() {
super.onResume();
mState.requestSize(mPackageName, mUserId);
}
private void setupViews() {
mComputingStr = getActivity().getText(R.string.computing_size);
mInvalidSizeStr = getActivity().getText(R.string.invalid_size_value);
// Set default values on sizes
mTotalSize = findPreference(KEY_TOTAL_SIZE);
mAppSize = findPreference(KEY_APP_SIZE);
mDataSize = findPreference(KEY_DATA_SIZE);
mExternalCodeSize = findPreference(KEY_EXTERNAL_CODE_SIZE);
mExternalDataSize = findPreference(KEY_EXTERNAL_DATA_SIZE);
if (Environment.isExternalStorageEmulated()) {
PreferenceCategory category = (PreferenceCategory) findPreference(KEY_STORAGE_CATEGORY);
category.removePreference(mExternalCodeSize);
category.removePreference(mExternalDataSize);
}
mClearDataButton = (Button) ((LayoutPreference) findPreference(KEY_CLEAR_DATA))
.findViewById(R.id.button);
mStorageUsed = findPreference(KEY_STORAGE_USED);
mChangeStorageButton = (Button) ((LayoutPreference) findPreference(KEY_CHANGE_STORAGE))
.findViewById(R.id.button);
mChangeStorageButton.setText(R.string.change);
mChangeStorageButton.setOnClickListener(this);
// Cache section
mCacheSize = findPreference(KEY_CACHE_SIZE);
mClearCacheButton = (Button) ((LayoutPreference) findPreference(KEY_CLEAR_CACHE))
.findViewById(R.id.button);
mClearCacheButton.setText(R.string.clear_cache_btn_text);
// URI permissions section
mUri = (PreferenceCategory) findPreference(KEY_URI_CATEGORY);
mClearUri = (LayoutPreference) mUri.findPreference(KEY_CLEAR_URI);
mClearUriButton = (Button) mClearUri.findViewById(R.id.button);
mClearUriButton.setText(R.string.clear_uri_btn_text);
mClearUriButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == mClearCacheButton) {
if (mAppsControlDisallowedAdmin != null && !mAppsControlDisallowedBySystem) {
RestrictedLockUtils.sendShowAdminSupportDetailsIntent(
getActivity(), mAppsControlDisallowedAdmin);
return;
} else if (mClearCacheObserver == null) { // Lazy initialization of observer
mClearCacheObserver = new ClearCacheObserver();
}
mPm.deleteApplicationCacheFiles(mPackageName, mClearCacheObserver);
} else if (v == mClearDataButton) {
if (mAppsControlDisallowedAdmin != null && !mAppsControlDisallowedBySystem) {
RestrictedLockUtils.sendShowAdminSupportDetailsIntent(
getActivity(), mAppsControlDisallowedAdmin);
} else if (mAppEntry.info.manageSpaceActivityName != null) {
if (!Utils.isMonkeyRunning()) {
Intent intent = new Intent(Intent.ACTION_DEFAULT);
intent.setClassName(mAppEntry.info.packageName,
mAppEntry.info.manageSpaceActivityName);
startActivityForResult(intent, REQUEST_MANAGE_SPACE);
}
} else {
showDialogInner(DLG_CLEAR_DATA, 0);
}
} else if (v == mChangeStorageButton && mDialogBuilder != null && !isMoveInProgress()) {
mDialogBuilder.show();
} else if (v == mClearUriButton) {
if (mAppsControlDisallowedAdmin != null && !mAppsControlDisallowedBySystem) {
RestrictedLockUtils.sendShowAdminSupportDetailsIntent(
getActivity(), mAppsControlDisallowedAdmin);
} else {
clearUriPermissions();
}
}
}
private boolean isMoveInProgress() {
try {
// TODO: define a cleaner API for this
AppGlobals.getPackageManager().checkPackageStartable(mPackageName,
UserHandle.myUserId());
return false;
} catch (RemoteException | SecurityException e) {
return true;
}
}
@Override
public void onClick(DialogInterface dialog, int which) {
final Context context = getActivity();
// If not current volume, kick off move wizard
final VolumeInfo targetVol = mCandidates[which];
final VolumeInfo currentVol = context.getPackageManager().getPackageCurrentVolume(
mAppEntry.info);
if (!Objects.equals(targetVol, currentVol)) {
final Intent intent = new Intent(context, StorageWizardMoveConfirm.class);
intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, targetVol.getId());
intent.putExtra(Intent.EXTRA_PACKAGE_NAME, mAppEntry.info.packageName);
startActivity(intent);
}
dialog.dismiss();
}
private String getSizeStr(long size) {
if (size == SIZE_INVALID) {
return mInvalidSizeStr.toString();
}
return Formatter.formatFileSize(getActivity(), size);
}
private void refreshSizeInfo() {
if (mAppEntry.size == ApplicationsState.SIZE_INVALID
|| mAppEntry.size == ApplicationsState.SIZE_UNKNOWN) {
mLastCodeSize = mLastDataSize = mLastCacheSize = mLastTotalSize = -1;
if (!mHaveSizes) {
mAppSize.setSummary(mComputingStr);
mDataSize.setSummary(mComputingStr);
mCacheSize.setSummary(mComputingStr);
mTotalSize.setSummary(mComputingStr);
}
mClearDataButton.setEnabled(false);
mClearCacheButton.setEnabled(false);
} else {
mHaveSizes = true;
long codeSize = mAppEntry.codeSize;
long dataSize = mAppEntry.dataSize;
if (Environment.isExternalStorageEmulated()) {
codeSize += mAppEntry.externalCodeSize;
dataSize += mAppEntry.externalDataSize;
} else {
if (mLastExternalCodeSize != mAppEntry.externalCodeSize) {
mLastExternalCodeSize = mAppEntry.externalCodeSize;
mExternalCodeSize.setSummary(getSizeStr(mAppEntry.externalCodeSize));
}
if (mLastExternalDataSize != mAppEntry.externalDataSize) {
mLastExternalDataSize = mAppEntry.externalDataSize;
mExternalDataSize.setSummary(getSizeStr( mAppEntry.externalDataSize));
}
}
if (mLastCodeSize != codeSize) {
mLastCodeSize = codeSize;
mAppSize.setSummary(getSizeStr(codeSize));
}
if (mLastDataSize != dataSize) {
mLastDataSize = dataSize;
mDataSize.setSummary(getSizeStr(dataSize));
}
long cacheSize = mAppEntry.cacheSize + mAppEntry.externalCacheSize;
if (mLastCacheSize != cacheSize) {
mLastCacheSize = cacheSize;
mCacheSize.setSummary(getSizeStr(cacheSize));
}
if (mLastTotalSize != mAppEntry.size) {
mLastTotalSize = mAppEntry.size;
mTotalSize.setSummary(getSizeStr(mAppEntry.size));
}
if ((mAppEntry.dataSize+ mAppEntry.externalDataSize) <= 0 || !mCanClearData) {
mClearDataButton.setEnabled(false);
} else {
mClearDataButton.setEnabled(true);
mClearDataButton.setOnClickListener(this);
}
if (cacheSize <= 0) {
mClearCacheButton.setEnabled(false);
} else {
mClearCacheButton.setEnabled(true);
mClearCacheButton.setOnClickListener(this);
}
}
if (mAppsControlDisallowedBySystem) {
mClearCacheButton.setEnabled(false);
mClearDataButton.setEnabled(false);
}
}
@Override
protected boolean refreshUi() {
retrieveAppEntry();
if (mAppEntry == null) {
return false;
}
refreshSizeInfo();
refreshGrantedUriPermissions();
final VolumeInfo currentVol = getActivity().getPackageManager()
.getPackageCurrentVolume(mAppEntry.info);
final StorageManager storage = getContext().getSystemService(StorageManager.class);
mStorageUsed.setSummary(storage.getBestVolumeDescription(currentVol));
refreshButtons();
return true;
}
private void refreshButtons() {
initMoveDialog();
initDataButtons();
}
private void initDataButtons() {
final boolean appHasSpaceManagementUI = mAppEntry.info.manageSpaceActivityName != null;
final boolean appHasActiveAdmins = mDpm.packageHasActiveAdmins(mPackageName);
// Check that SYSTEM_APP flag is set, and ALLOW_CLEAR_USER_DATA is not set.
final boolean isNonClearableSystemApp =
(mAppEntry.info.flags & (FLAG_SYSTEM | FLAG_ALLOW_CLEAR_USER_DATA)) == FLAG_SYSTEM;
final boolean appRestrictsClearingData = isNonClearableSystemApp || appHasActiveAdmins;
final Intent intent = new Intent(Intent.ACTION_DEFAULT);
if (appHasSpaceManagementUI) {
intent.setClassName(mAppEntry.info.packageName, mAppEntry.info.manageSpaceActivityName);
}
final boolean isManageSpaceActivityAvailable =
getPackageManager().resolveActivity(intent, 0) != null;
if ((!appHasSpaceManagementUI && appRestrictsClearingData)
|| !isManageSpaceActivityAvailable) {
mClearDataButton.setText(R.string.clear_user_data_text);
mClearDataButton.setEnabled(false);
mCanClearData = false;
} else {
if (appHasSpaceManagementUI) {
mClearDataButton.setText(R.string.manage_space_text);
} else {
mClearDataButton.setText(R.string.clear_user_data_text);
}
mClearDataButton.setOnClickListener(this);
}
if (mAppsControlDisallowedBySystem) {
mClearDataButton.setEnabled(false);
}
}
private void initMoveDialog() {
final Context context = getActivity();
final StorageManager storage = context.getSystemService(StorageManager.class);
final List<VolumeInfo> candidates = context.getPackageManager()
.getPackageCandidateVolumes(mAppEntry.info);
if (candidates.size() > 1) {
Collections.sort(candidates, VolumeInfo.getDescriptionComparator());
CharSequence[] labels = new CharSequence[candidates.size()];
int current = -1;
for (int i = 0; i < candidates.size(); i++) {
final String volDescrip = storage.getBestVolumeDescription(candidates.get(i));
if (Objects.equals(volDescrip, mStorageUsed.getSummary())) {
current = i;
}
labels[i] = volDescrip;
}
mCandidates = candidates.toArray(new VolumeInfo[candidates.size()]);
mDialogBuilder = new AlertDialog.Builder(getContext())
.setTitle(R.string.change_storage)
.setSingleChoiceItems(labels, current, this)
.setNegativeButton(R.string.cancel, null);
} else {
removePreference(KEY_STORAGE_USED);
removePreference(KEY_CHANGE_STORAGE);
removePreference(KEY_STORAGE_SPACE);
}
}
/*
* Private method to initiate clearing user data when the user clicks the clear data
* button for a system package
*/
private void initiateClearUserData() {
mClearDataButton.setEnabled(false);
// Invoke uninstall or clear user data based on sysPackage
String packageName = mAppEntry.info.packageName;
Log.i(TAG, "Clearing user data for package : " + packageName);
if (mClearDataObserver == null) {
mClearDataObserver = new ClearUserDataObserver();
}
ActivityManager am = (ActivityManager)
getActivity().getSystemService(Context.ACTIVITY_SERVICE);
boolean res = am.clearApplicationUserData(packageName, mClearDataObserver);
if (!res) {
// Clearing data failed for some obscure reason. Just log error for now
Log.i(TAG, "Couldnt clear application user data for package:"+packageName);
showDialogInner(DLG_CANNOT_CLEAR_DATA, 0);
} else {
mClearDataButton.setText(R.string.recompute_size);
}
}
/*
* Private method to handle clear message notification from observer when
* the async operation from PackageManager is complete
*/
private void processClearMsg(Message msg) {
int result = msg.arg1;
String packageName = mAppEntry.info.packageName;
mClearDataButton.setText(R.string.clear_user_data_text);
if (result == OP_SUCCESSFUL) {
Log.i(TAG, "Cleared user data for package : "+packageName);
mState.requestSize(mPackageName, mUserId);
} else {
mClearDataButton.setEnabled(true);
}
}
private void refreshGrantedUriPermissions() {
// Clear UI first (in case the activity has been resumed)
removeUriPermissionsFromUi();
// Gets all URI permissions from am.
ActivityManager am = (ActivityManager) getActivity().getSystemService(
Context.ACTIVITY_SERVICE);
List<UriPermission> perms =
am.getGrantedUriPermissions(mAppEntry.info.packageName).getList();
if (perms.isEmpty()) {
mClearUriButton.setVisibility(View.GONE);
return;
}
PackageManager pm = getActivity().getPackageManager();
// Group number of URIs by app.
Map<CharSequence, MutableInt> uriCounters = new TreeMap<>();
for (UriPermission perm : perms) {
String authority = perm.getUri().getAuthority();
ProviderInfo provider = pm.resolveContentProvider(authority, 0);
CharSequence app = provider.applicationInfo.loadLabel(pm);
MutableInt count = uriCounters.get(app);
if (count == null) {
uriCounters.put(app, new MutableInt(1));
} else {
count.value++;
}
}
// Dynamically add the preferences, one per app.
int order = 0;
for (Map.Entry<CharSequence, MutableInt> entry : uriCounters.entrySet()) {
int numberResources = entry.getValue().value;
Preference pref = new Preference(getPrefContext());
pref.setTitle(entry.getKey());
pref.setSummary(getPrefContext().getResources()
.getQuantityString(R.plurals.uri_permissions_text, numberResources,
numberResources));
pref.setSelectable(false);
pref.setLayoutResource(R.layout.horizontal_preference);
pref.setOrder(order);
Log.v(TAG, "Adding preference '" + pref + "' at order " + order);
mUri.addPreference(pref);
}
if (mAppsControlDisallowedBySystem) {
mClearUriButton.setEnabled(false);
}
mClearUri.setOrder(order);
mClearUriButton.setVisibility(View.VISIBLE);
}
private void clearUriPermissions() {
// Synchronously revoke the permissions.
final ActivityManager am = (ActivityManager) getActivity().getSystemService(
Context.ACTIVITY_SERVICE);
am.clearGrantedUriPermissions(mAppEntry.info.packageName);
// Update UI
refreshGrantedUriPermissions();
}
private void removeUriPermissionsFromUi() {
// Remove all preferences but the clear button.
int count = mUri.getPreferenceCount();
for (int i = count - 1; i >= 0; i--) {
Preference pref = mUri.getPreference(i);
if (pref != mClearUri) {
mUri.removePreference(pref);
}
}
}
@Override
protected AlertDialog createDialog(int id, int errorCode) {
switch (id) {
case DLG_CLEAR_DATA:
return new AlertDialog.Builder(getActivity())
.setTitle(getActivity().getText(R.string.clear_data_dlg_title))
.setMessage(getActivity().getText(R.string.clear_data_dlg_text))
.setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Clear user data here
initiateClearUserData();
}
})
.setNegativeButton(R.string.dlg_cancel, null)
.create();
case DLG_CANNOT_CLEAR_DATA:
return new AlertDialog.Builder(getActivity())
.setTitle(getActivity().getText(R.string.clear_failed_dlg_title))
.setMessage(getActivity().getText(R.string.clear_failed_dlg_text))
.setNeutralButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mClearDataButton.setEnabled(false);
//force to recompute changed value
setIntentAndFinish(false, false);
}
})
.create();
}
return null;
}
@Override
public void onPackageSizeChanged(String packageName) {
if (mAppEntry == null || mAppEntry.info == null) {
return;
} else if (packageName.equals(mAppEntry.info.packageName)) {
refreshSizeInfo();
}
}
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (getView() == null) {
return;
}
switch (msg.what) {
case MSG_CLEAR_USER_DATA:
processClearMsg(msg);
break;
case MSG_CLEAR_CACHE:
// Refresh size info
mState.requestSize(mPackageName, mUserId);
break;
}
}
};
public static CharSequence getSummary(AppEntry appEntry, Context context) {
if (appEntry.size == ApplicationsState.SIZE_INVALID
|| appEntry.size == ApplicationsState.SIZE_UNKNOWN) {
return context.getText(R.string.computing_size);
} else {
CharSequence storageType = context.getString(
(appEntry.info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0
? R.string.storage_type_external
: R.string.storage_type_internal);
return context.getString(R.string.storage_summary_format,
getSize(appEntry, context), storageType);
}
}
private static CharSequence getSize(AppEntry appEntry, Context context) {
long size = appEntry.size;
if (size == SIZE_INVALID) {
return context.getText(R.string.invalid_size_value);
}
return Formatter.formatFileSize(context, size);
}
@Override
protected int getMetricsCategory() {
return MetricsEvent.APPLICATIONS_APP_STORAGE;
}
class ClearCacheObserver extends IPackageDataObserver.Stub {
public void onRemoveCompleted(final String packageName, final boolean succeeded) {
final Message msg = mHandler.obtainMessage(MSG_CLEAR_CACHE);
msg.arg1 = succeeded ? OP_SUCCESSFUL : OP_FAILED;
mHandler.sendMessage(msg);
}
}
class ClearUserDataObserver extends IPackageDataObserver.Stub {
public void onRemoveCompleted(final String packageName, final boolean succeeded) {
final Message msg = mHandler.obtainMessage(MSG_CLEAR_USER_DATA);
msg.arg1 = succeeded ? OP_SUCCESSFUL : OP_FAILED;
mHandler.sendMessage(msg);
}
}
}
| {
"pile_set_name": "Github"
} |
#ifndef BOOST_MPL_AUX_CONFIG_OPERATORS_HPP_INCLUDED
#define BOOST_MPL_AUX_CONFIG_OPERATORS_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/aux_/config/gcc.hpp>
#include <boost/mpl/aux_/config/msvc.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>
#if !defined(BOOST_MPL_CFG_USE_OPERATORS_OVERLOADING) \
&& ( BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
|| BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) \
|| BOOST_WORKAROUND(__EDG_VERSION__, <= 245) \
|| BOOST_WORKAROUND(BOOST_MPL_CFG_GCC, <= 0x0295) \
|| BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) \
|| BOOST_WORKAROUND(__NVCC__, BOOST_TESTED_AT(1)) \
)
# define BOOST_MPL_CFG_USE_OPERATORS_OVERLOADING
#endif
#endif // BOOST_MPL_AUX_CONFIG_OPERATORS_HPP_INCLUDED
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Test\Unit\Model\Hostedpro;
use Magento\Framework\DataObject;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Payment;
class RequestTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
*/
protected $helper;
/**
* @var \Magento\Paypal\Model\Hostedpro\Request
*/
protected $_model;
protected $localeResolverMock;
/**
* @var \Magento\Tax\Helper\Data
*/
protected $taxData;
protected function setUp()
{
$this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$this->localeResolverMock = $this->getMockBuilder(\Magento\Framework\Locale\Resolver::class)
->disableOriginalConstructor()
->getMock();
$this->taxData = $this->helper->getObject(\Magento\Tax\Helper\Data::class);
$this->_model = $this->helper->getObject(
\Magento\Paypal\Model\Hostedpro\Request::class,
[
'localeResolver' => $this->localeResolverMock,
'taxData' => $this->taxData
]
);
}
/**
* @param $billing
* @param $shipping
* @param $billingState
* @param $state
* @param $countryId
* @dataProvider addressesDataProvider
*/
public function testSetOrderAddresses($billing, $shipping, $billingState, $state, $countryId)
{
$payment = $this->getMockBuilder(Payment::class)
->disableOriginalConstructor()
->setMethods(['__wakeup'])
->getMock();
$order = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->setMethods(['getPayment', '__wakeup', 'getBillingAddress', 'getShippingAddress'])
->getMock();
$order->expects(static::any())
->method('getPayment')
->will($this->returnValue($payment));
$order->expects(static::any())
->method('getBillingAddress')
->will($this->returnValue($billing));
$order->expects(static::any())
->method('getShippingAddress')
->will($this->returnValue($shipping));
$this->_model->setOrder($order);
static::assertEquals($billingState, $this->_model->getData('billing_state'));
static::assertEquals($state, $this->_model->getData('state'));
static::assertEquals($countryId, $this->_model->getData('billing_country'));
static::assertEquals($countryId, $this->_model->getData('country'));
}
/**
* @return array
*/
public function addressesDataProvider()
{
$billing = new DataObject([
'firstname' => 'Firstname',
'lastname' => 'Lastname',
'city' => 'City',
'region_code' => 'CA',
'postcode' => '12346',
'country_id' => 'US',
'street' => '1 Ln Ave',
]);
$shipping = new DataObject([
'firstname' => 'ShipFirstname',
'lastname' => 'ShipLastname',
'city' => 'ShipCity',
'region' => 'olala',
'postcode' => '12346',
'country_id' => 'US',
'street' => '1 Ln Ave',
]);
$billing2 = new DataObject([
'firstname' => 'Firstname',
'lastname' => 'Lastname',
'city' => 'Culver City',
'region_code' => 'CA',
'postcode' => '12346',
'country_id' => 'US',
'street' => '1 Ln Ave',
]);
$shipping2 = new DataObject([
'firstname' => 'ShipFirstname',
'lastname' => 'ShipLastname',
'city' => 'ShipCity',
'postcode' => '12346',
'country_id' => 'US',
'street' => '1 Ln Ave',
]);
return [
[$billing, $shipping, 'CA', 'olala', 'US'],
[$billing2, $shipping2, 'CA', 'ShipCity', 'US']
];
}
public function testSetPaymentMethod()
{
$expectedData = [
'paymentaction' => 'authorization',
'notify_url' => 'https://test.com/notifyurl',
'cancel_return' => 'https://test.com/cancelurl',
'return' => 'https://test.com/returnurl',
'lc' => 'US',
'template' => 'mobile-iframe',
'showBillingAddress' => 'false',
'showShippingAddress' => 'true',
'showBillingEmail' => 'false',
'showBillingPhone' => 'false',
'showCustomerName' => 'false',
'showCardInfo' => 'true',
'showHostedThankyouPage' => 'false'
];
$paymentMethodMock = $this->getMockBuilder(\Magento\Paypal\Model\Hostedpro::class)
->disableOriginalConstructor()
->setMethods([])
->getMock();
$paymentMethodMock->expects($this->once())
->method('getConfigData')->with('payment_action')->willReturn('Authorization');
$paymentMethodMock->expects($this->once())->method('getNotifyUrl')->willReturn('https://test.com/notifyurl');
$paymentMethodMock->expects($this->once())->method('getCancelUrl')->willReturn('https://test.com/cancelurl');
$paymentMethodMock->expects($this->once())->method('getReturnUrl')->willReturn('https://test.com/returnurl');
$this->localeResolverMock->expects($this->once())->method('getLocale')->willReturn('en_US');
$this->assertEquals($this->_model, $this->_model->setPaymentMethod($paymentMethodMock));
$this->assertEquals('US', $this->_model->getData('lc'));
$this->assertEquals($expectedData, $this->_model->getData());
}
/**
* @covers \Magento\Paypal\Model\Hostedpro\Request::setOrder
*/
public function testSetOrder()
{
$expectation = [
'invoice' => '#000001',
'address_override' => 'true',
'currency_code' => 'USD',
'buyer_email' => '[email protected]',
];
$order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)
->disableOriginalConstructor()
->getMock();
$order->expects(static::once())
->method('getIncrementId')
->willReturn($expectation['invoice']);
$order->expects(static::once())
->method('getBaseCurrencyCode')
->willReturn($expectation['currency_code']);
$order->expects(static::once())
->method('getCustomerEmail')
->willReturn($expectation['buyer_email']);
$this->_model->setOrder($order);
static::assertEquals($expectation, $this->_model->getData());
}
/**
* @covers \Magento\Paypal\Model\Hostedpro\Request::setAmount()
* @param $subtotal
* @param $total
* @param $tax
* @param $shipping
* @param $discount
* @dataProvider amountWithoutTaxDataProvider
*/
public function testSetAmountWithoutTax($total, $subtotal, $tax, $shipping, $discount)
{
$expectation = [
'subtotal' => $subtotal,
'total' => $total,
'tax' => $tax,
'shipping' => $shipping,
'discount' => abs($discount)
];
static::assertFalse($this->taxData->priceIncludesTax());
$payment = $this->getMockBuilder(Payment::class)
->disableOriginalConstructor()
->getMock();
$order = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
$payment->expects(static::once())
->method('getBaseAmountAuthorized')
->willReturn($total);
$order->expects(static::once())
->method('getPayment')
->willReturn($payment);
$order->expects(static::once())
->method('getBaseDiscountAmount')
->willReturn($discount);
$order->expects(static::once())
->method('getBaseTaxAmount')
->willReturn($tax);
$order->expects(static::once())
->method('getBaseShippingAmount')
->willReturn($shipping);
$order->expects(static::once())
->method('getBaseSubtotal')
->willReturn($subtotal);
$this->_model->setAmount($order);
static::assertEquals($expectation, $this->_model->getData());
}
/**
* @covers \Magento\Paypal\Model\Hostedpro\Request::setAmount()
* @param $total
* @param $subtotal
* @param $tax
* @param $shipping
* @param $discount
* @dataProvider amountWithoutTaxZeroSubtotalDataProvider
*/
public function testSetAmountWithoutTaxZeroSubtotal($total, $subtotal, $tax, $shipping, $discount)
{
$expectation = [
'subtotal' => $total,
'total' => $total,
'tax' => $tax,
'shipping' => $shipping,
'discount' => abs($discount)
];
static::assertFalse($this->taxData->priceIncludesTax());
$payment = $this->getMockBuilder(Payment::class)
->disableOriginalConstructor()
->getMock();
$order = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
$payment->expects(static::exactly(2))
->method('getBaseAmountAuthorized')
->willReturn($total);
$order->expects(static::exactly(2))
->method('getPayment')
->willReturn($payment);
$order->expects(static::once())
->method('getBaseDiscountAmount')
->willReturn($discount);
$order->expects(static::once())
->method('getBaseTaxAmount')
->willReturn($tax);
$order->expects(static::once())
->method('getBaseShippingAmount')
->willReturn($shipping);
$order->expects(static::once())
->method('getBaseSubtotal')
->willReturn($subtotal);
$this->_model->setAmount($order);
static::assertEquals($expectation, $this->_model->getData());
}
/**
* @covers \Magento\Paypal\Model\Hostedpro\Request::setAmount()
*/
public function testSetAmountWithIncludedTax()
{
/** @var \Magento\Tax\Model\Config $config */
$config = $this->helper->getObject(\Magento\Tax\Model\Config::class);
$config->setPriceIncludesTax(true);
$this->taxData = $this->helper->getObject(
\Magento\Tax\Helper\Data::class,
[
'taxConfig' => $config
]
);
$this->_model = $this->helper->getObject(
\Magento\Paypal\Model\Hostedpro\Request::class,
[
'localeResolver' => $this->localeResolverMock,
'taxData' => $this->taxData
]
);
static::assertTrue($this->taxData->getConfig()->priceIncludesTax());
$amount = 19.65;
$expectation = [
'amount' => $amount,
'subtotal' => $amount
];
$payment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class)
->disableOriginalConstructor()
->getMock();
$order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)
->disableOriginalConstructor()
->getMock();
$payment->expects(static::once())
->method('getBaseAmountAuthorized')
->willReturn($amount);
$order->expects(static::once())
->method('getPayment')
->willReturn($payment);
$this->_model->setAmount($order);
static::assertEquals($expectation, $this->_model->getData());
}
/**
* Get data for amount with tax tests
* @return array
*/
public function amountWithoutTaxDataProvider()
{
return [
['total' => 31.00, 'subtotal' => 10.00, 'tax' => 1.00, 'shipping' => 20.00, 'discount' => 0.00],
['total' => 5.00, 'subtotal' => 10.00, 'tax' => 0.00, 'shipping' => 20.00, 'discount' => -25.00],
];
}
/**
* @return array
*/
public function amountWithoutTaxZeroSubtotalDataProvider()
{
return [
['total' => 10.00, 'subtotal' => 0.00, 'tax' => 0.00, 'shipping' => 20.00, 'discount' => 0.00],
];
}
}
| {
"pile_set_name": "Github"
} |
#region Using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
#endregion
namespace Blazorise
{
public partial class Divider : BaseComponent
{
#region Members
private DividerType type = DividerType.Solid;
#endregion
#region Methods
protected override void BuildClasses( ClassBuilder builder )
{
builder.Append( ClassProvider.Divider() );
builder.Append( ClassProvider.DividerType( Type ) );
base.BuildClasses( builder );
}
#endregion
#region Properties
[Parameter]
public DividerType Type
{
get => type;
set
{
type = value;
DirtyClasses();
}
}
[Parameter] public string Text { get; set; }
#endregion
}
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace MonthViewInitiallyExpanded
{
public partial class App : Application
{
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new MainPage();
}
private void Application_Exit(object sender, EventArgs e)
{
}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// If the app is running outside of the debugger then report the exception using
// the browser's exception mechanism. On IE this will display it a yellow alert
// icon in the status bar and Firefox will display a script error.
if (!System.Diagnostics.Debugger.IsAttached)
{
// NOTE: This will allow the application to continue running after an exception has been thrown
// but not handled.
// For production applications this error handling should be replaced with something that will
// report the error to the website and stop the application.
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
}
}
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}
}
}
| {
"pile_set_name": "Github"
} |
title: Cisco ACE Server: Status of Real Server
agents: snmp
catalog: hw/network/cisco
license: GPL
distribution: check_mk
description:
This check monitors the status of the so-called real servers of Cisco
switches with the Application Control Engine (ACE) module. It uses snmp
to extract information from the CISCO-ENHANCED-SLB MIB.
The check monitors the operational and the administrative state of each
rserver, as well as the current number of connections. The criticality of
the check is determined from the operational state: if the operational
state is {in service}, the check is {OK}. If the operational state is
{probe testing} or {standby}, the check is {WARN}. Otherwise, it is {CRIT}.
If the administrative state is {out of service}, the worst total criticality
is {WARN}.
item:
The name of the real server, or, if this is not configured on the device,
the IP-address of the real server.
inventory:
One service is created for each real server.
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 90775f57ce581c94995f66790f9b428f
folderAsset: yes
timeCreated: 1426647464
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
namespace Org.BouncyCastle.Bcpg
{
/// <remarks>Basic PGP packet tag types.</remarks>
public enum PacketTag
{
Reserved = 0, // Reserved - a packet tag must not have this value
PublicKeyEncryptedSession = 1, // Public-Key Encrypted Session Key Packet
Signature = 2, // Signature Packet
SymmetricKeyEncryptedSessionKey = 3, // Symmetric-Key Encrypted Session Key Packet
OnePassSignature = 4, // One-Pass Signature Packet
SecretKey = 5, // Secret Key Packet
PublicKey = 6, // Public Key Packet
SecretSubkey = 7, // Secret Subkey Packet
CompressedData = 8, // Compressed Data Packet
SymmetricKeyEncrypted = 9, // Symmetrically Encrypted Data Packet
Marker = 10, // Marker Packet
LiteralData = 11, // Literal Data Packet
Trust = 12, // Trust Packet
UserId = 13, // User ID Packet
PublicSubkey = 14, // Public Subkey Packet
UserAttribute = 17, // User attribute
SymmetricEncryptedIntegrityProtected = 18, // Symmetric encrypted, integrity protected
ModificationDetectionCode = 19, // Modification detection code
Experimental1 = 60, // Private or Experimental Values
Experimental2 = 61,
Experimental3 = 62,
Experimental4 = 63
}
}
| {
"pile_set_name": "Github"
} |
.media {
// Proper spacing between instances of .media
margin-top: 15px;
&:first-child {
margin-top: 0;
}
}
.media,
.media-body {
zoom: 1;
overflow: hidden;
}
.media-body {
width: 10000px;
}
.media-object {
display: block;
// Fix collapse in webkit from max-width: 100% and display: table-cell.
&.img-thumbnail {
max-width: none;
}
}
.media-right,
.media > .pull-right {
padding-left: 10px;
}
.media-left,
.media > .pull-left {
padding-right: 10px;
}
.media-left,
.media-right,
.media-body {
display: table-cell;
vertical-align: top;
}
.media-middle {
vertical-align: middle;
}
.media-bottom {
vertical-align: bottom;
}
// Reset margins on headings for tighter default spacing
.media-heading {
margin-top: 0;
margin-bottom: 5px;
}
// Media list variation
//
// Undo default ul/ol styles
.media-list {
padding-left: 0;
list-style: none;
}
| {
"pile_set_name": "Github"
} |
Filter 1: ON PK Fc 42 Hz Gain -5.1 dB Q 0.28
Filter 2: ON PK Fc 174 Hz Gain -3.0 dB Q 0.89
Filter 3: ON PK Fc 3389 Hz Gain 5.8 dB Q 2.68
Filter 4: ON PK Fc 6331 Hz Gain 5.8 dB Q 2.50
Filter 5: ON PK Fc 18494 Hz Gain 6.7 dB Q 0.57
Filter 6: ON PK Fc 823 Hz Gain 1.8 dB Q 1.70
Filter 7: ON PK Fc 1711 Hz Gain -3.0 dB Q 1.65
Filter 8: ON PK Fc 5903 Hz Gain -2.0 dB Q 0.79
Filter 9: ON PK Fc 6054 Hz Gain 2.0 dB Q 0.28
Filter 10: ON PK Fc 12264 Hz Gain -2.2 dB Q 2.48 | {
"pile_set_name": "Github"
} |
package com.doublechaintech.retailscm.trainingcoursetype;
//import com.doublechaintech.retailscm.EntityNotFoundException;
import com.doublechaintech.retailscm.RetailscmException;
import com.doublechaintech.retailscm.Message;
import java.util.List;
public class TrainingCourseTypeManagerException extends RetailscmException {
private static final long serialVersionUID = 1L;
public TrainingCourseTypeManagerException(String string) {
super(string);
}
public TrainingCourseTypeManagerException(Message message) {
super(message);
}
public TrainingCourseTypeManagerException(List<Message> messageList) {
super(messageList);
}
}
| {
"pile_set_name": "Github"
} |
package org.ovirt.engine.ui.common;
import com.google.gwt.user.cellview.client.DataGrid;
public interface DataGridPopupTableResources extends DataGrid.Resources {
interface Style extends DataGrid.Style {
}
@Override
@Source({ DataGrid.Style.DEFAULT_CSS, "org/ovirt/engine/ui/common/css/TabDataGrid.css",
"org/ovirt/engine/ui/common/css/PopupDataGrid.css" })
Style dataGridStyle();
}
| {
"pile_set_name": "Github"
} |
-- Copyright (C) 2001 Bill Billowitch.
-- Some of the work to develop this test suite was done with Air Force
-- support. The Air Force and Bill Billowitch assume no
-- responsibilities for this software.
-- This file is part of VESTs (Vhdl tESTs).
-- VESTs is free software; you can redistribute it and/or modify it
-- under the terms of the GNU General Public License as published by the
-- Free Software Foundation; either version 2 of the License, or (at
-- your option) any later version.
-- VESTs is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-- for more details.
-- You should have received a copy of the GNU General Public License
-- along with VESTs; if not, write to the Free Software Foundation,
-- Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-- ---------------------------------------------------------------------
--
-- $Id: tc2290.vhd,v 1.2 2001-10-26 16:29:47 paw Exp $
-- $Revision: 1.2 $
--
-- ---------------------------------------------------------------------
ENTITY c07s02b06x00p32n01i02290ent IS
END c07s02b06x00p32n01i02290ent;
ARCHITECTURE c07s02b06x00p32n01i02290arch OF c07s02b06x00p32n01i02290ent IS
BEGIN
TESTING: PROCESS
BEGIN
wait for 5 ms;
assert NOT( ((1 ms * 1000) = 1 sec) and
((1 sec * 60) = 1 min) and
((1 min * 60) = 1 hr) and
((1000 * 1 ms) = 1 sec) and
((60 * 1 sec) = 1 min) and
((60 * 1 min) = 1 hr))
report "***PASSED TEST: c07s02b06x00p32n01i02290"
severity NOTE;
assert ( ((1 ms * 1000) = 1 sec) and
((1 sec * 60) = 1 min) and
((1 min * 60) = 1 hr) and
((1000 * 1 ms) = 1 sec) and
((60 * 1 sec) = 1 min) and
((60 * 1 min) = 1 hr))
report "***FAILED TEST: c07s02b06x00p32n01i02290 - Multiplication of a predefined physical type by an integer test failed."
severity ERROR;
wait;
END PROCESS TESTING;
END c07s02b06x00p32n01i02290arch;
| {
"pile_set_name": "Github"
} |
// Copyright(c) 2019-2020, Intel Corporation
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Intel Corporation nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __FPGA_BOARD_COMMON_H__
#define __FPGA_BOARD_COMMON_H__
#include <opae/types.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
* Get sysfs value.
*
* @param[in] token fpga_token object for device (FPGA_DEVICE type)
* @param[in] sysfs_path pointer to sysfs path
* @param[inout] sysfs_name returns sysfs value as string
* @param[in] len size of sysfs path
* @returns FPGA_OK on success. FPGA_NOT_FOUND if invalid MAC address.
* FPGA_INVALID_PARAM if invalid parameters were provided
*
*/
fpga_result read_sysfs(fpga_token token, char *sysfs_path,
char *sysfs_name, size_t len);
/**
* Prints sec info.
*
* @param[in] token fpga_token object for device (FPGA_DEVICE type)
* @returns FPGA_OK on success. FPGA_NOT_FOUND if invalid Security.
* FPGA_INVALID_PARAM if invalid parameters were provided
*
*/
fpga_result print_sec_common_info(fpga_token token);
/**
* Get sysfs value.
*
* @param[in] token fpga_token object for device (FPGA_DEVICE type)
* @param[in] sysfs_path pointer to sysfs path
* @param[inout] value returns sysfs value
* @returns FPGA_OK on success. FPGA_NOT_FOUND if invalid MAC address.
* FPGA_INVALID_PARAM if invalid parameters were provided
*
*/
fpga_result read_sysfs_int64(fpga_token token, char *sysfs_path,
uint64_t *value);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __FPGA_BOARD_DC_H__ */
| {
"pile_set_name": "Github"
} |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class Sku(Model):
"""SKU of the namespace.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar name: Required. Name of this SKU. Default value: "Standard" .
:vartype name: str
:param tier: The tier of this SKU. Possible values include: 'Standard'
:type tier: str or ~azure.mgmt.relay.models.SkuTier
"""
_validation = {
'name': {'required': True, 'constant': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'SkuTier'},
}
name = "Standard"
def __init__(self, *, tier=None, **kwargs) -> None:
super(Sku, self).__init__(**kwargs)
self.tier = tier
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2020.
~ Microsoft Corporation. All rights reserved.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_fluent_text_align_justify_24_filled" android:state_activated="true"/>
<item android:drawable="@drawable/ic_fluent_text_align_justify_24_filled" android:state_checked="true"/>
<item android:drawable="@drawable/ic_fluent_text_align_justify_24_filled" android:state_selected="true"/>
<item android:drawable="@drawable/ic_fluent_text_align_justify_24_regular"/>
</selector>
| {
"pile_set_name": "Github"
} |
import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
# Do some setup
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')
fname = input('Enter file name: ')
if len(fname) < 1:
fname = 'roster_data_sample.json'
# [
# [ "Charley", "si110", 1 ],
# [ "Mea", "si110", 0 ],
str_data = open(fname).read()
json_data = json.loads(str_data)
print(json_data)
for entry in json_data:
name = entry[0];
title = entry[1];
role=entry[2];
print((name, title, role))
cur.execute('''INSERT OR IGNORE INTO User (name)
VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Course (title)
VALUES ( ? )''', ( title, ) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id, role) VALUES ( ?, ?, ? )''',
( user_id, course_id, role ) )
conn.commit()
| {
"pile_set_name": "Github"
} |
<?php
/**
* The loop template file.
*
* Included on pages like index.php, archive.php and search.php to display a loop of posts
* Learn more: https://codex.wordpress.org/The_Loop
*
* @package storefront
*/
do_action( 'storefront_loop_before' );
while ( have_posts() ) :
the_post();
/**
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
endwhile;
/**
* Functions hooked in to storefront_paging_nav action
*
* @hooked storefront_paging_nav - 10
*/
do_action( 'storefront_loop_after' );
| {
"pile_set_name": "Github"
} |
/*
Fontname: -B&H-Lucida-Medium-I-Normal-Sans-26-190-100-100-P-147-ISO10646-1
Copyright: Copyright Bigelow & Holmes 1986, 1985.
Glyphs: 18/723
BBX Build Mode: 0
*/
const uint8_t u8g2_font_luIS19_tn[454] U8G2_FONT_SECTION("u8g2_font_luIS19_tn") =
"\22\0\4\3\5\5\4\5\6\22\30\0\373\23\373\23\374\0\0\0\0\1\251 \6\0`D\1*\26*"
"\261fK\60*D\310bDdhLBfD(H\4\0+\23\17*\204QZXZg\7\37\210"
"I\353XZ\20\0,\13%\351B\203\213\31M\324\0-\10F,F\341\240\0.\11d(D\343`"
"\2\0/\34\361\42k}\134=\200\270z\0q\361q\345\343\312\307\325\3\210\253\7\20\27\37\7\60'"
"n.\204\255\360lfhjdlDnbnBpB\320\241\304\334\304\334\304\234\310\330\310\324\320\314"
"\324A \35\0\61\24f>\204\343\200fFH\315\32!\65k\204\324\254\21\2\62\30n.\204\255\356"
"@J\210&nv\323\275\34\335v\364\200\346\200\6\0\63\33m.\204\351\354 *jtVtrY"
"\335)\355\350\226#R\63\7Rf\0\64!n*\204w\224\222\262pBnbldjFjHh"
"JfLFL\346\340K\331\265\302B\0\65\32n.\204\351`\350`(X\307\205\7\261\304\263\333\312"
"\316H\15\35H\335\1\66%n.\204\317\354@hJftVvE\325\1I\321\10\331\304\334\304\334"
"\304\234\310\330\310\230\320\252\203\270\62\0\67\26n\62\204\345\240\344\240\224t\337\216\256\35\35%\235\35\235"
"\235\5\70*n.\204\315\356 jhFNFNFlfh\210\202\314\356 j\244fjdnb"
"nbnbl\204\210\346`\314\12\0\71'n.\204\255\356@\210fHldlDnbnbn"
"b\214d\250\344\200\252bvVvtFj\350@\314\16\0:\13\305-De=V##\0\0\0"
"\0\4\377\377\0";
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="BuildingModelPayload" xml:space="preserve">
<value>{
"@id": "BUILDING_MODEL_ID",
"@type": "Interface",
"displayName": "Building",
"description": "A free-standing structure.",
"contents": [
{
"@type": "Relationship",
"name": "has",
"target": "FLOOR_MODEL_ID"
},
{
"@type": "Relationship",
"name": "isEquippedWith",
"target": "HVAC_MODEL_ID"
},
{
"@type": "Property",
"name": "AverageTemperature",
"schema": "double"
}
],
"@context": "dtmi:dtdl:context;2"
}</value>
</data>
<data name="FloorModelPayload" xml:space="preserve">
<value>{
"@id": "FLOOR_MODEL_ID",
"@type": "Interface",
"@context": "dtmi:dtdl:context;2",
"displayName": "Floor",
"description": "A building story.",
"contents": [
{
"@type": "Relationship",
"name": "contains",
"target": "ROOM_MODEL_ID",
"properties": [
{
"@type": "Property",
"name": "isAccessRestricted",
"schema": "boolean"
}
]
},
{
"@type": "Relationship",
"name": "cooledBy",
"target": "HVAC_MODEL_ID"
},
{
"@type": "Property",
"name": "AverageTemperature",
"schema": "double"
}
]
}</value>
</data>
<data name="FloorTwinPayload" xml:space="preserve">
<value>{
"$metadata": {
"$model": "FLOOR_MODEL_ID"
},
"AverageTemperature": 75
}</value>
</data>
<data name="HvacModelPayload" xml:space="preserve">
<value>{
"@id": "HVAC_MODEL_ID",
"@type": "Interface",
"displayName": "HVAC",
"description": "A heating, ventilation, and air conditioning unit.",
"contents": [
{
"@type": "Property",
"name": "Efficiency",
"schema": "double"
},
{
"@type": "Property",
"name": "TargetTemperature",
"schema": "double"
},
{
"@type": "Property",
"name": "TargetHumidity",
"schema": "double"
},
{
"@type": "Relationship",
"name": "cools",
"target": "FLOOR_MODEL_ID"
}
],
"@context": "dtmi:dtdl:context;2"
}</value>
</data>
<data name="HvacTwinPayload" xml:space="preserve">
<value>{
"$metadata": {
"$model": "HVAC_MODEL_ID"
},
"TargetTemperature": 80,
"TargetHumidity": 25
}</value>
</data>
<data name="RelationshipPayload" xml:space="preserve">
<value>{
"$targetId": "TARGET_TWIN_ID",
"$relationshipName": "RELATIONSHIP_NAME"
}</value>
</data>
<data name="RelationshipWithPropertyPayload" xml:space="preserve">
<value>{
"$targetId": "TARGET_TWIN_ID",
"$relationshipName": "RELATIONSHIP_NAME",
"PROPERTY_NAME": "PROPERTY_VALUE"
}</value>
</data>
<data name="RoomModelPayload" xml:space="preserve">
<value>{
"@id": "ROOM_MODEL_ID",
"@type": "Interface",
"displayName": "Room",
"description": "An enclosure inside a building.",
"contents": [
{
"@type": "Relationship",
"name": "containedIn",
"target": "FLOOR_MODEL_ID"
},
{
"@type": "Property",
"name": "Temperature",
"schema": "double"
},
{
"@type": "Property",
"name": "Humidity",
"schema": "double"
},
{
"@type": "Property",
"name": "IsOccupied",
"schema": "boolean"
},
{
"@type": "Property",
"name": "EmployeeId",
"schema": "string"
}
],
"@context": "dtmi:dtdl:context;2"
}</value>
</data>
<data name="RoomTwinPayload" xml:space="preserve">
<value>{
"$metadata": {
"$model": "ROOM_MODEL_ID"
},
"Temperature": 80,
"Humidity": 25,
"IsOccupied": true,
"EmployeeId": "Employee1"
}</value>
</data>
<data name="RoomWithWifiModelPayload" xml:space="preserve">
<value>{
"@id": "ROOM_WITH_WIFI_MODEL_ID",
"@type": "Interface",
"displayName": "RoomWithWifi",
"contents": [
{
"@type": "Property",
"name": "Temperature",
"schema": "double"
},
{
"@type": "Property",
"name": "Humidity",
"schema": "double"
},
{
"@type": "Property",
"name": "IsOccupied",
"schema": "boolean"
},
{
"@type": "Property",
"name": "EmployeeId",
"schema": "string"
},
{
"@type": "Component",
"name": "WIFI_COMPONENT_NAME",
"schema": "WIFI_MODEL_ID"
}
],
"@context": "dtmi:dtdl:context;2"
}</value>
</data>
<data name="RoomWithWifiTwinPayload" xml:space="preserve">
<value>{
"$metadata": {
"$model": "ROOM_WITH_WIFI_MODEL_ID"
},
"Temperature": 80,
"Humidity": 25,
"IsOccupied": true,
"EmployeeId": "Employee1",
"WIFI_COMPONENT_NAME": {
"$metadata": {
},
"RouterName": "Cisco1",
"Network": "Room1"
}
}</value>
</data>
<data name="WardModelPayload" xml:space="preserve">
<value>{
"@id": "WARD_MODEL_ID",
"@type": "Interface",
"displayName": "Ward",
"description": "A separate partition in a building, made of rooms and hallways.",
"contents": [
{
"@type": "Property",
"name": "VisitorCount",
"schema": "double"
},
{
"@type": "Property",
"name": "HandWashPercentage",
"schema": "double"
},
{
"@type": "Relationship",
"name": "managedRooms"
}
],
"@context": "dtmi:dtdl:context;2"
}</value>
</data>
<data name="WifiModelPayload" xml:space="preserve">
<value>{
"@id": "WIFI_MODEL_ID",
"@type": "Interface",
"@context": "dtmi:dtdl:context;2",
"displayName": "Wifi",
"contents": [
{
"@type": "Property",
"name": "RouterName",
"schema": "string"
},
{
"@type": "Property",
"name": "Network",
"schema": "string"
}
]
}</value>
</data>
</root>
| {
"pile_set_name": "Github"
} |
"""Tables: Distributed object K/V-store."""
from .base import Collection, CollectionT
from .globaltable import GlobalTable, GlobalTableT
from .manager import TableManager, TableManagerT
from .table import Table, TableT
__all__ = [
'Collection',
'CollectionT',
'GlobalTable',
'GlobalTableT',
'TableManager',
'TableManagerT',
'Table',
'TableT',
]
| {
"pile_set_name": "Github"
} |
-- Copyright 2004-2020 H2 Group. Multiple-Licensed under the MPL 2.0,
-- and the EPL 1.0 (https://h2database.com/html/license.html).
-- Initial Developer: H2 Group
--
-- Test for ALTER TABLE RENAME and ALTER VIEW RENAME
CREATE TABLE TABLE1A(ID INT);
> ok
INSERT INTO TABLE1A VALUES (1);
> update count: 1
-- ALTER TABLE RENAME
ALTER TABLE TABLE1A RENAME TO TABLE1B;
> ok
SELECT * FROM TABLE1B;
>> 1
ALTER TABLE IF EXISTS TABLE1B RENAME TO TABLE1C;
> ok
SELECT * FROM TABLE1C;
>> 1
ALTER TABLE BAD RENAME TO SMTH;
> exception TABLE_OR_VIEW_NOT_FOUND_1
ALTER TABLE IF EXISTS BAD RENAME TO SMTH;
> ok
-- ALTER VIEW RENAME
CREATE VIEW VIEW1A AS SELECT * FROM TABLE1C;
> ok
ALTER VIEW VIEW1A RENAME TO VIEW1B;
> ok
SELECT * FROM VIEW1B;
>> 1
ALTER TABLE IF EXISTS VIEW1B RENAME TO VIEW1C;
> ok
SELECT * FROM VIEW1C;
>> 1
ALTER VIEW BAD RENAME TO SMTH;
> exception VIEW_NOT_FOUND_1
ALTER VIEW IF EXISTS BAD RENAME TO SMTH;
> ok
SELECT * FROM VIEW1C;
>> 1
DROP TABLE TABLE1C CASCADE;
> ok
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: LGPL-2.1
// Copyright (C) 2018, Red Hat Inc, Arnaldo Carvalho de Melo <[email protected]>
#include "trace/beauty/beauty.h"
#include <uapi/linux/fs.h>
static size_t renameat2__scnprintf_flags(unsigned long flags, char *bf, size_t size, bool show_prefix)
{
#include "trace/beauty/generated/rename_flags_array.c"
static DEFINE_STRARRAY(rename_flags, "RENAME_");
return strarray__scnprintf_flags(&strarray__rename_flags, bf, size, show_prefix, flags);
}
size_t syscall_arg__scnprintf_renameat2_flags(char *bf, size_t size, struct syscall_arg *arg)
{
unsigned long flags = arg->val;
return renameat2__scnprintf_flags(flags, bf, size, arg->show_string_prefix);
}
| {
"pile_set_name": "Github"
} |
//
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2012-2015 Joerg Henrichs
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "karts/abstract_kart.hpp"
#include "config/user_config.hpp"
#include "items/attachment.hpp"
#include "items/powerup.hpp"
#include "karts/abstract_kart_animation.hpp"
#include "karts/kart_model.hpp"
#include "karts/kart_properties.hpp"
#include "karts/kart_properties_manager.hpp"
#include "network/network_config.hpp"
#include "physics/physics.hpp"
#include "utils/log.hpp"
/** Creates a kart.
* \param ident The identifier of the kart.
* \param world_kart_id The world index of this kart.
* \param position The start position of the kart (1<=position<=n).
* \param init_transform The start position of the kart.
*/
AbstractKart::AbstractKart(const std::string& ident,
int world_kart_id, int position,
const btTransform& init_transform,
HandicapLevel handicap,
std::shared_ptr<RenderInfo> ri)
: Moveable()
{
m_world_kart_id = world_kart_id;
loadKartProperties(ident, handicap, ri);
} // AbstractKart
// ----------------------------------------------------------------------------
AbstractKart::~AbstractKart()
{
if (m_kart_animation)
{
m_kart_animation->handleResetRace();
delete m_kart_animation;
}
} // ~AbstractKart
// ----------------------------------------------------------------------------
void AbstractKart::reset()
{
m_live_join_util = 0;
// important to delete animations before calling reset, as some animations
// set the kart velocity in their destructor (e.g. cannon) which "reset"
// can then cancel. See #2738
if (m_kart_animation)
{
m_kart_animation->handleResetRace();
delete m_kart_animation;
m_kart_animation = NULL;
}
Moveable::reset();
} // reset
// ----------------------------------------------------------------------------
void AbstractKart::loadKartProperties(const std::string& new_ident,
HandicapLevel handicap,
std::shared_ptr<RenderInfo> ri)
{
m_kart_properties.reset(new KartProperties());
const KartProperties* kp = kart_properties_manager->getKart(new_ident);
const KartProperties* kp_addon = NULL;
if (NetworkConfig::get()->isNetworking() &&
NetworkConfig::get()->useTuxHitboxAddon() && kp && kp->isAddon())
{
// For addon kart in network we use the same hitbox (tux) so anyone
// can use any addon karts with different graphical kart model
if (!UserConfigParams::m_addon_tux_online)
kp_addon = kp;
kp = kart_properties_manager->getKart(std::string("tux"));
}
if (kp == NULL)
{
if (!NetworkConfig::get()->isNetworking() ||
!NetworkConfig::get()->useTuxHitboxAddon())
{
Log::warn("Abstract_Kart", "Unknown kart %s, fallback to tux",
new_ident.c_str());
}
kp = kart_properties_manager->getKart(std::string("tux"));
}
m_kart_properties->copyForPlayer(kp, handicap);
if (kp_addon)
m_kart_properties->adjustForOnlineAddonKart(kp_addon);
m_name = m_kart_properties->getName();
m_handicap = handicap;
m_kart_animation = NULL;
assert(m_kart_properties);
// We have to take a copy of the kart model, since otherwise
// the animations will be mixed up (i.e. different instances of
// the same model will set different animation frames).
// Technically the mesh in m_kart_model needs to be grab'ed and
// released when the kart is deleted, but since the original
// kart_model is stored in the kart_properties all the time,
// there is no risk of a mesh being deleted too early.
if (kp_addon)
m_kart_model.reset(kp_addon->getKartModelCopy(ri));
else
m_kart_model.reset(m_kart_properties->getKartModelCopy(ri));
m_kart_width = kp->getMasterKartModel().getWidth();
m_kart_height = kp->getMasterKartModel().getHeight();
m_kart_length = kp->getMasterKartModel().getLength();
m_kart_highest_point = m_kart_model->getHighestPoint();
m_wheel_graphics_position = m_kart_model->getWheelsGraphicsPosition();
} // loadKartProperties
// ----------------------------------------------------------------------------
void AbstractKart::changeKart(const std::string& new_ident,
HandicapLevel handicap,
std::shared_ptr<RenderInfo> ri)
{
// Reset previous kart (including delete old animation above)
reset();
// Remove kart body
Physics::get()->removeKart(this);
loadKartProperties(new_ident, handicap, ri);
} // changeKart
// ----------------------------------------------------------------------------
/** Returns a unique identifier for this kart (name of the directory the
* kart was loaded from). */
const std::string& AbstractKart::getIdent() const
{
return m_kart_properties->getIdent();
} // getIdent
// ----------------------------------------------------------------------------
bool AbstractKart::isWheeless() const
{
return m_kart_model->getWheelModel(0)==NULL;
} // isWheeless
// ----------------------------------------------------------------------------
/** Sets a new kart animation. This function should either be called to
* remove an existing kart animation (ka=NULL), or to set a new kart
* animation, in which case the current kart animation must be NULL.
* \param ka The new kart animation, or NULL if the current kart animation
* is to be stopped.
*/
void AbstractKart::setKartAnimation(AbstractKartAnimation *ka)
{
#ifdef DEBUG
if( ( (ka!=NULL) ^ (m_kart_animation!=NULL) ) ==0)
{
if(ka) Log::debug("Abstract_Kart", "Setting kart animation to '%s'.",
ka->getName().c_str());
else Log::debug("Abstract_Kart", "Setting kart animation to NULL.");
if(m_kart_animation) Log::info("Abstract_Kart", "Current kart"
"animation is '%s'.",
m_kart_animation->getName().c_str());
else Log::debug("Abstract_Kart", "Current kart animation is NULL.");
}
#endif
if (ka != NULL && m_kart_animation != NULL)
{
delete m_kart_animation;
m_kart_animation = NULL;
}
// Make sure that the either the current animation is NULL and a new (!=0)
// is set, or there is a current animation, then it must be set to 0. This
// makes sure that the calling logic of this function is correct.
assert( (ka!=NULL) ^ (m_kart_animation!=NULL) );
m_kart_animation = ka;
} // setKartAnimation
// ----------------------------------------------------------------------------
/** Returns the time at which the kart was at a given distance.
* Returns -1.0f if none */
float AbstractKart::getTimeForDistance(float distance)
{
return -1.0f;
} // getTimeForDistance
// ----------------------------------------------------------------------------
/** Moves the current physical transform into this kart's position.
*/
void AbstractKart::kartIsInRestNow()
{
// Update the kart transforms with the newly computed position
// after all karts are reset
m_starting_transform = getBody()->getWorldTransform();
setTrans(m_starting_transform);
} // kartIsInRest
// ------------------------------------------------------------------------
/** Called before go phase to make sure all karts start at the same
* position in case there is a slope. */
void AbstractKart::makeKartRest()
{
btTransform t = m_starting_transform;
if (m_live_join_util != 0)
{
t.setOrigin(t.getOrigin() +
m_starting_transform.getBasis().getColumn(1) * 3.0f);
}
btRigidBody *body = getBody();
body->clearForces();
body->setLinearVelocity(Vec3(0.0f));
body->setAngularVelocity(Vec3(0.0f));
body->proceedToTransform(t);
setTrans(t);
} // makeKartRest
| {
"pile_set_name": "Github"
} |
/*************************************************
** auth: [email protected]
** date: 2018/2/26 19:36:23 (UTC +8:00)
** desc: ...
*************************************************/
using System;
namespace AutumnBox.OpenFramework.Exceptions
{
/// <summary>
/// 拒绝访问异常
/// </summary>
public class AccessDeniedException : Exception { }
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// +k8s:deepcopy-gen=package,register
// +k8s:openapi-gen=true
package policy
| {
"pile_set_name": "Github"
} |
//----------------------------------------------------------------------------
//
// ThreadImpl.h
//
// POSIX implementation of a cross-platform thread
//
// Copyright (c) 2010, Greg Satz <[email protected]>
// All rights reserved.
//
// SOFTWARE NOTICE AND LICENSE
//
// This file is part of OpenZWave.
//
// OpenZWave is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// OpenZWave is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with OpenZWave. If not, see <http://www.gnu.org/licenses/>.
//
//-----------------------------------------------------------------------------
#include <unistd.h>
#include "Defs.h"
#include "platform/Event.h"
#include "platform/Thread.h"
#include "ThreadImpl.h"
#ifdef DARWIN
#define pthread_yield pthread_yield_np
#endif
using namespace OpenZWave;
//-----------------------------------------------------------------------------
// <ThreadImpl::ThreadImpl>
// Constructor
//-----------------------------------------------------------------------------
ThreadImpl::ThreadImpl
(
Thread* _owner,
string const& _tname
):
m_owner( _owner ),
// m_hThread( NULL ), /* p_thread_t isn't a pointer in Linux, so can't do this */
m_bIsRunning( false ),
m_name( _tname )
{
}
//-----------------------------------------------------------------------------
// <ThreadImpl::~ThreadImpl>
// Destructor
//-----------------------------------------------------------------------------
ThreadImpl::~ThreadImpl
(
)
{
}
//-----------------------------------------------------------------------------
// <ThreadImpl::Start>
// Start a function running on this thread
//-----------------------------------------------------------------------------
bool ThreadImpl::Start
(
Thread::pfnThreadProc_t _pfnThreadProc,
Event* _exitEvent,
void* _pContext
)
{
pthread_attr_t ta;
pthread_attr_init( &ta );
pthread_attr_setstacksize ( &ta, 0 );
pthread_attr_setdetachstate ( &ta, PTHREAD_CREATE_JOINABLE );
// Create a thread to run the specified function
m_pfnThreadProc = _pfnThreadProc;
m_pContext = _pContext;
m_exitEvent = _exitEvent;
m_exitEvent->Reset();
pthread_create ( &m_hThread, &ta, ThreadImpl::ThreadProc, this );
//fprintf(stderr, "thread %s starting %08x\n", m_name.c_str(), m_hThread);
//fflush(stderr);
pthread_attr_destroy ( &ta );
return true;
}
//-----------------------------------------------------------------------------
// <ThreadImpl::Terminate>
// End this thread
//-----------------------------------------------------------------------------
bool ThreadImpl::Terminate
(
)
{
void* data = NULL;
//fprintf(stderr, "thread %s stopping %08x running %d\n", m_name.c_str(), m_hThread, m_bIsRunning );
//fflush(stderr);
if( !m_bIsRunning )
{
return false;
}
// This will kill an app that doesn't catch and ignore it.
// We need to find another way to interrupt select.
// thread_kill( m_hThread, SIGALRM );
//m_hThread = NULL;
m_bIsRunning = false;
pthread_cancel( m_hThread );
pthread_join( m_hThread, &data );
return true;
}
//-----------------------------------------------------------------------------
// <ThreadImpl::msSleep>
// Cause thread to sleep for the specified number of milliseconds
//-----------------------------------------------------------------------------
void ThreadImpl::Sleep
(
uint32 _millisecs
)
{
usleep( _millisecs*1000 );
}
//-----------------------------------------------------------------------------
// <ThreadImpl::IsSignalled>
// Test whether the thread has completed
//-----------------------------------------------------------------------------
bool ThreadImpl::IsSignalled
(
)
{
return !m_bIsRunning;
}
//-----------------------------------------------------------------------------
// <ThreadImpl::ThreadProc>
// Entry point for running a function on this thread
//-----------------------------------------------------------------------------
void *ThreadImpl::ThreadProc
(
void* _pArg
)
{
ThreadImpl* pImpl = (ThreadImpl*)_pArg;
//fprintf(stderr, "thread %s run begin %08x running %d\n", pImpl->m_name.c_str(), pImpl->m_hThread, pImpl->m_bIsRunning );
//fflush(stderr);
pImpl->Run();
//fprintf(stderr, "thread %s run end %08x running %d\n", pImpl->m_name.c_str(), pImpl->m_hThread, pImpl->m_bIsRunning );
//fflush(stderr);
return 0;
}
//-----------------------------------------------------------------------------
// <ThreadImpl::Run>
// Entry point for running a function on this thread
//-----------------------------------------------------------------------------
void ThreadImpl::Run
(
)
{
m_bIsRunning = true;
m_pfnThreadProc( m_exitEvent, m_pContext );
m_bIsRunning = false;
// Let any watchers know that the thread has finished running
m_owner->Notify();
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2013 KLab Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ILuaFuncLib.h"
ILuaFuncLib * ILuaFuncLib::m_begin = NULL;
ILuaFuncLib * ILuaFuncLib::m_end = NULL;
ILuaFuncLib::ILuaFuncLib() {}
ILuaFuncLib::ILuaFuncLib(DEFCONST * arrCmdItem){ addLink(arrCmdItem); }
ILuaFuncLib::~ILuaFuncLib()
{
if(m_pPrev) {
m_pPrev->m_pNext = m_pNext;
} else {
m_begin = m_pNext;
}
if(m_pNext) {
m_pNext->m_pPrev = m_pPrev;
} else {
m_end = m_pPrev;
}
}
bool
ILuaFuncLib::exist()
{
return true;
}
void
ILuaFuncLib::destroyResources() {}
bool
ILuaFuncLib::dumpObjects(IPlatformRequest& /*pForm*/)
{
return false;
}
void
ILuaFuncLib::addLink(DEFCONST * arrCmdItem)
{
m_arrCmdItem = arrCmdItem;
m_pPrev = NULL;
m_pNext = m_begin;
if(m_pNext) {
m_pNext->m_pPrev = this;
} else {
m_end = this;
}
m_begin = this;
}
void
ILuaFuncLib::registLib(lua_State * L)
{
m_L = L;
addLibrary(); // 関数群定義が書かれている筈の関数を呼び出す
registConst(); // 指定された定数リストを読んで定義する
}
void
ILuaFuncLib::registConst()
{
IPlatformRequest& pfif = CPFInterface::getInstance().platform();
// 定数定義リストが与えられていなければ、行う処理はない。
DEFCONST * pConst;
for(pConst = m_arrCmdItem; pConst && pConst->name; pConst++) {
lua_getglobal(m_L, pConst->name);
if(!lua_isnil(m_L, -1)) {
lua_pop(m_L, 1);
// 指定されたグローバルラベルがnilではないということは、
// 同名で値が定義済みであるため、エラーを出す。
DEBUG_PRINT("[LIB REGISTRATION ERROR] %s it is redefined.\n", pConst->name);
continue;
}
lua_pop(m_L, 1);
lua_pushinteger(m_L, pConst->cmd);
lua_setglobal(m_L, pConst->name);
pfif.logging("\t\t[def] %s = %d", pConst->name, pConst->cmd);
}
}
void
ILuaFuncLib::addFunction(const char * luaFuncName, int (*func)(lua_State * L))
{
lua_register(m_L, luaFuncName, func);
DEBUG_PRINT(" [func] %s", luaFuncName);
}
bool
ILuaFuncLib::registAllLibs(lua_State * L)
{
ILuaFuncLib * pLib = m_begin;
IPlatformRequest& pfif = CPFInterface::getInstance().platform();
// オブジェクトダンプ関数を登録する
lua_register(L, "LuaLibDUMP", ILuaFuncLib::luaDumpObjects);
pfif.logging("<<<supported Lua functions>>>");
while(pLib) {
pLib->registLib(L);
pLib = pLib->m_pNext;
}
return true;
}
void
ILuaFuncLib::destroyAllResources()
{
ILuaFuncLib * pLib = m_begin;
while(pLib) {
pLib->destroyResources();
pLib = pLib->m_pNext;
}
}
int
ILuaFuncLib::luaDumpObjects(lua_State * L)
{
CLuaState lua(L);
// この関数について、引数は一切考慮しない。
// 全ての引数を無視する。
IPlatformRequest& pForm = CPFInterface::getInstance().platform();
ILuaFuncLib * pLib = m_begin;
while(pLib) {
pLib->dumpObjects(pForm);
pLib = pLib->m_pNext;
}
lua.retBool(true);
return 1;
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "IOpenSaveObjectController.h"
#import "TOpenPanelCallbacks-Protocol.h"
@interface TChooseObjectController : IOpenSaveObjectController <TOpenPanelCallbacks>
{
struct TNSRef<TOpenPanel, void> _choosePanel;
}
- (id).cxx_construct;
- (void).cxx_destruct;
- (void)dealloc;
- (void)openPanelDidEnd:(id)arg1 returnCode:(long long)arg2;
- (void)run;
- (_Bool)validateNode:(const struct TFENode *)arg1;
- (_Bool)shouldEnableNode:(const struct TFENode *)arg1;
- (BOOL)panel:(id)arg1 shouldEnableURL:(id)arg2;
- (void)getSelectedNodes:(struct TFENodeVector *)arg1;
- (void)setAccessoryView:(id)arg1;
- (void)setOptions:(int)arg1;
- (int)options;
- (id)panel;
- (int)defaultOptions;
- (id)init;
@end
| {
"pile_set_name": "Github"
} |
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/cast_op_impl.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
std::function<void(OpKernelContext*, const Tensor&, Tensor*)>
GetCpuCastFromHalf(DataType dst_dtype) {
CURRY_TYPES3(CAST_CASE, CPUDevice, Eigen::half);
return nullptr;
}
#if GOOGLE_CUDA
std::function<void(OpKernelContext*, const Tensor&, Tensor*)>
GetGpuCastFromHalf(DataType dst_dtype) {
CURRY_TYPES3(CAST_CASE, GPUDevice, Eigen::half);
return nullptr;
}
#endif // GOOGLE_CUDA
} // namespace tensorflow
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// Generated with Bot Builder V4 SDK Template for Visual Studio EchoBot v$templateversion$
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
namespace $safeprojectname$.Controllers
{
// This ASP Controller is created to handle a request. Dependency Injection will provide the Adapter and IBot
// implementation at runtime. Multiple different IBot implementations running at different endpoints can be
// achieved by specifying a more specific type for the bot constructor argument.
[Route("api/messages")]
[ApiController]
public class BotController : ControllerBase
{
private readonly IBotFrameworkHttpAdapter Adapter;
private readonly IBot Bot;
public BotController(IBotFrameworkHttpAdapter adapter, IBot bot)
{
Adapter = adapter;
Bot = bot;
}
[HttpPost, HttpGet]
public async Task PostAsync()
{
// Delegate the processing of the HTTP POST to the adapter.
// The adapter will invoke the bot.
await Adapter.ProcessAsync(Request, Response, Bot);
}
}
}
| {
"pile_set_name": "Github"
} |
<ng-content></ng-content>
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import * as CaretFinder from '../caret/CaretFinder';
import CaretPosition from '../caret/CaretPosition';
import * as CaretUtils from '../caret/CaretUtils';
const createRange = (sc: Node, so: number, ec: Node, eo: number): Range => {
const rng = document.createRange();
rng.setStart(sc, so);
rng.setEnd(ec, eo);
return rng;
};
// If you triple click a paragraph in this case:
// <blockquote><p>a</p></blockquote><p>b</p>
// It would become this range in webkit:
// <blockquote><p>[a</p></blockquote><p>]b</p>
// We would want it to be:
// <blockquote><p>[a]</p></blockquote><p>b</p>
// Since it would otherwise produces spans out of thin air on insertContent for example.
const normalizeBlockSelectionRange = (rng: Range): Range => {
const startPos = CaretPosition.fromRangeStart(rng);
const endPos = CaretPosition.fromRangeEnd(rng);
const rootNode = rng.commonAncestorContainer;
return CaretFinder.fromPosition(false, rootNode, endPos)
.map(function (newEndPos) {
if (!CaretUtils.isInSameBlock(startPos, endPos, rootNode) && CaretUtils.isInSameBlock(startPos, newEndPos, rootNode)) {
return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
} else {
return rng;
}
}).getOr(rng);
};
const normalize = (rng: Range): Range => rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
export {
normalize
};
| {
"pile_set_name": "Github"
} |
Shared code for storing scopes in the database
| {
"pile_set_name": "Github"
} |
diff --git a/mesonbuild/environment.py b/mesonbuild/environment.py
index 6c270431..fc80b178 100644
--- a/mesonbuild/environment.py
+++ b/mesonbuild/environment.py
@@ -257,7 +257,7 @@ def detect_cpu(compilers):
def detect_system():
system = platform.system().lower()
- if system.startswith('cygwin'):
+ if system.startswith('cygwin') or system.startswith('msys'):
return 'cygwin'
return system
diff --git a/mesonbuild/mesonlib.py b/mesonbuild/mesonlib.py
index 8648a0dc..128092db 100644
--- a/mesonbuild/mesonlib.py
+++ b/mesonbuild/mesonlib.py
@@ -281,7 +281,7 @@ def is_windows():
return platname == 'windows' or 'mingw' in platname
def is_cygwin() -> bool:
- return platform.system().lower().startswith('cygwin')
+ return platform.system().lower().startswith('cygwin') or platform.system().lower().startswith('msys')
def is_debianlike() -> bool:
return os.path.isfile('/etc/debian_version')
--- meson-0.54.3/mesonbuild/mesonmain.py.orig 2020-05-15 09:23:11.000000000 +0200
+++ meson-0.54.3/mesonbuild/mesonmain.py 2020-08-30 18:13:12.849059300 +0200
@@ -192,7 +192,7 @@
ensure_stdout_accepts_unicode()
# https://github.com/mesonbuild/meson/issues/3653
- if sys.platform.lower() == 'msys':
+ if sys.platform.lower() == 'msys' and os.environ.get('MSYSTEM', '') != 'MSYS':
mlog.error('This python3 seems to be msys/python on MSYS2 Windows, which is known to have path semantics incompatible with Meson')
msys2_arch = detect_msys2_arch()
if msys2_arch:
diff --git a/mesonbuild/mtest.py b/mesonbuild/mtest.py
index 8d9a5853..7d0ea30d 100644
--- a/mesonbuild/mtest.py
+++ b/mesonbuild/mtest.py
@@ -41,7 +41,7 @@ def is_windows():
def is_cygwin():
platname = platform.system().lower()
- return 'cygwin' in platname
+ return 'cygwin' in platname or 'msys' in platname
def determine_worker_count():
varname = 'MESON_TESTTHREADS'
diff --git a/mesonbuild/scripts/meson_exe.py b/mesonbuild/scripts/meson_exe.py
index 84abfc33..59aabff0 100644
--- a/mesonbuild/scripts/meson_exe.py
+++ b/mesonbuild/scripts/meson_exe.py
@@ -34,7 +34,7 @@ def is_windows():
def is_cygwin():
platname = platform.system().lower()
- return 'cygwin' in platname
+ return 'cygwin' in platname or 'msys' in platname
def run_with_mono(fname):
if fname.endswith('.exe') and not (is_windows() or is_cygwin()):
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/compiler/java/java_field.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/java/java_context.h>
#include <google/protobuf/compiler/java/java_enum_field.h>
#include <google/protobuf/compiler/java/java_enum_field_lite.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_lazy_message_field.h>
#include <google/protobuf/compiler/java/java_lazy_message_field_lite.h>
#include <google/protobuf/compiler/java/java_map_field.h>
#include <google/protobuf/compiler/java/java_map_field_lite.h>
#include <google/protobuf/compiler/java/java_message_field.h>
#include <google/protobuf/compiler/java/java_message_field_lite.h>
#include <google/protobuf/compiler/java/java_primitive_field.h>
#include <google/protobuf/compiler/java/java_primitive_field_lite.h>
#include <google/protobuf/compiler/java/java_string_field.h>
#include <google/protobuf/compiler/java/java_string_field_lite.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace java {
namespace {
ImmutableFieldGenerator* MakeImmutableGenerator(
const FieldDescriptor* field, int messageBitIndex, int builderBitIndex,
Context* context) {
if (field->is_repeated()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsMapEntry(field->message_type())) {
return new ImmutableMapFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
if (IsLazy(field)) {
return new RepeatedImmutableLazyMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new RepeatedImmutableMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
}
case JAVATYPE_ENUM:
return new RepeatedImmutableEnumFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_STRING:
return new RepeatedImmutableStringFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
default:
return new RepeatedImmutablePrimitiveFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
} else {
if (field->containing_oneof()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field)) {
return new ImmutableLazyMessageOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new ImmutableEnumOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_STRING:
return new ImmutableStringOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
default:
return new ImmutablePrimitiveOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
} else {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field)) {
return new ImmutableLazyMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new ImmutableEnumFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_STRING:
return new ImmutableStringFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
default:
return new ImmutablePrimitiveFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
}
}
}
ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
const FieldDescriptor* field, int messageBitIndex, int builderBitIndex,
Context* context) {
if (field->is_repeated()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsMapEntry(field->message_type())) {
return new ImmutableMapFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
if (IsLazy(field)) {
return new RepeatedImmutableLazyMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new RepeatedImmutableMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
}
case JAVATYPE_ENUM:
return new RepeatedImmutableEnumFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_STRING:
return new RepeatedImmutableStringFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
default:
return new RepeatedImmutablePrimitiveFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
} else {
if (field->containing_oneof()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field)) {
return new ImmutableLazyMessageOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new ImmutableEnumOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_STRING:
return new ImmutableStringOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
default:
return new ImmutablePrimitiveOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
} else {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field)) {
return new ImmutableLazyMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new ImmutableEnumFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_STRING:
return new ImmutableStringFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
default:
return new ImmutablePrimitiveFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
}
}
}
static inline void ReportUnexpectedPackedFieldsCall(io::Printer* printer) {
// Reaching here indicates a bug. Cases are:
// - This FieldGenerator should support packing,
// but this method should be overridden.
// - This FieldGenerator doesn't support packing, and this method
// should never have been called.
GOOGLE_LOG(FATAL) << "GenerateParsingCodeFromPacked() "
<< "called on field generator that does not support packing.";
}
} // namespace
ImmutableFieldGenerator::~ImmutableFieldGenerator() {}
void ImmutableFieldGenerator::
GenerateParsingCodeFromPacked(io::Printer* printer) const {
ReportUnexpectedPackedFieldsCall(printer);
}
ImmutableFieldLiteGenerator::~ImmutableFieldLiteGenerator() {}
void ImmutableFieldLiteGenerator::
GenerateParsingCodeFromPacked(io::Printer* printer) const {
ReportUnexpectedPackedFieldsCall(printer);
}
// ===================================================================
template <>
FieldGeneratorMap<ImmutableFieldGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
: descriptor_(descriptor),
field_generators_(new google::protobuf::scoped_ptr<
ImmutableFieldGenerator>[descriptor->field_count()]) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
int messageBitIndex = 0;
int builderBitIndex = 0;
for (int i = 0; i < descriptor->field_count(); i++) {
ImmutableFieldGenerator* generator = MakeImmutableGenerator(
descriptor->field(i), messageBitIndex, builderBitIndex, context);
field_generators_[i].reset(generator);
messageBitIndex += generator->GetNumBitsForMessage();
builderBitIndex += generator->GetNumBitsForBuilder();
}
}
template<>
FieldGeneratorMap<ImmutableFieldGenerator>::~FieldGeneratorMap() {}
template <>
FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
: descriptor_(descriptor),
field_generators_(new google::protobuf::scoped_ptr<
ImmutableFieldLiteGenerator>[descriptor->field_count()]) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
int messageBitIndex = 0;
int builderBitIndex = 0;
for (int i = 0; i < descriptor->field_count(); i++) {
ImmutableFieldLiteGenerator* generator = MakeImmutableLiteGenerator(
descriptor->field(i), messageBitIndex, builderBitIndex, context);
field_generators_[i].reset(generator);
messageBitIndex += generator->GetNumBitsForMessage();
builderBitIndex += generator->GetNumBitsForBuilder();
}
}
template<>
FieldGeneratorMap<ImmutableFieldLiteGenerator>::~FieldGeneratorMap() {}
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
const FieldGeneratorInfo* info,
map<string, string>* variables) {
(*variables)["field_name"] = descriptor->name();
(*variables)["name"] = info->name;
(*variables)["capitalized_name"] = info->capitalized_name;
(*variables)["disambiguated_reason"] = info->disambiguated_reason;
(*variables)["constant_name"] = FieldConstantName(descriptor);
(*variables)["number"] = SimpleItoa(descriptor->number());
}
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
const OneofGeneratorInfo* info,
map<string, string>* variables) {
(*variables)["oneof_name"] = info->name;
(*variables)["oneof_capitalized_name"] = info->capitalized_name;
(*variables)["oneof_index"] =
SimpleItoa(descriptor->containing_oneof()->index());
(*variables)["set_oneof_case_message"] = info->name +
"Case_ = " + SimpleItoa(descriptor->number());
(*variables)["clear_oneof_case_message"] = info->name +
"Case_ = 0";
(*variables)["has_oneof_case_message"] = info->name +
"Case_ == " + SimpleItoa(descriptor->number());
}
void PrintExtraFieldInfo(const map<string, string>& variables,
io::Printer* printer) {
const map<string, string>::const_iterator it =
variables.find("disambiguated_reason");
if (it != variables.end() && !it->second.empty()) {
printer->Print(
variables,
"// An alternative name is used for field \"$field_name$\" because:\n"
"// $disambiguated_reason$\n");
}
}
} // namespace java
} // namespace compiler
} // namespace protobuf
} // namespace google
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<!-- Copyright Contributors to the ODPi Egeria project. -->
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>discovery-engine</artifactId>
<groupId>org.odpi.egeria</groupId>
<version>2.3-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<scm>
<connection>scm:git:git://github.com/odpi/egeria.git</connection>
<developerConnection>scm:git:ssh://github.com/odpi/egeria.git</developerConnection>
<url>http://github.com/odpi/egeria/tree/master</url>
</scm>
<name>Discovery Engine OMAS with Spring</name>
<description>
Spring-based REST API for the Discovery Engine Open Metadata Access Service (OMAS).
</description>
<artifactId>discovery-engine-spring</artifactId>
<dependencies>
<dependency>
<groupId>org.odpi.egeria</groupId>
<artifactId>ffdc-services</artifactId>
</dependency>
<dependency>
<groupId>org.odpi.egeria</groupId>
<artifactId>ocf-metadata-api</artifactId>
</dependency>
<dependency>
<groupId>org.odpi.egeria</groupId>
<artifactId>odf-metadata-api</artifactId>
</dependency>
<dependency>
<groupId>org.odpi.egeria</groupId>
<artifactId>discovery-engine-server</artifactId>
</dependency>
<dependency>
<groupId>org.odpi.egeria</groupId>
<artifactId>open-discovery-framework</artifactId>
</dependency>
<!-- Spring for REST APIs -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
</dependencies>
</project>
| {
"pile_set_name": "Github"
} |
from __future__ import print_function, division
import sys,os
# line 4 and line 5 below are for development purposes and can be removed
qspin_path = os.path.join(os.getcwd(),"../../")
sys.path.insert(0,qspin_path)
#####################################################################
# example 5 #
# In this script we demonstrate how to use QuSpin's to build #
# the Hamiltonian of the SSH model in real and momentum space. #
# Along the way, we showcase the block tools which allow the #
# user to create block-diagonal Hamiltonians. Last, we show #
# how to time-evolve free fermion states like the Fermi sea #
# and measure correlators. #
#####################################################################
from quspin.operators import hamiltonian,exp_op # Hamiltonians and operators
from quspin.basis import spinless_fermion_basis_1d # Hilbert space fermion basis
from quspin.tools.block_tools import block_diag_hamiltonian # block diagonalisation
import numpy as np # generic math functions
import matplotlib.pyplot as plt # plotting library
try: # import python 3 zip function in python 2 and pass if already using python 3
import itertools.izip as zip
except ImportError:
pass
##### define model parameters #####
L=100 # system size
J=1.0 # uniform hopping
deltaJ=0.1 # bond dimerisation
Delta=0.5 # staggered potential
beta=100.0 # inverse temperature for Fermi-Dirac distribution
##### construct single-particle Hamiltonian #####
# define site-coupling lists
hop_pm=[[-J-deltaJ*(-1)**i,i,(i+1)%L] for i in range(L)] # PBC
hop_mp=[[+J+deltaJ*(-1)**i,i,(i+1)%L] for i in range(L)] # PBC
stagg_pot=[[Delta*(-1)**i,i] for i in range(L)]
# define static and dynamic lists
static=[["+-",hop_pm],["-+",hop_mp],['n',stagg_pot]]
dynamic=[]
# define basis
basis=spinless_fermion_basis_1d(L,Nf=1)
# build real-space Hamiltonian
H=hamiltonian(static,dynamic,basis=basis,dtype=np.float64)
# diagonalise real-space Hamiltonian
E,V=H.eigh()
##### compute Fourier transform and momentum-space Hamiltonian #####
# define momentm blocks and basis arguments
blocks=[dict(Nf=1,kblock=i,a=2) for i in range(L//2)] # only L//2 distinct momenta
basis_args = (L,)
# construct block-diagonal Hamiltonian
FT,Hblock = block_diag_hamiltonian(blocks,static,dynamic,spinless_fermion_basis_1d,
basis_args,np.complex128,get_proj_kwargs=dict(pcon=True))
# diagonalise momentum-space Hamiltonian
Eblock,Vblock=Hblock.eigh()
##### prepare the density observables and initial states #####
# grab single-particle states and treat them as initial states
psi0=Vblock
# construct operator n_1 = $n_{j=0}$
n_1_static=[['n',[[1.0,0]]]]
n_1=hamiltonian(n_1_static,[],basis=basis,dtype=np.float64,
check_herm=False,check_pcon=False)
# construct operator n_2 = $n_{j=L/2}$
n_2_static=[['n',[[1.0,L//2]]]]
n_2=hamiltonian(n_2_static,[],basis=basis,dtype=np.float64,
check_herm=False,check_pcon=False)
# transform n_j operators to momentum space
n_1=n_1.rotate_by(FT,generator=False)
n_2=n_2.rotate_by(FT,generator=False)
##### evaluate nonequal time correlator <FS|n_2(t) n_1(0)|FS> #####
# define time vector
t=np.linspace(0.0,90.0,901)
# calcualte state acted on by n_1
n_psi0=n_1.dot(psi0)
# construct time-evolution operator using exp_op class (sometimes faster)
U = exp_op(Hblock,a=-1j,start=t.min(),stop=t.max(),num=len(t),iterate=True)
# evolve states
psi_t=U.dot(psi0)
n_psi_t = U.dot(n_psi0)
# alternative method for time evolution using Hamiltonian class
#psi_t=Hblock.evolve(psi0,0.0,t,iterate=True)
#n_psi_t=Hblock.evolve(n_psi0,0.0,t,iterate=True)
# preallocate variable
correlators=np.zeros(t.shape+psi0.shape[1:])
# loop over the time-evolved states
for i, (psi,n_psi) in enumerate( zip(psi_t,n_psi_t) ):
correlators[i,:]=n_2.matrix_ele(psi,n_psi,diagonal=True).real
# evaluate correlator at finite temperature
n_FD=1.0/(np.exp(beta*E)+1.0)
correlator = (n_FD*correlators).sum(axis=-1)
##### plot spectra
plt.plot(np.arange(H.Ns),E/L,
marker='o',color='b',label='real space')
plt.plot(np.arange(Hblock.Ns),Eblock/L,
marker='x',color='r',markersize=2,label='momentum space')
plt.xlabel('state number',fontsize=16)
plt.ylabel('energy',fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend(fontsize=16)
plt.grid()
plt.tight_layout()
plt.savefig('example5a.pdf', bbox_inches='tight')
#plt.show()
plt.close()
##### plot correlator
plt.plot(t,correlator,linewidth=2)
plt.xlabel('$t$',fontsize=16)
plt.ylabel('$C_{0,L/2}(t,\\beta)$',fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.grid()
plt.tight_layout()
plt.savefig('example5b.pdf', bbox_inches='tight')
#plt.show()
plt.close() | {
"pile_set_name": "Github"
} |
"use strict";
var o = {};
module.exports = function (t, a) {
a(t(o)(), o);
};
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
*
* DESCRIPTION
* Clear of an image to a specific color.
* -- VIS version low level functions.
*
* NOTE
* These functions are separated from mlib_v_ImageClear.c
* for structure clarity.
*/
#include <vis_proto.h>
#include <mlib_image.h>
#include <mlib_v_ImageClear_f.h>
/***************************************************************/
#define PREPAREVARS(type, chan) \
type *pimg = (type *) mlib_ImageGetData(img); \
mlib_s32 img_height = mlib_ImageGetHeight(img); \
mlib_s32 img_width = mlib_ImageGetWidth(img); \
mlib_s32 img_stride = mlib_ImageGetStride(img) / sizeof(type); \
mlib_s32 i, l, j; \
mlib_s32 emask; \
mlib_d64 dcolor, *dpimg; \
\
if ((img_width * chan) == img_stride) { \
img_width *= img_height; \
img_height = 1; \
}
/***************************************************************/
#define STRIP(pd, color, w, h, chan, data_type) \
for (l = 0; l < chan; l++) { \
data_type color_i = color[l]; \
for (i = 0; i < h; i++) { \
for (j = 0; j < w; j++) pd[i*img_stride+l+j*chan] = color_i; \
} \
}
/***************************************************************/
void mlib_v_ImageClear_BIT_1(mlib_image *img,
const mlib_s32 *color)
{
mlib_u8 *pimg = (mlib_u8 *) mlib_ImageGetData(img);
mlib_s32 img_height = mlib_ImageGetHeight(img);
mlib_s32 img_width = mlib_ImageGetWidth(img);
mlib_s32 img_stride = mlib_ImageGetStride(img);
mlib_s32 img_bitoff = mlib_ImageGetBitOffset(img);
mlib_s32 i, j, b_j, k;
mlib_u8 bcolor0, bmask, emask, src;
mlib_d64 dcolor, *dpimg;
mlib_u32 color0;
if (img_width == img_stride * 8) {
img_width *= img_height;
img_height = 1;
}
color0 = ((color[0] & 1) << 31) >> 31;
bcolor0 = color0 & 0xFF;
dcolor = vis_to_double_dup(color0);
for (i = 0, j = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end;
if (img_bitoff + img_width <= 8) {
bmask = (0xFF >> (8 - img_width)) << (8 - img_bitoff - img_width);
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
continue;
}
else {
bmask = 0xFF >> img_bitoff;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
pimg_row++;
j = 8 - img_bitoff;
b_j = (img_width - j) / 8;
}
if (b_j < 16) {
mlib_s32 ii;
for (ii = 0; ii < b_j; ii++)
pimg_row[ii] = bcolor0;
pimg_row += ii;
j += ii << 3;
if (j < img_width) {
bmask = (0xFF << (8 - (img_width - j))) & 0xFF;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
}
continue;
}
pimg_row_end = pimg_row + b_j - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge8(pimg_row, pimg_row_end);
vis_pst_8(dcolor, dpimg++, emask);
k = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; k < (b_j - 8); k += 8)
*dpimg++ = dcolor;
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor, dpimg, emask);
j += b_j << 3;
if (j < img_width) {
pimg_row = (mlib_u8 *) (pimg_row_end + 1);
bmask = (0xFF << (8 - (img_width - j))) & 0xFF;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
}
}
}
/***************************************************************/
void mlib_v_ImageClear_BIT_2(mlib_image *img,
const mlib_s32 *color)
{
mlib_u8 *pimg = (mlib_u8 *) mlib_ImageGetData(img); /* pointer to the data of img-image */
mlib_s32 img_height = mlib_ImageGetHeight(img); /* height of source image */
mlib_s32 img_width = mlib_ImageGetWidth(img) << 1; /* width of source image */
mlib_s32 img_stride = mlib_ImageGetStride(img); /* elements to next row */
mlib_s32 img_bitoff = mlib_ImageGetBitOffset(img); /* bits to first byte */
mlib_s32 i, j, b_j, k; /* indicies */
mlib_u8 bcolor0, bmask, emask, src;
mlib_d64 dcolor, *dpimg;
mlib_u32 color0 = color[0] & 1, color1 = color[1] & 1;
if (img_width == img_stride * 8) {
img_width *= img_height;
img_height = 1;
}
color1 = (color0 << 1) | color1;
color1 = (color1 << 2) | color1;
color1 = (color1 << 4) | color1;
color0 = ((color1 << 1) & 0xFE) | color0;
bcolor0 = ((img_bitoff & 1) == 0) ? color1 : color0;
color0 = (bcolor0 << 8) | bcolor0;
color0 = (color0 << 16) | color0;
dcolor = vis_to_double_dup(color0);
for (i = 0, j = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end;
if (img_bitoff + img_width <= 8) {
bmask = (0xFF >> (8 - img_width)) << (8 - img_bitoff - img_width);
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
continue;
}
else {
bmask = 0xFF >> img_bitoff;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
pimg_row++;
j = 8 - img_bitoff;
b_j = (img_width - j) / 8;
}
if (b_j < 16) {
mlib_s32 ii;
for (ii = 0; ii < b_j; ii++)
pimg_row[ii] = bcolor0;
pimg_row += ii;
j += ii << 3;
if (j < img_width) {
bmask = (0xFF << (8 - (img_width - j))) & 0xFF;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
}
continue;
}
pimg_row_end = pimg_row + b_j - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge8(pimg_row, pimg_row_end);
vis_pst_8(dcolor, dpimg++, emask);
k = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; k < (b_j - 8); k += 8)
*dpimg++ = dcolor;
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor, dpimg, emask);
j += b_j << 3;
if (j < img_width) {
pimg_row = (mlib_u8 *) (pimg_row_end + 1);
bmask = (0xFF << (8 - (img_width - j))) & 0xFF;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
}
}
}
/***************************************************************/
void mlib_v_ImageClear_BIT_3(mlib_image *img,
const mlib_s32 *color)
{
mlib_u8 *pimg = (mlib_u8 *) mlib_ImageGetData(img); /* pointer to the data of img-image */
mlib_s32 img_height = mlib_ImageGetHeight(img); /* height of source image */
mlib_s32 img_width = mlib_ImageGetWidth(img) * 3; /* width of source image */
mlib_s32 img_stride = mlib_ImageGetStride(img); /* elements to next row */
mlib_s32 img_bitoff = mlib_ImageGetBitOffset(img); /* bits to first byte */
mlib_s32 i, j, b_j, k, bit_shift; /* indicies */
mlib_u8 bcolor, bmask, emask, src;
mlib_d64 dcolor0, dcolor1, dcolor2, *dpimg;
mlib_d64 dcolor00, dcolor11, dcolor22;
mlib_u32 color0 = color[0] & 1, color1 = color[1] & 1, color2 = color[2] & 1;
mlib_u32 col0, col1, col2;
if (img_width == img_stride * 8) {
img_width *= img_height;
img_height = 1;
}
col0 = (color0 << 3) | (color1 << 2) | (color2 << 1) | color0;
col1 = (col0 >> 1) | (color2 << 3);
col2 = (col1 >> 1) | (color1 << 3);
color0 = (col0 << 4) | col2;
color1 = (col1 << 4) | col0;
color2 = (col2 << 4) | col1;
color0 = (color0 << 24) | (color1 << 16) | (color2 << 8) | color0;
color1 = (color0 << 8) | color1;
color2 = (color1 << 8) | color2;
dcolor0 = vis_to_double(color0, color1);
dcolor1 = vis_to_double(color2, color0);
dcolor2 = vis_to_double(color1, color2);
for (i = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end;
if (img_bitoff + img_width <= 8) {
bmask = (0xFF >> (8 - img_width)) << (8 - img_bitoff - img_width);
src = pimg_row[0];
bcolor = (color0 >> img_bitoff) & 0xFF;
pimg_row[0] = (src & ~bmask) | (bcolor & bmask);
continue;
}
else {
bmask = 0xFF >> img_bitoff;
src = pimg_row[0];
bcolor = (color0 >> img_bitoff) & 0xFF;
bit_shift = (((mlib_addr) pimg_row & 7) << 3) + img_bitoff;
pimg_row[0] = (src & ~bmask) | (bcolor & bmask);
pimg_row++;
j = 8 - img_bitoff;
b_j = (img_width - j) / 8;
}
pimg_row_end = pimg_row + b_j - 1;
dpimg = (mlib_d64 *) ((mlib_addr) pimg_row & ~7);
vis_alignaddr((void *)(bit_shift % 3), 0);
dcolor22 = vis_faligndata(dcolor0, dcolor1);
dcolor00 = vis_faligndata(dcolor1, dcolor2);
dcolor11 = vis_faligndata(dcolor2, dcolor0);
emask = vis_edge8(pimg_row, pimg_row_end);
if ((mlib_addr) pimg_row & 7)
vis_pst_8(dcolor22, dpimg++, emask);
k = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; k <= (b_j - 24); k += 24) {
dpimg[0] = dcolor00;
dpimg[1] = dcolor11;
dpimg[2] = dcolor22;
dpimg += 3;
}
if (k < b_j) {
if (k < (b_j - 8)) {
*dpimg++ = dcolor00;
if (k < (b_j - 16)) {
*dpimg++ = dcolor11;
dcolor00 = dcolor22;
}
else
dcolor00 = dcolor11;
}
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor00, dpimg, emask);
}
j = img_width - j - (b_j << 3);
if (j > 0) {
pimg_row = (mlib_u8 *) (pimg_row_end + 1);
bmask = (0xFF << (8 - j)) & 0xFF;
bcolor = (color0 >> j) & 0xFF;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (bcolor & bmask);
}
}
}
/***************************************************************/
void mlib_v_ImageClear_BIT_4(mlib_image *img,
const mlib_s32 *color)
{
mlib_u8 *pimg = (mlib_u8 *) mlib_ImageGetData(img); /* pointer to the data of img-image */
mlib_s32 img_height = mlib_ImageGetHeight(img); /* height of source image */
mlib_s32 img_width = mlib_ImageGetWidth(img) << 2; /* width of source image */
mlib_s32 img_stride = mlib_ImageGetStride(img); /* elements to next row */
mlib_s32 img_bitoff = mlib_ImageGetBitOffset(img); /* bits to first byte */
mlib_s32 i, j, b_j, k; /* indicies */
mlib_u8 bcolor0, bmask, emask, src;
mlib_d64 dcolor, *dpimg;
mlib_u32 color0 = color[0] & 1, color1 = color[1] & 1, color2 = color[2] & 1, color3 = color[3] & 1;
if (img_width == img_stride * 8) {
img_width *= img_height;
img_height = 1;
}
color0 = (color0 << 3) | (color1 << 2) | (color2 << 1) | color3;
color0 = (color0 << 4) | color0;
color3 = (color0 << 1) | (color0 >> 7);
color2 = (color0 << 2) | (color0 >> 6);
color1 = (color0 << 3) | (color0 >> 5);
bcolor0 = (img_bitoff & 2) ? ((img_bitoff & 1) ? color3 : color2) : ((img_bitoff & 1) ? color1 : color0);
color0 = (bcolor0 << 24) | (bcolor0 << 16) | (bcolor0 << 8) | bcolor0;
dcolor = vis_to_double_dup(color0);
for (i = 0, j = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end;
if (img_bitoff + img_width <= 8) {
bmask = (0xFF >> (8 - img_width)) << (8 - img_bitoff - img_width);
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
continue;
}
else {
bmask = 0xFF >> img_bitoff;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
pimg_row++;
j = 8 - img_bitoff;
b_j = (img_width - j) / 8;
}
if (b_j < 16) {
mlib_s32 ii;
for (ii = 0; ii < b_j; ii++)
pimg_row[ii] = bcolor0;
pimg_row += ii;
j += ii << 3;
if (j < img_width) {
bmask = (0xFF << (8 - (img_width - j))) & 0xFF;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
}
continue;
}
pimg_row_end = pimg_row + b_j - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge8(pimg_row, pimg_row_end);
vis_pst_8(dcolor, dpimg++, emask);
k = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; k < (b_j - 8); k += 8)
*dpimg++ = dcolor;
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor, dpimg, emask);
j += b_j << 3;
if (j < img_width) {
pimg_row = (mlib_u8 *) (pimg_row_end + 1);
bmask = (0xFF << (8 - (img_width - j))) & 0xFF;
src = pimg_row[0];
pimg_row[0] = (src & ~bmask) | (color0 & bmask);
}
}
}
/***************************************************************/
void mlib_v_ImageClear_U8_1(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFF;
PREPAREVARS(mlib_u8, 1);
if (img_width < 16) {
STRIP(pimg, color, img_width, img_height, 1, mlib_u8);
return;
}
color0 |= (color0 << 8);
color0 |= (color0 << 16);
dcolor = vis_to_double_dup(color0);
for (i = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge8(pimg_row, pimg_row_end);
vis_pst_8(dcolor, dpimg++, emask);
j = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; j < (img_width - 8); j += 8)
*dpimg++ = dcolor;
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_U8_2(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFF, color1 = color[1] & 0xFF;
mlib_d64 dcolor0;
PREPAREVARS(mlib_u8, 2);
if (img_width < 8) {
STRIP(pimg, color, img_width, img_height, 2, mlib_u8);
return;
}
color0 = (color0 << 8) | color1;
color0 |= (color0 << 16);
dcolor0 = vis_to_double_dup(color0);
for (i = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 2 - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge8(pimg_row, pimg_row_end);
dcolor = vis_faligndata(dcolor0, dcolor0);
vis_pst_8(dcolor, dpimg++, emask);
j = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; j < (img_width * 2 - 8); j += 8)
*dpimg++ = dcolor;
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_U8_3(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFF, color1 = color[1] & 0xFF, color2 = color[2] & 0xFF, col;
mlib_d64 dcolor1, dcolor2, dcolor00, dcolor11, dcolor22;
PREPAREVARS(mlib_u8, 3);
if (img_width < 16) {
STRIP(pimg, color, img_width, img_height, 3, mlib_u8);
return;
}
col = (color0 << 16) | (color1 << 8) | color2;
color0 = (col << 8) | color0;
color1 = (color0 << 8) | color1;
color2 = (color1 << 8) | color2;
dcolor = vis_to_double(color0, color1);
dcolor1 = vis_to_double(color2, color0);
dcolor2 = vis_to_double(color1, color2);
for (i = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 3 - 1;
dpimg = (mlib_d64 *) ((mlib_addr) pimg_row & ~7);
vis_alignaddr((void *)(-(mlib_addr) pimg_row), 8);
dcolor22 = vis_faligndata(dcolor2, dcolor);
dcolor00 = vis_faligndata(dcolor, dcolor1);
dcolor11 = vis_faligndata(dcolor1, dcolor2);
emask = vis_edge8(pimg_row, pimg_row_end);
if ((mlib_addr) pimg_row & 7)
vis_pst_8(dcolor22, dpimg++, emask);
j = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; j < (img_width * 3 - 24); j += 24) {
dpimg[0] = dcolor00;
dpimg[1] = dcolor11;
dpimg[2] = dcolor22;
dpimg += 3;
}
if (j < (img_width * 3 - 8)) {
*dpimg++ = dcolor00;
if (j < (img_width * 3 - 16)) {
*dpimg++ = dcolor11;
dcolor00 = dcolor22;
}
else
dcolor00 = dcolor11;
}
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor00, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_U8_4(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFF, color1 = color[1] & 0xFF, color2 = color[2] & 0xFF, color3 = color[3] & 0xFF;
mlib_d64 dcolor0;
PREPAREVARS(mlib_u8, 4);
if (img_width < 4) {
STRIP(pimg, color, img_width, img_height, 4, mlib_u8);
return;
}
color0 = (color0 << 24) | (color1 << 16) | (color2 << 8) | color3;
dcolor0 = vis_to_double_dup(color0);
for (i = 0; i < img_height; i++) {
mlib_u8 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 4 - 1;
dpimg = (mlib_d64 *) ((mlib_addr) pimg_row & ~7);
vis_alignaddr((void *)(-(mlib_addr) pimg_row), 8);
emask = vis_edge8(pimg_row, pimg_row_end);
dcolor = vis_faligndata(dcolor0, dcolor0);
vis_pst_8(dcolor, dpimg++, emask);
j = (mlib_addr) dpimg - (mlib_addr) pimg_row;
for (; j < (img_width * 4 - 8); j += 8)
*dpimg++ = dcolor;
emask = vis_edge8(dpimg, pimg_row_end);
vis_pst_8(dcolor, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_S16_1(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFFFF;
PREPAREVARS(mlib_s16, 1);
if (img_width < 8) {
STRIP(pimg, color, img_width, img_height, 1, mlib_s16);
return;
}
color0 |= (color0 << 16);
dcolor = vis_to_double_dup(color0);
for (i = 0; i < img_height; i++) {
mlib_s16 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge16(pimg_row, pimg_row_end);
vis_pst_16(dcolor, dpimg++, emask);
j = (mlib_s16 *) dpimg - pimg_row;
for (; j < (img_width - 4); j += 4)
*dpimg++ = dcolor;
emask = vis_edge16(dpimg, pimg_row_end);
vis_pst_16(dcolor, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_S16_2(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFFFF, color1 = color[1] & 0xFFFF;
mlib_d64 dcolor0;
PREPAREVARS(mlib_s16, 2);
if (img_width < 4) {
STRIP(pimg, color, img_width, img_height, 2, mlib_s16);
return;
}
color0 = (color0 << 16) | color1;
dcolor0 = vis_to_double_dup(color0);
for (i = 0; i < img_height; i++) {
mlib_s16 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 2 - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge16(pimg_row, pimg_row_end);
dcolor = vis_faligndata(dcolor0, dcolor0);
vis_pst_16(dcolor, dpimg++, emask);
j = (mlib_s16 *) dpimg - pimg_row;
for (; j < (img_width * 2 - 4); j += 4)
*dpimg++ = dcolor;
emask = vis_edge16(dpimg, pimg_row_end);
vis_pst_16(dcolor, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_S16_3(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFFFF, color1 = color[1] & 0xFFFF, color2 = color[2] & 0xFFFF, col0, col1, col2;
mlib_d64 dcolor1, dcolor2, dcolor00, dcolor11, dcolor22;
PREPAREVARS(mlib_s16, 3);
if (img_width < 8) {
STRIP(pimg, color, img_width, img_height, 3, mlib_s16);
return;
}
col0 = (color0 << 16) | color1;
col1 = (color2 << 16) | color0;
col2 = (color1 << 16) | color2;
dcolor = vis_to_double(col0, col1);
dcolor1 = vis_to_double(col2, col0);
dcolor2 = vis_to_double(col1, col2);
for (i = 0; i < img_height; i++) {
mlib_s16 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 3 - 1;
dpimg = (mlib_d64 *) ((mlib_addr) pimg_row & ~7);
vis_alignaddr((void *)(-(mlib_addr) pimg_row), 8);
dcolor22 = vis_faligndata(dcolor2, dcolor);
dcolor00 = vis_faligndata(dcolor, dcolor1);
dcolor11 = vis_faligndata(dcolor1, dcolor2);
emask = vis_edge16(pimg_row, pimg_row_end);
if ((mlib_addr) pimg_row & 7)
vis_pst_16(dcolor22, dpimg++, emask);
j = (mlib_s16 *) dpimg - pimg_row;
for (; j < (img_width * 3 - 12); j += 12) {
dpimg[0] = dcolor00;
dpimg[1] = dcolor11;
dpimg[2] = dcolor22;
dpimg += 3;
}
if (j < (img_width * 3 - 4)) {
*dpimg++ = dcolor00;
if (j < (img_width * 3 - 8)) {
*dpimg++ = dcolor11;
dcolor00 = dcolor22;
}
else
dcolor00 = dcolor11;
}
emask = vis_edge16(dpimg, pimg_row_end);
vis_pst_16(dcolor00, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_S16_4(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0] & 0xFFFF, color1 = color[1] & 0xFFFF, color2 = color[2] & 0xFFFF, color3 = color[3] & 0xFFFF;
mlib_d64 dcolor0;
PREPAREVARS(mlib_s16, 4);
if (img_width < 2) {
STRIP(pimg, color, img_width, img_height, 4, mlib_s16);
return;
}
color0 = (color0 << 16) | color1;
color1 = (color2 << 16) | color3;
dcolor0 = vis_to_double(color0, color1);
for (i = 0; i < img_height; i++) {
mlib_s16 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 4 - 1;
dpimg = (mlib_d64 *) ((mlib_addr) pimg_row & ~7);
vis_alignaddr((void *)(-(mlib_addr) pimg_row), 8);
emask = vis_edge16(pimg_row, pimg_row_end);
dcolor = vis_faligndata(dcolor0, dcolor0);
vis_pst_16(dcolor, dpimg++, emask);
j = (mlib_s16 *) dpimg - pimg_row;
for (; j < (img_width * 4 - 4); j += 4)
*dpimg++ = dcolor;
emask = vis_edge16(dpimg, pimg_row_end);
vis_pst_16(dcolor, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_S32_1(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0];
PREPAREVARS(mlib_s32, 1);
if (img_width < 4) {
STRIP(pimg, color, img_width, img_height, 1, mlib_s32);
return;
}
dcolor = vis_to_double_dup(color0);
for (i = 0; i < img_height; i++) {
mlib_s32 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge32(pimg_row, pimg_row_end);
vis_pst_32(dcolor, dpimg++, emask);
j = (mlib_s32 *) dpimg - pimg_row;
for (; j <= (img_width - 2); j += 2)
*dpimg++ = dcolor;
if (j < img_width) {
emask = vis_edge32(dpimg, pimg_row_end);
vis_pst_32(dcolor, dpimg, emask);
}
}
}
/***************************************************************/
void mlib_v_ImageClear_S32_2(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0], color1 = color[1];
mlib_d64 dcolor0;
PREPAREVARS(mlib_s32, 2);
if (img_width < 2) {
STRIP(pimg, color, img_width, img_height, 2, mlib_s32);
return;
}
dcolor0 = vis_to_double(color0, color1);
for (i = 0; i < img_height; i++) {
mlib_s32 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 2 - 1;
dpimg = (mlib_d64 *) vis_alignaddr(pimg_row, 0);
emask = vis_edge32(pimg_row, pimg_row_end);
dcolor = vis_faligndata(dcolor0, dcolor0);
vis_pst_32(dcolor, dpimg++, emask);
j = (mlib_s32 *) dpimg - pimg_row;
for (; j < (img_width * 2 - 2); j += 2)
*dpimg++ = dcolor;
emask = vis_edge32(dpimg, pimg_row_end);
vis_pst_32(dcolor, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_S32_3(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0], color1 = color[1], color2 = color[2];
mlib_d64 dcolor1, dcolor2, dcolor00, dcolor11, dcolor22;
PREPAREVARS(mlib_s32, 3);
if (img_width < 2) {
STRIP(pimg, color, img_width, img_height, 3, mlib_s32);
return;
}
dcolor = vis_to_double(color0, color1);
dcolor1 = vis_to_double(color2, color0);
dcolor2 = vis_to_double(color1, color2);
for (i = 0; i < img_height; i++) {
mlib_s32 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 3 - 1;
dpimg = (mlib_d64 *) ((mlib_addr) pimg_row & ~7);
vis_alignaddr((void *)(-(mlib_addr) pimg_row), 8);
dcolor22 = vis_faligndata(dcolor2, dcolor);
dcolor00 = vis_faligndata(dcolor, dcolor1);
dcolor11 = vis_faligndata(dcolor1, dcolor2);
emask = vis_edge32(pimg_row, pimg_row_end);
if ((mlib_addr) pimg_row & 7)
vis_pst_32(dcolor22, dpimg++, emask);
j = (mlib_s32 *) dpimg - pimg_row;
for (; j < (img_width * 3 - 6); j += 6) {
dpimg[0] = dcolor00;
dpimg[1] = dcolor11;
dpimg[2] = dcolor22;
dpimg += 3;
}
if (j < (img_width * 3 - 2)) {
*dpimg++ = dcolor00;
if (j < (img_width * 3 - 4)) {
*dpimg++ = dcolor11;
dcolor00 = dcolor22;
}
else
dcolor00 = dcolor11;
}
emask = vis_edge32(dpimg, pimg_row_end);
vis_pst_32(dcolor00, dpimg, emask);
}
}
/***************************************************************/
void mlib_v_ImageClear_S32_4(mlib_image *img,
const mlib_s32 *color)
{
mlib_u32 color0 = color[0], color1 = color[1], color2 = color[2], color3 = color[3];
mlib_d64 dcolor0, dcolor00, dcolor0_, dcolor00_, dcolor1;
PREPAREVARS(mlib_s32, 4);
if (img_width < 2) {
STRIP(pimg, color, img_width, img_height, 4, mlib_s32);
return;
}
dcolor0 = vis_to_double(color2, color3);
dcolor00 = vis_to_double(color0, color1);
vis_alignaddr((void *)0, 4);
dcolor0_ = vis_faligndata(dcolor0, dcolor00);
dcolor00_ = vis_faligndata(dcolor00, dcolor0);
for (i = 0; i < img_height; i++) {
mlib_s32 *pimg_row = pimg + i * img_stride, *pimg_row_end = pimg_row + img_width * 4 - 1;
dpimg = (mlib_d64 *) ((mlib_addr) pimg_row & ~7);
vis_alignaddr((void *)(-(mlib_addr) pimg_row), 4);
emask = vis_edge32(pimg_row, pimg_row_end);
dcolor = vis_faligndata(dcolor0_, dcolor00_);
dcolor1 = vis_faligndata(dcolor00_, dcolor0_);
vis_pst_32(dcolor, dpimg++, emask);
*dpimg++ = dcolor1;
j = (mlib_s32 *) dpimg - pimg_row;
for (; j <= (img_width * 4 - 4); j += 4) {
dpimg[0] = dcolor;
dpimg[1] = dcolor1;
dpimg += 2;
}
if (j < (img_width * 4)) {
emask = vis_edge32(dpimg, pimg_row_end);
vis_pst_32(dcolor, dpimg, emask);
}
}
}
/***************************************************************/
| {
"pile_set_name": "Github"
} |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RGoplot(RPackage):
"""Implementation of multilayered visualizations for enhanced graphical
representation of functional analysis data. It combines and integrates
omics data derived from expression and functional annotation enrichment
analyses. Its plotting functions have been developed with an
hierarchical structure in mind: starting from a general overview to
identify the most enriched categories (modified bar plot, bubble plot)
to a more detailed one displaying different types of relevant
information for the molecules in a given set of categories
(circle plot, chord plot, cluster plot, Venn diagram, heatmap)."""
homepage = "https://github.com/wencke/wencke.github.io/issues"
url = "https://cloud.r-project.org/src/contrib/GOplot_1.0.2.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/GOplot"
version('1.0.2', sha256='3ddaa2b6d1297ad6daad30d18af708adf43d86e8804b1b92fa29dfbf26d80df9')
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
| {
"pile_set_name": "Github"
} |
#!/bin/bash
# Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
export WORLD_SIZE=4
python -m torch.distributed.launch --nnodes=2 --node_rank=0 --nproc_per_node=2 --master_addr="30.57.186.244" --master_port=333 \
train.py \
--use-fp16 \
--nhwc \
--pad-input \
--jit \
--delay-allreduce \
--opt-loss \
--epochs 1 \
--warmup-factor 0 \
--no-save \
--threshold=0.23 \
--data coco \
--evaluation 120000 160000 180000 200000 220000 240000 260000 280000
| {
"pile_set_name": "Github"
} |
<?php
//CURL_MULTI_GETCONTENT TEST
//CREATE RESOURCES
$ch1=curl_init();
$ch2=curl_init();
//SET URL AND OTHER OPTIONS
include 'server.inc';
$host = curl_cli_server_start();
curl_setopt($ch1, CURLOPT_URL, "{$host}/get.php?test=getpost&get_param=Hello%20World");
curl_setopt($ch2, CURLOPT_URL, "file://".dirname(__FILE__). DIRECTORY_SEPARATOR . "curl_testdata2.txt");
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
//CREATE MULTIPLE CURL HANDLE
$mh=curl_multi_init();
//ADD THE 2 HANDLES
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);
//EXECUTE
$running=0;
do {
curl_multi_exec($mh,$running);
} while ($running>0);
$results1=curl_multi_getcontent($ch1);
$results2=curl_multi_getcontent($ch2);
//CLOSE
curl_multi_remove_handle($mh,$ch1);
curl_multi_remove_handle($mh,$ch2);
curl_multi_close($mh);
echo $results1;
echo $results2;
?>
| {
"pile_set_name": "Github"
} |
#####################################################
# Olimex LPC2378STK eval board
#
# http://olimex.com/dev/lpc-2378stk.html
#
# Author: Sten, [email protected]
#####################################################
#
source [find target/lpc2378.cfg]
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright 2019 Broadcom.
*/
#ifndef BCM_HWRNG_H
#define BCM_HWRNG_H
#include <stdlib.h>
uint32_t bcm_hwrng_read_rng(uint32_t *p_out, uint32_t words_to_read);
#endif /* BCM_HWRNG_H */
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2011 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import INST from './INST'
import I18n from 'i18n!ajax_errors'
import $ from 'jquery'
import htmlEscape from './str/htmlEscape'
import './jquery.ajaxJSON' // ajaxJSON, defaultAjaxError
import 'compiled/jquery.rails_flash_notifications' // flashError
INST.errorCount = 0
window.onerror = function(msg, url, line, column, errorObj) {
INST.errorCount += 1
}
// puts the little red box when something bad happens in ajax.
$(document).ready(function() {
$('#instructure_ajax_error_result').defaultAjaxError(function(
event,
request,
settings,
error,
debugOnly
) {
if (error === 'abort') return
let status = '0'
let text = I18n.t('no_text', 'No text')
try {
status = request.status
text = request.responseText
} catch (e) {}
$.ajaxJSON(
location.protocol +
'//' +
location.host +
'/simple_response.json?rnd=' +
Math.round(Math.random() * 9999999),
'GET',
{},
() => {
if ($.ajaxJSON.isUnauthenticated(request)) {
let message = htmlEscape(
I18n.t(
'errors.logged_out',
'You are not currently logged in, possibly due to a long period of inactivity.'
)
)
message +=
"<br/><a href='/login' id='inactivity_login_link' target='_new'>" +
htmlEscape(I18n.t('links.login', 'Login')) +
'</a>'
$.flashError({html: message}, 30000)
$('#inactivity_login_link').focus()
} else if (status != 409) {
ajaxErrorFlash(
I18n.t('errors.unhandled', "Oops! The last request didn't work out."),
request
)
}
},
() => {
ajaxErrorFlash(
I18n.t(
'errors.connection_lost',
"Connection to %{host} was lost. Please make sure you're connected to the Internet and try again.",
{host: location.host}
),
request
)
},
{skipDefaultError: true}
)
const $obj = $(this)
var ajaxErrorFlash = function(message, xhr) {
const i = $obj[0]
if (!i) {
return
}
const d =
i.contentDocument ||
(i.contentWindow && i.contentWindow.document) ||
window.frames[$obj.attr('id')].document
const $body = $(d).find('body')
$body.html(
$('<h1 />').text(
I18n.t('error_heading', 'Ajax Error: %{status_code}', {status_code: status})
)
)
$body.append(htmlEscape(text))
$('#instructure_ajax_error_box').hide()
const pre = ''
message = htmlEscape(message)
if (debugOnly) {
message += "<br/><span style='font-size: 0.7em;'>(Development Only)</span>"
}
if (debugOnly || INST.environment != 'production') {
message +=
"<br/><a href='#' class='last_error_details_link'>" +
htmlEscape(I18n.t('links.details', 'details...')) +
'</a>'
}
$.flashError({html: message})
}
window.ajaxErrorFlash = ajaxErrorFlash
let data = $.ajaxJSON.findRequest(request)
data = data || {}
if (data.data) {
data.params = ''
for (const name in data.data) {
data.params += '&' + name + '=' + data.data[name]
}
}
let username = ''
try {
username = $('#identity .user_name').text()
} catch (e) {}
if (INST.ajaxErrorURL) {
const txt =
'&Msg=' +
escape(text) +
'&StatusCode=' +
escape(status) +
'&URL=' +
escape(data.url || 'unknown') +
'&Page=' +
escape(location.href) +
'&Method=' +
escape(data.submit_type || 'unknown') +
'&UserName=' +
escape(username) +
'&Platform=' +
escape(navigator.platform) +
'&UserAgent=' +
escape(navigator.userAgent) +
'&Params=' +
escape(data.params || 'unknown')
$('body').append(
"<img style='position: absolute; left: -1000px; top: 0;' src='" +
htmlEscape(INST.ajaxErrorURL + txt.substring(0, 2000)) +
"' />"
)
}
})
$('.last_error_details_link').live('click', event => {
event.preventDefault()
event.stopPropagation()
$('#instructure_ajax_error_box').show()
})
$('.close_instructure_ajax_error_box_link').click(event => {
event.preventDefault()
$('#instructure_ajax_error_box').hide()
})
})
| {
"pile_set_name": "Github"
} |
{
"type": "bundle",
"id": "bundle--5fbdbb6d-3e22-400f-be7c-8492bdd5342c",
"spec_version": "2.0",
"objects": [
{
"created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",
"object_marking_refs": [
"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168"
],
"source_ref": "malware--cc5497f7-a9e8-436f-94da-b2b4a9b9ad3c",
"target_ref": "attack-pattern--00f90846-cbd1-4fc5-9233-df5c2bf2a662",
"external_references": [
{
"source_name": "Talos PoetRAT April 2020",
"url": "https://blog.talosintelligence.com/2020/04/poetrat-covid-19-lures.html",
"description": "Mercer, W, et al. (2020, April 16). PoetRAT: Python RAT uses COVID-19 lures to target Azerbaijan public and private sectors. Retrieved April 27, 2020."
}
],
"description": "[PoetRAT](https://attack.mitre.org/software/S0428) has the ability to compress files with zip.(Citation: Talos PoetRAT April 2020)",
"relationship_type": "uses",
"id": "relationship--f64733fd-acc7-4570-90ee-79c117c37d7e",
"type": "relationship",
"modified": "2020-04-28T14:37:51.446Z",
"created": "2020-04-28T12:47:25.946Z"
}
]
} | {
"pile_set_name": "Github"
} |
var r = 600;
function baseVisual(parent) {
var that = {};
that.getColor = function (node) {
if (node.currentState) {
return '#ff0000';
}
return '#fff';
};
that.getOpacity = function (node) {
if (node.currentState) {
return '.7';
}
return '0';
};
that.reLayout = function (n, size, yOffset, transpose) {
var counts = [];
n.forEach(function (d) {
if (!counts[d.depth]) {
counts[d.depth] = 1;
} else {
++counts[d.depth];
}
d.order = counts[d.depth] - 1;
});
n.forEach(function (d) {
var xSize = size / counts[d.depth];
if (transpose) {
d.x = d.y + yOffset;
d.y = d.order * xSize + xSize / 2;
} else {
d.x = d.order * xSize + xSize / 2;
d.y = d.y + yOffset;
}
});
};
that.getTitle = function (node) {
var displayEntries = '';
if (node.currentState) {
for (var propertyName in node.currentState) {
if (propertyName !== 'id') {
displayEntries = displayEntries + '\t' + propertyName + ':\t' + node.currentState[propertyName] + '\n';
}
}
return displayEntries;
}
return '';
};
return that;
}
function stateVisual(root, links, x, y, title, parent, state, base) {
var base = base || baseVisual(parent);
var that = {};
var selectedLink = null;
var zoomedLink = null;
var pSize = 150;
var tTime = 0;
var k = x(r) - x(0);
k = k / r;
var n = d3.layout.pack()
.size([r, r])
.padding(100)
.value(function (d) { return d.size; })
.nodes(root);
n.forEach(function (d) { d.y = d.y + 25; });
parent.append('svg:defs').append('svg:marker')
.attr('id', 'end-arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 6)
.attr('markerWidth', 6)
.attr('markerHeight', 6)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-5L10,0L0,5')
.attr('fill', '#ccc');
var circle = parent.append('svg:g')
.selectAll('g')
.data(n);
var path = parent.append('svg:g')
.selectAll('path')
.data(links);
var pathText = parent.append('svg:g')
.selectAll('text')
.data(links);
if (title) {
var titleText = parent.append('svg:text')
.attr('class', 'time label')
.attr('x', function (d) { return x(30); })
.attr('y', function (d) { return y(45); })
.style('font-size', 40 * k + 'px')
.text(title);
}
var popup = parent.append('svg:g')
.selectAll('g')
.data(links);
that.update = function (transitionTime) {
tTime = transitionTime || 0;
path.transition()
.duration(tTime)
.attr('d', drawLink);
circle.selectAll('circle').transition()
.duration(tTime)
.attr('cx', function (d) { return x(d.x); })
.attr('cy', function (d) { return y(d.y); })
.attr('r', function (d) { return k * d.r; })
.style('fill', base.getColor)
.style('fill-opacity', base.getOpacity);
circle.selectAll('title')
.text(base.getTitle);
circle.selectAll('text')
.transition()
.duration(tTime)
.attr('x', function (d) { return x(d.x); })
.attr('y', function (d) { return y(d.y); })
.style('font-size', function (d) { return 12 * k + 'px'; });
popup.selectAll('rect[tag=\'smPopupBack\']')
.transition()
.duration(tTime)
.attr('x', function (d) { return x(d.$refX) + 4; })
.attr('y', function (d) { return y(d.$refY) + 4; })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
popup.selectAll('rect[tag=\'smPopup\']')
.transition()
.duration(tTime)
.attr('x', function (d) { return x(d.$refX); })
.attr('y', function (d) { return y(d.$refY); })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
popup.each(updateTransition);
};
var updateSelection = function (d) {
popup.style('opacity', function (d1) {
if (d1 === d) {
if (selectedLink === d) {
selectedLink = null;
return '0';
} else {
selectedLink = d;
return '1';
}
}
return '0';
});
path.classed('selected', function (d) { return d === selectedLink; })
popup.selectAll('rect[tag=\'smPopupBack\']')
.attr('x', function (d) { return x(d.$refX) + 4; })
.attr('y', function (d) { return y(d.$refY) + 4; })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
popup.selectAll('rect[tag=\'smPopup\']')
.attr('x', function (d) { return x(d.$refX); })
.attr('y', function (d) { return y(d.$refY); })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
d3.event.stopPropagation();
};
var drawLink = function (d) {
var sourceX, sourceY, targetX, targetY, refX, refY;
if (d.reflexive) {
sourceX = d.source.x;
sourceY = d.source.y - d.source.r;
targetX = d.source.x + d.source.r;
targetY = d.source.y;
refX = d.source.x + d.source.r * (1 + (d.order + 1) * 0.4);
refY = d.source.y - d.source.r * (1 + (d.order + 1) * 0.4);
d.$refX = d.source.x + d.source.r * (1 + d.order * 0.2);
d.$refY = d.source.y - d.source.r * (1 + d.order * 0.2);
} else if (d.target) {
var deltaX = Math.abs(d.target.x - d.source.x),
deltaY = Math.abs(d.target.y - d.source.y),
dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
orderFactor = (d.order % 2 ? -1 : 1) * (Math.floor(d.order / 2) + 1),
angle = Math.atan(deltaY / deltaX);
refX = Math.cos(angle) * dist / 2 * (d.source.x > d.target.x ? -1 : 1) + Math.sin(angle) * dist * orderFactor / 8 * (d.source.y < d.target.y ? -1 : 1) + d.source.x;
refY = Math.sin(angle) * dist / 2 * (d.source.y > d.target.y ? -1 : 1) + Math.cos(angle) * dist * orderFactor / 8 * (d.source.x > d.target.x ? -1 : 1) + d.source.y;
var deltaSourceX = Math.abs(refX - d.source.x),
deltaSourceY = Math.abs(refY - d.source.y),
sourceAngle = Math.atan(Math.abs(deltaSourceY / deltaSourceX)),
deltaTargetX = Math.abs(refX - d.target.x),
deltaTargetY = Math.abs(refY - d.target.y),
targetAngle = Math.atan(Math.abs(deltaTargetY / deltaTargetX)),
sourceR = d.left ? d.source.r : d.source.r,
targetR = d.right ? d.target.r + 5 : d.target.r + 5;
sourceX = d.source.x + Math.cos(sourceAngle) * sourceR * (d.source.x === d.target.x ? (d.source.y > d.target.y ? -1 : 1) : d.source.x > d.target.x ? -1 : 1);
sourceY = d.source.y + Math.sin(sourceAngle) * sourceR * (d.source.y === d.target.y ? (d.source.x > d.target.x ? -1 : 1) : d.source.y > d.target.y ? -1 : 1);
targetX = d.target.x + Math.cos(targetAngle) * targetR * (d.source.x === d.target.x ? (d.source.y > d.target.y ? -1 : 1) : d.source.x > d.target.x ? 1 : -1);
targetY = d.target.y + Math.sin(targetAngle) * targetR * (d.source.y === d.target.y ? (d.source.x > d.target.x ? -1 : 1) : d.source.y > d.target.y ? 1 : -1);
d.$refX = refX;
d.$refY = refY;
} else {
return '';
}
d.$startX = sourceX;
d.$startY = sourceY;
return 'M' + x(sourceX) + ',' + y(sourceY) + 'Q' + x(refX) + ',' + y(refY) + ',' + x(targetX) + ',' + y(targetY);
};
var zoom = function (d) {
if (zoomedLink !== d) {
x = d3.scale.linear().range([25 * k, (r - 25) * k]);
y = d3.scale.linear().range([25 * k, (r - 25) * k]);
x.domain([d.$refX, d.$refX + pSize]);
y.domain([d.$refY, d.$refY + pSize]);
k = k * (r - 50) / pSize;
zoomedLink = d;
that.update(1000);
} else {
k = (k * pSize) / (r - 50);
x = d3.scale.linear().range([0, r * k]);
y = d3.scale.linear().range([0, r * k]);
x.domain([0, r]);
y.domain([0, r]);
zoomedLink = null;
that.update(1000);
}
d3.event.stopPropagation();
};
var drawTransition = function (d) {
if (d.nodes) {
var newX = d3.scale.linear().range([x(d.$refX), x(d.$refX + pSize)]);
var newY = d3.scale.linear().range([y(d.$refY), y(d.$refY + pSize)]);
newX.domain([0, r]);
newY.domain([0, r + 50]);
d.update = ruleVisual(d.nodes[0], d.links, newX, newY, d.id, d3.select(this), false, base).update;
}
};
var updateTransition = function (d) {
if (d.nodes) {
var newX = d3.scale.linear().range([x(d.$refX), x(d.$refX + pSize)]);
var newY = d3.scale.linear().range([y(d.$refY), y(d.$refY + pSize)]);
newX.domain([0, r]);
newY.domain([0, r + 50]);
d.update(tTime, newX, newY);
}
};
path.enter()
.append('svg:path')
.attr('class', 'link')
.attr('id', function (d) { return d.source.id + d.id; })
.style('marker-end', function (d) { return 'url(#end-arrow)'; })
.on('click', updateSelection)
.attr('d', drawLink);
pathText.enter()
.append('svg:text')
.attr('class', 'linkDisplay')
.attr('dy', -5)
.on('click', updateSelection)
.append('svg:textPath')
.attr('xlink:href', function (d) { return '#' + d.source.id + d.id })
.attr('startOffset', '5%')
.text(function (d) { return d.id })
.style('font-size', function (d) { return 12 * k + 'px'; });
var g = circle.enter().append('svg:g');
g.append('svg:circle')
.attr('class', 'node')
.attr('cx', function (d) { return x(d.x); })
.attr('cy', function (d) { return y(d.y); })
.attr('r', function (d) { return k * d.r })
.style('opacity', function (d) { return (d === root) ? '0' : '1'; });
g.append('title');
g.append('svg:text')
.attr('class', 'id')
.attr('text-anchor', 'middle')
.attr('x', function (d) { return x(d.x); })
.attr('y', function (d) { return y(d.y); })
.text(function (d) { return d.id; })
.style('font-size', function (d) { return 12 * k + 'px'; });
g = popup.enter()
.append('svg:g')
.style('opacity', '0');
g.append('svg:rect')
.attr('class', 'popupBack')
.attr('tag', 'smPopupBack');
g.append('svg:rect')
.attr('class', 'popup')
.attr('tag', 'smPopup')
.on('click', zoom);
popup.each(drawTransition);
state.onStateChanged(function () {
that.update(500)
});
d3.select(window).on('click', function () {
if (zoomedLink !== null) {
zoom(zoomedLink);
} else if (selectedLink !== null) {
updateSelection(selectedLink);
}
});
return that;
}
function flowVisual(root, links, x, y, title, parent, state, base) {
var base = base || baseVisual(parent);
var that = {};
var selectedLink = null;
var zoomedLink = null;
var pSize = 150;
var tTime = 0;
var k = x(r) - x(0);
k = k / r;
var n = d3.layout.tree()
.size([r, r])
.nodes(root);
base.reLayout(n, r, 45);
parent.append('svg:defs').append('svg:marker')
.attr('id', 'end-arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 6)
.attr('markerWidth', 6)
.attr('markerHeight', 6)
.attr('orient', 'auto')
.append('svg:path')
.attr('tag', 'arrow')
.attr('d', 'M0,-5L10,0L0,5')
.attr('fill', '#ccc');
var path = parent.append('svg:g')
.selectAll('path')
.data(links);
var pathText = parent.append('svg:g')
.selectAll('text')
.data(links);
var step = parent.append('svg:g')
.selectAll('g')
.data(n);
if (title) {
var titleText = parent.append('svg:text')
.attr('class', 'time label')
.attr('x', function (d) { return x(30); })
.attr('y', function (d) { return y(45); })
.style('font-size', 40 * k + 'px')
.text(title);
}
var popup = parent.append('svg:g')
.selectAll('g')
.data(links);
var getSource = function (d) {
var deltaX = Math.abs(d.target.x - d.source.x),
deltaY = Math.abs(d.target.y - d.source.y),
sourceR = d.source.r / 2 + 2,
sourceX = d.source.x,
sourceY = d.source.y;
// aligned vertically,
if (!deltaX) {
// only if pointing upwards
if (d.source.y > d.target.y) {
// offset the origin
sourceX += sourceR;
}
} else {
//if source on the right
if (d.source.x > d.target.x) {
sourceX -= sourceR;
} else {
sourceX += sourceR;
}
}
// not a switch
if (!d.source.condition) {
// not aligned vertically or pointing downwards
if (deltaX || (d.source.y < d.target.y)) {
//if source below
if (d.source.y > d.target.y) {
sourceY -= sourceR;
} else {
sourceY += sourceR;
}
}
} else {
// aligned vertically and pointing downwards
if (!deltaX && (d.source.y < d.target.y)) {
//if source below
if (d.source.y > d.target.y) {
sourceY -= sourceR;
} else {
sourceY += sourceR;
}
}
}
d.$refX = d.source.x + (d.target.x - d.source.x)/2;
d.$refY = d.source.y + (d.target.y - d.source.y)/2;
return { x: x(sourceX), y: y(sourceY) };
}
var getTarget = function (d) {
var deltaX = Math.abs(d.target.x - d.source.x),
deltaY = Math.abs(d.target.y - d.source.y),
targetR = d.target.r / 2 + 2,
targetX = d.target.x + targetR * ((!deltaX && d.source.y > d.target.y) ? 1 : 0),
targetY = d.target.y + targetR * (d.source.y > d.target.y ? 1 : -1);
return { x: x(targetX), y: y(targetY) };
}
var diagonal = d3.svg.diagonal()
.source(getSource)
.target(getTarget);
that.update = function (transitionTime) {
tTime = transitionTime || 0;
path.transition()
.duration(tTime)
.attr('d', diagonal);
step.selectAll('rect').transition()
.duration(tTime)
.attr('x', function (d) { return x(d.x - d.r / 2 / ((d.condition) ? Math.sqrt(2) : 1)); })
.attr('y', function (d) { return y(d.y - d.r / 2 / ((d.condition) ? Math.sqrt(2) : 1)); })
.attr('height', function (d) { return (d.r / ((d.condition) ? Math.sqrt(2) : 1)) * k; })
.attr('width', function (d) { return (d.r / ((d.condition) ? Math.sqrt(2) : 1)) * k; })
.style('fill', base.getColor)
.style('fill-opacity', base.getOpacity)
.attr('transform', function (d) { return (d.condition) ? 'rotate(45,' + x(d.x) + ',' + y(d.y) + ')' : ''; });
step.selectAll('title')
.text(base.getTitle);
step.selectAll('text')
.transition()
.duration(tTime)
.attr('x', function (d) { return x(d.x); })
.attr('y', function (d) { return y(d.y + 3); })
.style('font-size', function (d) { return 12 * k + 'px'; });
popup.selectAll('rect[tag=\'fcPopupBack\']')
.transition()
.duration(tTime)
.attr('x', function (d) { return x(d.$refX) + 4; })
.attr('y', function (d) { return y(d.$refY) + 4; })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
popup.selectAll('rect[tag=\'fcPopup\']')
.transition()
.duration(tTime)
.attr('x', function (d) { return x(d.$refX); })
.attr('y', function (d) { return y(d.$refY); })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
popup.each(updateTransition);
}
var updateSelection = function (d) {
popup.style('opacity', function (d1) {
if (d1 === d) {
if (selectedLink === d) {
selectedLink = null;
return '0';
} else {
selectedLink = d;
return '1';
}
}
return '0';
});
path.classed('selected', function (d) { return d === selectedLink; })
popup.selectAll('rect[tag=\'fcPopupBack\']')
.attr('x', function (d) { return x(d.$refX) + 4; })
.attr('y', function (d) { return y(d.$refY) + 4; })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
popup.selectAll('rect[tag=\'fcPopup\']')
.attr('x', function (d) { return x(d.$refX); })
.attr('y', function (d) { return y(d.$refY); })
.attr('rx', 8 * k)
.attr('ry', 8 * k)
.attr('height', function (d) { return ((d === selectedLink) ? pSize * k : 0) })
.attr('width', function (d) { return ((d === selectedLink) ? pSize * k : 0) });
d3.event.stopPropagation();
};
var drawTransition = function (d) {
if (d.nodes) {
var newX = d3.scale.linear().range([x(d.$refX), x(d.$refX + pSize)]);
var newY = d3.scale.linear().range([y(d.$refY), y(d.$refY + pSize)]);
newX.domain([0, r]);
newY.domain([0, r + 50]);
d.update = ruleVisual(d.nodes[0], d.links, newX, newY, d.id, d3.select(this), false, base).update;
}
};
var updateTransition = function (d) {
if (d.nodes) {
var newX = d3.scale.linear().range([x(d.$refX), x(d.$refX + pSize)]);
var newY = d3.scale.linear().range([y(d.$refY), y(d.$refY + pSize)]);
newX.domain([0, r]);
newY.domain([0, r + 50]);
d.update(tTime, newX, newY);
}
};
var zoom = function (d) {
if (zoomedLink !== d) {
x = d3.scale.linear().range([25 * k, (r - 25) * k]);
y = d3.scale.linear().range([25 * k, (r - 25) * k]);
x.domain([d.$refX, d.$refX + pSize]);
y.domain([d.$refY, d.$refY + pSize]);
k = k * (r - 50) / pSize;
zoomedLink = d;
that.update(1000);
}
else {
k = (k * pSize) / (r - 50);
x = d3.scale.linear().range([0, r * k]);
y = d3.scale.linear().range([0, r * k]);
x.domain([0, r]);
y.domain([0, r]);
zoomedLink = null;
that.update(1000);
}
d3.event.stopPropagation();
};
path.enter()
.append('svg:path')
.attr('class', 'link')
.attr('id', function (d) { return d.source.x + '-' + d.source.y + '-' + d.target.x + '-' + d.target.y;})
.style('marker-end', function (d) { return 'url(#end-arrow)'; })
.on('click', updateSelection)
.attr('d', diagonal);
pathText.enter()
.append('svg:text')
.attr('class', 'linkDisplay')
.attr('dy', -5)
.on('click', updateSelection)
.append('svg:textPath')
.attr('xlink:href', function (d) { return '#' + d.source.x + '-' + d.source.y + '-' + d.target.x + '-' + d.target.y;})
.attr('startOffset', '5%')
.text(function (d) { return d.id })
.style('font-size', function (d) { return 12 * k + 'px'; });
var g = step.enter().append('svg:g');
g.append('svg:rect')
.attr('class', 'node')
.attr('x', function (d) { return x(d.x - d.r / 2 / ((d.condition) ? Math.sqrt(2) : 1)); })
.attr('y', function (d) { return y(d.y - d.r / 2 / ((d.condition) ? Math.sqrt(2) : 1)); })
.attr('height', function (d) { return (d.r / ((d.condition) ? Math.sqrt(2) : 1)) * k; })
.attr('width', function (d) { return (d.r / ((d.condition) ? Math.sqrt(2) : 1)) * k; })
.attr('transform', function (d) { return (d.condition) ? 'rotate(45,' + x(d.x) + ',' + x(d.y) + ')' : ''; });
g.append('title');
g.append('svg:text')
.attr('class', 'id')
.attr('text-anchor', 'middle')
.attr('x', function (d) { return x(d.x); })
.attr('y', function (d) { return y(d.y + 3); })
.style('font-size', function (d) { return 12 * k + 'px'; })
.text(function (d) { return d.id; });
g = popup.enter()
.append('svg:g')
.style('opacity', '0');
g.append('svg:rect')
.attr('class', 'popupBack')
.attr('tag', 'fcPopupBack');
g.append('svg:rect')
.attr('class', 'popup')
.attr('tag', 'fcPopup')
.on('click', zoom);
popup.each(drawTransition);
state.onStateChanged(function () {
that.update(500)
});
d3.select(window).on('click', function () {
if (zoomedLink !== null) {
zoom(zoomedLink);
} else if (selectedLink !== null) {
updateSelection(selectedLink);
}
});
return that;
}
function rulesetVisual(roots, links, x, y, title, parent, state, base) {
var base = base || baseVisual(parent);
var that = {};
var visuals = [];
var zoomedSelection;
var selection;
var rulesLength = Object.keys(roots).length;
var currentY = 0;
var linkHash = links[0];
for (var ruleName in roots) {
var currentRoot = roots[ruleName];
var currentLinkArray = linkHash[ruleName];
var newX = d3.scale.linear().range([0, x(r / rulesLength)]);
var newY = d3.scale.linear().range([y(currentY), y(currentY + r / rulesLength)]);
newX.domain([0, r]);
newY.domain([0, r]);
visuals.push(ruleVisual(currentRoot, currentLinkArray, newX, newY, ruleName, parent, true, base).update);
currentY += r / rulesLength;
}
var zoom = function () {
var ruleSize = r / rulesLength;
var selection = Math.floor(d3.mouse(this)[1] / ruleSize);
var currentVisual = visuals[selection];
var newX;
var newY;
if (zoomedSelection !== selection) {
for (var i = 0; i < visuals.length; ++i) {
newX = d3.scale.linear().range([0, ruleSize]);
newY = d3.scale.linear().range([r * (i - selection), r * (i - selection) + ruleSize]);
newX.domain([0, ruleSize]);
newY.domain([0, ruleSize]);
visuals[i](1000, newX, newY);
}
zoomedSelection = selection;
} else {
for (var i = 0; i < visuals.length; ++i) {
newX = d3.scale.linear().range([0, ruleSize]);
newY = d3.scale.linear().range([ruleSize * i, ruleSize * (i + 1)]);
newX.domain([0, r]);
newY.domain([0, r]);
visuals[i](1000, newX, newY);
}
zoomedSelection = null;
}
d3.event.stopPropagation();
}
parent.on('click', zoom);
return that;
}
function ruleVisual(root, links, x, y, title, parent, transpose, base) {
var base = base || baseVisual(parent);
var that = {};
var pSize = 150;
var k = x(r) - x(0);
k = k / r;
var n = d3.layout.tree()
.size([r, r])
.nodes(root);
var offset = -400 + n.length * 80;
if (offset > 0) {
offset = 0;
}
base.reLayout(n, r, offset, transpose);
parent.append('svg:defs').append('svg:marker')
.attr('id', 'end-arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 6)
.attr('markerWidth', 6)
.attr('markerHeight', 6)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-4L8,0L0,4')
.attr('fill', '#ccc');
var path = parent.append('svg:g')
.selectAll('path')
.data(links);
var step = parent.append('svg:g')
.selectAll('g')
.data(n);
if (title) {
var titleText = parent.append('svg:text')
.attr('class', 'time label')
.attr('x', function (d) { return x(30); })
.attr('y', function (d) { return y(45); })
.style('font-size', 40 * k + 'px')
.text(title);
}
var getSource = function (d) {
if (transpose) {
sourceX = (d.source.x + d.source.r);
sourceY = d.source.y;
} else {
sourceX = d.source.x;
sourceY = (d.source.y + d.source.r);
}
return { x: x(sourceX), y: y(sourceY) };
}
var getTarget = function (d) {
if (transpose) {
if (d.source.y < d.target.y) {
// pointing down
targetY = d.target.y - d.target.r;
targetX = d.target.x;
} else if (d.source.y > d.target.y) {
// pointing up
targetY = d.target.y + d.target.r;
targetX = d.target.x;
} else {
// aligned
targetY = d.target.y;
targetX = d.target.x - d.target.r - 5;
}
} else {
targetX = d.target.x;
targetY = d.target.y - d.target.r;
}
return { x: x(targetX), y: y(targetY) };
}
var diagonal = d3.svg.diagonal()
.source(getSource)
.target(getTarget);
var drawSymbol = function (d) {
if (d.type === 'op') {
return d3.svg.symbol()
.type('circle')
.size(d.r * d.r * 3.14 / 2)(d);
}
if (d.type === 'input') {
var h = d.r * 2 / 3;
return 'M ' + (d.r * -1) + ' 0 L ' + (h * -1) + ' ' + (h * -1) + ' L ' + h + ' ' + (h * -1) + ' L ' + d.r
+ ' 0 L ' + h + ' ' + h + ' L ' + (h * -1) + ' ' + h + ' z';
}
if (d.type === 'function') {
var h = d.r * 2 / 3;
return 'M ' + (d.r * -1) + ' ' + (h * -1) + ' L ' + d.r + ' ' + (h * -1) + ' L ' + d.r + ' ' + h + ' L '
+ (d.r * -1) + ' ' + h + ' z';
}
return;
};
var getColor = function(d) {
if (d.type === 'op') {
return d3.rgb(236,236,236);
}
if (d.type === 'input') {
return d3.rgb(252,99,93);
}
if (d.type === 'function') {
return d3.rgb(95,191,96);
}
};
var getTextX = function(d) {
if (d.type === 'op') {
return x(d.x - d.r - d.exp.length * 6);
}
if (d.exp) {
return x(d.x - d.exp.length / 2 * 6);
}
return x(d.x - d.r);
};
var getTextY = function(d) {
if (d.type === 'op') {
return y(d.y + 12 * k / 2);
}
return y(d.y - d.r);
};
that.update = function (transitionTime, newX, newY) {
x = newX || x;
y = newY || y;
k = x(r) - x(0);
k = k / r;
transitionTime = transitionTime || 0;
path.transition()
.duration(transitionTime)
.attr('d', diagonal);
step.selectAll('path')
.transition()
.duration(transitionTime)
.attr('transform', function (d) { return 'translate(' + x(d.x) + ',' + y(d.y) + '),scale(' + k + ')'; });
step.selectAll('title')
.text(base.getTitle);
step.selectAll('text')
.transition()
.duration(transitionTime)
.attr('x', getTextX)
.attr('y', getTextY)
.style('font-size', function (d) { return 12 * k + 'px'; });
if (titleText) {
titleText.transition()
.duration(transitionTime)
.attr('x', function (d) { return x(30); })
.attr('y', function (d) { return y(45); })
.style('font-size', 40 * k + 'px');
}
};
path.enter()
.append('svg:path')
.attr('class', 'link')
.style('marker-end', function (d) { return 'url(#end-arrow)'; })
.attr('d', diagonal);
var g = step.enter().append('svg:g');
g.append('svg:path')
.attr('class', 'sequenceNode')
.attr('transform', function (d) { return 'translate(' + x(d.x) + ',' + y(d.y) + '),scale(' + k + ')'; })
.attr('d', drawSymbol)
.style('fill', getColor)
.style('fill-opacity', '.7');
g.append('title');
g.append('svg:text')
.attr('class', 'id')
.attr('text-anchor', 'right')
.attr('x', getTextX)
.attr('y', getTextY)
.style('font-size', function (d) { return 12 * k + 'px'; })
.text(function (d) { return d.exp; });
return that;
}
function rulesetState(url) {
var that = {};
var stateChangedEvents = [];
var errorEvents = [];
var currentState;
var sid = url.substring(0, url.lastIndexOf('/'));
var rulesetUrl = sid.substring(0, sid.lastIndexOf('/'));
sid = sid.substring(sid.lastIndexOf('/') + 1);
that.onStateChanged = function (stateChangedFunc) {
stateChangedEvents.push(stateChangedFunc);
return that;
}
that.onError = function (errorFunc) {
errorEvents.push(errorFunc);
return that;
}
that.getCurrentState = function () {
return currentState;
}
var update = function () {
var i;
var statusUrl = rulesetUrl + '/state/' + sid;
d3.json(statusUrl, function (err, status) {
if (err) {
for (i = 0; i < errorEvents.length; ++i) {
errorEvents[i](err.responseText);
}
} else {
if (JSON.stringify(currentState) !== JSON.stringify(status)) {
currentState = status;
for (i = 0; i < stateChangedEvents.length; ++i) {
stateChangedEvents[i](currentState, sid);
}
}
}
});
}
var timeout = function () {
update();
setTimeout(timeout, 2000);
}
that.start = function () {
timeout();
}
return that;
}
function rulesetGraph(url, state) {
var that = {};
var links = [];
var nodes;
var nodeDictionary = {};
var sid = url.substring(0, url.lastIndexOf('/'));
var rulesetUrl = sid.substring(0, sid.lastIndexOf('/'));
sid= sid.substring(sid.lastIndexOf('/') + 1);
if (sid.indexOf('.') !== -1) {
sid = sid.substring(0, sid.indexOf('.'));
}
var getExpression = function(expression, typeName) {
var operator;
var lop;
var rop;
var result = '';
var expressions;
var i;
var atLeast;
var atMost;
var skipParens = false;
if (!typeName.indexOf('$')) {
typeName = typeName.substring(1, typeName.length);
}
for (var opName in expression) {
if (opName === '$atLeast') {
atLeast = expression[opName];
} else if (opName === '$atMost') {
atMost = expression[opName];
} else {
operator = opName;
}
}
if (operator === '$ne' || operator === '$lte' || operator === '$lt' ||
operator === '$gte' || operator === '$gt' || operator === '$nex' || operator === '$ex') {
var operands = expression[operator];
for (lop in operands) {
break;
}
rop = operands[lop];
if (typeof (rop) === 'object') {
ropo = rop['$s'];
if (typeof (ropo) === 'object') {
rop = 's';
if (ropo['id']) {
rop = rop + '.id(\'' + ropo['id'] + '\')';
}
if (ropo['time']) {
rop = rop + '.time(' + ropo['time'] + ')';
}
rop = rop + '.' + ropo['name'];
} else {
rop = 's.' + ropo;
}
}
}
switch (operator) {
case '$ne':
result = typeName + '.' + lop + ' <> ' + rop;
break;
case '$lte':
result = typeName + '.' + lop + ' <= ' + rop;
break;
case '$lt':
result = typeName + '.' + lop + ' < ' + rop;
break;
case '$gte':
result = typeName + '.' + lop + ' >= ' + rop;
break;
case '$gt':
result = typeName + '.' + lop + ' > ' + rop;
break;
case '$ex':
result = 'ex(' + typeName + '.' + lop + ')';
skipParens = true;
break;
case '$nex':
result = 'nex(' + typeName + '.' + lop + ')';
skipParens = true;
break;
case '$t':
result = 'timeout(\'' + expression[operator] + '\')';
skipParens = true;
break;
case '$and':
expressions = expression[operator];
for (i = 0; i < expressions.length; ++i) {
if (i !== 0) {
result = result + ' & ';
}
result = result + getExpression(expressions[i], typeName);
}
break;
case '$or':
expressions = expression[operator];
for (i = 0; i < expressions.length; ++i) {
if (i !== 0) {
result = result + ' | ';
}
result = result + getExpression(expressions[i], typeName);
}
break;
default:
rop = expression[operator];
result = typeName + '.' + operator + ' == ' + rop;
}
if (!skipParens) {
result = '(' + result + ')';
}
if (atLeast) {
result = result + '.at_least(' + atLeast + ')'
}
if (atMost) {
result = result + '.at_most(' + atMost + ')'
}
return result;
};
var getStateNodes = function (chart, links, parentId) {
var currentState;
var resultNode = { size: 20, id: '', currentState: null, children: [] };
var stateNode;
var stateId;
var stateName;
var linkCounter = {};
for (stateName in chart) {
currentState = chart[stateName];
if (parentId) {
stateId = parentId + '.' + stateName;
} else {
stateId = stateName;
}
if (currentState.$chart) {
stateNode = getStateNodes(currentState.$chart, links, stateId);
stateNode.id = stateId;
} else {
stateNode = { id: stateId, currentState: null, size: 20 };
}
nodeDictionary[stateId] = stateNode;
resultNode.children.push(stateNode);
}
for (stateName in chart) {
currentState = chart[stateName];
if (parentId) {
stateId = parentId + '.' + stateName;
} else {
stateId = stateName;
}
for (var transitionName in currentState) {
var transition = currentState[transitionName];
if (transition.to) {
var transitionNode = { r: 25, type: 'start', top: true, children: [] };
var transitionLinks = [];
var outputNode;
var transitionId;
if (parentId) {
transitionId = parentId + '.' + transitionName;
} else {
transitionId = transitionName;
}
outputNode = getRuleNodes(transitionId, transition, transitionNode, transitionLinks);
var link = {
source: nodeDictionary[stateId],
target: nodeDictionary[transition.to],
nodes: [transitionNode, outputNode],
links: transitionLinks,
id: transitionId,
left: false,
right: true
};
if (transition.to === stateId) {
link.reflexive = true;
}
var counter = linkCounter[stateId + transition.to];
if (counter) {
counter.count = counter.count + 1;
link.order = counter.count;
}
else {
linkCounter[stateId + transition.to] = { count: 0 };
link.order = 0;
}
links.push(link);
}
}
}
resultNode.type = 'stateChart';
return resultNode;
};
var getFlowNodes = function (chart, links) {
var resultNode;
var visitedNodes = {};
for (var stageName in chart) {
var currentStage = chart[stageName];
var stageNode = { id: stageName, r: 50, currentStage: null, children: [] };
nodeDictionary[stageName] = stageNode;
if (!resultNode) {
resultNode = stageNode;
visitedNodes[stageName] = stageNode;
}
}
var targetNode;
var sourceNode;
var currentStage;
for (var stageName in chart) {
currentStage = chart[stageName];
sourceNode = nodeDictionary[stageName];
if (currentStage.to) {
if (typeof (currentStage.to) === 'string') {
targetNode = nodeDictionary[currentStage.to];
if (targetNode) {
if (!visitedNodes[currentStage.to]) {
sourceNode.children.push(targetNode);
visitedNodes[currentStage.to] = targetNode;
}
links.push({ source: sourceNode, target: targetNode, left: false, right: true });
}
}
else if (Object.keys(currentStage.to).length) {
var conditionNode = { id: 'switch', r: 50, children: [], condition: true };
sourceNode.children.push(conditionNode);
links.push({ source: sourceNode, target: conditionNode, left: false, right: true });
for (var targetName in currentStage.to) {
targetNode = nodeDictionary[targetName];
if (targetNode) {
var transition = currentStage.to[targetName];
var transitionNode = { r: 25, type: 'start', top: true, children: [] };
var transitionLinks = [];
var outputNode;
outputNode = getRuleNodes(targetName, {when: transition}, transitionNode, transitionLinks);
var link = {
source: conditionNode,
target: targetNode,
nodes: [transitionNode, outputNode],
links: transitionLinks,
id: targetName,
left: false,
right: true
};
if (!visitedNodes[targetName]) {
conditionNode.children.push(targetNode);
visitedNodes[targetName] = targetNode;
}
links.push(link);
}
}
}
}
}
resultNode.type = 'flowChart';
return resultNode;
};
var getRulesetNodes = function (ruleset, links) {
var topNode;
var rule;
var roots = {};
var linkHash = {};
var linkArray;
for (var ruleName in ruleset) {
linkArray = [];
rule = ruleset[ruleName];
rule.run = '#';
topNode = { r: 25, type: 'start', top: true, children: [] };
getRuleNodes(ruleName, rule, topNode, linkArray);
roots[ruleName] = topNode;
linkHash[ruleName] = linkArray;
}
links.push(linkHash);
return roots;
}
var getRuleNodes = function (ruleName, rule, parentNode, links) {
var outputNode;
if (rule.whenAny) {
outputNode = getAlgebraNodes(parentNode, rule.whenAny, 'any', links);
} else if (rule.whenAll) {
outputNode = getAlgebraNodes(parentNode, rule.whenAll, 'all', links);
} else if (rule.when) {
var typeName;
for (typeName in rule.when) {
break;
}
if (typeName.indexOf('$all') !== -1) {
outputNode = getAlgebraNodes(parentNode, rule.when[typeName], 'all', links);
} else if (typeName.indexOf('$any') !== -1) {
outputNode = getAlgebraNodes(parentNode, rule.when[typeName], 'any', links);
} else {
outputNode = { r: 25, top: true, type: 'input' ,children: [] };
if (typeName === '$m' || typeName === '$s') {
outputNode.exp = getExpression(rule.when[typeName], typeName);
} else {
outputNode.exp = getExpression(rule.when, '$m');
}
parentNode.children.push(outputNode);
}
} else {
outputNode = parentNode;
}
if (rule.run) {
var runNode = { r: 25, exp: ruleName, type: 'function', top: true, children: [] };
outputNode.children.push(runNode);
links.push({ source: outputNode, target: runNode, left: false, right: true });
}
return outputNode;
}
var getAlgebraNodes = function (rootNode, events, op, links) {
var endNode = { r: 25, type: 'op', children: [] };
var endNodes = [];
var currentNode;
var atLeast;
var atMost;
for (var eventName in events) {
var currentExpression = events[eventName];
if (eventName == '$atLeast') {
atLeast = currentExpression;
break;
} else if (eventName == '$atMost') {
atMost = currentExpression;
break;
} else if (eventName.indexOf('$all') !== -1) {
currentNode = getAlgebraNodes(rootNode, currentExpression, 'all', links);
} else if (eventName.indexOf('$any') !== -1) {
currentNode = getAlgebraNodes(rootNode, currentExpression, 'any', links);
} else {
currentNode = { r: 25, type: 'input', children: [] };
if (eventName !== '$s') {
currentNode.exp = getExpression(currentExpression, 'm');
} else {
currentNode.exp = getExpression(currentExpression, 's');
}
currentNode.depth = 0;
rootNode.children.push(currentNode);
}
endNodes.push(currentNode);
links.push({ source: currentNode, target: endNode, left: false, right: true });
}
if (atLeast) {
op = op + '.at_least(' + atLeast + ')';
}
if (atMost) {
op = op + '.at_most(' + atMost + ')';
}
endNode['exp'] = op;
var maxDepthNode;
for (var i = 0; i < endNodes.length; ++i) {
currentNode = endNodes[i];
if (!maxDepthNode) {
maxDepthNode = currentNode;
}
else {
if (currentNode.depth > maxDepthNode.depth) {
maxDepthNode = currentNode;
}
}
}
maxDepthNode.children.push(endNode);
endNode.depth = maxDepthNode.depth + 1;
return endNode;
};
var getNodes = function (ruleset, links) {
if (ruleset.$type === 'stateChart') {
delete(ruleset.$type);
return getStateNodes(ruleset, links);
}
else if (ruleset.$type === 'flowChart') {
delete(ruleset.$type);
return getFlowNodes(ruleset, links);
} else {
return getRulesetNodes(ruleset, links);
}
};
var setCurrentState = function (entry) {
if (nodeDictionary[entry.label]) {
nodeDictionary[entry.label].currentState = entry;
}
};
that.createVisual = function (frameSize, callback) {
d3.json(rulesetUrl + '/definition', function (err, ruleSet) {
if (err) {
alert(err)
var error;
try {
error = JSON.parse(err.responseText);
} catch (ex) {
error = { error: ex };
}
callback(error);
}
else {
var svg = d3.select('body')
.append('svg')
.attr('width', r + 200)
.attr('height', r + 75);
var x;
var y;
nodes = getNodes(ruleSet, links);
if (frameSize) {
frameSize = parseInt(frameSize);
x = d3.scale.linear().range([0, frameSize]);
y = d3.scale.linear().range([0, frameSize]);
x.domain([0, r + 50]);
y.domain([0, r + 50]);
} else {
x = d3.scale.linear().range([0, r]);
y = d3.scale.linear().range([0, r]);
x.domain([0, r]);
y.domain([0, r]);
}
var title = rulesetUrl.substring(1) + '/' + sid;
if (nodes.type === 'stateChart') {
stateVisual(nodes, links, x, y, title, svg, state);
} else if (nodes.type === 'flowChart') {
flowVisual(nodes, links, x, y, title, svg, state);
} else {
rulesetVisual(nodes, links, x, y, title, svg, state);
}
state.start();
if (callback) {
callback();
}
}
});
};
state.onStateChanged(setCurrentState);
return that;
}
| {
"pile_set_name": "Github"
} |
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
'config': resolve('config')
}
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: "pre",
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
},
{
test: /\.pug$/,
loader: 'pug-loader'
}
]
}
}
| {
"pile_set_name": "Github"
} |
5+HDXH/ieN8Bzxd3dfxKZoqbbhsm7jyeqWdemt6Xy0kx+7zwSYsh9Ng5KRdy6wtA
| {
"pile_set_name": "Github"
} |
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
/*
* standard table class.
*
* paint functions.
*
* see table.h for interface description
*/
#include "precomp.h"
#include "table.h"
#include "tpriv.h"
int
GetTextExtent(HDC hdc, LPSTR text, INT len)
{
SIZE sz;
GetTextExtentPoint(hdc, text, len, &sz);
return(sz.cx);
}
void gtab_updatecontig(HWND hwnd, lpTable ptab, int line, int cell1, int count);
/* change all cr/lf chars in input text to nul chars */
void gtab_delcr(LPSTR ptext)
{
LPSTR chp;
if (ptext == NULL) {
return;
}
for (chp = ptext; (chp = My_mbschr(chp, '\r')) != NULL; ) {
*chp = '\0';
}
for (chp = ptext; (chp = My_mbschr(chp, '\n')) != NULL; ) {
*chp = '\0';
}
}
void gtab_delcrW(LPWSTR pwzText)
{
LPWSTR pwch;
if (pwzText)
for (pwch = pwzText; *pwch; pwch++)
if (*pwch == '\r' || *pwch == '\n')
*pwch = 0;
}
/* ensure that all visible cells in the given line have valid
* text and property contents. loop through the cells, picking out
* contiguous blocks of visible, invalid cells and call
* gtab_updatecontig to update these from the owner window.
*/
void
gtab_updateline(HWND hwnd, lpTable ptab, int line)
{
lpCellPos ppos;
int cell1, cellcount;
lpLineData pline;
lpCellData cd;
int i;
if (line < 0 || line >= ptab->nlines)
return;
pline = &ptab->pdata[line];
cell1 = 0;
cellcount = 0;
for (i = 0; i < ptab->hdr.ncols; i++) {
ppos = &ptab->pcellpos[i];
cd = &pline->pdata[i];
if (ppos->clipstart < ppos->clipend) {
if ((cd->flags & CELL_VALID) == 0) {
/* add a cell to the list to be updated*/
if (cellcount++ == 0) {
cell1 = i;
}
} else {
/* this cell already valid - so end of
* a contig block. if the contig
* block just ended contained cells to update,
* do it now
*/
if (cellcount > 0) {
gtab_updatecontig(hwnd, ptab,
line, cell1, cellcount);
}
cellcount = 0;
}
}
/* cell not visible - end of a contig block. If it was a
* non-empty contig block, then update it now.
*/
if (cellcount > 0) {
gtab_updatecontig(hwnd, ptab, line, cell1, cellcount);
cellcount = 0;
}
}
if (cellcount > 0) {
gtab_updatecontig(hwnd, ptab, line, cell1, cellcount);
cellcount = 0;
}
}
/*
* update a contiguous block of invalid cells by calling the owner window
*/
void
gtab_updatecontig(HWND hwnd, lpTable ptab, int line, int cell1, int count)
{
lpLineData pline;
lpCellData cd;
CellDataList list;
lpProps colprops;
int i;
COLORREF rgb;
pline = &ptab->pdata[line];
cd = &pline->pdata[cell1];
list.id = ptab->hdr.id;
list.row = gtab_linetorow(hwnd, ptab, line);
list.startcell = cell1;
list.ncells = count;
list.plist = cd;
/* clear out prop flags */
rgb = GetSysColor(COLOR_WINDOW);
for (i = 0; i < count; i++) {
cd[i].props.valid = P_BCOLOUR;
cd[i].props.backcolour = rgb;
if (cd[i].nchars > 0) {
cd[i].ptext[0] = '\0';
if (cd[i].pwzText) {
cd[i].pwzText[0] = '\0';
}
}
}
if (list.row < ptab->hdr.nrows) {
gtab_sendtq(hwnd, TQ_GETDATA, (LPARAM) &list);
}
/* for each cell, mark valid and set properties */
for (i = 0; i < count; i++) {
cd[i].flags |= CELL_VALID;
gtab_delcr(cd[i].ptext);
gtab_delcrW(cd[i].pwzText);
/* fetch properties from hdr and colhdr */
colprops = &ptab->pcolhdr[i + cell1].props;
if (!(cd[i].props.valid & P_FCOLOUR)) {
if (colprops->valid & P_FCOLOUR) {
cd[i].props.valid |= P_FCOLOUR;
cd[i].props.forecolour = colprops->forecolour;
} else if (ptab->hdr.props.valid & P_FCOLOUR) {
cd[i].props.valid |= P_FCOLOUR;
cd[i].props.forecolour =
ptab->hdr.props.forecolour;
}
}
if (!(cd[i].props.valid & P_FCOLOURWS)) {
if (colprops->valid & P_FCOLOURWS) {
cd[i].props.valid |= P_FCOLOURWS;
cd[i].props.forecolourws = colprops->forecolourws;
} else if (ptab->hdr.props.valid & P_FCOLOURWS) {
cd[i].props.valid |= P_FCOLOURWS;
cd[i].props.forecolourws =
ptab->hdr.props.forecolourws;
}
}
if (!(cd[i].props.valid & P_BCOLOUR)) {
if (colprops->valid & P_BCOLOUR) {
cd[i].props.valid |= P_BCOLOUR;
cd[i].props.backcolour = colprops->backcolour;
} else if (ptab->hdr.props.valid & P_BCOLOUR) {
cd[i].props.valid |= P_BCOLOUR;
cd[i].props.backcolour =
ptab->hdr.props.backcolour;
}
}
if (!(cd[i].props.valid & P_FONT)) {
if (colprops->valid & P_FONT) {
cd[i].props.valid |= P_FONT;
cd[i].props.hFont = colprops->hFont;
} else if (ptab->hdr.props.valid & P_FONT) {
cd[i].props.valid |= P_FONT;
cd[i].props.hFont = ptab->hdr.props.hFont;
}
}
if (!(cd[i].props.valid & P_ALIGN)) {
if (colprops->valid & P_ALIGN) {
cd[i].props.valid |= P_ALIGN;
cd[i].props.alignment = colprops->alignment;
} else if (ptab->hdr.props.valid & P_ALIGN) {
cd[i].props.valid |= P_ALIGN;
cd[i].props.alignment =
ptab->hdr.props.alignment;
}
}
if (!(cd[i].props.valid & P_BOX)) {
if (colprops->valid & P_BOX) {
cd[i].props.valid |= P_BOX;
cd[i].props.box = colprops->box;
} else if (ptab->hdr.props.valid & P_BOX) {
cd[i].props.valid |= P_BOX;
cd[i].props.box = ptab->hdr.props.box;
}
}
/* you can't set width/height per cell - this
* is ignored at cell level.
*/
}
}
void
gtab_boxcell(HWND hwnd, HDC hdc, LPRECT rcp, LPRECT pclip, UINT boxmode)
{
if (boxmode & P_BOXTOP) {
MoveToEx(hdc, max(rcp->left, pclip->left),
max(rcp->top, pclip->top), NULL);
LineTo(hdc, min(rcp->right, pclip->right),
max(rcp->top, pclip->top));
}
if (boxmode & P_BOXBOTTOM) {
MoveToEx(hdc, max(rcp->left, pclip->left),
min(rcp->bottom, pclip->bottom), NULL);
LineTo(hdc, min(rcp->right, pclip->right),
min(rcp->bottom, pclip->bottom));
}
if (boxmode & P_BOXLEFT) {
MoveToEx(hdc, max(rcp->left, pclip->left),
max(rcp->top, pclip->top), NULL);
MoveToEx(hdc, max(rcp->left, pclip->left),
min(rcp->bottom, pclip->bottom), NULL);
}
if (boxmode & P_BOXRIGHT) {
MoveToEx(hdc, min(rcp->right, pclip->right),
max(rcp->top, pclip->top), NULL);
LineTo(hdc, min(rcp->right, pclip->right),
min(rcp->bottom, pclip->bottom));
}
}
void
gtab_paintcell(HWND hwnd, HDC hdc, lpTable ptab, int line, int cell, BOOL show_whitespace, BOOL fPrinting)
{
lpLineData pline;
lpCellData cd;
lpCellPos ppos;
RECT rc, rcbox;
int cx, x, y;
UINT align;
LPSTR chp, tabp=NULL;
LPWSTR pwch, pwchBreak=NULL;
DWORD fcol, fcolOld=0, fcolws=0;
DWORD bkcol, bkcolOld=0;
HFONT hfont, hfontOld=NULL;
HBRUSH hbr;
char szCharSet[] = "\t ";
WCHAR wzCharSet[] = L"\t ";
char szSpaceReplace[] = { (unsigned char)183,(unsigned char) 0};
char szTabReplace[] = { (unsigned char)187, (unsigned char) 0};
int cxSpaceReplace;
int cxTabReplace;
SIZE size ={0,0};
TEXTMETRIC tm;
int yOfs;
DWORD etoFlags = ETO_CLIPPED;
fcol = 0; bkcol = 0;
hfont = 0;
/* init pointers to cell text and properties */
pline = &ptab->pdata[line];
cd = &pline->pdata[cell];
ppos = &ptab->pcellpos[cell];
/* draw gutter */
rc.top = pline->linepos.clipstart;
rc.bottom = pline->linepos.clipend;
rc.left = (cell > 0) ? ptab->pcellpos[cell - 1].clipend : 0;
rc.right = ppos->clipstart;
if (cell > ptab->hdr.fixedcols && ptab->hdr.fixedcols < ptab->hdr.ncols) {
rc.left = max(rc.left, ptab->pcellpos[ptab->hdr.fixedcols].clipstart);
}
if (ptab->hdr.fixedcols > 0 && cell == ptab->hdr.fixedcols) {
rc.right--;
}
if (!fPrinting && rc.right > rc.left) {
FillRect(hdc, &rc, (HBRUSH)(COLOR_WINDOW + 1));
}
/* clip all output to this rectangle */
rc.top = pline->linepos.clipstart;
rc.bottom = pline->linepos.clipend;
rc.left = ppos->clipstart;
rc.right = ppos->clipend;
/* check cell properties and colours */
if (cd->props.valid & P_ALIGN) {
align = cd->props.alignment;
} else {
align = P_LEFT;
}
if (!fPrinting && cd->props.valid & P_FONT) {
hfontOld = (HFONT)SelectObject(hdc, cd->props.hFont);
}
// get y offset to center text vertically within cell
GetTextMetrics(hdc, &tm);
yOfs = (rc.bottom - rc.top - tm.tmHeight) / 2;
/* set replacement chars and char widths */
cxSpaceReplace = GetTextExtent(hdc, szSpaceReplace, 1);
cxTabReplace = cxSpaceReplace * ptab->tabchars;
/* set colours if not default */
if (!fPrinting) {
if (cd->props.valid & P_FCOLOUR) {
fcol = cd->props.forecolour;
fcolOld = SetTextColor(hdc, fcol);
}
if (cd->props.valid & P_FCOLOURWS) {
fcolws = cd->props.forecolourws;
}
else {
fcolws = fcol;
}
if (cd->props.valid & P_BCOLOUR) {
/* there is a non-default background colour.
* create a brush and fill the entire cell with it
*/
hbr = CreateSolidBrush(cd->props.backcolour);
if (hbr)
{
FillRect(hdc, &rc, hbr);
DeleteObject(hbr);
}
/* also set colour as background colour for the text */
bkcolOld = SetBkColor(hdc, cd->props.backcolour);
}
}
/* calc offset of text within cell for right-align or centering */
if (align == P_LEFT) {
cx = ptab->avewidth/2;
} else {
cx = 0;
if (cd->pwzText) {
GetTextExtentPoint32W(hdc, cd->pwzText, (int)wcslen(cd->pwzText), &size);
} else if (cd->ptext) {
GetTextExtentPoint32A(hdc, cd->ptext, (int)lstrlen(cd->ptext), &size);
}
cx = size.cx;
if (align == P_CENTRE) {
cx = (ppos->size - cx) / 2;
} else {
cx = ppos->size - cx - (ptab->avewidth/2);
}
}
cx += ppos->start;
/* expand tabs on output and show whitespace on output */
x = 0;
y = pline->linepos.start + yOfs;
/* set search string for strpbrk fn;
don't search for space chars unless we're showing whitespace */
if (!show_whitespace)
{
szCharSet[1] = '\0';
wzCharSet[1] = '\0';
}
// determine the string to display (ansi/unicode). if we have a string
// and it's not empty, then loop and display it.
chp = cd->ptext;
pwch = cd->pwzText;
if (pwch ? *pwch : (chp && *chp))
{
while (TRUE)
{
if (pwch)
{
pwchBreak = wcspbrk(pwch, wzCharSet);
if (!pwchBreak)
pwchBreak = pwch + wcslen(pwch);
}
else
{
tabp = (LPSTR)My_mbspbrk((PUCHAR)chp, (PUCHAR)szCharSet);
if (!tabp)
tabp = chp + lstrlen(chp);
}
/* perform output up to tab/space char */
if (pwch)
ExtTextOutW(hdc, x+cx, y, etoFlags, &rc, pwch, (UINT)(pwchBreak-pwch), NULL);
else
ExtTextOutA(hdc, x+cx, y, etoFlags, &rc, chp, (UINT)(tabp-chp), NULL);
/* advance past the tab */
if (pwch)
{
GetTextExtentPoint32W(hdc, pwch, (UINT)(pwchBreak - pwch), &size);
pwch = pwchBreak;
}
else
{
GetTextExtentPoint32A(hdc, chp, (UINT)(tabp - chp), &size);
chp = tabp;
}
x += size.cx;
// bail if we hit null terminator
if (pwch ? !*pwch : !*chp)
break;
/* handle tab chars */
while (pwch ? (*pwch == '\t') : (*chp == '\t'))
{
/* print replacement char */
if (show_whitespace)
{
if (!fPrinting)
SetTextColor(hdc, fcolws);
ExtTextOut(hdc, x + cx, y, etoFlags, &rc, szTabReplace, 1, NULL);
if (!fPrinting)
SetTextColor(hdc, fcol);
}
/* advance past the tab */
if (cxTabReplace > 0)
x += cxTabReplace - (x % cxTabReplace);
if (pwch)
pwch = ++pwchBreak;
else
chp = ++tabp;
}
/* handle space chars */
if (show_whitespace)
{
while (pwch ? (*pwch == ' ') : (*chp == ' '))
{
/* replace space char with visible char */
if (!fPrinting)
SetTextColor(hdc, fcolws);
ExtTextOut(hdc, x + cx, y, etoFlags, &rc, szSpaceReplace, 1, NULL);
if (!fPrinting)
SetTextColor(hdc, fcol);
x += cxSpaceReplace;
if (pwch)
pwch = ++pwchBreak;
else
chp = ++tabp;
}
}
}
}
/* reset colours to original if not default */
if (!fPrinting) {
if (cd->props.valid & P_FCOLOUR) {
SetTextColor(hdc, fcolOld);
}
if (cd->props.valid & P_BCOLOUR) {
SetBkColor(hdc, bkcolOld);
}
if ( (cd->props.valid & P_FONT) && ( NULL != hfontOld)) {
SelectObject(hdc, hfontOld);
}
}
/* now box cell if marked */
if (!fPrinting) {
if ((cd->props.valid & P_BOX)) {
if (cd->props.box != 0) {
rcbox.top = y;
rcbox.bottom = rcbox.top + pline->linepos.size;
rcbox.left = ppos->start;
rcbox.right = ppos->start + ppos->size;
gtab_boxcell(hwnd, hdc, &rcbox, &rc, cd->props.box);
}
}
}
}
/* fetch and paint the specified line */
void
gtab_paintline(HWND hwnd, HDC hdc, lpTable ptab, int line, BOOL show_whitespace, BOOL fPrinting)
{
lpCellPos ppos = NULL;
int i;
RECT rc;
if (line < 0 || line >= ptab->nlines)
return;
if (!fPrinting)
GetClientRect(hwnd, &rc);
gtab_updateline(hwnd, ptab, line);
for (i = 0; i < ptab->hdr.ncols; i++) {
ppos = &ptab->pcellpos[i];
/* show whitespace iff the flag is set
and we're painting the main text column */
if (ppos->clipstart < ppos->clipend) {
gtab_paintcell(hwnd, hdc, ptab, line, i,
(show_whitespace && (i == 2)), fPrinting);
}
}
if (!fPrinting && ppos) {
rc.top = ptab->pdata[line].linepos.clipstart;
rc.bottom = ptab->pdata[line].linepos.clipend;
rc.left = ppos->clipend;
FillRect(hdc, &rc, (HBRUSH)(COLOR_WINDOW + 1));
}
}
void
gtab_paint(HWND hwnd)
{
PAINTSTRUCT ps;
int y, y2, i;
HDC hDC = BeginPaint(hwnd, &ps);
lpTable ptab = (lpTable) GetWindowLongPtr(hwnd, WL_TABLE);
if (!ptab) {
FillRect(hDC, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
} else {
/* separator lines between fixed rows/columns
* (ie headers) and the rest - if enabled
*/
/* paint here first for good impression,
* and again after to clean up!!
*/
if (ptab->hdr.vseparator) {
gtab_vsep(hwnd, ptab, hDC);
}
if (ptab->hdr.hseparator) {
gtab_hsep(hwnd, ptab, hDC);
}
/* paint only the rows that need painting */
for (i = 0; i < ptab->nlines; i++) {
y = ptab->pdata[i].linepos.start;
y2 = y + ptab->pdata[i].linepos.size;
if ( (y <= ps.rcPaint.bottom) &&
(y2 >= ps.rcPaint.top)) {
gtab_paintline(hwnd, hDC, ptab, i, ptab->show_whitespace, FALSE);
}
}
if (ptab->hdr.vseparator) {
gtab_vsep(hwnd, ptab, hDC);
}
if (ptab->hdr.hseparator) {
gtab_hsep(hwnd, ptab, hDC);
}
if (ptab->selvisible) {
gtab_invertsel(hwnd, ptab, hDC);
}
}
EndPaint(hwnd, &ps);
}
void
gtab_vsep(HWND hwnd, lpTable ptab, HDC hdc)
{
int x;
RECT rc;
if (ptab->hdr.fixedcols < 1) {
return;
}
x = ptab->pcellpos[ptab->hdr.fixedcols - 1].clipend+1;
GetClientRect(hwnd, &rc);
MoveToEx(hdc, x, rc.top, NULL);
LineTo(hdc, x, rc.bottom);
}
void
gtab_hsep(HWND hwnd, lpTable ptab, HDC hdc)
{
int y;
RECT rc;
if (ptab->hdr.fixedrows < 1) {
return;
}
y = ptab->rowheight * ptab->hdr.fixedrows;
GetClientRect(hwnd, &rc);
MoveToEx(hdc, rc.left, y-1, NULL);
LineTo(hdc, rc.right, y-1);
}
/* draw in (inverting) the dotted selection lines for tracking a col width
*/
void
gtab_drawvertline(HWND hwnd, lpTable ptab)
{
RECT rc;
HDC hdc;
HPEN hpen;
hdc = GetDC(hwnd);
if (hdc)
{
SetROP2(hdc, R2_XORPEN);
hpen = (HPEN)SelectObject(hdc, hpenDotted);
GetClientRect(hwnd, &rc);
MoveToEx(hdc, ptab->trackline1, rc.top, NULL);
LineTo(hdc, ptab->trackline1, rc.bottom);
if (ptab->trackline2 != -1) {
MoveToEx(hdc, ptab->trackline2, rc.top, NULL);
LineTo(hdc, ptab->trackline2, rc.bottom);
}
SelectObject(hdc, hpen);
ReleaseDC(hwnd, hdc);
}
}
/*
* mark the selected line, if visible, in the style chosen by the
* client app. This can be TM_SOLID, meaning an inversion of
* the whole selected area or TM_FOCUS, meaning, inversion of the first
* cell, and then a dotted focus rectangle for the rest.
*
* this function inverts either style, and so will turn the selection
* both on and off.
*/
void
gtab_invertsel(HWND hwnd, lpTable ptab, HDC hdc_in)
{
HDC hdc;
int firstline, lastline;
long startrow, lastrow, toprow, bottomrow;
RECT rc;
int lastcell;
/* get the selection start and end rows ordered vertically */
if (ptab->select.nrows == 0) {
return;
} else if (ptab->select.nrows < 0) {
startrow = ptab->select.startrow + ptab->select.nrows + 1;
lastrow = ptab->select.startrow;
} else {
startrow = ptab->select.startrow;
lastrow = ptab->select.startrow + ptab->select.nrows -1;
}
/* is selected area (or part of it) visible on screen ? */
firstline = gtab_rowtoline(hwnd, ptab, startrow);
lastline = gtab_rowtoline(hwnd, ptab, lastrow);
if (firstline < 0) {
toprow = gtab_linetorow(hwnd, ptab,
ptab->hdr.fixedselectable ? 0: ptab->hdr.fixedrows);
if ((toprow >= startrow) &&
(toprow <= lastrow)) {
firstline = gtab_rowtoline(hwnd, ptab, toprow);
} else {
return;
}
} else {
toprow = 0;
}
if (lastline < 0) {
bottomrow = gtab_linetorow(hwnd, ptab, ptab->nlines-1);
if ((bottomrow <= lastrow) &&
(bottomrow >=startrow)) {
lastline = gtab_rowtoline(hwnd, ptab, bottomrow);
} else {
return;
}
}
rc.top = ptab->pdata[firstline].linepos.clipstart;
rc.bottom = ptab->pdata[lastline].linepos.clipend;
/* selection mode includes a flag TM_FOCUS indicating we should
* use a focus rect instead of the traditional inversion for
* selections in this table. This interferes with multiple backgrnd
* colours less. However we still do inversion for fixedcols.
*/
lastcell = (int)(ptab->select.startcell + ptab->select.ncells - 1);
/*
* invert the whole area for TM_SOLID or just the first
* cell for TM_FOCUS
*/
rc.left = ptab->pcellpos[ptab->select.startcell].clipstart;
if (ptab->hdr.selectmode & TM_FOCUS) {
rc.right = ptab->pcellpos[ptab->select.startcell].clipend;
} else {
rc.right = ptab->pcellpos[lastcell].clipend;
}
if (hdc_in == NULL) {
hdc = GetDC(hwnd);
if (!hdc)
{
return;
}
} else {
hdc = hdc_in;
}
InvertRect(hdc, &rc);
/*
* draw focus rectangle around remaining cells on this line, if there
* are any
*/
if (ptab->hdr.selectmode & TM_FOCUS) {
if (toprow > startrow) {
rc.top--;
}
if (ptab->select.ncells > 1) {
rc.left = ptab->pcellpos[ptab->select.startcell+1].clipstart;
rc.right = ptab->pcellpos[lastcell].clipend;
DrawFocusRect(hdc, &rc);
}
}
if (hdc_in == NULL) {
ReleaseDC(hwnd, hdc);
}
}
| {
"pile_set_name": "Github"
} |
//
// MPTTheoryViewController.m
// MobileProject
//
// Created by wujunyang on 2017/3/1.
// Copyright © 2017年 wujunyang. All rights reserved.
//
#import "MPTTheoryViewController.h"
@interface MPTTheoryViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,strong) UITableView *myTableView;
@end
@implementation MPTTheoryViewController
//常见的五个宏
//1:
//RAC(TARGET, [KEYPATH, [NIL_VALUE]]):用于给某个对象的某个属性绑定
// 只要文本框文字改变,就会修改label的文字
//RAC(self.labelView,text) = _textField.rac_textSignal;
//2:
//RACObserve(self, name):监听某个对象的某个属性,返回的是信号。
//[RACObserve(self.view, center) subscribeNext:^(id x) {
// NSLog(@"%@",x);
//}];
//当RACObserve放在block里面使用时一定要加上weakify,不管里面有没有使用到self;否则会内存泄漏,因为RACObserve宏里面就有一个self
//@weakify(self);
//RACSignal *signal3 = [anotherSignal flattenMap:^(NSArrayController *arrayController) {
// Avoids a retain cycle because of RACObserve implicitly referencing self
// @strongify(self);
// return RACObserve(arrayController, items);
//}];
//3:
//@weakify(Obj)和@strongify(Obj),一般两个都是配套使用,在主头文件(ReactiveCocoa.h)中并没有导入,需要自己手动导入,RACEXTScope.h才可以使用。但是每次导入都非常麻烦,只需要在主头文件自己导入就好了
//4:
//RACTuplePack:把数据包装成RACTuple(元组类)
// 把参数中的数据包装成元组
//RACTuple *tuple = RACTuplePack(@10,@20);
//5:
//RACTupleUnpack:把RACTuple(元组类)解包成对应的数据
//// 把参数中的数据包装成元组
//RACTuple *tuple = RACTuplePack(@"xmg",@20);
//
//// 解包元组,会把元组的值,按顺序给参数里面的变量赋值
//// name = @"xmg" age = @20
//RACTupleUnpack(NSString *name,NSNumber *age) = tuple;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor=[UIColor whiteColor];
self.navigationItem.title=@"基础知识点";
if (!self.dataArray) {
self.dataArray=@[@"RACSigner基础知识点",@"RACSubject基础知识点",@"RACSequence基础知识点",@"RACCommand基础知识点",@"RACMulticastConnection基础知识点",@"RAC结合UI一般事件",@"高阶操作知识内容",@"RAC并发编程知识点",@"冷信号跟热信号知识点",@"RACDisposable知识点",@"RACChannel知识点",@"RAC倒计时小实例"];
}
//初始化表格
if (!_myTableView) {
_myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0.5, Main_Screen_Width, Main_Screen_Height) style:UITableViewStylePlain];
_myTableView.showsVerticalScrollIndicator = NO;
_myTableView.showsHorizontalScrollIndicator = NO;
_myTableView.dataSource = self;
_myTableView.delegate = self;
[_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
[self.view addSubview:_myTableView];
[_myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
}];
}
}
#pragma mark UITableViewDataSource, UITableViewDelegate相关内容
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = self.dataArray[indexPath.row];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
switch (indexPath.row) {
case 0:
{
MPTRACSignerViewController *vc=[[MPTRACSignerViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 1:
{
MPTRACSubjectViewController *vc=[[MPTRACSubjectViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 2:
{
MPTRACSequenceViewController *vc=[[MPTRACSequenceViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 3:
{
MPTRACCommandViewController *vc=[[MPTRACCommandViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 4:
{
MPTRACMulticastConnectionViewController *vc=[[MPTRACMulticastConnectionViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 5:
{
MPTRACUIKitViewController *vc=[[MPTRACUIKitViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 6:
{
MPTRACHightSignalViewController *vc=[[MPTRACHightSignalViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 7:
{
MPTRACSchedulerViewController *vc=[[MPTRACSchedulerViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 8:
{
MPTHotAndColdSignalViewController *vc=[[MPTHotAndColdSignalViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 9:
{
MPTRACDisposableViewController *vc=[[MPTRACDisposableViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 10:
{
RACChannelViewController *vc=[[RACChannelViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
case 11:
{
MPTCountDownViewController *vc=[[MPTCountDownViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
default:
break;
}
}
@end
| {
"pile_set_name": "Github"
} |
/**************************************************************************
*
* Copyright 2007 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
#ifndef ST_CB_FEEDBACK_H
#define ST_CB_FEEDBACK_H
struct dd_function_table;
extern void
st_init_feedback_functions(struct dd_function_table *functions);
#endif /* ST_CB_FEEDBACK_H */
| {
"pile_set_name": "Github"
} |
#ifndef BOOST_MPL_IS_PLACEHOLDER_HPP_INCLUDED
#define BOOST_MPL_IS_PLACEHOLDER_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/arg_fwd.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/aux_/yes_no.hpp>
#include <boost/mpl/aux_/type_wrapper.hpp>
#include <boost/mpl/aux_/nttp_decl.hpp>
#include <boost/mpl/aux_/config/ctps.hpp>
#include <boost/mpl/aux_/config/static_constant.hpp>
namespace boost { namespace mpl {
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template< typename T >
struct is_placeholder
: bool_<false>
{
};
template< BOOST_MPL_AUX_NTTP_DECL(int, N) >
struct is_placeholder< arg<N> >
: bool_<true>
{
};
#else
namespace aux {
aux::no_tag is_placeholder_helper(...);
template< BOOST_MPL_AUX_NTTP_DECL(int, N) >
aux::yes_tag is_placeholder_helper(aux::type_wrapper< arg<N> >*);
} // namespace aux
template< typename T >
struct is_placeholder
{
static aux::type_wrapper<T>* get();
BOOST_STATIC_CONSTANT(bool, value =
sizeof(aux::is_placeholder_helper(get())) == sizeof(aux::yes_tag)
);
typedef bool_<value> type;
};
#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
}}
#endif // BOOST_MPL_IS_PLACEHOLDER_HPP_INCLUDED
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __FIB_NODE_H__
#define __FIB_NODE_H__
#include <vnet/fib/fib_types.h>
/**
* The types of nodes in a FIB graph
*/
typedef enum fib_node_type_t_ {
/**
* Marker. New types after this one.
*/
FIB_NODE_TYPE_FIRST = 0,
/**
* See the respective fib_*.h files for descriptions of these objects.
*/
FIB_NODE_TYPE_WALK,
FIB_NODE_TYPE_ENTRY,
FIB_NODE_TYPE_MFIB_ENTRY,
FIB_NODE_TYPE_PATH_LIST,
FIB_NODE_TYPE_PATH,
FIB_NODE_TYPE_ADJ,
FIB_NODE_TYPE_MPLS_ENTRY,
FIB_NODE_TYPE_MPLS_TUNNEL,
FIB_NODE_TYPE_LISP_GPE_FWD_ENTRY,
FIB_NODE_TYPE_LISP_ADJ,
FIB_NODE_TYPE_VXLAN_TUNNEL,
FIB_NODE_TYPE_MAP_E,
FIB_NODE_TYPE_VXLAN_GPE_TUNNEL,
FIB_NODE_TYPE_GENEVE_TUNNEL,
FIB_NODE_TYPE_UDP_ENCAP,
FIB_NODE_TYPE_BIER_FMASK,
FIB_NODE_TYPE_BIER_ENTRY,
FIB_NODE_TYPE_VXLAN_GBP_TUNNEL,
FIB_NODE_TYPE_IPSEC_SA,
FIB_NODE_TYPE_IP_PUNT_REDIRECT,
FIB_NODE_TYPE_ENTRY_TRACK,
/**
* Marker. New types before this one. leave the test last.
*/
FIB_NODE_TYPE_TEST,
FIB_NODE_TYPE_LAST = FIB_NODE_TYPE_TEST,
} __attribute__ ((packed)) fib_node_type_t;
#define FIB_NODE_TYPE_MAX (FIB_NODE_TYPE_LAST + 1)
#define FIB_NODE_TYPES { \
[FIB_NODE_TYPE_ENTRY] = "entry", \
[FIB_NODE_TYPE_MFIB_ENTRY] = "mfib-entry", \
[FIB_NODE_TYPE_WALK] = "walk", \
[FIB_NODE_TYPE_PATH_LIST] = "path-list", \
[FIB_NODE_TYPE_PATH] = "path", \
[FIB_NODE_TYPE_MPLS_ENTRY] = "mpls-entry", \
[FIB_NODE_TYPE_MPLS_TUNNEL] = "mpls-tunnel", \
[FIB_NODE_TYPE_ADJ] = "adj", \
[FIB_NODE_TYPE_LISP_GPE_FWD_ENTRY] = "lisp-gpe-fwd-entry", \
[FIB_NODE_TYPE_LISP_ADJ] = "lisp-adj", \
[FIB_NODE_TYPE_VXLAN_TUNNEL] = "vxlan-tunnel", \
[FIB_NODE_TYPE_MAP_E] = "map-e", \
[FIB_NODE_TYPE_VXLAN_GPE_TUNNEL] = "vxlan-gpe-tunnel", \
[FIB_NODE_TYPE_UDP_ENCAP] = "udp-encap", \
[FIB_NODE_TYPE_BIER_FMASK] = "bier-fmask", \
[FIB_NODE_TYPE_BIER_ENTRY] = "bier-entry", \
[FIB_NODE_TYPE_VXLAN_GBP_TUNNEL] = "vxlan-gbp-tunnel", \
[FIB_NODE_TYPE_IPSEC_SA] = "ipsec-sa", \
[FIB_NODE_TYPE_IP_PUNT_REDIRECT] = "ip-punt-redirect", \
[FIB_NODE_TYPE_ENTRY_TRACK] = "fib-entry-track" \
}
/**
* Reasons for backwalking the FIB object graph
*/
typedef enum fib_node_back_walk_reason_t_ {
/**
* Marker. Add new ones after.
*/
FIB_NODE_BW_REASON_FIRST = 0,
/**
* Walk to re-resolve the child.
* Used when the parent is no longer a valid resolution target
*/
FIB_NODE_BW_REASON_RESOLVE = FIB_NODE_BW_REASON_FIRST,
/**
* Walk to re-evaluate the forwarding contributed by the parent.
* Used when a parent's forwarding changes and the child needs to
* incorporate this change in its forwarding.
*/
FIB_NODE_BW_REASON_EVALUATE,
/**
* A resolving interface has come up
*/
FIB_NODE_BW_REASON_INTERFACE_UP,
/**
* A resolving interface has gone down
*/
FIB_NODE_BW_REASON_INTERFACE_DOWN,
/**
* A resolving interface has been deleted.
*/
FIB_NODE_BW_REASON_INTERFACE_DELETE,
/**
* Walk to re-collapse the multipath adjs when the rewrite of
* a unipath adjacency changes
*/
FIB_NODE_BW_REASON_ADJ_UPDATE,
/**
* Walk to update children to inform them the adjacency is now down.
*/
FIB_NODE_BW_REASON_ADJ_DOWN,
/**
* Marker. Add new before and update
*/
FIB_NODE_BW_REASON_LAST = FIB_NODE_BW_REASON_ADJ_DOWN,
} fib_node_back_walk_reason_t;
#define FIB_NODE_BW_REASONS { \
[FIB_NODE_BW_REASON_RESOLVE] = "resolve", \
[FIB_NODE_BW_REASON_EVALUATE] = "evaluate", \
[FIB_NODE_BW_REASON_INTERFACE_UP] = "if-up", \
[FIB_NODE_BW_REASON_INTERFACE_DOWN] = "if-down", \
[FIB_NODE_BW_REASON_INTERFACE_DELETE] = "if-delete", \
[FIB_NODE_BW_REASON_ADJ_UPDATE] = "adj-update", \
[FIB_NODE_BW_REASON_ADJ_DOWN] = "adj-down", \
}
#define FOR_EACH_FIB_NODE_BW_REASON(_item) \
for (_item = FIB_NODE_BW_REASON_FIRST; \
_item <= FIB_NODE_BW_REASON_LAST; \
_item++)
/**
* Flags enum constructed from the reaons
*/
typedef enum fib_node_bw_reason_flag_t_ {
FIB_NODE_BW_REASON_FLAG_NONE = 0,
FIB_NODE_BW_REASON_FLAG_RESOLVE = (1 << FIB_NODE_BW_REASON_RESOLVE),
FIB_NODE_BW_REASON_FLAG_EVALUATE = (1 << FIB_NODE_BW_REASON_EVALUATE),
FIB_NODE_BW_REASON_FLAG_INTERFACE_UP = (1 << FIB_NODE_BW_REASON_INTERFACE_UP),
FIB_NODE_BW_REASON_FLAG_INTERFACE_DOWN = (1 << FIB_NODE_BW_REASON_INTERFACE_DOWN),
FIB_NODE_BW_REASON_FLAG_INTERFACE_DELETE = (1 << FIB_NODE_BW_REASON_INTERFACE_DELETE),
FIB_NODE_BW_REASON_FLAG_ADJ_UPDATE = (1 << FIB_NODE_BW_REASON_ADJ_UPDATE),
FIB_NODE_BW_REASON_FLAG_ADJ_DOWN = (1 << FIB_NODE_BW_REASON_ADJ_DOWN),
} __attribute__ ((packed)) fib_node_bw_reason_flag_t;
STATIC_ASSERT(sizeof(fib_node_bw_reason_flag_t) < 2,
"BW Reason enum < 2 byte. Consequences for cover_upd_res_t");
extern u8 *format_fib_node_bw_reason(u8 *s, va_list *args);
/**
* Flags on the walk
*/
typedef enum fib_node_bw_flags_t_
{
FIB_NODE_BW_FLAG_NONE = 0,
/**
* Force the walk to be synchronous
*/
FIB_NODE_BW_FLAG_FORCE_SYNC = (1 << 0),
} fib_node_bw_flags_t;
/**
* Forward declarations
*/
struct fib_node_t_;
/**
* A representation of one pointer to another node.
* To fully qualify a node, one must know its type and its index so it
* can be retrieved from the appropriate pool. Direct pointers to nodes
* are forbidden, since all nodes are allocated from pools, which are vectors,
* and thus subject to realloc at any time.
*/
typedef struct fib_node_ptr_t_ {
/**
* node type
*/
fib_node_type_t fnp_type;
/**
* node's index
*/
fib_node_index_t fnp_index;
} fib_node_ptr_t;
/**
* @brief A list of FIB nodes.
*/
typedef u32 fib_node_list_t;
/**
* Context passed between object during a back walk.
*/
typedef struct fib_node_back_walk_ctx_t_ {
/**
* The reason/trigger for the backwalk
*/
fib_node_bw_reason_flag_t fnbw_reason;
/**
* additional flags for the walk
*/
fib_node_bw_flags_t fnbw_flags;
/**
* the number of levels the walk has already traversed.
* this value is maintained by the walk infra, tp limit the depth of
* a walk so it does not run indefinately the presence of a loop/cycle
* in the graph.
*/
u32 fnbw_depth;
} fib_node_back_walk_ctx_t;
/**
* We consider a depth of 32 to be sufficient to cover all sane
* network topologies. Anything more is then an indication that
* there is a loop/cycle in the FIB graph.
* Note that all object types contribute to 1 to the depth.
*/
#define FIB_NODE_GRAPH_MAX_DEPTH ((u32)32)
/**
* A callback function for walking a node dependency list
*/
typedef int (*fib_node_ptr_walk_t)(fib_node_ptr_t *depend,
void *ctx);
/**
* A list of dependent nodes.
* This is currently implemented as a hash_table of fib_node_ptr_t
*/
typedef fib_node_ptr_t fib_node_ptr_list_t;
/**
* Return code from a back walk function
*/
typedef enum fib_node_back_walk_rc_t_ {
FIB_NODE_BACK_WALK_MERGE,
FIB_NODE_BACK_WALK_CONTINUE,
} fib_node_back_walk_rc_t;
/**
* Function definition to backwalk a FIB node
*/
typedef fib_node_back_walk_rc_t (*fib_node_back_walk_t)(
struct fib_node_t_ *node,
fib_node_back_walk_ctx_t *ctx);
/**
* Function definition to get a FIB node from its index
*/
typedef struct fib_node_t_* (*fib_node_get_t)(fib_node_index_t index);
/**
* Function definition to inform the FIB node that its last lock has gone.
*/
typedef void (*fib_node_last_lock_gone_t)(struct fib_node_t_ *node);
/**
* Function definition to display the amount of memory used by a type.
* Implementations should call fib_show_memory_usage()
*/
typedef void (*fib_node_memory_show_t)(void);
/**
* A FIB graph nodes virtual function table
*/
typedef struct fib_node_vft_t_ {
fib_node_get_t fnv_get;
fib_node_last_lock_gone_t fnv_last_lock;
fib_node_back_walk_t fnv_back_walk;
format_function_t *fnv_format;
fib_node_memory_show_t fnv_mem_show;
} fib_node_vft_t;
/**
* An node in the FIB graph
*
* Objects in the FIB form a graph.
*/
typedef struct fib_node_t_ {
/**
* The node's type. make sure we are dynamic/down casting correctly
*/
fib_node_type_t fn_type;
/**
* Some pad space the concrete/derived type is free to use
*/
u16 fn_pad;
/**
* Vector of nodes that depend upon/use/share this node
*/
fib_node_list_t fn_children;
/**
* Number of dependents on this node. This number includes the number
* of children
*/
u32 fn_locks;
} fib_node_t;
STATIC_ASSERT(sizeof(fib_node_t) == 12, "FIB node type is growing");
/**
* @brief
* Register the function table for a given type
*
* @param ft
* FIB node type
*
* @param vft
* virtual function table
*/
extern void fib_node_register_type (fib_node_type_t ft,
const fib_node_vft_t *vft);
/**
* @brief
* Create a new FIB node type and Register the function table for it.
*
* @param vft
* virtual function table
*
* @return new FIB node type
*/
extern fib_node_type_t fib_node_register_new_type (const fib_node_vft_t *vft);
/**
* @brief Show the memory usage for a type
*
* This should be invoked by the type in response to the infra calling
* its registered memory show function
*
* @param name the name of the type
* @param in_use_elts The number of elements in use
* @param allocd_elts The number of allocated pool elemenets
* @param size_elt The size of one element
*/
extern void fib_show_memory_usage(const char *name,
u32 in_use_elts,
u32 allocd_elts,
size_t size_elt);
extern void fib_node_init(fib_node_t *node,
fib_node_type_t ft);
extern void fib_node_deinit(fib_node_t *node);
extern void fib_node_lock(fib_node_t *node);
extern void fib_node_unlock(fib_node_t *node);
extern u32 fib_node_get_n_children(fib_node_type_t parent_type,
fib_node_index_t parent_index);
extern u32 fib_node_child_add(fib_node_type_t parent_type,
fib_node_index_t parent_index,
fib_node_type_t child_type,
fib_node_index_t child_index);
extern void fib_node_child_remove(fib_node_type_t parent_type,
fib_node_index_t parent_index,
fib_node_index_t sibling_index);
extern fib_node_back_walk_rc_t fib_node_back_walk_one(fib_node_ptr_t *ptr,
fib_node_back_walk_ctx_t *ctx);
extern u8* fib_node_children_format(fib_node_list_t list,
u8 *s);
extern const char* fib_node_type_get_name(fib_node_type_t type);
static inline int
fib_node_index_is_valid (fib_node_index_t ni)
{
return (FIB_NODE_INDEX_INVALID != ni);
}
#endif
| {
"pile_set_name": "Github"
} |
chr7 108705793 108706018 AAAAGCAATGATACACAAAAATAAT 0 - foo bar
chr2 46996145 46996370 AAGGGTGAGTGAACTAGCGCACTCT 0 - foo bar
chr10 98040386 98040611 ATCTATGCCATAATATGCTGTGCAG 0 - foo bar
chr8 97310720 97310945 AAAGGCTCTTTTAATAGTGATTTCA 0 - foo bar
chr11 69173904 69174129 AACAGACCTTCCACAAGGAGCAGGG 0 - foo bar
chr18 66143906 66144131 AACGGTCGTCAGAACTGTCCCGAAC 0 - foo bar
chr4 9725469 9725694 AAGGCCCTTCGGCTTTCTAGGAATC 0 + foo bar
chr15 56563614 56563839 ACACAGGTGTGGACAGGGTCAAGCA 0 + foo bar
chr18 22058559 22058784 AACGTGTGCCGGCACGTTTAGATAA 0 - foo bar
chr1 190953098 190953323 AAATAACAAAAAGTTAAAAGTGTGG 0 + foo bar
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2015, Cisco Systems
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file is autogenerated
//
// The following edits are possible, without affecting the validity of the
// file:
//
// * Fields may be renamed.
// * Fields may be deleted.
// * The unique numbered tag for a field may be changed, provided that
// the ordering of tags for fields within a message is preserved.
// * Message types may be renamed.
// * Message types may be deleted (if all fields that reference them
// have been deleted).
//
// All Cisco message and field extensions must be preserved (except when the
// field itself is being deleted).
syntax = "proto3";
package cisco_ios_xr_l2vpn_oper.l2vpnv2.nodes.node.mvrp.mvrp_main_ports.mvrp_main_port.mvrp_main_port_info;
// L2VPN MVRP
message l2vpn_mvrp_KEYS {
string node_id = 1;
string main_port_interface_name = 2;
}
message l2vpn_mvrp {
// Main Port Interface name
string main_port_interface_name = 50;
// Is main port a trunk
bool is_trunk = 51;
// Is default encap set
bool is_default_encap = 52;
// Trunk or default Bridge Port
l2vpn_mvrp_bp default_bridge_port = 53;
// Number of Bridge Ports
uint32 number_of_bridge_ports = 54;
}
// EFP range
message l2vpn_efp_range {
uint32 lower = 1;
uint32 upper = 2;
}
// L2VPN MVRP BP
message l2vpn_mvrp_bp {
// Bridge port Interface name
string bridge_port_interface_name = 1;
// Bridge port XConnect ID
uint32 bridge_port_x_connect_id = 2;
// MVRP Sequence Number
uint32 mvrp_sequence_number = 3;
// VLAN IDs
repeated l2vpn_efp_range vlan_ranges = 4;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<title>Dojo Gesture Testing</title>
<style type="text/css">
#outer {
width: 350px;
height: 180px;
border: 1px solid #54A201;
background-color: #54A201;
}
#inner {
width: 250px;
height: 140px;
border: 1px solid #7FB0DB;
background-color: #7FB0DB
}
#log1, #log2 {
width: 350px;
height: 50px;
}
</style>
<script type="text/javascript" src="../../../dojo/dojo.js" data-dojo-config="parseOnLoad: true"></script>
<script>
require([
"dojo/_base/kernel",
"dojo/_base/connect",
"dojo/_base/html",
"dojo/_base/event",
"dojo/on",
"dojo/touch",
"dojo/ready",
"dojox/gesture/tap",
"dojox/gesture/swipe"
], function(dojo, conn, html, evt, on, touch, ready, tap, swipe){
ready(function(){
var action = function(e){
html.byId("log1").innerHTML = "";
var info = " e.target.id=" + e.target.id + " | e.type=" + e.type + " | e.currentTarget.id="+ e.currentTarget.id;
/*
for(var i in e){
if(typeof e[i] != "function"){
info += "- " + i + ": " + e[i] + (e[i] && e[i]['id'] ? ' id = '+e[i]['id'] : '') + "<br/>";
}
}*/
html.byId("log1").innerHTML += info;
//evt.stop(e);
};
var swipeAction = function(e){
html.byId("log2").innerHTML = "";
var info = " e.target.id=" + e.target.id + " | e.type=" + e.type + " | e.currentTarget.id="+ e.currentTarget.id +
" e.dx=" + e.dx + " e.dy=" + e.dy + " e.time=" + e.time + "<br/>";
html.byId("log2").innerHTML += info;
//evt.stop(e);
};
//tap and swipe gestures both work well both on PC and touch devices
var inner = html.byId("inner");
on(inner, tap, action);
on(inner, tap.hold, action);
on(inner, tap.doubletap, action);
on(inner, swipe, swipeAction);
//test gesture events bubbling from inner div
var outer = html.byId("outer");
conn.connect(outer, tap, action);
conn.connect(outer, tap.hold, action);
conn.connect(outer, tap.doubletap, action);
conn.connect(outer, swipe, swipeAction);
conn.connect(outer, swipe.end, swipeAction);
//conn.connect(outer, touch.press, function(){console.log('outer.touch.press!');});
on(dojo.doc, "orientationchange", function(e){
html.byId("log1").innerHTML="";
html.byId("log2").innerHTML="";
});
});
});
</script>
</head>
<body>
<div id="outer">
outer
<div id="inner">inner
<br/>
<input id="input" type="text" placeholder="type here"/>input
<br/>
<input id="pwd" type="password" name="pwd" placeholder="type here"/>password
<br/>
<textarea id="textarea" rows="3" cols="20" style="width: 150px; height:30px" placeholder="type here" ></textarea>textarea
</div>
</div>
<div id="log1"></div>
<hr/>
<div id="log2"></div>
</body>
</html> | {
"pile_set_name": "Github"
} |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* ViewContextInterface is the interface that should implemented by classes who want to support relative view names.
*
* The method [[getViewPath()]] should be implemented to return the view path that may be prefixed to a relative view name.
*
* @author Paul Klimov <[email protected]>
* @since 2.0
*/
interface ViewContextInterface
{
/**
* @return string the view path that may be prefixed to a relative view name.
*/
public function getViewPath();
}
| {
"pile_set_name": "Github"
} |
Name: Plato Questions Star
Description: Adds the ability for users to star or favorite questions.
Author: InstantASP
WebSite: https://www.instantasp.co.uk/
Category: Questions
PlatoVersion: 2.0.0
Version: 1.0.0
Icon: /plato.questions.star/content/images/icon.png
Dependencies:
[
{
Id: "Plato.Questions",
Version: "1.0.0"
},
{
Id: "Plato.Stars",
Version: "1.0.0"
}
] | {
"pile_set_name": "Github"
} |
/* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/**
* This file defines the <code>PPB_Flash_Menu</code> interface.
*/
label Chrome {
M14 = 0.2
};
/* Menu item type.
*
* TODO(viettrungluu): Radio items not supported yet. Will also probably want
* special menu items tied to clipboard access.
*/
[assert_size(4)]
enum PP_Flash_MenuItem_Type {
PP_FLASH_MENUITEM_TYPE_NORMAL = 0,
PP_FLASH_MENUITEM_TYPE_CHECKBOX = 1,
PP_FLASH_MENUITEM_TYPE_SEPARATOR = 2,
PP_FLASH_MENUITEM_TYPE_SUBMENU = 3
};
struct PP_Flash_MenuItem {
PP_Flash_MenuItem_Type type;
str_t name;
int32_t id;
PP_Bool enabled;
PP_Bool checked;
[ref] PP_Flash_Menu submenu;
};
struct PP_Flash_Menu {
uint32_t count;
[size_is(count)] PP_Flash_MenuItem[] items;
};
interface PPB_Flash_Menu {
PP_Resource Create([in] PP_Instance instance_id,
[in] PP_Flash_Menu menu_data);
PP_Bool IsFlashMenu(PP_Resource resource_id);
/* Display a context menu at the given location. If the user selects an item,
* |selected_id| will be set to its |id| and the callback called with |PP_OK|.
* If the user dismisses the menu without selecting an item,
* |PP_ERROR_USERCANCEL| will be indicated.
*/
int32_t Show([in] PP_Resource menu_id,
[in] PP_Point location,
[out] int32_t selected_id,
[in] PP_CompletionCallback callback);
};
| {
"pile_set_name": "Github"
} |
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Package: CLIM-UTILS; Base: 10; Lowercase: Yes -*-
(in-package :clim-utils)
"Copyright (c) 1990, 1991, 1992 Symbolics, Inc. All rights reserved.
Portions copyright (c) 1989, 1990 International Lisp Associates."
;;; All of this is taken from the STREAM-DEFINITION-BY-USER proposal to
;;; the X3J13 committee, made by David Gray of TI on 22 March 1989. No
;;; Lisp implementation yet supports this proposal, so we implement it
;;; here in this separate package. This way we will be ready when some
;;; Lisp implementation adopts it (or something like it).
;;; just for development
#+ignore
(eval-when (compile load eval)
(defparameter sym-list '("PEEK-CHAR" "READ-BYTE" "READ-CHAR" "UNREAD-CHAR"
"READ-CHAR-NO-HANG" "LISTEN" "READ-LINE"
"CLEAR-INPUT" "WRITE-BYTE" "WRITE-CHAR"
"WRITE-STRING" "TERPRI" "FRESH-LINE" "FORCE-OUTPUT"
"FINISH-OUTPUT" "CLEAR-OUTPUT" ))
(dolist (sym sym-list)
(unintern (find-symbol sym :clim-lisp) :clim-lisp)
(unintern (find-symbol sym :clim) :clim)))
;;; Output functions
(defmacro write-forwarding-lucid-output-stream-function (name args)
(let* ((cl-name (find-symbol (symbol-name name) (find-package 'lisp)))
(method-name (intern (lisp:format nil "~A-~A" 'stream (symbol-name name))))
(optional-args (or (member '&optional args) (member '&key args)))
(required-args (ldiff args optional-args))
(optional-parameters (mapcan #'(lambda (arg)
(cond ((member arg lambda-list-keywords) nil)
((atom arg) (list arg))
(t (list (car arg)))))
optional-args))
(pass-args (append required-args optional-parameters))
;; optional-args are &optional in the method,
;; even if &key in the Common Lisp function
(method-args (if (eq (first optional-args) '&key)
(append required-args '(&optional) (cdr optional-args))
args))
(pass-keys (if (eq (first optional-args) '&key)
(mapcan #'(lambda (arg)
(unless (atom arg)
(setq arg (car arg)))
(list (intern (string arg) :keyword) arg))
(cdr optional-args))
optional-parameters))
)
(when (eq (first optional-args) '&optional)
(pop optional-args))
`(let ((orig-lucid-closure (or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
;;(proclaim '(inline ,name))
(defun ,name (,@required-args &optional stream ,@optional-args)
(cond ((null stream) (setq stream *standard-output*))
((eq stream t) (setq stream *terminal-io*)))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(,method-name stream ,@pass-args)
(funcall orig-lucid-closure ,@required-args stream ,@pass-keys)))
;; Define a default method for the generic function that calls back to the
;; system stream implementation. Call back via a message if there is one,
;; otherwise via the Common Lisp function.
;; Uses T as a parameter specializer name as a standin for cl:stream,
;; which Genera doesn't support as a builtin class
(defmethod ,method-name ((stream t) ,@method-args)
(,cl-name ,@required-args stream ,@pass-keys))
;;(import ',name :clim-lisp)
;;(export ',name :clim-lisp)
)))
(write-forwarding-lucid-output-stream-function lisp:write-byte (integer))
(write-forwarding-lucid-output-stream-function lisp:write-char (character))
(write-forwarding-lucid-output-stream-function lisp:write-string (string &key (start 0) end))
(write-forwarding-lucid-output-stream-function lisp:terpri ())
(write-forwarding-lucid-output-stream-function lisp:fresh-line ())
(write-forwarding-lucid-output-stream-function lisp:force-output ())
(write-forwarding-lucid-output-stream-function lisp:finish-output ())
(write-forwarding-lucid-output-stream-function lisp:clear-output ())
;;; Input functions
(defmacro write-forwarding-lucid-input-stream-function (name lambda-list
&key eof
additional-arguments)
(let* ((cl-name (find-symbol (symbol-name name) (find-package 'lisp)))
(method-name (intern (lisp:format nil "~A-~A" 'stream (symbol-name name))))
(method-lambda-list (set-difference lambda-list '(stream peek-type)))
(args (mapcar #'(lambda (var) (if (atom var) var (first var)))
(remove-if #'(lambda (x) (member x lambda-list-keywords))
lambda-list)))
(method-calling-args (set-difference args '(stream peek-type)))
(cleanup `(cond ((null stream) (setq stream *standard-input*))
((eq stream t) (setq stream *terminal-io*))))
(call-method `(,method-name stream ,@method-calling-args))
(calling-lambda-list (remove '&optional lambda-list)))
(when (member (first (last method-lambda-list)) lambda-list-keywords)
(setf method-lambda-list (butlast method-lambda-list)))
`(let ((orig-lucid-closure
(or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
;;(proclaim '(inline ,name))
,(if eof
(let ((args `(eof-error-p eof-value ,@(and (not (eq eof :no-recursive))
'(recursive-p)))))
`(defun ,name (,@lambda-list ,@args)
,cleanup
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(let ((result ,call-method))
(cond ((not (eq result *end-of-file-marker*))
result)
(eof-error-p
(signal-stream-eof stream ,@(and (not (eq eof :no-recursive))
'(recursive-p))))
(t
eof-value)))
(funcall orig-lucid-closure ,@calling-lambda-list ,@args))))
`(defun ,name ,lambda-list
,cleanup
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
,call-method
(funcall orig-lucid-closure ,@calling-lambda-list))))
;; Define a default method for the generic function that calls back to the
;; system stream implementation. Call back via a message if there is one,
;; otherwise via the Common Lisp function.
(defmethod ,method-name ((stream t) ,@method-lambda-list)
(,cl-name ,@additional-arguments ,@(remove 'peek-type args)
,@(when eof `(nil *end-of-file-marker*))))
;;(import ',name :clim-lisp)
;;(export ',name :clim-lisp)
)))
(write-forwarding-lucid-input-stream-function lisp:peek-char (&optional peek-type stream)
:eof t
:additional-arguments (nil))
(write-forwarding-lucid-input-stream-function lisp:read-byte (&optional stream)
:eof :no-recursive)
(write-forwarding-lucid-input-stream-function lisp:read-char (&optional stream) :eof t)
(write-forwarding-lucid-input-stream-function lisp:unread-char (character
&optional stream))
(write-forwarding-lucid-input-stream-function lisp:read-char-no-hang (&optional stream)
:eof t)
(write-forwarding-lucid-input-stream-function lisp:listen (&optional stream))
(write-forwarding-lucid-input-stream-function lisp:read-line (&optional stream) :eof t)
(write-forwarding-lucid-input-stream-function lisp:clear-input (&optional stream))
(defun signal-stream-eof (stream &optional recursive-p)
(declare (ignore recursive-p))
(error 'end-of-file :stream stream))
;;; Make CLIM-LISP:FORMAT do something useful on CLIM windows.
#||
(defun format (stream format-control &rest format-args)
(when (null stream)
(return-from format
(apply #'lisp:format nil format-control format-args)))
(when (eq stream 't)
(setq stream *standard-output*))
(cond ((streamp stream)
;; this isn't going to quite work for ~&,
;; but it's better than nothing.
(write-string (apply #'lisp:format nil format-control format-args) stream)
nil)
(t
(apply #'lisp:format stream format-control format-args))))
||#
;;; Higher level lisp printing functions.
(eval-when (load)
(let ((original-lucid-closure
(or (getf (symbol-plist 'lisp:format) :original-lucid-closure)
(setf (getf (symbol-plist 'lisp:format) :original-lucid-closure)
(symbol-function 'lisp:format)))))
(defun format (stream format-control &rest format-args)
(when (eq stream 't)
(setq stream *standard-output*))
(cond ((null stream)
(apply original-lucid-closure nil format-control format-args))
;; clim stream
((and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(write-string (apply original-lucid-closure nil format-control format-args)
stream))
;; Lucid stream
(t
(apply original-lucid-closure stream format-control format-args))))))
;;; Support for the IO functions with more varied argument templates and no
;;; Grey stream equivalent. Assumes there is an argument called "STREAM".
(defmacro redefine-lucid-io-function (name lambda-list &body clim-body)
(let ((args (mapcar #'(lambda (var) (if (atom var) var (first var)))
(remove-if #'(lambda (x) (member x lambda-list-keywords))
lambda-list))))
`(let ((orig-lucid-closure
(or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
(defun ,name ,lambda-list
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
,@clim-body
(funcall orig-lucid-closure ,@args))))))
(defmacro %string-stream (stream &body body)
`(let (result
(new-stream (cond ((encapsulating-stream-p ,stream)
(encapsulating-stream-stream ,stream))
((typep ,stream 'fundamental-stream)
,stream)
(t
(let ((*standard-output* *terminal-io*))
(error "Unknown stream type, ~S" ,stream))))))
(write-string
;; execute the body using the STREAM locally rebound
;; to an output stream object for I/O purposes:
(let ((,stream (make-string-output-stream)))
;; stream I/O stuff goes here
(setq result ,@body )
;; return the accumulated output string:
(get-output-stream-string ,stream))
;; use original output stream here ....
new-stream)
result))
(redefine-lucid-io-function lisp:streamp (stream) t)
(redefine-lucid-io-function lcl:underlying-stream (stream &optional direction
(recurse t)
exact-same)
(if (encapsulating-stream-p stream)
(encapsulating-stream-stream stream)
stream))
(redefine-lucid-io-function lisp:prin1 (object &optional (stream *standard-output*))
(%string-stream stream (lisp:prin1 object stream)))
(redefine-lucid-io-function lisp:print (object &optional (stream *standard-output*))
(%string-stream stream (lisp:print object stream)))
(redefine-lucid-io-function lisp:princ (object &optional (stream *standard-output*))
(%string-stream stream (lisp:princ object stream)))
(redefine-lucid-io-function lisp:pprint (object &optional (stream *standard-output*))
(%string-stream stream (lisp:pprint object stream)))
(redefine-lucid-io-function lisp:write-line (string &optional (stream *standard-output*)
&key (start 0) end)
(%string-stream stream (lisp:write-line string stream :start start :end end)))
;;; Easier to write this one out.
;;;
(let ((orig-lucid-closure (symbol-function 'lisp:write)))
(defun lisp:write (object
&key
((:stream stream) *standard-output*)
((:escape escapep) *print-escape*)
((:radix *print-radix*) *print-radix*)
((:base new-print-base) *print-base* print-base-p)
((:circle *print-circle*) *print-circle*)
((:pretty *print-pretty*) *print-pretty*)
((:level *print-level*) *print-level*)
((:length *print-length*) *print-length*)
((:case new-print-case) *print-case* print-case-p)
((:array *print-array*) *print-array*)
((:gensym *print-gensym*) *print-gensym*)
((:structure lcl:*print-structure*) lcl:*print-structure*))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(%string-stream stream (lisp:write object :stream stream
:escape escapep
:radix *print-radix*
:base new-print-base :circle *print-circle*
:pretty *print-pretty*
:level *print-level* :length *print-length*
:case new-print-case
:array *print-array* :gensym *print-gensym*
:structure lcl:*print-structure*))
(funcall orig-lucid-closure object :stream stream :escape escapep
:radix *print-radix*
:base new-print-base :circle *print-circle* :pretty *print-pretty*
:level *print-level* :length *print-length* :case new-print-case
:array *print-array* :gensym *print-gensym*
:structure lcl:*print-structure*))))
;;; Higher level lisp reading functions.
;; this hack is necessary in order to allow (ACCEPT 'T ...) and
;; (ACCEPT 'EXPRESSION ...) to function (sort of) correctly ....
(defmethod make-instance ((t-class (eql (find-class t))) &rest args)
(declare (ignore args) (dynamic-extent args))
t)
(redefine-lucid-io-function lisp:read (&optional (stream *standard-input*)
(eof-error-p t)
(eof-value nil)
(recursive-p nil))
;; ACCEPT is only a rough equivalent of READ
(clim:accept 'clim:expression :stream stream))
;;; Don't forget about this guys even if we don't implement them.
;; READ-PRESERVING-WHITESPACE (&OPTIONAL (STREAM *STANDARD-INPUT*)
;; (EOF-ERROR-P T)
;; (EOF-VALUE NIL)
;; (RECURSIVE-P NIL))
;; READ-DELIMITED-LIST (CHAR &OPTIONAL (STREAM *STANDARD-INPUT*) (RECURSIVE-P NIL))
;;; User Query Functions (interacts with the *QUERY-IO* stream):
;;; Y-OR-N-P (&OPTIONAL FORMAT-STRING &REST FORMAT-ARGS)
;;; NOTE: the built-in presentation type CLIM:BOOLEAN requires YES or NO -- not
;;; Y or P -- as would normally be expected from Y-OR-N-P.
(lcl:defadvice (lisp:y-or-n-p stream-wrapper) (&optional format-string &rest args)
(declare (dynamic-extent args))
(if (and (system:standard-object-p *query-io*)
(typep *query-io* 'fundamental-stream))
(clim:accept 'clim:boolean :prompt (apply #'lisp::format nil format-string
args))
(lcl:apply-advice-continue format-string args)))
;;; YES-OR-NO-P (&OPTIONAL FORMAT-STRING &REST FORMAT-ARGS)
;;;
(lcl:defadvice (lisp:yes-or-no-p stream-wrapper) (&optional format-string &rest args)
(declare (dynamic-extent args))
(if (and (system:standard-object-p *query-io*)
(typep *query-io* 'fundamental-stream))
(clim:accept 'clim:boolean :prompt (apply #'lisp:format nil format-string
args))
(lcl:apply-advice-continue format-string args)))
#+nope
(lcl:defadvice (lisp:format stream-wrapper) (stream control-string &rest args)
(let ((stream (if (eq stream t) *standard-output* stream)))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(apply #'clim:format stream control-string args)
(lcl:apply-advice-continue stream control-string args))))
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
/*
* PCI Virtual Channel support
*
* Copyright (C) 2013 Red Hat, Inc. All rights reserved.
* Author: Alex Williamson <[email protected]>
*/
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/pci_regs.h>
#include <linux/types.h>
/**
* pci_vc_save_restore_dwords - Save or restore a series of dwords
* @dev: device
* @pos: starting config space position
* @buf: buffer to save to or restore from
* @dwords: number of dwords to save/restore
* @save: whether to save or restore
*/
static void pci_vc_save_restore_dwords(struct pci_dev *dev, int pos,
u32 *buf, int dwords, bool save)
{
int i;
for (i = 0; i < dwords; i++, buf++) {
if (save)
pci_read_config_dword(dev, pos + (i * 4), buf);
else
pci_write_config_dword(dev, pos + (i * 4), *buf);
}
}
/**
* pci_vc_load_arb_table - load and wait for VC arbitration table
* @dev: device
* @pos: starting position of VC capability (VC/VC9/MFVC)
*
* Set Load VC Arbitration Table bit requesting hardware to apply the VC
* Arbitration Table (previously loaded). When the VC Arbitration Table
* Status clears, hardware has latched the table into VC arbitration logic.
*/
static void pci_vc_load_arb_table(struct pci_dev *dev, int pos)
{
u16 ctrl;
pci_read_config_word(dev, pos + PCI_VC_PORT_CTRL, &ctrl);
pci_write_config_word(dev, pos + PCI_VC_PORT_CTRL,
ctrl | PCI_VC_PORT_CTRL_LOAD_TABLE);
if (pci_wait_for_pending(dev, pos + PCI_VC_PORT_STATUS,
PCI_VC_PORT_STATUS_TABLE))
return;
pci_err(dev, "VC arbitration table failed to load\n");
}
/**
* pci_vc_load_port_arb_table - Load and wait for VC port arbitration table
* @dev: device
* @pos: starting position of VC capability (VC/VC9/MFVC)
* @res: VC resource number, ie. VCn (0-7)
*
* Set Load Port Arbitration Table bit requesting hardware to apply the Port
* Arbitration Table (previously loaded). When the Port Arbitration Table
* Status clears, hardware has latched the table into port arbitration logic.
*/
static void pci_vc_load_port_arb_table(struct pci_dev *dev, int pos, int res)
{
int ctrl_pos, status_pos;
u32 ctrl;
ctrl_pos = pos + PCI_VC_RES_CTRL + (res * PCI_CAP_VC_PER_VC_SIZEOF);
status_pos = pos + PCI_VC_RES_STATUS + (res * PCI_CAP_VC_PER_VC_SIZEOF);
pci_read_config_dword(dev, ctrl_pos, &ctrl);
pci_write_config_dword(dev, ctrl_pos,
ctrl | PCI_VC_RES_CTRL_LOAD_TABLE);
if (pci_wait_for_pending(dev, status_pos, PCI_VC_RES_STATUS_TABLE))
return;
pci_err(dev, "VC%d port arbitration table failed to load\n", res);
}
/**
* pci_vc_enable - Enable virtual channel
* @dev: device
* @pos: starting position of VC capability (VC/VC9/MFVC)
* @res: VC res number, ie. VCn (0-7)
*
* A VC is enabled by setting the enable bit in matching resource control
* registers on both sides of a link. We therefore need to find the opposite
* end of the link. To keep this simple we enable from the downstream device.
* RC devices do not have an upstream device, nor does it seem that VC9 do
* (spec is unclear). Once we find the upstream device, match the VC ID to
* get the correct resource, disable and enable on both ends.
*/
static void pci_vc_enable(struct pci_dev *dev, int pos, int res)
{
int ctrl_pos, status_pos, id, pos2, evcc, i, ctrl_pos2, status_pos2;
u32 ctrl, header, cap1, ctrl2;
struct pci_dev *link = NULL;
/* Enable VCs from the downstream device */
if (!dev->has_secondary_link)
return;
ctrl_pos = pos + PCI_VC_RES_CTRL + (res * PCI_CAP_VC_PER_VC_SIZEOF);
status_pos = pos + PCI_VC_RES_STATUS + (res * PCI_CAP_VC_PER_VC_SIZEOF);
pci_read_config_dword(dev, ctrl_pos, &ctrl);
id = ctrl & PCI_VC_RES_CTRL_ID;
pci_read_config_dword(dev, pos, &header);
/* If there is no opposite end of the link, skip to enable */
if (PCI_EXT_CAP_ID(header) == PCI_EXT_CAP_ID_VC9 ||
pci_is_root_bus(dev->bus))
goto enable;
pos2 = pci_find_ext_capability(dev->bus->self, PCI_EXT_CAP_ID_VC);
if (!pos2)
goto enable;
pci_read_config_dword(dev->bus->self, pos2 + PCI_VC_PORT_CAP1, &cap1);
evcc = cap1 & PCI_VC_CAP1_EVCC;
/* VC0 is hardwired enabled, so we can start with 1 */
for (i = 1; i < evcc + 1; i++) {
ctrl_pos2 = pos2 + PCI_VC_RES_CTRL +
(i * PCI_CAP_VC_PER_VC_SIZEOF);
status_pos2 = pos2 + PCI_VC_RES_STATUS +
(i * PCI_CAP_VC_PER_VC_SIZEOF);
pci_read_config_dword(dev->bus->self, ctrl_pos2, &ctrl2);
if ((ctrl2 & PCI_VC_RES_CTRL_ID) == id) {
link = dev->bus->self;
break;
}
}
if (!link)
goto enable;
/* Disable if enabled */
if (ctrl2 & PCI_VC_RES_CTRL_ENABLE) {
ctrl2 &= ~PCI_VC_RES_CTRL_ENABLE;
pci_write_config_dword(link, ctrl_pos2, ctrl2);
}
/* Enable on both ends */
ctrl2 |= PCI_VC_RES_CTRL_ENABLE;
pci_write_config_dword(link, ctrl_pos2, ctrl2);
enable:
ctrl |= PCI_VC_RES_CTRL_ENABLE;
pci_write_config_dword(dev, ctrl_pos, ctrl);
if (!pci_wait_for_pending(dev, status_pos, PCI_VC_RES_STATUS_NEGO))
pci_err(dev, "VC%d negotiation stuck pending\n", id);
if (link && !pci_wait_for_pending(link, status_pos2,
PCI_VC_RES_STATUS_NEGO))
pci_err(link, "VC%d negotiation stuck pending\n", id);
}
/**
* pci_vc_do_save_buffer - Size, save, or restore VC state
* @dev: device
* @pos: starting position of VC capability (VC/VC9/MFVC)
* @save_state: buffer for save/restore
* @name: for error message
* @save: if provided a buffer, this indicates what to do with it
*
* Walking Virtual Channel config space to size, save, or restore it
* is complicated, so we do it all from one function to reduce code and
* guarantee ordering matches in the buffer. When called with NULL
* @save_state, return the size of the necessary save buffer. When called
* with a non-NULL @save_state, @save determines whether we save to the
* buffer or restore from it.
*/
static int pci_vc_do_save_buffer(struct pci_dev *dev, int pos,
struct pci_cap_saved_state *save_state,
bool save)
{
u32 cap1;
char evcc, lpevcc, parb_size;
int i, len = 0;
u8 *buf = save_state ? (u8 *)save_state->cap.data : NULL;
/* Sanity check buffer size for save/restore */
if (buf && save_state->cap.size !=
pci_vc_do_save_buffer(dev, pos, NULL, save)) {
pci_err(dev, "VC save buffer size does not match @0x%x\n", pos);
return -ENOMEM;
}
pci_read_config_dword(dev, pos + PCI_VC_PORT_CAP1, &cap1);
/* Extended VC Count (not counting VC0) */
evcc = cap1 & PCI_VC_CAP1_EVCC;
/* Low Priority Extended VC Count (not counting VC0) */
lpevcc = (cap1 & PCI_VC_CAP1_LPEVCC) >> 4;
/* Port Arbitration Table Entry Size (bits) */
parb_size = 1 << ((cap1 & PCI_VC_CAP1_ARB_SIZE) >> 10);
/*
* Port VC Control Register contains VC Arbitration Select, which
* cannot be modified when more than one LPVC is in operation. We
* therefore save/restore it first, as only VC0 should be enabled
* after device reset.
*/
if (buf) {
if (save)
pci_read_config_word(dev, pos + PCI_VC_PORT_CTRL,
(u16 *)buf);
else
pci_write_config_word(dev, pos + PCI_VC_PORT_CTRL,
*(u16 *)buf);
buf += 4;
}
len += 4;
/*
* If we have any Low Priority VCs and a VC Arbitration Table Offset
* in Port VC Capability Register 2 then save/restore it next.
*/
if (lpevcc) {
u32 cap2;
int vcarb_offset;
pci_read_config_dword(dev, pos + PCI_VC_PORT_CAP2, &cap2);
vcarb_offset = ((cap2 & PCI_VC_CAP2_ARB_OFF) >> 24) * 16;
if (vcarb_offset) {
int size, vcarb_phases = 0;
if (cap2 & PCI_VC_CAP2_128_PHASE)
vcarb_phases = 128;
else if (cap2 & PCI_VC_CAP2_64_PHASE)
vcarb_phases = 64;
else if (cap2 & PCI_VC_CAP2_32_PHASE)
vcarb_phases = 32;
/* Fixed 4 bits per phase per lpevcc (plus VC0) */
size = ((lpevcc + 1) * vcarb_phases * 4) / 8;
if (size && buf) {
pci_vc_save_restore_dwords(dev,
pos + vcarb_offset,
(u32 *)buf,
size / 4, save);
/*
* On restore, we need to signal hardware to
* re-load the VC Arbitration Table.
*/
if (!save)
pci_vc_load_arb_table(dev, pos);
buf += size;
}
len += size;
}
}
/*
* In addition to each VC Resource Control Register, we may have a
* Port Arbitration Table attached to each VC. The Port Arbitration
* Table Offset in each VC Resource Capability Register tells us if
* it exists. The entry size is global from the Port VC Capability
* Register1 above. The number of phases is determined per VC.
*/
for (i = 0; i < evcc + 1; i++) {
u32 cap;
int parb_offset;
pci_read_config_dword(dev, pos + PCI_VC_RES_CAP +
(i * PCI_CAP_VC_PER_VC_SIZEOF), &cap);
parb_offset = ((cap & PCI_VC_RES_CAP_ARB_OFF) >> 24) * 16;
if (parb_offset) {
int size, parb_phases = 0;
if (cap & PCI_VC_RES_CAP_256_PHASE)
parb_phases = 256;
else if (cap & (PCI_VC_RES_CAP_128_PHASE |
PCI_VC_RES_CAP_128_PHASE_TB))
parb_phases = 128;
else if (cap & PCI_VC_RES_CAP_64_PHASE)
parb_phases = 64;
else if (cap & PCI_VC_RES_CAP_32_PHASE)
parb_phases = 32;
size = (parb_size * parb_phases) / 8;
if (size && buf) {
pci_vc_save_restore_dwords(dev,
pos + parb_offset,
(u32 *)buf,
size / 4, save);
buf += size;
}
len += size;
}
/* VC Resource Control Register */
if (buf) {
int ctrl_pos = pos + PCI_VC_RES_CTRL +
(i * PCI_CAP_VC_PER_VC_SIZEOF);
if (save)
pci_read_config_dword(dev, ctrl_pos,
(u32 *)buf);
else {
u32 tmp, ctrl = *(u32 *)buf;
/*
* For an FLR case, the VC config may remain.
* Preserve enable bit, restore the rest.
*/
pci_read_config_dword(dev, ctrl_pos, &tmp);
tmp &= PCI_VC_RES_CTRL_ENABLE;
tmp |= ctrl & ~PCI_VC_RES_CTRL_ENABLE;
pci_write_config_dword(dev, ctrl_pos, tmp);
/* Load port arbitration table if used */
if (ctrl & PCI_VC_RES_CTRL_ARB_SELECT)
pci_vc_load_port_arb_table(dev, pos, i);
/* Re-enable if needed */
if ((ctrl ^ tmp) & PCI_VC_RES_CTRL_ENABLE)
pci_vc_enable(dev, pos, i);
}
buf += 4;
}
len += 4;
}
return buf ? 0 : len;
}
static struct {
u16 id;
const char *name;
} vc_caps[] = { { PCI_EXT_CAP_ID_MFVC, "MFVC" },
{ PCI_EXT_CAP_ID_VC, "VC" },
{ PCI_EXT_CAP_ID_VC9, "VC9" } };
/**
* pci_save_vc_state - Save VC state to pre-allocate save buffer
* @dev: device
*
* For each type of VC capability, VC/VC9/MFVC, find the capability and
* save it to the pre-allocated save buffer.
*/
int pci_save_vc_state(struct pci_dev *dev)
{
int i;
for (i = 0; i < ARRAY_SIZE(vc_caps); i++) {
int pos, ret;
struct pci_cap_saved_state *save_state;
pos = pci_find_ext_capability(dev, vc_caps[i].id);
if (!pos)
continue;
save_state = pci_find_saved_ext_cap(dev, vc_caps[i].id);
if (!save_state) {
pci_err(dev, "%s buffer not found in %s\n",
vc_caps[i].name, __func__);
return -ENOMEM;
}
ret = pci_vc_do_save_buffer(dev, pos, save_state, true);
if (ret) {
pci_err(dev, "%s save unsuccessful %s\n",
vc_caps[i].name, __func__);
return ret;
}
}
return 0;
}
/**
* pci_restore_vc_state - Restore VC state from save buffer
* @dev: device
*
* For each type of VC capability, VC/VC9/MFVC, find the capability and
* restore it from the previously saved buffer.
*/
void pci_restore_vc_state(struct pci_dev *dev)
{
int i;
for (i = 0; i < ARRAY_SIZE(vc_caps); i++) {
int pos;
struct pci_cap_saved_state *save_state;
pos = pci_find_ext_capability(dev, vc_caps[i].id);
save_state = pci_find_saved_ext_cap(dev, vc_caps[i].id);
if (!save_state || !pos)
continue;
pci_vc_do_save_buffer(dev, pos, save_state, false);
}
}
/**
* pci_allocate_vc_save_buffers - Allocate save buffers for VC caps
* @dev: device
*
* For each type of VC capability, VC/VC9/MFVC, find the capability, size
* it, and allocate a buffer for save/restore.
*/
void pci_allocate_vc_save_buffers(struct pci_dev *dev)
{
int i;
for (i = 0; i < ARRAY_SIZE(vc_caps); i++) {
int len, pos = pci_find_ext_capability(dev, vc_caps[i].id);
if (!pos)
continue;
len = pci_vc_do_save_buffer(dev, pos, NULL, false);
if (pci_add_ext_cap_save_buffer(dev, vc_caps[i].id, len))
pci_err(dev, "unable to preallocate %s save buffer\n",
vc_caps[i].name);
}
}
| {
"pile_set_name": "Github"
} |
#region BSD License
/* Copyright (c) 2013-2020, Doxense SAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Doxense nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
namespace FoundationDB.Client
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using JetBrains.Annotations;
/// <summary>Settings used when establishing the connection with a FoundationDB cluster</summary>
[DebuggerDisplay("{" + nameof(ToString) + "(),nq}")]
public sealed class FdbConnectionOptions
{
//REVIEW: rename this to "FdbConnectionString"? (so that it feels more like ADO.NET?)
[Obsolete("This value should not be used anymore.")]
public const string DefaultDbName = "DB";
/// <summary>Full path to a specific 'fdb.cluster' file</summary>
public string? ClusterFile { get; set; }
/// <summary>Default database name</summary>
/// <remarks>Only "DB" is supported for now</remarks>
[Obsolete("This property should not be used anymore, and its value will be ignored.")]
public string DbName { get; set; } = DefaultDbName;
/// <summary>If true, opens a read-only view of the database</summary>
/// <remarks>If set to true, only read-only transactions will be allowed on the database instance</remarks>
public bool ReadOnly { get; set; }
/// <summary>Default timeout for all transactions, in milliseconds precision (or infinite if 0)</summary>
public TimeSpan DefaultTimeout { get; set; } // sec
/// <summary>Default maximum number of retries for all transactions (or infinite if 0)</summary>
public int DefaultRetryLimit { get; set; }
/// <summary>Default maximum retry delay for all transactions (or infinite if 0)</summary>
public int DefaultMaxRetryDelay { get; set; }
/// <summary>Default root location used by the database (empty prefix by default)</summary>
/// <remarks>If specified, all started transactions will be automatically rooted to this location.</remarks>
public FdbPath? Root { get; set; }
/// <summary>If set, specify the datacenter ID that was passed to fdbserver processes running in the same datacenter as this client, for better location-aware load balancing.</summary>
public string? DataCenterId { get; set; }
/// <summary>If set, specify the machine ID that was passed to fdbserver processes running on the same machine as this client, for better location-aware load balancing.</summary>
public string? MachineId { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
AddKeyValue(sb, "cluster_file", this.ClusterFile ?? "default");
if (this.Root != null) AddKeyValue(sb, "root", this.Root.ToString());
//REVIEW: cannot serialize subspace into a string ! :(
if (this.ReadOnly) AddKeyword(sb, "readonly");
if (this.DefaultTimeout > TimeSpan.Zero) AddKeyValue(sb, "timeout", this.DefaultTimeout.TotalSeconds);
if (this.DefaultRetryLimit > 0) AddKeyValue(sb, "retry_limit", this.DefaultRetryLimit);
if (this.DefaultMaxRetryDelay > 0) AddKeyValue(sb, "retry_delay", this.DefaultMaxRetryDelay);
AddKeyValue(sb, "dc_id", this.DataCenterId);
AddKeyValue(sb, "machine_id", this.MachineId);
return sb.ToString();
}
private static void AddKeyValue(StringBuilder sb, string key, string? value)
{
if (value == null) return;
if (value.IndexOf(' ') >= 0 || value.IndexOf(';') >= 0)
{ // encode '"' into '\"'
value = "\"" + value.Replace("\"", "\\\"") + "\"";
}
if (sb.Length > 0) sb.Append("; ");
sb.Append(key).Append('=').Append(value);
}
private static void AddKeyValue(StringBuilder sb, string key, long value)
{
if (sb.Length > 0) sb.Append("; ");
sb.Append(key).Append('=').Append(value.ToString(CultureInfo.InvariantCulture));
}
private static void AddKeyValue(StringBuilder sb, string key, double value)
{
if (sb.Length > 0) sb.Append("; ");
sb.Append(key).Append('=').Append(value.ToString("R", CultureInfo.InvariantCulture));
}
private static void AddKeyword(StringBuilder sb, string key)
{
if (sb.Length > 0) sb.Append("; ");
sb.Append(key);
}
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.