text stringlengths 2 1.04M | meta dict |
|---|---|
#import "NSObject.h"
@class NSMapTable, NSMutableSet, NSOrderedSet, NSSet;
@interface PUPhotoSelectionManager : NSObject
{
NSMapTable *_selectionEntriesByContainer;
NSMutableSet *_uniqueAssetSelection;
long long _selectionChangeCount;
long long _options;
id <PUPhotoSelectionManagerDelegate> _delegate;
}
@property(nonatomic) id <PUPhotoSelectionManagerDelegate> delegate; // @synthesize delegate=_delegate;
@property(readonly, nonatomic) long long options; // @synthesize options=_options;
- (void).cxx_destruct;
- (_Bool)_shouldUniqueAssets;
- (void)_endSelectionChange;
- (void)_beginSelectionChange;
- (void)invalidateAllAssetIndexes;
- (void)handleCollectionListChangeNotifications:(id)arg1 collectionChangeNotifications:(id)arg2;
- (id)localizedSelectionString;
@property(readonly, nonatomic) NSOrderedSet *orderedSelectedAssets;
@property(readonly, nonatomic) NSSet *selectedAssets;
- (id)selectedAssetsWithContainerOrdering:(id)arg1;
- (void)enumerateSelectedAssetsWithContainerOrdering:(id)arg1 block:(id)arg2;
- (id)selectedAssetIndexesWithContainerOrdering:(id)arg1;
- (_Bool)areAllAssetsSelectedInContainers:(id)arg1;
- (_Bool)areAllAssetsSelectedInContainer:(id)arg1;
- (_Bool)isAnyAssetSelectedInContainers:(id)arg1;
- (_Bool)isAnyAssetSelectedInContainer:(id)arg1;
- (_Bool)isAssetAtIndexSelected:(unsigned long long)arg1 inContainer:(id)arg2;
- (void)deselectAllAssets;
- (void)deselectAllAssetsInContainers:(id)arg1;
- (void)deselectAssetsAtIndexes:(id)arg1 inContainer:(id)arg2;
- (void)deselectAssetAtIndex:(unsigned long long)arg1 inContainer:(id)arg2;
- (void)selectAllAssetsInContainers:(id)arg1;
- (void)selectAssetsAtIndexes:(id)arg1 inContainer:(id)arg2;
- (void)selectAssetAtIndex:(unsigned long long)arg1 inContainer:(id)arg2;
- (id)_selectionEntryForContainer:(id)arg1 createIfNeeded:(_Bool)arg2;
- (id)initWithOptions:(long long)arg1;
- (id)init;
@end
| {
"content_hash": "c588ce8f4bec85fa69672b32be9b4e62",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 102,
"avg_line_length": 40.59574468085106,
"alnum_prop": 0.7940251572327044,
"repo_name": "matthewsot/CocoaSharp",
"id": "9748d4cf09a9af1a9614f05f6eae822021becf53",
"size": "2048",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Headers/PrivateFrameworks/PhotosUI/PUPhotoSelectionManager.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "259784"
},
{
"name": "C#",
"bytes": "2789005"
},
{
"name": "C++",
"bytes": "252504"
},
{
"name": "Objective-C",
"bytes": "24301417"
},
{
"name": "Smalltalk",
"bytes": "167909"
}
],
"symlink_target": ""
} |
from keystone.tests.unit.ksfixtures.auth_plugins import ConfigAuthPlugins # noqa
from keystone.tests.unit.ksfixtures.backendloader import BackendLoader # noqa
from keystone.tests.unit.ksfixtures.cache import Cache # noqa
from keystone.tests.unit.ksfixtures.key_repository import KeyRepository # noqa
from keystone.tests.unit.ksfixtures.policy import Policy # noqa
| {
"content_hash": "8b3265926234f72498cc5082e2b70251",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 81,
"avg_line_length": 73.8,
"alnum_prop": 0.8319783197831978,
"repo_name": "cernops/keystone",
"id": "eb30572ca9aa9f49265932b0c75ad59d5ccfd087",
"size": "915",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "keystone/tests/unit/ksfixtures/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "665"
},
{
"name": "Python",
"bytes": "4691908"
}
],
"symlink_target": ""
} |
static char *rcsid="@(#)$Id: charstring.old.c,v 1.1.1.1 2003/11/20 07:46:26 eus Exp $";
#include <ctype.h>
#include "eus.h"
extern byte *get_string();
pointer CHAR(ctx,n,argv)
register context *ctx;
register int n;
register pointer argv[];
{ register pointer a=argv[0];
ckarg(2);
n=ckintval(argv[1]);
if (!isstring(a)) error(E_NOSTRING);
if (n<0 || vecsize(a)<=n) error(E_ARRAYINDEX);
/* This code should be eliminated, because the compiler cannot know if
this object is a normal string or a foreign string, thus no optimization.
if (elmtypeof(a)==ELM_FOREIGN)
return(makeint((a->c.foreign.chars)[n]));
else */
return(makeint(a->c.str.chars[n]));}
pointer SETCHAR(ctx,n,argv)
register context *ctx;
register int n;
register pointer argv[];
{ register pointer a=argv[0];
register int newval=ckintval(argv[2]);
ckarg(3);
n=ckintval(argv[1]);
if (!isstring(a)) error(E_NOSTRING);
if (n<0 || vecsize(a)<=n) error(E_ARRAYINDEX);
/* if (elmtypeof(a)==ELM_FOREIGN)
((byte *)(a->c.ivec.iv[0]))[n]=newval;
else */
a->c.str.chars[n]=newval;
return(argv[2]);}
pointer UPCASEP(ctx,n,argv)
register context *ctx;
register int n;
register pointer argv[];
{ ckarg(1); n=ckintval(argv[0]);
return((isupper(n))?T:NIL);}
pointer LOWCASEP(ctx,n,argv)
register context *ctx;
register int n;
register pointer argv[];
{ ckarg(1); n=ckintval(argv[0]);
return((islower(n))?T:NIL);}
pointer ALPHAP(ctx,n,argv)
register context *ctx;
register int n;
pointer argv[];
{ ckarg(1); n=ckintval(argv[0]);
return((isalpha(n))?T:NIL);}
pointer DIGITP(ctx,n,argv)
register context *ctx;
register int n;
pointer argv[];
{ ckarg(1); n=ckintval(argv[0]);
return((isdigit(n))?T:NIL);}
pointer ALNUMP(ctx,n,argv)
register context *ctx;
register int n;
register pointer argv[];
{ ckarg(1); n=ckintval(argv[0]);
return((isalnum(n))?T:NIL);}
pointer CHUPCASE(ctx,n,argv)
register context *ctx;
register int n;
pointer argv[];
{ ckarg(1); n=ckintval(argv[0]);
return((islower(n))?(makeint(toupper(n))):argv[0]);}
pointer CHDOWNCASE(ctx,n,argv)
register context *ctx;
register int n;
pointer argv[];
{ ckarg(1); n=ckintval(argv[0]);
return((isupper(n))?(makeint(tolower(n))):argv[0]);}
pointer STRINGEQ(ctx,n,argv)
register context *ctx;
int n;
register pointer argv[];
{ register byte *str1, *str2;
int start1,end1,start2,end2;
register int len;
pointer s1=Getstring(argv[0]), s2=Getstring(argv[1]);
ckarg(6);
start1=ckintval(argv[2]); end1=ckintval(argv[3]);
end1=min(end1,vecsize(s1));
start2=ckintval(argv[4]); end2=ckintval(argv[5]);
end2=min(end2,vecsize(s2));
len=end1-start1;
if (len!=end2-start2) return(NIL);
str1= &s1->c.str.chars[start1]; str2= &s2->c.str.chars[start2];
while (len-->0) if (*str1++ != *str2++) return(NIL);
return(T);}
pointer STRINGEQUAL(ctx,n,argv)
register context *ctx;
int n;
register pointer argv[];
{ register byte *str1, *str2;
int start1,end1,start2,end2,ch1,ch2;
pointer s1=Getstring(argv[0]),s2=Getstring(argv[1]);
register int len;
ckarg(6);
start1=ckintval(argv[2]); end1=ckintval(argv[3]); end1=min(end1,vecsize(s1));
start2=ckintval(argv[4]); end2=ckintval(argv[5]); end2=min(end2,vecsize(s2));
len=end1-start1;
if (len!=end2-start2) return(NIL);
str1= &s1->c.str.chars[start1]; str2= &s2->c.str.chars[start2];
while (len-->0) {
ch1= *str1++; ch2= *str2++;
if (islower(ch1)) ch1=toupper(ch1);
if (islower(ch2)) ch2=toupper(ch2);
if (ch1!=ch2) return(NIL);}
return(T);}
/****************************************************************/
/* S T R I N G compare
/****************************************************************/
pointer STR_LT(ctx,n,argv)
register context *ctx;
int n;
register pointer argv[];
{ ckarg(2);
if (strcmp(get_string(argv[0]),get_string(argv[1]))<0) return(T);
else return(NIL);}
pointer STR_LE(ctx,n,argv)
register context *ctx;
int n;
register pointer argv[];
{ ckarg(2);
if (strcmp(get_string(argv[0]),get_string(argv[1]))<=0) return(T);
else return(NIL);}
pointer STR_EQ(ctx,n,argv)
register context *ctx;
int n;
register pointer argv[];
{ ckarg(2);
if (strcmp(get_string(argv[0]),get_string(argv[1]))==0) return(T);
else return(NIL);}
pointer STR_GT(ctx,n,argv)
register context *ctx;
int n;
register pointer argv[];
{ ckarg(2);
if (strcmp(get_string(argv[0]),get_string(argv[1]))>0) return(T);
else return(NIL);}
pointer STR_GE(ctx,n,argv)
register context *ctx;
int n;
register pointer argv[];
{ ckarg(2);
if (strcmp(get_string(argv[0]),get_string(argv[1]))>=0) return(T);
else return(NIL);}
/* initializers */
charstring(ctx,mod)
register context *ctx;
register pointer mod;
{
defun(ctx,"CHAR",mod,CHAR);
defun(ctx,"SCHAR",mod,CHAR);
defun(ctx,"SETCHAR",mod,SETCHAR);
defun(ctx,"ALPHA-CHAR-P",mod,ALPHAP);
defun(ctx,"UPPER-CASE-P",mod,UPCASEP);
defun(ctx,"LOWER-CASE-P",mod,LOWCASEP);
defun(ctx,"DIGIT-CHAR-P",mod,DIGITP);
defun(ctx,"ALPHANUMERICP",mod,ALNUMP);
defun(ctx,"CHAR-UPCASE",mod,CHUPCASE);
defun(ctx,"CHAR-DOWNCASE",mod,CHDOWNCASE);
defun(ctx,"STRINGEQ",mod,STRINGEQ);
defun(ctx,"STRINGEQUAL",mod,STRINGEQUAL);
defun(ctx,"STRING<",mod,STR_LT);
defun(ctx,"STRING<=",mod,STR_LE);
defun(ctx,"STRING=",mod,STR_EQ);
defun(ctx,"STRING>",mod,STR_GT);
defun(ctx,"STRING>=",mod,STR_GE);
}
| {
"content_hash": "814408e5620d94b08dc3ada4b267fae3",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 87,
"avg_line_length": 26.944444444444443,
"alnum_prop": 0.6521087160262418,
"repo_name": "wkentaro/EusLisp",
"id": "1238b5e294273f0c74213cac5b986ffac2ab8553",
"size": "5561",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "lisp/c/charstring.old.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "2046"
},
{
"name": "C",
"bytes": "1437144"
},
{
"name": "C++",
"bytes": "3097"
},
{
"name": "Common Lisp",
"bytes": "26739463"
},
{
"name": "Groff",
"bytes": "7765"
},
{
"name": "Makefile",
"bytes": "4756"
},
{
"name": "OpenEdge ABL",
"bytes": "2647"
},
{
"name": "Prolog",
"bytes": "96412"
},
{
"name": "Shell",
"bytes": "5171"
},
{
"name": "TeX",
"bytes": "9814"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/nav_menu_height"
android:padding="@dimen/nav_frame_padding"
android:theme="?navButtonsTheme">
<ImageButton
android:id="@+id/traffic"
style="@style/MwmWidget.MapButton.Traffic"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="invisible"/>
<ImageButton
android:id="@+id/subway"
style="@style/MwmWidget.MapButton.Traffic"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="?attr/nav_bg_subway"
android:visibility="invisible"/>
<ImageButton
android:id="@+id/nav_zoom_in"
style="@style/MwmWidget.MapButton"
android:layout_above="@+id/nav_zoom_out"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="?nav_background"
android:src="@drawable/ic_zoom_in"/>
<ImageButton
android:id="@id/nav_zoom_out"
style="@style/MwmWidget.MapButton"
android:layout_above="@+id/my_position"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="?nav_background"
android:src="@drawable/ic_zoom_out"/>
<ImageButton
android:id="@id/my_position"
style="@style/MwmWidget.MapButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="@dimen/margin_base_plus"
android:background="?nav_background"
android:contentDescription="@string/core_my_position"
android:tint="@null"/>
</RelativeLayout>
| {
"content_hash": "af98aa78ba49ebf6459fef766ef50794",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 60,
"avg_line_length": 34.6,
"alnum_prop": 0.7230688386757751,
"repo_name": "alexzatsepin/omim",
"id": "a6ca63341b6bf7bd33b4f52a0885c4d9fb86c417",
"size": "1903",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "android/res/layout-land/map_navigation_buttons.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "3962"
},
{
"name": "Batchfile",
"bytes": "5586"
},
{
"name": "C",
"bytes": "13984459"
},
{
"name": "C++",
"bytes": "148411082"
},
{
"name": "CMake",
"bytes": "249320"
},
{
"name": "CSS",
"bytes": "26798"
},
{
"name": "Common Lisp",
"bytes": "17587"
},
{
"name": "DIGITAL Command Language",
"bytes": "36710"
},
{
"name": "GLSL",
"bytes": "58384"
},
{
"name": "Gherkin",
"bytes": "305230"
},
{
"name": "Go",
"bytes": "12771"
},
{
"name": "HTML",
"bytes": "9503594"
},
{
"name": "Inno Setup",
"bytes": "4337"
},
{
"name": "Java",
"bytes": "2486120"
},
{
"name": "JavaScript",
"bytes": "29076"
},
{
"name": "Lua",
"bytes": "57672"
},
{
"name": "M4",
"bytes": "53992"
},
{
"name": "Makefile",
"bytes": "429637"
},
{
"name": "Metal",
"bytes": "77540"
},
{
"name": "Module Management System",
"bytes": "2080"
},
{
"name": "Objective-C",
"bytes": "2046640"
},
{
"name": "Objective-C++",
"bytes": "1300948"
},
{
"name": "PHP",
"bytes": "2841"
},
{
"name": "Perl",
"bytes": "57807"
},
{
"name": "PowerShell",
"bytes": "1885"
},
{
"name": "Python",
"bytes": "584274"
},
{
"name": "Roff",
"bytes": "13545"
},
{
"name": "Ruby",
"bytes": "66800"
},
{
"name": "Shell",
"bytes": "1317925"
},
{
"name": "Swift",
"bytes": "511409"
},
{
"name": "sed",
"bytes": "236"
}
],
"symlink_target": ""
} |
appControllers.controller('ListController', ['$scope','$http', function($scope, $http) {
var createEvent = function(eventType, name, date, reason) {
return {
EventType: eventType,
Name: name,
OccurDate: date,
Reason: reason,
}
};
var extractEventsFromData = function(data) {
var entries = data.entries;
$scope.events = [];
for (var i = 0; i <entries.length ; i++) {
var e = entries[i];
var strippedData = e.data.replace("/\r?\n|\r/g","");
var objectData = JSON.parse(strippedData);
var newEvent = createEvent(e.eventType,objectData.Name, e.updated.substring(0,10) ,objectData.Reason );
$scope.events.push(newEvent);
}
}
$http.get("http://localhost:2113/streams/moods?embed=tryHarder")
.success(function(data, status) {
$scope.status = status;
var serializedData = angular.toJson(data,true);
//var strippedData = serializedData.replace("/\r?\n|\r/g","");
var strippedData = serializedData.replace(/(\\r\\n|\\n|\\r|)/gm,"");
var furtherStrippedData = strippedData.replace(/( \\\"| \\\"|\\\")/gm,"\"")
console.log(strippedData);
console.log("---------------------------------");
console.log(furtherStrippedData);
//var goodData = JSON.parse(strippedData.replace(/(\\\")/gm,"\""));
extractEventsFromData(data);
})
.error(function(data, status) {
$scope.status = status;
});
}]);
| {
"content_hash": "19e0245a8138953665ff39ea10d736eb",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 110,
"avg_line_length": 28.433962264150942,
"alnum_prop": 0.5713337757133378,
"repo_name": "still-adam-k/HappyFace",
"id": "76bdd0e5dd5b0f1de04ab5c529fbceef6e18a36b",
"size": "1507",
"binary": false,
"copies": "1",
"ref": "refs/heads/happy_face",
"path": "app/js/listController.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "601"
},
{
"name": "JavaScript",
"bytes": "127095"
}
],
"symlink_target": ""
} |
package org.elasticsearch.search.aggregations.pipeline;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.TreeMap;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.BUCKETS_PATH;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.FORMAT;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.GAP_POLICY;
public class BucketScriptPipelineAggregationBuilder extends AbstractPipelineAggregationBuilder<BucketScriptPipelineAggregationBuilder> {
public static final String NAME = "bucket_script";
private final Script script;
private final Map<String, String> bucketsPathsMap;
private String format = null;
private GapPolicy gapPolicy = GapPolicy.SKIP;
public static final ConstructingObjectParser<BucketScriptPipelineAggregationBuilder, String> PARSER = new ConstructingObjectParser<>(
NAME, false, (args, name) -> {
@SuppressWarnings("unchecked")
var bucketsPathsMap = (Map<String, String>) args[0];
return new BucketScriptPipelineAggregationBuilder(name, bucketsPathsMap, (Script) args[1]);
});
static {
PARSER.declareField(constructorArg(), BucketScriptPipelineAggregationBuilder::extractBucketPath,
BUCKETS_PATH_FIELD, ObjectParser.ValueType.OBJECT_ARRAY_OR_STRING);
Script.declareScript(PARSER, constructorArg());
PARSER.declareString(BucketScriptPipelineAggregationBuilder::format, FORMAT);
PARSER.declareField(BucketScriptPipelineAggregationBuilder::gapPolicy, p -> {
if (p.currentToken() == XContentParser.Token.VALUE_STRING) {
return GapPolicy.parse(p.text().toLowerCase(Locale.ROOT), p.getTokenLocation());
}
throw new IllegalArgumentException("Unsupported token [" + p.currentToken() + "]");
}, GAP_POLICY, ObjectParser.ValueType.STRING);
};
public BucketScriptPipelineAggregationBuilder(String name, Map<String, String> bucketsPathsMap, Script script) {
super(name, NAME, new TreeMap<>(bucketsPathsMap).values().toArray(new String[bucketsPathsMap.size()]));
this.bucketsPathsMap = bucketsPathsMap;
this.script = script;
}
public BucketScriptPipelineAggregationBuilder(String name, Script script, String... bucketsPaths) {
this(name, convertToBucketsPathMap(bucketsPaths), script);
}
/**
* Read from a stream.
*/
public BucketScriptPipelineAggregationBuilder(StreamInput in) throws IOException {
super(in, NAME);
int mapSize = in.readVInt();
bucketsPathsMap = new HashMap<>(mapSize);
for (int i = 0; i < mapSize; i++) {
bucketsPathsMap.put(in.readString(), in.readString());
}
script = new Script(in);
format = in.readOptionalString();
gapPolicy = GapPolicy.readFrom(in);
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeVInt(bucketsPathsMap.size());
for (Entry<String, String> e : bucketsPathsMap.entrySet()) {
out.writeString(e.getKey());
out.writeString(e.getValue());
}
script.writeTo(out);
out.writeOptionalString(format);
gapPolicy.writeTo(out);
}
private static Map<String, String> extractBucketPath(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
if (token == XContentParser.Token.VALUE_STRING) {
// input is a string, name of the path set to '_value'.
// This is a bit odd as there is not constructor for it
return Collections.singletonMap("_value", parser.text());
} else if (token == XContentParser.Token.START_ARRAY) {
// input is an array, name of the path set to '_value' + position
Map<String, String> bucketsPathsMap = new HashMap<>();
int i =0;
while ((parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String path = parser.text();
bucketsPathsMap.put("_value" + i++, path);
}
return bucketsPathsMap;
} else {
// input is an object, it should contain name / value pairs
return parser.mapStrings();
}
}
private static Map<String, String> convertToBucketsPathMap(String[] bucketsPaths) {
Map<String, String> bucketsPathsMap = new HashMap<>();
for (int i = 0; i < bucketsPaths.length; i++) {
bucketsPathsMap.put("_value" + i, bucketsPaths[i]);
}
return bucketsPathsMap;
}
/**
* Sets the format to use on the output of this aggregation.
*/
public BucketScriptPipelineAggregationBuilder format(String format) {
if (format == null) {
throw new IllegalArgumentException("[format] must not be null: [" + name + "]");
}
this.format = format;
return this;
}
/**
* Gets the format to use on the output of this aggregation.
*/
public String format() {
return format;
}
protected DocValueFormat formatter() {
if (format != null) {
return new DocValueFormat.Decimal(format);
} else {
return DocValueFormat.RAW;
}
}
/**
* Sets the gap policy to use for this aggregation.
*/
public BucketScriptPipelineAggregationBuilder gapPolicy(GapPolicy gapPolicy) {
if (gapPolicy == null) {
throw new IllegalArgumentException("[gapPolicy] must not be null: [" + name + "]");
}
this.gapPolicy = gapPolicy;
return this;
}
/**
* Gets the gap policy to use for this aggregation.
*/
public GapPolicy gapPolicy() {
return gapPolicy;
}
@Override
protected PipelineAggregator createInternal(Map<String, Object> metadata) {
return new BucketScriptPipelineAggregator(name, bucketsPathsMap, script, formatter(), gapPolicy, metadata);
}
@Override
protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(BUCKETS_PATH.getPreferredName(), bucketsPathsMap);
builder.field(Script.SCRIPT_PARSE_FIELD.getPreferredName(), script);
if (format != null) {
builder.field(FORMAT.getPreferredName(), format);
}
builder.field(GAP_POLICY.getPreferredName(), gapPolicy.getName());
return builder;
}
@Override
protected void validate(ValidationContext context) {
context.validateHasParent(NAME, name);
}
@Override
protected boolean overrideBucketsPath() {
return true;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bucketsPathsMap, script, format, gapPolicy);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
if (super.equals(obj) == false) return false;
BucketScriptPipelineAggregationBuilder other = (BucketScriptPipelineAggregationBuilder) obj;
return Objects.equals(bucketsPathsMap, other.bucketsPathsMap)
&& Objects.equals(script, other.script)
&& Objects.equals(format, other.format)
&& Objects.equals(gapPolicy, other.gapPolicy);
}
@Override
public String getWriteableName() {
return NAME;
}
}
| {
"content_hash": "216ec676287680ca809d7f4820f2fa89",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 137,
"avg_line_length": 38.734883720930235,
"alnum_prop": 0.6706292026897214,
"repo_name": "gingerwizard/elasticsearch",
"id": "ffe704326861fd520cf367e6e6daf22caaab47f7",
"size": "9116",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "server/src/main/java/org/elasticsearch/search/aggregations/pipeline/BucketScriptPipelineAggregationBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10862"
},
{
"name": "Groovy",
"bytes": "510"
},
{
"name": "HTML",
"bytes": "1502"
},
{
"name": "Java",
"bytes": "29923429"
},
{
"name": "Perl",
"bytes": "264378"
},
{
"name": "Perl6",
"bytes": "103207"
},
{
"name": "Python",
"bytes": "91186"
},
{
"name": "Ruby",
"bytes": "17776"
},
{
"name": "Shell",
"bytes": "85779"
}
],
"symlink_target": ""
} |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.camel.impl;
import org.flowable.camel.FlowableEndpoint;
import org.flowable.camel.SpringCamelBehavior;
/**
* This implementation of the CamelBehavior abstract class works just like CamelBehaviour does; it copies variables into Camel as properties.
*
* @author Ryan Johnston (@rjfsu), Tijs Rademakers, Saeid Mirzaei
*/
public class CamelBehaviorDefaultImpl extends SpringCamelBehavior {
private static final long serialVersionUID = 003L;
@Override
protected void setPropertTargetVariable(FlowableEndpoint endpoint) {
toTargetType = TargetType.PROPERTIES;
}
}
| {
"content_hash": "fc2689667328383947c3fae8d4b94d33",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 141,
"avg_line_length": 36.65625,
"alnum_prop": 0.7612958226768969,
"repo_name": "paulstapleton/flowable-engine",
"id": "d62fbe95f45758e12cfb149b108a7f4512e113a9",
"size": "1173",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "modules/flowable-camel/src/main/java/org/flowable/camel/impl/CamelBehaviorDefaultImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "166"
},
{
"name": "CSS",
"bytes": "688913"
},
{
"name": "Dockerfile",
"bytes": "6367"
},
{
"name": "Groovy",
"bytes": "482"
},
{
"name": "HTML",
"bytes": "1100650"
},
{
"name": "Java",
"bytes": "33678803"
},
{
"name": "JavaScript",
"bytes": "12395741"
},
{
"name": "PLSQL",
"bytes": "109354"
},
{
"name": "PLpgSQL",
"bytes": "11691"
},
{
"name": "SQLPL",
"bytes": "1265"
},
{
"name": "Shell",
"bytes": "19145"
}
],
"symlink_target": ""
} |
<?php namespace Zizaco\Confide;
use Illuminate\Support\Facades\App as App;
use Illuminate\Support\Facades\Lang as Lang;
use Illuminate\Support\MessageBag;
/**
* This is the default validator used by ConfideUser. You may overwrite this
* class and implement your own validator by creating a class that implements
* the `UserValidatorInterface` and by registering that class in IoC container
* as 'confide.user_validator'.
*
* This validator will look for the basic fields (username, email,
* password), and if the user is unique.
*
* In order to use a custom validator:
* // MyOwnValidator.php
* class MyOwnValidator implements UserValidatorInterface {
* ...
* }
*
* // routes.php
* ...
* App::bind('confide.user_validator', 'MyOwnValidator');
*
* @see \Zizaco\Confide\UserValidator
* @license MIT
* @package Zizaco\Confide
*/
class UserValidator implements UserValidatorInterface
{
/**
* Confide repository instance.
*
* @var \Zizaco\Confide\RepositoryInterface
*/
public $repo;
/**
* Validation rules for this Validator.
*
* @var array
*/
public $rules = [
'create' => [
'username' => 'required|alpha_dash',
'email' => 'required|email',
'password' => 'required|min:4',
],
'update' => [
'username' => 'required|alpha_dash',
'email' => 'required|email',
'password' => 'required|min:4',
]
];
/**
* Validates the given user. Should check if all the fields are correctly.
*
* @param ConfideUserInterface $user Instance to be tested.
*
* @return boolean True if the $user is valid.
*/
public function validate(ConfideUserInterface $user, $ruleset = 'create')
{
// Set the $repo as a ConfideRepository object
$this->repo = App::make('confide.repository');
// Validate object
$result = $this->validateAttributes($user, $ruleset) ? true : false;
$result = ($this->validatePassword($user) && $result) ? true : false;
$result = ($this->validateIsUnique($user) && $result) ? true : false;
return $result;
}
/**
* Validates the password and password_confirmation of the given user.
*
* @param ConfideUserInterface $user
*
* @return boolean True if password is valid.
*/
public function validatePassword(ConfideUserInterface $user)
{
$hash = App::make('hash');
if ($user->getOriginal('password') != $user->password) {
if ($user->password === $user->password_confirmation) {
// Hashes password and unset password_confirmation field
$user->password = $hash->make($user->password);
} else {
$this->attachErrorMsg(
$user,
'confide::confide.alerts.password_confirmation',
'password_confirmation'
);
return false;
}
}
unset($user->password_confirmation);
return true;
}
/**
* Validates if the given user is unique. If there is another
* user with the same credentials but a different id, this
* method will return false.
*
* @param ConfideUserInterface $user
*
* @return boolean True if user is unique.
*/
public function validateIsUnique(ConfideUserInterface $user)
{
$identity = [
'email' => $user->email,
'username' => $user->username,
];
foreach ($identity as $attribute => $value) {
$similar = $this->repo->getUserByIdentity([$attribute => $value]);
if (!$similar || $similar->getKey() == $user->getKey()) {
unset($identity[$attribute]);
} else {
$this->attachErrorMsg(
$user,
'confide::confide.alerts.duplicated_credentials',
$attribute
);
}
}
if (!$identity) {
return true;
}
return false;
}
/**
* Uses Laravel Validator in order to check if the attributes of the
* $user object are valid for the given $ruleset.
*
* @param ConfideUserInterface $user
* @param string $ruleset The name of the key in the UserValidator->$rules array
*
* @return boolean True if the attributes are valid.
*/
public function validateAttributes(ConfideUserInterface $user, $ruleset = 'create')
{
$attributes = $user->toArray();
// Force getting password since it may be hidden from array form
$attributes['password'] = $user->getAuthPassword();
$rules = $this->rules[$ruleset];
$validator = App::make('validator')
->make($attributes, $rules);
// Validate and attach errors
if ($validator->fails()) {
$user->errors = $validator->errors();
return false;
} else {
return true;
}
}
/**
* Creates a \Illuminate\Support\MessageBag object, add the error message
* to it and then set the errors attribute of the user with that bag.
*
* @param ConfideUserInterface $user
* @param string $errorMsg The error message.
* @param string $key The key if the error message.
*/
public function attachErrorMsg(ConfideUserInterface $user, $errorMsg, $key = 'confide')
{
$messageBag = $user->errors;
if (! $messageBag instanceof MessageBag) {
$messageBag = App::make('Illuminate\Support\MessageBag');
}
$messageBag->add($key, Lang::get($errorMsg));
$user->errors = $messageBag;
}
}
| {
"content_hash": "335bb2b2e1b55d58f228f006067794f0",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 98,
"avg_line_length": 30.01530612244898,
"alnum_prop": 0.565017848036716,
"repo_name": "nguyentamvinhlong/antamu_v1",
"id": "a036e320a6fcecfd7eaa890ee77654be05d0bbed",
"size": "5883",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/zizaco/confide/src/Confide/UserValidator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "268763"
},
{
"name": "JavaScript",
"bytes": "1326824"
},
{
"name": "PHP",
"bytes": "146156"
}
],
"symlink_target": ""
} |
using Microsoft.AspNetCore.SignalR.Protocol;
namespace Microsoft.AspNetCore.SignalR.Tests;
public static class HubProtocolHelpers
{
private static readonly IHubProtocol NewtonsoftJsonHubProtocol = new NewtonsoftJsonHubProtocol();
private static readonly IHubProtocol MessagePackHubProtocol = new MessagePackHubProtocol();
public static readonly List<string> AllProtocolNames = new List<string>
{
NewtonsoftJsonHubProtocol.Name,
MessagePackHubProtocol.Name
};
public static readonly IList<IHubProtocol> AllProtocols = new List<IHubProtocol>()
{
NewtonsoftJsonHubProtocol,
MessagePackHubProtocol
};
public static IHubProtocol GetHubProtocol(string name)
{
var protocol = AllProtocols.SingleOrDefault(p => p.Name == name);
if (protocol == null)
{
throw new InvalidOperationException($"Could not find protocol with name '{name}'.");
}
return protocol;
}
}
| {
"content_hash": "895892a1cb31c59df39ee3a66c2e3866",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 101,
"avg_line_length": 30.87878787878788,
"alnum_prop": 0.6849852796859667,
"repo_name": "aspnet/AspNetCore",
"id": "cd23a8dcd3a0cd7698fe1467a072f903ad4de39a",
"size": "1157",
"binary": false,
"copies": "1",
"ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2",
"path": "src/SignalR/common/testassets/Tests.Utils/HubProtocolHelpers.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "19526"
},
{
"name": "C",
"bytes": "213916"
},
{
"name": "C#",
"bytes": "47455169"
},
{
"name": "C++",
"bytes": "1900454"
},
{
"name": "CMake",
"bytes": "7955"
},
{
"name": "CSS",
"bytes": "62326"
},
{
"name": "Dockerfile",
"bytes": "3584"
},
{
"name": "F#",
"bytes": "7982"
},
{
"name": "Groovy",
"bytes": "1529"
},
{
"name": "HTML",
"bytes": "1130653"
},
{
"name": "Java",
"bytes": "297552"
},
{
"name": "JavaScript",
"bytes": "2726829"
},
{
"name": "Lua",
"bytes": "4904"
},
{
"name": "Makefile",
"bytes": "220"
},
{
"name": "Objective-C",
"bytes": "222"
},
{
"name": "PowerShell",
"bytes": "241706"
},
{
"name": "Python",
"bytes": "19476"
},
{
"name": "Roff",
"bytes": "6044"
},
{
"name": "Shell",
"bytes": "142293"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "TypeScript",
"bytes": "797435"
}
],
"symlink_target": ""
} |
import _plotly_utils.basevalidators
class UidValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="uid", parent_name="densitymapbox", **kwargs):
super(UidValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
role=kwargs.pop("role", "info"),
**kwargs
)
| {
"content_hash": "b589beabcdfb978eec570ce4cb8c3b82",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 81,
"avg_line_length": 36.25,
"alnum_prop": 0.6022988505747127,
"repo_name": "plotly/python-api",
"id": "7a70dc6221611b0905e60a4f4b6895199c19115a",
"size": "435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/python/plotly/plotly/validators/densitymapbox/_uid.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6870"
},
{
"name": "Makefile",
"bytes": "1708"
},
{
"name": "Python",
"bytes": "823245"
},
{
"name": "Shell",
"bytes": "3238"
}
],
"symlink_target": ""
} |
require "utils"
require 'capistrano/configuration/connections'
class ConfigurationConnectionsTest < Test::Unit::TestCase
class MockConfig
attr_reader :original_initialize_called
attr_reader :values
attr_reader :dry_run
attr_accessor :current_task
def initialize
@original_initialize_called = true
@values = {}
end
def fetch(*args)
@values.fetch(*args)
end
def [](key)
@values[key]
end
def exists?(key)
@values.key?(key)
end
include Capistrano::Configuration::Connections
end
def setup
@config = MockConfig.new
@config.stubs(:logger).returns(stub_everything)
Net::SSH.stubs(:configuration_for).returns({})
@ssh_options = {
:user => "user",
:port => 8080,
:password => "g00b3r",
:ssh_options => { :debug => :verbose }
}
end
def test_initialize_should_initialize_collections_and_call_original_initialize
assert @config.original_initialize_called
assert @config.sessions.empty?
end
def test_connection_factory_should_return_default_connection_factory_instance
factory = @config.connection_factory
assert_instance_of Capistrano::Configuration::Connections::DefaultConnectionFactory, factory
end
def test_connection_factory_instance_should_be_cached
assert_same @config.connection_factory, @config.connection_factory
end
def test_default_connection_factory_honors_config_options
server = server("capistrano")
Capistrano::SSH.expects(:connect).with(server, @config).returns(:session)
assert_equal :session, @config.connection_factory.connect_to(server)
end
def test_should_connect_through_gateway_if_gateway_variable_is_set
@config.values[:gateway] = "j@gateway"
Net::SSH::Gateway.expects(:new).with("gateway", "j", :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
assert_instance_of Capistrano::Configuration::Connections::GatewayConnectionFactory, @config.connection_factory
end
def test_connection_factory_as_gateway_should_honor_config_options
@config.values[:gateway] = "gateway"
@config.values.update(@ssh_options)
Net::SSH::Gateway.expects(:new).with("gateway", "user", :debug => :verbose, :port => 8080, :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
assert_instance_of Capistrano::Configuration::Connections::GatewayConnectionFactory, @config.connection_factory
end
def test_connection_factory_as_gateway_should_chain_gateways_if_gateway_variable_is_an_array
@config.values[:gateway] = ["j@gateway1", "k@gateway2"]
gateway1 = mock
Net::SSH::Gateway.expects(:new).with("gateway1", "j", :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(gateway1)
gateway1.expects(:open).returns(65535)
Net::SSH::Gateway.expects(:new).with("127.0.0.1", "k", :port => 65535, :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
assert_instance_of Capistrano::Configuration::Connections::GatewayConnectionFactory, @config.connection_factory
end
def test_connection_factory_as_gateway_should_chain_gateways_if_gateway_variable_is_a_hash
@config.values[:gateway] = { ["j@gateway1", "k@gateway2"] => :default }
gateway1 = mock
Net::SSH::Gateway.expects(:new).with("gateway1", "j", :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(gateway1)
gateway1.expects(:open).returns(65535)
Net::SSH::Gateway.expects(:new).with("127.0.0.1", "k", :port => 65535, :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
assert_instance_of Capistrano::Configuration::Connections::GatewayConnectionFactory, @config.connection_factory
end
def test_connection_factory_as_gateway_should_share_gateway_between_connections
@config.values[:gateway] = "j@gateway"
Net::SSH::Gateway.expects(:new).once.with("gateway", "j", :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
Capistrano::SSH.stubs(:connect).returns(stub_everything)
assert_instance_of Capistrano::Configuration::Connections::GatewayConnectionFactory, @config.connection_factory
@config.establish_connections_to(server("capistrano"))
@config.establish_connections_to(server("another"))
end
def test_connection_factory_as_gateway_should_share_gateway_between_like_connections_if_gateway_variable_is_a_hash
@config.values[:gateway] = { "j@gateway" => [ "capistrano", "another"] }
Net::SSH::Gateway.expects(:new).once.with("gateway", "j", :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
Capistrano::SSH.stubs(:connect).returns(stub_everything)
assert_instance_of Capistrano::Configuration::Connections::GatewayConnectionFactory, @config.connection_factory
@config.establish_connections_to(server("capistrano"))
@config.establish_connections_to(server("another"))
end
def test_connection_factory_as_gateways_should_not_share_gateway_between_unlike_connections_if_gateway_variable_is_a_hash
@config.values[:gateway] = { "j@gateway" => [ "capistrano", "another"], "k@gateway2" => "yafhost" }
Net::SSH::Gateway.expects(:new).once.with("gateway", "j", :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
Net::SSH::Gateway.expects(:new).once.with("gateway2", "k", :password => nil, :auth_methods => %w(publickey hostbased), :config => false).returns(stub_everything)
Capistrano::SSH.stubs(:connect).returns(stub_everything)
assert_instance_of Capistrano::Configuration::Connections::GatewayConnectionFactory, @config.connection_factory
@config.establish_connections_to(server("capistrano"))
@config.establish_connections_to(server("another"))
@config.establish_connections_to(server("yafhost"))
end
def test_establish_connections_to_should_accept_a_single_nonarray_parameter
Capistrano::SSH.expects(:connect).with { |s,| s.host == "capistrano" }.returns(:success)
assert @config.sessions.empty?
@config.establish_connections_to(server("capistrano"))
assert_equal ["capistrano"], @config.sessions.keys.map(&:host)
end
def test_establish_connections_to_should_accept_an_array
Capistrano::SSH.expects(:connect).times(3).returns(:success)
assert @config.sessions.empty?
@config.establish_connections_to(%w(cap1 cap2 cap3).map { |s| server(s) })
assert_equal %w(cap1 cap2 cap3), @config.sessions.keys.sort.map(&:host)
end
def test_establish_connections_to_should_not_attempt_to_reestablish_existing_connections
Capistrano::SSH.expects(:connect).times(2).returns(:success)
@config.sessions[server("cap1")] = :ok
@config.establish_connections_to(%w(cap1 cap2 cap3).map { |s| server(s) })
assert_equal %w(cap1 cap2 cap3), @config.sessions.keys.sort.map(&:host)
end
def test_establish_connections_to_should_raise_one_connection_error_on_failure
Capistrano::SSH.expects(:connect).times(2).raises(Exception)
assert_raises(Capistrano::ConnectionError) {
@config.establish_connections_to(%w(cap1 cap2).map { |s| server(s) })
}
end
def test_connection_error_should_include_accessor_with_host_array
Capistrano::SSH.expects(:connect).times(2).raises(Exception)
begin
@config.establish_connections_to(%w(cap1 cap2).map { |s| server(s) })
flunk "expected an exception to be raised"
rescue Capistrano::ConnectionError => e
assert e.respond_to?(:hosts)
assert_equal %w(cap1 cap2), e.hosts.map { |h| h.to_s }.sort
end
end
def test_connection_error_should_only_include_failed_hosts
Capistrano::SSH.expects(:connect).with(server('cap1'), anything).raises(Exception)
Capistrano::SSH.expects(:connect).with(server('cap2'), anything).returns(:success)
begin
@config.establish_connections_to(%w(cap1 cap2).map { |s| server(s) })
flunk "expected an exception to be raised"
rescue Capistrano::ConnectionError => e
assert_equal %w(cap1), e.hosts.map { |h| h.to_s }
end
end
def test_execute_on_servers_should_require_a_block
assert_raises(ArgumentError) { @config.execute_on_servers }
end
def test_execute_on_servers_without_current_task_should_call_find_servers
list = [server("first"), server("second")]
@config.expects(:find_servers).with(:a => :b, :c => :d).returns(list)
@config.expects(:establish_connections_to).with(list).returns(:done)
@config.execute_on_servers(:a => :b, :c => :d) do |result|
assert_equal list, result
end
end
def test_execute_on_servers_without_current_task_should_raise_error_if_no_matching_servers
@config.expects(:find_servers).with(:a => :b, :c => :d).returns([])
assert_raises(Capistrano::NoMatchingServersError) { @config.execute_on_servers(:a => :b, :c => :d) { |list| } }
end
def test_execute_on_servers_without_current_task_should_not_raise_error_if_no_matching_servers_and_continue_on_no_matching_servers
@config.expects(:find_servers).with(:a => :b, :c => :d, :on_no_matching_servers => :continue).returns([])
assert_nothing_raised { @config.execute_on_servers(:a => :b, :c => :d, :on_no_matching_servers => :continue) { |list| } }
end
def test_execute_on_servers_should_raise_an_error_if_the_current_task_has_no_matching_servers_by_default
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([])
assert_raises(Capistrano::NoMatchingServersError) do
@config.execute_on_servers do
flunk "should not get here"
end
end
end
def test_execute_on_servers_should_not_raise_an_error_if_the_current_task_has_no_matching_servers_by_default_and_continue_on_no_matching_servers
@config.current_task = mock_task(:on_no_matching_servers => :continue)
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([])
assert_nothing_raised do
@config.execute_on_servers do
flunk "should not get here"
end
end
end
def test_execute_on_servers_should_not_raise_an_error_if_the_current_task_has_no_matching_servers_by_default_and_command_continues_on_no_matching_servers
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, :on_no_matching_servers => :continue).returns([])
assert_nothing_raised do
@config.execute_on_servers(:on_no_matching_servers => :continue) do
flunk "should not get here"
end
end
end
def test_execute_on_servers_should_determine_server_list_from_active_task
assert @config.sessions.empty?
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([server("cap1"), server("cap2"), server("cap3")])
Capistrano::SSH.expects(:connect).times(3).returns(:success)
@config.execute_on_servers {}
assert_equal %w(cap1 cap2 cap3), @config.sessions.keys.sort.map { |s| s.host }
end
def test_execute_on_servers_should_yield_server_list_to_block
assert @config.sessions.empty?
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([server("cap1"), server("cap2"), server("cap3")])
Capistrano::SSH.expects(:connect).times(3).returns(:success)
block_called = false
@config.execute_on_servers do |servers|
block_called = true
assert servers.detect { |s| s.host == "cap1" }
assert servers.detect { |s| s.host == "cap2" }
assert servers.detect { |s| s.host == "cap3" }
assert servers.all? { |s| @config.sessions[s] }
end
assert block_called
end
def test_execute_on_servers_with_once_option_should_establish_connection_to_and_yield_only_the_first_server
assert @config.sessions.empty?
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, :once => true).returns([server("cap1"), server("cap2"), server("cap3")])
Capistrano::SSH.expects(:connect).returns(:success)
block_called = false
@config.execute_on_servers(:once => true) do |servers|
block_called = true
assert_equal %w(cap1), servers.map { |s| s.host }
end
assert block_called
assert_equal %w(cap1), @config.sessions.keys.sort.map { |s| s.host }
end
def test_execute_servers_should_raise_connection_error_on_failure_by_default
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([server("cap1")])
Capistrano::SSH.expects(:connect).raises(Exception)
assert_raises(Capistrano::ConnectionError) do
@config.execute_on_servers do
flunk "expected an exception to be raised"
end
end
end
def test_execute_servers_should_not_raise_connection_error_on_failure_with_on_errors_continue
@config.current_task = mock_task(:on_error => :continue)
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([server("cap1"), server("cap2")])
Capistrano::SSH.expects(:connect).with(server('cap1'), anything).raises(Exception)
Capistrano::SSH.expects(:connect).with(server('cap2'), anything).returns(:success)
assert_nothing_raised {
@config.execute_on_servers do |servers|
assert_equal %w(cap2), servers.map { |s| s.host }
end
}
end
def test_execute_on_servers_should_not_try_to_connect_to_hosts_with_connection_errors_with_on_errors_continue
list = [server("cap1"), server("cap2")]
@config.current_task = mock_task(:on_error => :continue)
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns(list)
Capistrano::SSH.expects(:connect).with(server('cap1'), anything).raises(Exception)
Capistrano::SSH.expects(:connect).with(server('cap2'), anything).returns(:success)
@config.execute_on_servers do |servers|
assert_equal %w(cap2), servers.map { |s| s.host }
end
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns(list)
@config.execute_on_servers do |servers|
assert_equal %w(cap2), servers.map { |s| s.host }
end
end
def test_execute_on_servers_should_not_try_to_connect_to_hosts_with_command_errors_with_on_errors_continue
cap1 = server("cap1")
cap2 = server("cap2")
@config.current_task = mock_task(:on_error => :continue)
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([cap1, cap2])
Capistrano::SSH.expects(:connect).times(2).returns(:success)
@config.execute_on_servers do |servers|
error = Capistrano::CommandError.new
error.hosts = [cap1]
raise error
end
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([cap1, cap2])
@config.execute_on_servers do |servers|
assert_equal %w(cap2), servers.map { |s| s.host }
end
end
def test_execute_on_servers_should_not_try_to_connect_to_hosts_with_transfer_errors_with_on_errors_continue
cap1 = server("cap1")
cap2 = server("cap2")
@config.current_task = mock_task(:on_error => :continue)
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([cap1, cap2])
Capistrano::SSH.expects(:connect).times(2).returns(:success)
@config.execute_on_servers do |servers|
error = Capistrano::TransferError.new
error.hosts = [cap1]
raise error
end
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([cap1, cap2])
@config.execute_on_servers do |servers|
assert_equal %w(cap2), servers.map { |s| s.host }
end
end
def test_connect_should_establish_connections_to_all_servers_in_scope
assert @config.sessions.empty?
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([server("cap1"), server("cap2"), server("cap3")])
Capistrano::SSH.expects(:connect).times(3).returns(:success)
@config.connect!
assert_equal %w(cap1 cap2 cap3), @config.sessions.keys.sort.map { |s| s.host }
end
def test_execute_on_servers_should_only_run_on_tasks_max_hosts_hosts_at_once
cap1 = server("cap1")
cap2 = server("cap2")
connection1 = mock()
connection2 = mock()
connection1.expects(:close)
connection2.expects(:close)
@config.current_task = mock_task(:max_hosts => 1)
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([cap1, cap2])
Capistrano::SSH.expects(:connect).times(2).returns(connection1).then.returns(connection2)
block_called = 0
@config.execute_on_servers do |servers|
block_called += 1
assert_equal 1, servers.size
end
assert_equal 2, block_called
end
def test_execute_on_servers_should_only_run_on_max_hosts_hosts_at_once
cap1 = server("cap1")
cap2 = server("cap2")
connection1 = mock()
connection2 = mock()
connection1.expects(:close)
connection2.expects(:close)
@config.current_task = mock_task(:max_hosts => 1)
@config.expects(:find_servers_for_task).with(@config.current_task, {}).returns([cap1, cap2])
Capistrano::SSH.expects(:connect).times(2).returns(connection1).then.returns(connection2)
block_called = 0
@config.execute_on_servers do |servers|
block_called += 1
assert_equal 1, servers.size
end
assert_equal 2, block_called
end
def test_execute_on_servers_should_cope_with_already_dropped_connections_when_attempting_to_close_them
cap1 = server("cap1")
cap2 = server("cap2")
connection1 = mock()
connection2 = mock()
connection3 = mock()
connection4 = mock()
connection1.expects(:close).raises(IOError)
connection2.expects(:close)
connection3.expects(:close)
connection4.expects(:close)
@config.current_task = mock_task(:max_hosts => 1)
@config.expects(:find_servers_for_task).times(2).with(@config.current_task, {}).returns([cap1, cap2])
Capistrano::SSH.expects(:connect).times(4).returns(connection1).then.returns(connection2).then.returns(connection3).then.returns(connection4)
@config.execute_on_servers {}
@config.execute_on_servers {}
end
def test_execute_on_servers_should_cope_with_already_disconnected_connections_when_attempting_to_close_them
cap1 = server("cap1")
cap2 = server("cap2")
connection1 = mock()
connection2 = mock()
connection3 = mock()
connection4 = mock()
connection1.expects(:close).raises(Net::SSH::Disconnect)
connection2.expects(:close)
connection3.expects(:close)
connection4.expects(:close)
@config.current_task = mock_task(:max_hosts => 1)
@config.expects(:find_servers_for_task).times(2).with(@config.current_task, {}).returns([cap1, cap2])
Capistrano::SSH.expects(:connect).times(4).returns(connection1).then.returns(connection2).then.returns(connection3).then.returns(connection4)
@config.execute_on_servers {}
@config.execute_on_servers {}
end
def test_connect_should_honor_once_option
assert @config.sessions.empty?
@config.current_task = mock_task
@config.expects(:find_servers_for_task).with(@config.current_task, :once => true).returns([server("cap1"), server("cap2"), server("cap3")])
Capistrano::SSH.expects(:connect).returns(:success)
@config.connect! :once => true
assert_equal %w(cap1), @config.sessions.keys.sort.map { |s| s.host }
end
private
def mock_task(options={})
continue_on_error = options[:on_error] == :continue
stub("task",
:fully_qualified_name => "name",
:options => options,
:continue_on_error? => continue_on_error,
:max_hosts => options[:max_hosts]
)
end
end
| {
"content_hash": "0ea4f64758da290b39d6d30c0391e110",
"timestamp": "",
"source": "github",
"line_count": 439,
"max_line_length": 197,
"avg_line_length": 45.40318906605923,
"alnum_prop": 0.6937086092715232,
"repo_name": "piousbox/microsites2-cities",
"id": "41bcb7ec7c3ee9cd86511290f7fac7bdbdab683e",
"size": "19932",
"binary": false,
"copies": "1",
"ref": "refs/heads/cities2",
"path": "vendor/ruby/1.9.1/gems/capistrano-2.15.4/test/configuration/connections_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34286"
},
{
"name": "JavaScript",
"bytes": "32921"
},
{
"name": "Ruby",
"bytes": "153682"
},
{
"name": "Shell",
"bytes": "1616"
}
],
"symlink_target": ""
} |
import masterPlugin
import MatrixUtils
## Wrapper for MatrixUtils.paint()
class paint(masterPlugin.masterPlugin):
def __init__(this):
super().__init__()
this.command = "paint"
this.aliases = None
this.commandInfo = {'requiredArguments': [[0, int, 'col1'],
[1, int, 'row1'],
[2, int, 'col2'],
[3, int, 'row2']],
'optionalArguments': [[0, float, 'val']],
'argumentInfo': ['column of top-left corner',
'row of top-left corner',
'column of bottom-right corner',
'row of bottom-right corner',
'new value for elements'],
'help': """Modifies the values of the rectangular range of elements
whose top-left corner is (col1, row1) and whose bottom right
corner is (col2, row2). If val is given, elements are set equal
val, otherwise they are set to zero"""}
def execute(this, arguments, WORKINGMATRIX):
col1 = arguments[0]
row1 = arguments[1]
col2 = arguments[2]
row2 = arguments[3]
val = 0
if len(arguments) == 5:
val = arguments[4]
MatrixUtils.paint(row1, row2, col1, col2, val, WORKINGMATRIX)
def validate(this, arguments, WORKINGMATRIX):
if not super().validate(arguments, WORKINGMATRIX):
return False
return True | {
"content_hash": "ebc386b3b55bb21ba617130b42969bb2",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 80,
"avg_line_length": 35.24390243902439,
"alnum_prop": 0.5515570934256055,
"repo_name": "charlesdaniels/hercm",
"id": "018f4e7b2cb884d6735f945e0bf46422edc1279e",
"size": "1445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/python33/menuPlugins/paint.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "8577"
},
{
"name": "Makefile",
"bytes": "139"
},
{
"name": "Python",
"bytes": "113163"
}
],
"symlink_target": ""
} |
package command
import (
"encoding/json"
. "launchpad.net/gocheck"
)
type FailoverSuite struct{}
var _ = Suite(&FailoverSuite{})
func (s *FailoverSuite) TestFailoverFromObj(c *C) {
failovers := []struct {
Expected Failover
Parse string
}{
{
Parse: `true`,
Expected: Failover{
Active: true,
},
},
{
Parse: `false`,
Expected: Failover{
Active: false,
},
},
{
Parse: `{"active": true, "codes": [405, 503]}`,
Expected: Failover{
Active: true,
Codes: []int{405, 503},
},
},
}
for _, f := range failovers {
var value interface{}
err := json.Unmarshal([]byte(f.Parse), &value)
parsed, err := NewFailoverFromObj(value)
c.Assert(err, IsNil)
c.Assert(*parsed, DeepEquals, f.Expected)
}
}
| {
"content_hash": "05f8bc351787a53152ff4ac56d29d132",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 51,
"avg_line_length": 16.955555555555556,
"alnum_prop": 0.601572739187418,
"repo_name": "pquerna/vulcan",
"id": "307986236adf826208245e9854961dfe94a75aa8",
"size": "763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "command/failover_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "170662"
},
{
"name": "JavaScript",
"bytes": "610"
}
],
"symlink_target": ""
} |
layout: posts_by_category
categories: ITU
title: İstanbul Teknik Üniversitesi
permalink: /category/ITU
--- | {
"content_hash": "0ae83e9220ec70f72a871c608cea1da5",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 35,
"avg_line_length": 21.2,
"alnum_prop": 0.8018867924528302,
"repo_name": "ynsgnr/ynsgnr.github.io",
"id": "d2011a926d8d32d39dfa042684674c7b5a6e3322",
"size": "112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "category/ITU.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11539"
},
{
"name": "HTML",
"bytes": "20009"
},
{
"name": "JavaScript",
"bytes": "827"
},
{
"name": "Ruby",
"bytes": "171"
},
{
"name": "SCSS",
"bytes": "12475"
}
],
"symlink_target": ""
} |
Switchboard
===========
Switchboard is a WebSub Hub
Credits
-------
| {
"content_hash": "1f37f70040c5b1c9e845611fafe2c201",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 27,
"avg_line_length": 7.3,
"alnum_prop": 0.5616438356164384,
"repo_name": "aaronpk/Switchboard",
"id": "72ce2871aca30f0d15c92f0f89b91b47338744d8",
"size": "73",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2454"
},
{
"name": "PHP",
"bytes": "44924"
}
],
"symlink_target": ""
} |
/**
* \file
* \brief RPC-URPC scheduler.
*/
/*
* Copyright (c) 2016, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file. If
* you do not find this file, copies can be found by writing to: ETH Zurich
* D-INFK, Universitaetstr. 6, CH-8092 Zurich. Attn: Systems Group.
*/
#include <string.h>
#include "rpc_server.h"
#include "scheduler.h"
errval_t process_urpc_task(struct scheduler* sc, struct urpc_task* task)
{
errval_t err;
struct ic_frame_node* client_frame;
struct frame_identity client_frame_id;
switch (task->type) {
case UrpcOpType_Refill:
// Please refill my ic frame buffer.x
err = urpc_write_request(sc->urpc_buf, sc->my_core_id,
URPC_CODE_REFILL, 0, NULL);
break;
case UrpcOpType_Channel:
// Please connect this client to your server.
client_frame = task->client->client_frame;
CHECK("identifying client frame to create URPC channel request",
frame_identify(client_frame->frame, &client_frame_id));
uint64_t msg[2];
msg[0] = (uint64_t) client_frame_id.base;
msg[1] = (uint64_t) client_frame_id.bytes;
err = urpc_write_request(sc->urpc_buf, sc->my_core_id,
URPC_CODE_CHANNEL, sizeof(msg[0]) + sizeof(msg[1]), msg);
break;
default:
return URPC_ERR_INVALID_CODE;
}
if (err_is_fail(err)) {
// Error means we can't send a new request atm, because the previous one
// hasn't completely been responded to.
// Therefore we re-enqueue the task too look into it again later.
add_urpc_task(sc, task);
}
return SYS_ERR_OK;
}
void add_urpc_task(struct scheduler* sc, struct urpc_task* task)
{
task->prev = NULL;
if (sc->urpc_queue == NULL) {
task->next = NULL;
sc->tail_urpc_queue = task;
sc->tail_urpc_queue->next = NULL;
sc->tail_urpc_queue->prev = NULL;
} else {
task->next = sc->urpc_queue;
sc->urpc_queue->prev = task;
}
sc->urpc_queue = task;
}
struct urpc_task* pop_urpc_task(struct scheduler* sc)
{
if (sc->urpc_queue == NULL) {
// printf("Careful, URPC queue is NULL\n");
return NULL;
}
struct urpc_task* task = sc->urpc_queue;
sc->urpc_queue = sc->urpc_queue->next;
return task;
}
errval_t process_rpc_task(struct scheduler* sc, struct rpc_task* task)
{
if (task->status == RpcStatus_New) {
struct capref client_cap;
if (try_serving_locally(sc, task, &task->msg, &client_cap)) {
return SYS_ERR_OK;
}
struct client_state* client = identify_client(&client_cap,
sc->local_clients);
if (client == NULL) {
return INIT_ERR_RPC_CANNOT_SERVE;
}
task->client = client;
if (client->client_frame == NULL) {
task->status = RpcStatus_Allocate_Cframe;
} else if (client->server_frame == NULL) {
task->status = RpcStatus_Bind_Sframe;
} else {
task->status = RpcStatus_Write_Cframe;
}
}
if (task->status == RpcStatus_Allocate_Cframe) {
if (should_refill_ic_frame_buffer(sc)) {
refill_ic_frame_buffer(sc);
add_rpc_task(sc, task);
return SYS_ERR_OK;
} else if (sc->is_refilling_buffer) {
// We're not done refilling, nothing to do but return.
add_rpc_task(sc, task);
return SYS_ERR_OK;
}
task->client->client_frame = allocate_ic_frame_node(sc);
task->status = RpcStatus_Bind_Sframe;
}
if (task->status == RpcStatus_Bind_Sframe) {
if (task->client->server_frame != NULL) {
task->status = RpcStatus_Write_Cframe;
} else {
if (!task->client->binding_in_progress) {
struct urpc_task* urpc = (struct urpc_task*) malloc(
sizeof(struct urpc_task*));
urpc->type = UrpcOpType_Channel;
urpc->client = task->client;
add_urpc_task(sc, urpc);
task->client->binding_in_progress = true;
}
add_rpc_task(sc, task);
return SYS_ERR_OK;
}
}
if (task->status == RpcStatus_Write_Cframe) {
size_t req_size;
uint32_t remaining;
size_t stop;
errval_t err = SYS_ERR_OK;
switch (task->msg.words[0]) {
case AOS_RPC_MEMORY:
req_size = (size_t) task->msg.words[1];
if (req_size + task->client->ram >= MAX_CLIENT_RAM) {
// Limit to MAX_CLIENT_RAM.
req_size = MAX_CLIENT_RAM - task->client->ram;
}
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_MEMORY,
sizeof(size_t),
&req_size);
break;
case AOS_RPC_PUTCHAR:
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_PUTCHAR,
sizeof(char),
&task->msg.words[1]);
break;
case AOS_RPC_GETCHAR:
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_GETCHAR,
0,
NULL);
break;
case AOS_RPC_STRING:
remaining = task->msg.words[2];
if (task->client->str_buf == NULL) {
task->client->str_buf = (char*) malloc(
remaining * sizeof(char));
task->client->str_buf_idx = 0;
}
stop = remaining < 24 ? remaining : 24;
for (size_t i = 0; i < stop; ++i) {
uint32_t word = task->msg.words[3 + i / 4];
task->client->str_buf[task->client->str_buf_idx++] =
(char) (word >> (8 * (i % 4)));
}
remaining -= stop;
if (remaining == 0) {
// Write to c-frame and reset.
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_STRING, task->client->str_buf_idx,
task->client->str_buf);
task->client->str_buf_idx = 0;
free(task->client->str_buf);
task->client->str_buf = NULL;
} else {
// Send ok to client, will keep receiving the rest of the
// string.
CHECK("register send back to local client, for string",
lmp_chan_register_send(&task->client->lc,
get_default_waitset(),
MKCLOSURE((void*) send_simple_ok,
(void*) &task->client->lc)));
return SYS_ERR_OK;
}
break;
case AOS_RPC_SPAWN:
remaining = task->msg.words[2];
if (task->client->spawn_buf == NULL) {
task->client->spawn_buf = (char*) malloc(
remaining * sizeof(char));
task->client->spawn_buf_idx = 0;
}
stop = remaining < 24 ? remaining : 24;
for (size_t i = 0; i < stop; ++i) {
uint32_t word = task->msg.words[3 + i / 4];
task->client->spawn_buf[task->client->spawn_buf_idx++] =
(char) (word >> (8 * (i % 4)));
}
remaining -= stop;
if (remaining == 0) {
// Write to c-frame and reset.
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_SPAWN, task->client->spawn_buf_idx,
task->client->spawn_buf);
task->client->spawn_buf_idx = 0;
free(task->client->spawn_buf);
task->client->spawn_buf = NULL;
} else {
// Send ok to client, will keep receiving the rest of the
// string.
CHECK("register send back to local client, for spawn proc",
lmp_chan_register_send(&task->client->lc,
get_default_waitset(),
MKCLOSURE((void*) send_simple_ok,
(void*) &task->client->lc)));
return SYS_ERR_OK;
}
break;
case AOS_RPC_SPAWN_ARGS:
remaining = task->msg.words[2];
if (task->client->spawn_buf == NULL) {
task->client->spawn_buf = (char*) malloc(
remaining * sizeof(char));
task->client->spawn_buf_idx = 0;
}
stop = remaining < 24 ? remaining : 24;
for (size_t i = 0; i < stop; ++i) {
uint32_t word = task->msg.words[3 + i / 4];
task->client->spawn_buf[task->client->spawn_buf_idx++] =
(char) (word >> (8 * (i % 4)));
}
remaining -= stop;
if (remaining == 0) {
// Write to c-frame and reset.
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_SPAWN_ARGS, task->client->spawn_buf_idx,
task->client->spawn_buf);
task->client->spawn_buf_idx = 0;
free(task->client->spawn_buf);
task->client->spawn_buf = NULL;
} else {
// Send ok to client, will keep receiving the rest of the
// string.
CHECK("register send back to local client, for spawn proc",
lmp_chan_register_send(&task->client->lc,
get_default_waitset(),
MKCLOSURE((void*) send_simple_ok,
(void*) &task->client->lc)));
return SYS_ERR_OK;
}
break;
case AOS_RPC_GET_PNAME:
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_GET_PNAME,
sizeof(domainid_t),
&task->msg.words[2]);
break;
case AOS_RPC_GET_PLIST:
err = cross_core_rpc_write_request(
task->client->client_frame->addr,
AOS_RPC_GET_PLIST,
0,
NULL);
break;
}
if (err_is_fail(err)) {
// Error means we can't send a new request atm, because the previous
// one hasn't completely been responded to.
// Therefore we re-enqueue the task too look into it again later.
add_rpc_task(sc, task);
}
return SYS_ERR_OK;
} else {
debug_printf("Invalid RPC task status: %u\n", task->status);
return INIT_ERR_RPC_INVALID_STATUS;
}
}
void add_rpc_task(struct scheduler* sc, struct rpc_task* task)
{
task->prev = NULL;
if (sc->rpc_queue == NULL) {
task->next = NULL;
sc->tail_rpc_queue = task;
sc->tail_rpc_queue->next = NULL;
sc->tail_rpc_queue->prev = NULL;
} else {
task->next = sc->rpc_queue;
sc->rpc_queue->prev = task;
}
sc->rpc_queue = task;
}
struct rpc_task* pop_rpc_task(struct scheduler* sc)
{
if (sc->rpc_queue == NULL) {
// printf("Careful, RPC queue is NULL\n");
return NULL;
}
struct rpc_task* task = sc->rpc_queue;
sc->rpc_queue = sc->rpc_queue->next;
return task;
}
errval_t refill_ic_frame_buffer(struct scheduler* sc)
{
if (sc->my_core_id == 0) {
// We can just frame_alloc.
struct capref frames[IC_FRAME_BUF_CAPACITY];
size_t retsize;
for (size_t i = 0; i < IC_FRAME_BUF_CAPACITY; ++i) {
CHECK("allocating ic frame for refill",
frame_alloc(&frames[i], BASE_PAGE_SIZE, &retsize));
struct ic_frame_node* node = (struct ic_frame_node*) malloc(
sizeof(struct ic_frame_node));
node->frame = frames[i];
node->free = true;
node->addr = NULL;
if (sc->tail_ic_frame_list == NULL) {
sc->tail_ic_frame_list = sc->ic_frame_list = node;
sc->tail_ic_frame_list->next = sc->ic_frame_list->next = NULL;
sc->tail_ic_frame_list->prev = sc->ic_frame_list->prev = NULL;
} else {
sc->tail_ic_frame_list->next = node;
node->prev = sc->tail_ic_frame_list;
sc->tail_ic_frame_list = node;
}
}
sc->ic_frame_buf_size += IC_FRAME_BUF_CAPACITY;
} else {
// Need to enqueue a URPC refill task.
sc->is_refilling_buffer = true;
// This can be static as no two refill requests sent by the same client
// will be alive at any given time.
static struct urpc_task refill_task;
refill_task.type = UrpcOpType_Refill;
add_urpc_task(sc, &refill_task);
}
return SYS_ERR_OK;
}
struct ic_frame_node* allocate_ic_frame_node(struct scheduler* sc)
{
assert(sc->ic_frame_buf_size > 0);
sc->ic_frame_buf_size--;
struct ic_frame_node* node = sc->tail_ic_frame_list;
while (node != NULL) {
if (node->free) {
node->free = false;
return node;
}
node = node->prev;
}
return NULL; // This should never happen O_O.
}
errval_t bind_remote_client(struct scheduler* sc, void* bind_req,
struct ic_frame_node* server_frame)
{
genpaddr_t* base = (genpaddr_t*) bind_req;
bind_req += sizeof(genpaddr_t);
gensize_t* size = (gensize_t*) bind_req;
struct ic_frame_node* client_frame = (struct ic_frame_node*) malloc(
sizeof(struct ic_frame_node));
CHECK("allocating slot for c-frame", slot_alloc(&client_frame->frame));
CHECK("forging remote c-frame cap",
frame_forge(client_frame->frame, *base, *size, sc->my_core_id));
cross_core_rpc_init(&client_frame->frame,
&server_frame->frame,
&client_frame->addr,
&server_frame->addr);
struct client_state* remote_client = (struct client_state*) malloc(
sizeof(struct client_state));
remote_client->client_frame = client_frame;
remote_client->server_frame = server_frame;
if (sc->remote_clients == NULL) {
remote_client->prev = remote_client->next = NULL;
} else {
sc->remote_clients->prev = remote_client;
remote_client->next = sc->remote_clients;
sc->remote_clients = remote_client;
}
sc->remote_clients = remote_client;
return SYS_ERR_OK;
}
errval_t process_urpc_request(struct scheduler* sc, uint32_t code,
size_t req_len, void* req, size_t* resp_len, void** resp)
{
switch (code) {
case URPC_CODE_REFILL:
// Other core asked us to refill its ic frame buffer.
if (sc->my_core_id != 0) {
return URPC_ERR_REFILL;
}
static uint64_t refill_msg[2 * IC_FRAME_BUF_CAPACITY];
for (size_t i = 0; i < IC_FRAME_BUF_CAPACITY; ++i) {
struct capref frame;
size_t retsize;
CHECK("process_urpc_request refill frame_alloc",
frame_alloc(&frame, BASE_PAGE_SIZE, &retsize));
struct frame_identity frame_id;
CHECK("identifying urpc_request refill frame",
frame_identify(frame, &frame_id));
refill_msg[2 * i] = (uint64_t) frame_id.base;
refill_msg[2 * i + 1] = (uint64_t) frame_id.bytes;
}
*resp_len = (sizeof(genpaddr_t) + sizeof(gensize_t))
* IC_FRAME_BUF_CAPACITY;
*resp = refill_msg;
break;
case URPC_CODE_CHANNEL:
// Other core gave us a client to bind to our server.
if (req_len != sizeof(genpaddr_t) + sizeof(gensize_t)) {
return URPC_ERR_SETUP_CHANNEL;
}
if (should_refill_ic_frame_buffer(sc)) {
refill_ic_frame_buffer(sc);
return URPC_ERR_FRAME_BUFFER;
} else if (sc->is_refilling_buffer) {
return URPC_ERR_FRAME_BUFFER;
}
struct ic_frame_node* server_frame = allocate_ic_frame_node(sc);
CHECK("binding other core's client to my server",
bind_remote_client(sc, req, server_frame));
struct frame_identity frame_id;
CHECK("identifying urpc_request s-frame for binding",
frame_identify(server_frame->frame, &frame_id));
static uint64_t bind_msg[4];
bind_msg[0] = *((uint64_t*) req);
bind_msg[1] = *((uint64_t*) (req + sizeof(uint64_t)));
bind_msg[2] = (uint64_t) frame_id.base;
bind_msg[3] = (uint64_t) frame_id.bytes;
*resp_len = (sizeof(genpaddr_t) + sizeof(gensize_t)) * 2;
*resp = bind_msg;
break;
default:
return URPC_ERR_INVALID_CODE;
}
return SYS_ERR_OK;
}
errval_t process_urpc_response(struct scheduler* sc, uint32_t code,
size_t resp_len, void* resp)
{
switch (code) {
case URPC_CODE_REFILL:
assert(resp_len == (sizeof(genpaddr_t) + sizeof(gensize_t))
* IC_FRAME_BUF_CAPACITY);
// We got a bunch of buffer frames for our c- and s-frames.
for (size_t i = 0; i < IC_FRAME_BUF_CAPACITY; ++i) {
genpaddr_t* base = (genpaddr_t*) resp;
resp += sizeof(genpaddr_t);
gensize_t* size = (gensize_t*) resp;
resp += sizeof(gensize_t);
struct capref frame;
CHECK("allocating slot for refill frame",
slot_alloc(&frame));
CHECK("forging refill frame",
frame_forge(frame, *base, *size, sc->my_core_id));
struct ic_frame_node* node = (struct ic_frame_node*) malloc(
sizeof(struct ic_frame_node));
node->frame = frame;
node->free = true;
node->addr = NULL;
if (sc->tail_ic_frame_list == NULL) {
sc->tail_ic_frame_list = sc->ic_frame_list = node;
sc->tail_ic_frame_list->next = sc->ic_frame_list->next =
NULL;
sc->tail_ic_frame_list->prev = sc->ic_frame_list->prev =
NULL;
} else {
sc->tail_ic_frame_list->next = node;
node->prev = sc->tail_ic_frame_list;
sc->tail_ic_frame_list = node;
}
}
sc->ic_frame_buf_size += IC_FRAME_BUF_CAPACITY;
sc->is_refilling_buffer = false;
break;
case URPC_CODE_CHANNEL:
assert(resp_len == (sizeof(genpaddr_t) + sizeof(gensize_t)) * 2);
// Other core responded to our binding request with its s-frame.
genpaddr_t* client_base = (genpaddr_t*) resp;
resp += sizeof(genpaddr_t);
gensize_t* client_size = (gensize_t*) resp;
resp += sizeof(gensize_t);
genpaddr_t* server_base = (genpaddr_t*) resp;
resp += sizeof(genpaddr_t);
gensize_t* server_size = (gensize_t*) resp;
struct client_state* local_client = sc->local_clients;
while (local_client != NULL) {
struct frame_identity frame_id;
CHECK("identifying c-frame to match with s-frame",
frame_identify(local_client->client_frame->frame,
&frame_id));
if (frame_id.base == *client_base
&& frame_id.bytes == *client_size) {
break;
}
local_client = local_client->next;
}
if (local_client == NULL) {
return URPC_ERR_INVALID_CLIENT;
}
local_client->server_frame = (struct ic_frame_node*) malloc(
sizeof(struct ic_frame_node));
CHECK("allocating slot for s-frame", slot_alloc(
&local_client->server_frame->frame));
CHECK("forging s-frame frame",
frame_forge(local_client->server_frame->frame, *server_base,
*server_size, sc->my_core_id));
cross_core_rpc_init(&local_client->client_frame->frame,
&local_client->server_frame->frame,
&local_client->client_frame->addr,
&local_client->server_frame->addr);
break;
local_client->binding_in_progress = false;
default:
return URPC_ERR_INVALID_CODE;
}
return SYS_ERR_OK;
}
errval_t check_task_urpc(struct scheduler* sc) {
// 1. Check if the other core has sent us a new request as a client.
uint32_t code;
size_t req_len;
void* req;
errval_t err = urpc_read_request(sc->urpc_buf, 1 - sc->my_core_id, &code,
&req_len, &req);
if (err_is_ok(err)) {
// There's a request we can process & respond to.
size_t resp_len;
void* resp;
err = process_urpc_request(sc, code, req_len, req, &resp_len, &resp);
if (err_is_ok(err)) {
CHECK("writing URPC response",
urpc_write_response(sc->urpc_buf, 1 - sc->my_core_id, code,
resp_len, resp));
} else if (err != URPC_ERR_REFILL && err != URPC_ERR_SETUP_CHANNEL) {
// We failed to process the request, hence we need to re-mark it as
// unread.
urpc_mark_request_unread(sc->urpc_buf, 1 - sc->my_core_id);
}
}
// 2. Check if a former request of ours has been responded to.
size_t resp_len;
void* resp;
err = urpc_read_response(sc->urpc_buf, sc->my_core_id, &code, &resp_len,
&resp);
if (err_is_ok(err)) {
// We have a response.
CHECK("processing URPC response",
process_urpc_response(sc, code, resp_len, resp));
}
// 3. Check if there are any pending URPC tasks to create new requests for.
struct urpc_task* task = pop_urpc_task(sc);
if (task != NULL) {
// There's a pending task, create requests for it.
CHECK("processing URPC task", process_urpc_task(sc, task));
}
return SYS_ERR_OK;
}
errval_t process_rpc_request(struct scheduler* sc, uint32_t code,
size_t req_len, void* req, size_t* resp_len, void** resp)
{
struct capref ram;
size_t retsize;
struct capref frame;
struct frame_identity frame_id;
errval_t err;
domainid_t pid;
size_t num_pids;
switch (code) {
case AOS_RPC_MEMORY:
if (sc->my_core_id != 0) {
return INIT_ERR_RPC_CANNOT_SERVE;
}
CHECK("rpc_ram_alloc",
rpc_ram_alloc(&ram, *((size_t*) req), &retsize));
CHECK("allocating slot for corss-core mem request frame",
slot_alloc(&frame));
CHECK("retyping RAM into frame to identify",
cap_retype(frame, ram, 0, ObjType_Frame, retsize, 1));
CHECK("identifying frame for cross-core mem request",
frame_identify(frame, &frame_id));
CHECK("destroying frame cap", cap_destroy(frame));
*resp_len = sizeof(genpaddr_t) + sizeof(gensize_t);
*resp = malloc(*resp_len);
*((genpaddr_t*) *resp) = frame_id.base;
*((gensize_t*) (*resp + sizeof(genpaddr_t))) = frame_id.bytes;
break;
case AOS_RPC_PUTCHAR:
if (sc->my_core_id != 0) {
return INIT_ERR_RPC_CANNOT_SERVE;
}
rpc_putchar((char*) req);
*resp_len = 0;
break;
case AOS_RPC_GETCHAR:
if (sc->my_core_id != 0) {
return INIT_ERR_RPC_CANNOT_SERVE;
}
*resp_len = sizeof(char);
*resp = malloc(*resp_len);
*((char*) *resp) = rpc_getchar();
break;
case AOS_RPC_STRING:
if (sc->my_core_id != 0) {
return INIT_ERR_RPC_CANNOT_SERVE;
}
rpc_string((char*) req, req_len);
*resp_len = 0;
break;
case AOS_RPC_SPAWN:
err = rpc_spawn((char*) req, &pid);
*resp_len = sizeof(errval_t) + sizeof(domainid_t);
*resp = malloc(*resp_len);
*((errval_t*) *resp) = err;
*((domainid_t*) (*resp + sizeof(errval_t))) = pid;
break;
case AOS_RPC_SPAWN_ARGS:
err = rpc_spawn_args((char*) req, &pid);
*resp_len = sizeof(errval_t) + sizeof(domainid_t);
*resp = malloc(*resp_len);
*((errval_t*) *resp) = err;
*((domainid_t*) (*resp + sizeof(errval_t))) = pid;
break;
case AOS_RPC_GET_PNAME:
*resp = rpc_process_name(*((domainid_t*) req), resp_len);
break;
case AOS_RPC_GET_PLIST:
*resp = rpc_process_list(&num_pids);
*resp_len = num_pids * sizeof(domainid_t);
break;
default:
return INIT_ERR_RPC_INVALID_CODE;
}
return SYS_ERR_OK;
}
errval_t process_rpc_response(struct scheduler* sc, uint32_t code,
size_t resp_len, void* resp, struct client_state* client,
void** local_response_fn, void** local_response)
{
genpaddr_t* base;
gensize_t* size;
struct capref ram;
errval_t err;
size_t args_size;
void *aux;
switch (code) {
case AOS_RPC_MEMORY:
assert(resp_len == sizeof(genpaddr_t) + sizeof(gensize_t));
base = (genpaddr_t*) resp;
resp += sizeof(genpaddr_t);
size = (gensize_t*) resp;
CHECK("allocating slot for ram from core 0", slot_alloc(&ram));
err = ram_forge(ram, *base, *size, sc->my_core_id);
// Response args.
args_size = ROUND_UP(sizeof(struct lmp_chan), 4)
+ ROUND_UP(sizeof(errval_t), 4)
+ ROUND_UP(sizeof(struct capref), 4)
+ sizeof(size_t);
*local_response = malloc(args_size);
aux = *local_response;
// 1. Channel to send down.
*((struct lmp_chan*) aux) = client->lc;
// 2. Error code from frame_forge.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(struct lmp_chan), 4);
*((errval_t*) aux) = err;
// 3. Cap for newly allocated RAM.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(errval_t), 4);
*((struct capref*) aux) = ram;
// 4. Size returned by ram_alloc.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(struct capref), 4);
*((size_t*) aux) = *size;
*local_response_fn = (void*) send_memory;
break;
case AOS_RPC_PUTCHAR:
case AOS_RPC_STRING:
*local_response = &client->lc;
*local_response_fn = (void*) send_simple_ok;
break;
case AOS_RPC_GETCHAR:
args_size = ROUND_UP(sizeof(struct lmp_chan), 4)
+ ROUND_UP(sizeof(char), 4);
*local_response = malloc(args_size);
aux = *local_response;
// 1. Channel to send down.
*((struct lmp_chan*) aux) = client->lc;
// 2. Character returned by sys_getchar
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(struct lmp_chan), 4);
*((char*) aux) = *((char*) resp);
*local_response_fn = (void*) send_serial_getchar;
break;
case AOS_RPC_SPAWN:
args_size = ROUND_UP(sizeof(struct lmp_chan), 4)
+ ROUND_UP(sizeof(errval_t), 4)
+ ROUND_UP(sizeof(domainid_t), 4);
*local_response = malloc(args_size);
aux = *local_response;
// 1. Channel to send down.
*((struct lmp_chan*) aux) = client->lc;
// 2. Error code returned by spawn.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(struct lmp_chan), 4);
*((errval_t*) aux) = *((errval_t*) resp);
// 3. PID of the newly spawned process.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(errval_t), 4);
*((domainid_t*) aux) = *((domainid_t*) (resp + sizeof(errval_t)));
*local_response_fn = (void*) send_pid;
break;
case AOS_RPC_SPAWN_ARGS:
args_size = ROUND_UP(sizeof(struct lmp_chan), 4)
+ ROUND_UP(sizeof(errval_t), 4)
+ ROUND_UP(sizeof(domainid_t), 4);
*local_response = malloc(args_size);
aux = *local_response;
// 1. Channel to send down.
*((struct lmp_chan*) aux) = client->lc;
// 2. Error code returned by spawn.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(struct lmp_chan), 4);
*((errval_t*) aux) = *((errval_t*) resp);
// 3. PID of the newly spawned process.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(errval_t), 4);
*((domainid_t*) aux) = *((domainid_t*) (resp + sizeof(errval_t)));
*local_response_fn = (void*) send_pid;
break;
case AOS_RPC_GET_PNAME:
args_size = ROUND_UP(sizeof(struct lmp_chan), 4)
+ ROUND_UP(resp_len, 4);
*local_response = malloc(args_size);
aux = *local_response;
// 1. Channel to send down.
*((struct lmp_chan*) aux) = client->lc;
// 2. Requested process name.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(struct lmp_chan), 4);
strncpy((char*) aux, (char*) resp, resp_len);
*local_response_fn = (void*) send_process_name;
break;
case AOS_RPC_GET_PLIST:
args_size = ROUND_UP(sizeof(struct lmp_chan), 4)
+ ROUND_UP(sizeof(uint32_t), 4)
+ ROUND_UP(resp_len, 4);
*local_response = malloc(args_size);
aux = *local_response;
// 1. Channel to send down.
*((struct lmp_chan*) aux) = client->lc;
// 2. Size of PIDs list.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(struct lmp_chan), 4);
*((uint32_t*) aux) = resp_len / sizeof(domainid_t);
// 3. List of PIDs.
aux = (void*) ROUND_UP((uintptr_t) aux + sizeof(uint32_t), 4);
memcpy(aux, resp, resp_len);
*local_response_fn = (void*) send_ps_list;
break;
default:
return INIT_ERR_RPC_INVALID_CODE;
}
return SYS_ERR_OK;
}
errval_t check_task_rpc(struct scheduler* sc)
{
// 1. Check for any new requests from remote clients, i.e. clients running
// on the other core.
struct client_state* remote_client = sc->remote_clients;
while (remote_client != NULL) {
if (remote_client->client_frame == NULL) {
// Hasn't been yet initialized, continue.
remote_client = remote_client->next;
continue;
}
uint32_t code;
size_t req_len;
void* req;
errval_t err = cross_core_rpc_read_request(
remote_client->client_frame->addr,
&code,
&req_len,
&req);
if (err_is_ok(err)) {
// Got a new request, try to serve it.
size_t resp_len;
void* resp;
CHECK("processing cross-core RPC request",
process_rpc_request(sc, code, req_len, req, &resp_len,
&resp));
CHECK("writing cross-core RPC response",
cross_core_rpc_write_response(
remote_client->server_frame->addr,
code,
resp_len,
resp));
}
remote_client = remote_client->next;
}
// 2. Check if any cross-core requests performed by local clients have been
// responded to by the other core.
struct client_state* local_client = sc->local_clients;
while (local_client != NULL) {
if (local_client->server_frame == NULL) {
// Hasn't been yet initialized, continue.
local_client = local_client->next;
continue;
}
uint32_t code;
size_t resp_len;
void* resp;
errval_t err = cross_core_rpc_read_response(
local_client->server_frame->addr,
&code,
&resp_len,
&resp);
if (err_is_ok(err)) {
// Got response for a previous request.
void* local_response_fn;
void* local_response;
CHECK("processing cross-core RPC response",
process_rpc_response(sc, code, resp_len, resp,
local_client, &local_response_fn, &local_response));
// Send response to local client.
struct lmp_chan* out = (struct lmp_chan*) local_response;
CHECK("register send back to local client",
lmp_chan_register_send(out, get_default_waitset(),
MKCLOSURE(local_response_fn, local_response)));
}
local_client = local_client->next;
}
// 3. Pop recent local RPC tasks (events) from the default waitset.
struct waitset *default_ws = get_default_waitset();
errval_t err;
size_t task_count = 0;
do {
err = check_for_event(default_ws);
if (err_is_ok(err)) {
// We got an event => pop and queue-up in our RPC queue.
struct event_closure retclosure;
CHECK("popping next RPC event from default_ws",
get_next_event(default_ws, &retclosure));
struct rpc_task* task = (struct rpc_task*) malloc(
sizeof(struct rpc_task));
task->status = RpcStatus_New;
task->closure = retclosure;
task->client = NULL;
add_rpc_task(sc, task);
++task_count;
} else {
break;
}
} while (task_count < RPC_TASK_LIMIT);
// 4. Process local tasks.
for (size_t i = 0; i < RPC_TASK_LIMIT; ++i) {
struct rpc_task* task = pop_rpc_task(sc);
if (task == NULL) {
break;
}
CHECK("processing RPC task", process_rpc_task(sc, task));
}
return SYS_ERR_OK;
}
bool try_serving_locally(struct scheduler* sc, struct rpc_task* task,
struct lmp_recv_msg* msg, struct capref* client_cap)
{
struct lmp_chan* lc = (struct lmp_chan*) task->closure.arg;
struct lmp_recv_msg aux_msg = LMP_RECV_MSG_INIT;
*msg = aux_msg;
lmp_chan_recv(lc, msg, client_cap);
// Reregister.
lmp_chan_alloc_recv_slot(lc);
lmp_chan_register_recv(lc, get_default_waitset(), task->closure);
switch (msg->words[0]) {
case AOS_RPC_OK:
case AOS_RPC_FAILED:
task->closure.handler(task->closure.arg);
// lmp_chan_send1(lc, LMP_FLAG_SYNC, NULL_CAP, msg->words[0]);
return true;
case AOS_RPC_DEVICE:
case AOS_RPC_IRQ:
case AOS_RPC_SDMA_EP:
// These are always core-local.
break;
case AOS_RPC_MEMORY:
case AOS_RPC_STRING:
case AOS_RPC_PUTCHAR:
case AOS_RPC_GETCHAR:
if (sc->my_core_id != 0) {
return false;
}
break;
default:
if (msg->words[0] != AOS_RPC_HANDSHAKE
&& sc->my_core_id != msg->words[1]) {
return false;
}
break;
}
// RPC can be solved locally, do it.
// TODO: Change the outer function to return error instead of bool.
serve_locally(msg, client_cap, &sc->local_clients);
return true;
}
void dummy_closure(void* dummy_arg);
void dummy_closure(void* dummy_arg) {
}
errval_t scheduler_start(struct scheduler* sc, struct lmp_chan* lc)
{
CHECK("lmp_chan_register_recv child",
lmp_chan_register_recv(lc, get_default_waitset(),
MKCLOSURE(dummy_closure, lc)));
while (true) {
CHECK("check_task_urpc", check_task_urpc(sc));
CHECK("check_task_rpc", check_task_rpc(sc));
}
}
void scheduler_init(struct scheduler* sc, coreid_t my_core_id, void* urpc_buf) {
sc->my_core_id = my_core_id;
sc->urpc_buf = urpc_buf;
sc->rpc_queue = sc->tail_rpc_queue = NULL;
sc->urpc_queue = sc->tail_urpc_queue = NULL;
sc->ic_frame_buf_size = 0;
sc->is_refilling_buffer = false;
sc->ic_frame_list = NULL;
sc->tail_ic_frame_list = NULL;
sc->local_clients = sc->remote_clients = NULL;
}
| {
"content_hash": "38e752c75d60a60fd7a97c901ec3704b",
"timestamp": "",
"source": "github",
"line_count": 1049,
"max_line_length": 81,
"avg_line_length": 36.66920877025739,
"alnum_prop": 0.49589247647272916,
"repo_name": "jinankjain/barrelfish",
"id": "4e4845a58201b5f403a56fc785a3eb56b5df448f",
"size": "38466",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "usr/init/scheduler.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2290523"
},
{
"name": "Awk",
"bytes": "570"
},
{
"name": "Batchfile",
"bytes": "1875"
},
{
"name": "C",
"bytes": "64605437"
},
{
"name": "C++",
"bytes": "6712275"
},
{
"name": "DIGITAL Command Language",
"bytes": "1044"
},
{
"name": "Emacs Lisp",
"bytes": "21698"
},
{
"name": "Groff",
"bytes": "81134"
},
{
"name": "Haskell",
"bytes": "98984"
},
{
"name": "Logos",
"bytes": "14359"
},
{
"name": "M4",
"bytes": "437022"
},
{
"name": "Makefile",
"bytes": "12680887"
},
{
"name": "Mathematica",
"bytes": "3483"
},
{
"name": "Objective-C",
"bytes": "73847"
},
{
"name": "Perl",
"bytes": "131093"
},
{
"name": "Python",
"bytes": "8193"
},
{
"name": "Shell",
"bytes": "380813"
},
{
"name": "SuperCollider",
"bytes": "8638"
},
{
"name": "Tcl",
"bytes": "123"
},
{
"name": "TeX",
"bytes": "409568"
},
{
"name": "XSLT",
"bytes": "4240"
},
{
"name": "Yacc",
"bytes": "8101"
}
],
"symlink_target": ""
} |
<?php //[STAMP] f2b91dc7f5d231b3907f473a06687a93
// This class was automatically generated by build task
// You should not change it manually as it will be overwritten on next build
// @codingStandardsIgnoreFile
use Codeception\Module\PhpBrowser;
use Codeception\Module\AcceptanceHelper;
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method void haveFriend($name, $actorClass = null)
*
* @SuppressWarnings(PHPMD)
*/
class AcceptanceTester extends \Codeception\Actor
{
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Sets the HTTP header to the passed value - which is used on
* subsequent HTTP requests through PhpBrowser.
*
* Example:
* ```php
* <?php
* $I->setHeader('X-Requested-With', 'Codeception');
* $I->amOnPage('test-headers.php');
* ?>
* ```
*
* @param string $name the name of the request header
* @param string $value the value to set it to for subsequent
* requests
* @see \Codeception\Module\PhpBrowser::setHeader()
*/
public function setHeader($name, $value) {
return $this->scenario->runStep(new \Codeception\Step\Action('setHeader', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Deletes the header with the passed name. Subsequent requests
* will not have the deleted header in its request.
*
* Example:
* ```php
* <?php
* $I->setHeader('X-Requested-With', 'Codeception');
* $I->amOnPage('test-headers.php');
* // ...
* $I->deleteHeader('X-Requested-With');
* $I->amOnPage('some-other-page.php');
* ?>
* ```
*
* @param string $name the name of the header to delete.
* @see \Codeception\Module\PhpBrowser::deleteHeader()
*/
public function deleteHeader($name) {
return $this->scenario->runStep(new \Codeception\Step\Action('deleteHeader', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Authenticates user for HTTP_AUTH
*
* @param $username
* @param $password
* @see \Codeception\Module\PhpBrowser::amHttpAuthenticated()
*/
public function amHttpAuthenticated($username, $password) {
return $this->scenario->runStep(new \Codeception\Step\Condition('amHttpAuthenticated', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Opens the page for the given relative URI.
*
* ``` php
* <?php
* // opens front page
* $I->amOnPage('/');
* // opens /register page
* $I->amOnPage('/register');
* ?>
* ```
*
* @param $page
* @see \Codeception\Module\PhpBrowser::amOnPage()
*/
public function amOnPage($page) {
return $this->scenario->runStep(new \Codeception\Step\Condition('amOnPage', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Open web page at the given absolute URL and sets its hostname as the base host.
*
* ``` php
* <?php
* $I->amOnUrl('http://codeception.com');
* $I->amOnPage('/quickstart'); // moves to http://codeception.com/quickstart
* ?>
* ```
* @see \Codeception\Module\PhpBrowser::amOnUrl()
*/
public function amOnUrl($url) {
return $this->scenario->runStep(new \Codeception\Step\Condition('amOnUrl', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Changes the subdomain for the 'url' configuration parameter.
* Does not open a page; use `amOnPage` for that.
*
* ``` php
* <?php
* // If config is: 'http://mysite.com'
* // or config is: 'http://www.mysite.com'
* // or config is: 'http://company.mysite.com'
*
* $I->amOnSubdomain('user');
* $I->amOnPage('/');
* // moves to http://user.mysite.com/
* ?>
* ```
*
* @param $subdomain
*
* @return mixed
* @see \Codeception\Module\PhpBrowser::amOnSubdomain()
*/
public function amOnSubdomain($subdomain) {
return $this->scenario->runStep(new \Codeception\Step\Condition('amOnSubdomain', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Low-level API method.
* If Codeception commands are not enough, use [Guzzle HTTP Client](http://guzzlephp.org/) methods directly
*
* Example:
*
* ``` php
* <?php
* $I->executeInGuzzle(function (\GuzzleHttp\Client $client) {
* $client->get('/get', ['query' => ['foo' => 'bar']]);
* });
* ?>
* ```
*
* It is not recommended to use this command on a regular basis.
* If Codeception lacks important Guzzle Client methods, implement them and submit patches.
*
* @param callable $function
* @see \Codeception\Module\PhpBrowser::executeInGuzzle()
*/
public function executeInGuzzle($function) {
return $this->scenario->runStep(new \Codeception\Step\Action('executeInGuzzle', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Perform a click on a link or a button, given by a locator.
* If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
* For buttons, the "value" attribute, "name" attribute, and inner text are searched.
* For links, the link text is searched.
* For images, the "alt" attribute and inner text of any parent links are searched.
*
* The second parameter is a context (CSS or XPath locator) to narrow the search.
*
* Note that if the locator matches a button of type `submit`, the form will be submitted.
*
* ``` php
* <?php
* // simple link
* $I->click('Logout');
* // button of form
* $I->click('Submit');
* // CSS button
* $I->click('#form input[type=submit]');
* // XPath
* $I->click('//form/*[@type=submit]');
* // link in context
* $I->click('Logout', '#nav');
* // using strict locator
* $I->click(['link' => 'Login']);
* ?>
* ```
*
* @param $link
* @param $context
* @see \Codeception\Lib\InnerBrowser::click()
*/
public function click($link, $context = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('click', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current page contains the given string.
* Specify a locator as the second parameter to match a specific region.
*
* ``` php
* <?php
* $I->see('Logout'); // I can suppose user is logged in
* $I->see('Sign Up','h1'); // I can suppose it's a signup page
* $I->see('Sign Up','//body/h1'); // with XPath
* ?>
* ```
*
* @param $text
* @param null $selector
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::see()
*/
public function canSee($text, $selector = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('see', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current page contains the given string.
* Specify a locator as the second parameter to match a specific region.
*
* ``` php
* <?php
* $I->see('Logout'); // I can suppose user is logged in
* $I->see('Sign Up','h1'); // I can suppose it's a signup page
* $I->see('Sign Up','//body/h1'); // with XPath
* ?>
* ```
*
* @param $text
* @param null $selector
* @see \Codeception\Lib\InnerBrowser::see()
*/
public function see($text, $selector = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('see', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current page doesn't contain the text specified.
* Give a locator as the second parameter to match a specific region.
*
* ```php
* <?php
* $I->dontSee('Login'); // I can suppose user is already logged in
* $I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
* $I->dontSee('Sign Up','//body/h1'); // with XPath
* ?>
* ```
*
* @param $text
* @param null $selector
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSee()
*/
public function cantSee($text, $selector = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSee', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current page doesn't contain the text specified.
* Give a locator as the second parameter to match a specific region.
*
* ```php
* <?php
* $I->dontSee('Login'); // I can suppose user is already logged in
* $I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
* $I->dontSee('Sign Up','//body/h1'); // with XPath
* ?>
* ```
*
* @param $text
* @param null $selector
* @see \Codeception\Lib\InnerBrowser::dontSee()
*/
public function dontSee($text, $selector = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSee', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that there's a link with the specified text.
* Give a full URL as the second parameter to match links with that exact URL.
*
* ``` php
* <?php
* $I->seeLink('Logout'); // matches <a href="#">Logout</a>
* $I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
* ?>
* ```
*
* @param $text
* @param null $url
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeLink()
*/
public function canSeeLink($text, $url = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeLink', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that there's a link with the specified text.
* Give a full URL as the second parameter to match links with that exact URL.
*
* ``` php
* <?php
* $I->seeLink('Logout'); // matches <a href="#">Logout</a>
* $I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
* ?>
* ```
*
* @param $text
* @param null $url
* @see \Codeception\Lib\InnerBrowser::seeLink()
*/
public function seeLink($text, $url = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeLink', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the page doesn't contain a link with the given string.
* If the second parameter is given, only links with a matching "href" attribute will be checked.
*
* ``` php
* <?php
* $I->dontSeeLink('Logout'); // I suppose user is not logged in
* $I->dontSeeLink('Checkout now', '/store/cart.php');
* ?>
* ```
*
* @param $text
* @param null $url
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeLink()
*/
public function cantSeeLink($text, $url = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeLink', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the page doesn't contain a link with the given string.
* If the second parameter is given, only links with a matching "href" attribute will be checked.
*
* ``` php
* <?php
* $I->dontSeeLink('Logout'); // I suppose user is not logged in
* $I->dontSeeLink('Checkout now', '/store/cart.php');
* ?>
* ```
*
* @param $text
* @param null $url
* @see \Codeception\Lib\InnerBrowser::dontSeeLink()
*/
public function dontSeeLink($text, $url = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeLink', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that current URI contains the given string.
*
* ``` php
* <?php
* // to match: /home/dashboard
* $I->seeInCurrentUrl('home');
* // to match: /users/1
* $I->seeInCurrentUrl('/users/');
* ?>
* ```
*
* @param $uri
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeInCurrentUrl()
*/
public function canSeeInCurrentUrl($uri) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeInCurrentUrl', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that current URI contains the given string.
*
* ``` php
* <?php
* // to match: /home/dashboard
* $I->seeInCurrentUrl('home');
* // to match: /users/1
* $I->seeInCurrentUrl('/users/');
* ?>
* ```
*
* @param $uri
* @see \Codeception\Lib\InnerBrowser::seeInCurrentUrl()
*/
public function seeInCurrentUrl($uri) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeInCurrentUrl', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URI doesn't contain the given string.
*
* ``` php
* <?php
* $I->dontSeeInCurrentUrl('/users/');
* ?>
* ```
*
* @param $uri
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeInCurrentUrl()
*/
public function cantSeeInCurrentUrl($uri) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeInCurrentUrl', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URI doesn't contain the given string.
*
* ``` php
* <?php
* $I->dontSeeInCurrentUrl('/users/');
* ?>
* ```
*
* @param $uri
* @see \Codeception\Lib\InnerBrowser::dontSeeInCurrentUrl()
*/
public function dontSeeInCurrentUrl($uri) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeInCurrentUrl', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URL is equal to the given string.
* Unlike `seeInCurrentUrl`, this only matches the full URL.
*
* ``` php
* <?php
* // to match root url
* $I->seeCurrentUrlEquals('/');
* ?>
* ```
*
* @param $uri
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeCurrentUrlEquals()
*/
public function canSeeCurrentUrlEquals($uri) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeCurrentUrlEquals', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URL is equal to the given string.
* Unlike `seeInCurrentUrl`, this only matches the full URL.
*
* ``` php
* <?php
* // to match root url
* $I->seeCurrentUrlEquals('/');
* ?>
* ```
*
* @param $uri
* @see \Codeception\Lib\InnerBrowser::seeCurrentUrlEquals()
*/
public function seeCurrentUrlEquals($uri) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeCurrentUrlEquals', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URL doesn't equal the given string.
* Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
*
* ``` php
* <?php
* // current url is not root
* $I->dontSeeCurrentUrlEquals('/');
* ?>
* ```
*
* @param $uri
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlEquals()
*/
public function cantSeeCurrentUrlEquals($uri) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeCurrentUrlEquals', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URL doesn't equal the given string.
* Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
*
* ``` php
* <?php
* // current url is not root
* $I->dontSeeCurrentUrlEquals('/');
* ?>
* ```
*
* @param $uri
* @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlEquals()
*/
public function dontSeeCurrentUrlEquals($uri) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeCurrentUrlEquals', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URL matches the given regular expression.
*
* ``` php
* <?php
* // to match root url
* $I->seeCurrentUrlMatches('~$/users/(\d+)~');
* ?>
* ```
*
* @param $uri
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeCurrentUrlMatches()
*/
public function canSeeCurrentUrlMatches($uri) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeCurrentUrlMatches', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the current URL matches the given regular expression.
*
* ``` php
* <?php
* // to match root url
* $I->seeCurrentUrlMatches('~$/users/(\d+)~');
* ?>
* ```
*
* @param $uri
* @see \Codeception\Lib\InnerBrowser::seeCurrentUrlMatches()
*/
public function seeCurrentUrlMatches($uri) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeCurrentUrlMatches', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that current url doesn't match the given regular expression.
*
* ``` php
* <?php
* // to match root url
* $I->dontSeeCurrentUrlMatches('~$/users/(\d+)~');
* ?>
* ```
*
* @param $uri
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlMatches()
*/
public function cantSeeCurrentUrlMatches($uri) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeCurrentUrlMatches', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that current url doesn't match the given regular expression.
*
* ``` php
* <?php
* // to match root url
* $I->dontSeeCurrentUrlMatches('~$/users/(\d+)~');
* ?>
* ```
*
* @param $uri
* @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlMatches()
*/
public function dontSeeCurrentUrlMatches($uri) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeCurrentUrlMatches', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Executes the given regular expression against the current URI and returns the first match.
* If no parameters are provided, the full URI is returned.
*
* ``` php
* <?php
* $user_id = $I->grabFromCurrentUrl('~$/user/(\d+)/~');
* $uri = $I->grabFromCurrentUrl();
* ?>
* ```
*
* @param null $uri
*
* @internal param $url
* @return mixed
* @see \Codeception\Lib\InnerBrowser::grabFromCurrentUrl()
*/
public function grabFromCurrentUrl($uri = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('grabFromCurrentUrl', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the specified checkbox is checked.
*
* ``` php
* <?php
* $I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
* $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
* $I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
* ?>
* ```
*
* @param $checkbox
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeCheckboxIsChecked()
*/
public function canSeeCheckboxIsChecked($checkbox) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeCheckboxIsChecked', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the specified checkbox is checked.
*
* ``` php
* <?php
* $I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
* $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
* $I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
* ?>
* ```
*
* @param $checkbox
* @see \Codeception\Lib\InnerBrowser::seeCheckboxIsChecked()
*/
public function seeCheckboxIsChecked($checkbox) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeCheckboxIsChecked', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Check that the specified checkbox is unchecked.
*
* ``` php
* <?php
* $I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
* $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
* ?>
* ```
*
* @param $checkbox
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeCheckboxIsChecked()
*/
public function cantSeeCheckboxIsChecked($checkbox) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeCheckboxIsChecked', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Check that the specified checkbox is unchecked.
*
* ``` php
* <?php
* $I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
* $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
* ?>
* ```
*
* @param $checkbox
* @see \Codeception\Lib\InnerBrowser::dontSeeCheckboxIsChecked()
*/
public function dontSeeCheckboxIsChecked($checkbox) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeCheckboxIsChecked', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given input field or textarea contains the given value.
* For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
*
* ``` php
* <?php
* $I->seeInField('Body','Type your comment here');
* $I->seeInField('form textarea[name=body]','Type your comment here');
* $I->seeInField('form input[type=hidden]','hidden_value');
* $I->seeInField('#searchform input','Search');
* $I->seeInField('//form/*[@name=search]','Search');
* $I->seeInField(['name' => 'search'], 'Search');
* ?>
* ```
*
* @param $field
* @param $value
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeInField()
*/
public function canSeeInField($field, $value) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeInField', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given input field or textarea contains the given value.
* For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
*
* ``` php
* <?php
* $I->seeInField('Body','Type your comment here');
* $I->seeInField('form textarea[name=body]','Type your comment here');
* $I->seeInField('form input[type=hidden]','hidden_value');
* $I->seeInField('#searchform input','Search');
* $I->seeInField('//form/*[@name=search]','Search');
* $I->seeInField(['name' => 'search'], 'Search');
* ?>
* ```
*
* @param $field
* @param $value
* @see \Codeception\Lib\InnerBrowser::seeInField()
*/
public function seeInField($field, $value) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeInField', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that an input field or textarea doesn't contain the given value.
* For fuzzy locators, the field is matched by label text, CSS and XPath.
*
* ``` php
* <?php
* $I->dontSeeInField('Body','Type your comment here');
* $I->dontSeeInField('form textarea[name=body]','Type your comment here');
* $I->dontSeeInField('form input[type=hidden]','hidden_value');
* $I->dontSeeInField('#searchform input','Search');
* $I->dontSeeInField('//form/*[@name=search]','Search');
* $I->dontSeeInField(['name' => 'search'], 'Search');
* ?>
* ```
*
* @param $field
* @param $value
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeInField()
*/
public function cantSeeInField($field, $value) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeInField', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that an input field or textarea doesn't contain the given value.
* For fuzzy locators, the field is matched by label text, CSS and XPath.
*
* ``` php
* <?php
* $I->dontSeeInField('Body','Type your comment here');
* $I->dontSeeInField('form textarea[name=body]','Type your comment here');
* $I->dontSeeInField('form input[type=hidden]','hidden_value');
* $I->dontSeeInField('#searchform input','Search');
* $I->dontSeeInField('//form/*[@name=search]','Search');
* $I->dontSeeInField(['name' => 'search'], 'Search');
* ?>
* ```
*
* @param $field
* @param $value
* @see \Codeception\Lib\InnerBrowser::dontSeeInField()
*/
public function dontSeeInField($field, $value) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeInField', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks if the array of form parameters (name => value) are set on the form matched with the
* passed selector.
*
* ``` php
* <?php
* $I->seeInFormFields('form[name=myform]', [
* 'input1' => 'value',
* 'input2' => 'other value',
* ]);
* ?>
* ```
*
* For multi-select elements, or to check values of multiple elements with the same name, an
* array may be passed:
*
* ``` php
* <?php
* $I->seeInFormFields('.form-class', [
* 'multiselect' => [
* 'value1',
* 'value2',
* ],
* 'checkbox[]' => [
* 'a checked value',
* 'another checked value',
* ],
* ]);
* ?>
* ```
*
* Additionally, checkbox values can be checked with a boolean.
*
* ``` php
* <?php
* $I->seeInFormFields('#form-id', [
* 'checkbox1' => true, // passes if checked
* 'checkbox2' => false, // passes if unchecked
* ]);
* ?>
* ```
*
* Pair this with submitForm for quick testing magic.
*
* ``` php
* <?php
* $form = [
* 'field1' => 'value',
* 'field2' => 'another value',
* 'checkbox1' => true,
* // ...
* ];
* $I->submitForm('//form[@id=my-form]', $form, 'submitButton');
* // $I->amOnPage('/path/to/form-page') may be needed
* $I->seeInFormFields('//form[@id=my-form]', $form);
* ?>
* ```
*
* @param $formSelector
* @param $params
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeInFormFields()
*/
public function canSeeInFormFields($formSelector, $params) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeInFormFields', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks if the array of form parameters (name => value) are set on the form matched with the
* passed selector.
*
* ``` php
* <?php
* $I->seeInFormFields('form[name=myform]', [
* 'input1' => 'value',
* 'input2' => 'other value',
* ]);
* ?>
* ```
*
* For multi-select elements, or to check values of multiple elements with the same name, an
* array may be passed:
*
* ``` php
* <?php
* $I->seeInFormFields('.form-class', [
* 'multiselect' => [
* 'value1',
* 'value2',
* ],
* 'checkbox[]' => [
* 'a checked value',
* 'another checked value',
* ],
* ]);
* ?>
* ```
*
* Additionally, checkbox values can be checked with a boolean.
*
* ``` php
* <?php
* $I->seeInFormFields('#form-id', [
* 'checkbox1' => true, // passes if checked
* 'checkbox2' => false, // passes if unchecked
* ]);
* ?>
* ```
*
* Pair this with submitForm for quick testing magic.
*
* ``` php
* <?php
* $form = [
* 'field1' => 'value',
* 'field2' => 'another value',
* 'checkbox1' => true,
* // ...
* ];
* $I->submitForm('//form[@id=my-form]', $form, 'submitButton');
* // $I->amOnPage('/path/to/form-page') may be needed
* $I->seeInFormFields('//form[@id=my-form]', $form);
* ?>
* ```
*
* @param $formSelector
* @param $params
* @see \Codeception\Lib\InnerBrowser::seeInFormFields()
*/
public function seeInFormFields($formSelector, $params) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeInFormFields', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks if the array of form parameters (name => value) are not set on the form matched with
* the passed selector.
*
* ``` php
* <?php
* $I->dontSeeInFormFields('form[name=myform]', [
* 'input1' => 'non-existent value',
* 'input2' => 'other non-existent value',
* ]);
* ?>
* ```
*
* To check that an element hasn't been assigned any one of many values, an array can be passed
* as the value:
*
* ``` php
* <?php
* $I->dontSeeInFormFields('.form-class', [
* 'fieldName' => [
* 'This value shouldn\'t be set',
* 'And this value shouldn\'t be set',
* ],
* ]);
* ?>
* ```
*
* Additionally, checkbox values can be checked with a boolean.
*
* ``` php
* <?php
* $I->dontSeeInFormFields('#form-id', [
* 'checkbox1' => true, // fails if checked
* 'checkbox2' => false, // fails if unchecked
* ]);
* ?>
* ```
*
* @param $formSelector
* @param $params
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeInFormFields()
*/
public function cantSeeInFormFields($formSelector, $params) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeInFormFields', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks if the array of form parameters (name => value) are not set on the form matched with
* the passed selector.
*
* ``` php
* <?php
* $I->dontSeeInFormFields('form[name=myform]', [
* 'input1' => 'non-existent value',
* 'input2' => 'other non-existent value',
* ]);
* ?>
* ```
*
* To check that an element hasn't been assigned any one of many values, an array can be passed
* as the value:
*
* ``` php
* <?php
* $I->dontSeeInFormFields('.form-class', [
* 'fieldName' => [
* 'This value shouldn\'t be set',
* 'And this value shouldn\'t be set',
* ],
* ]);
* ?>
* ```
*
* Additionally, checkbox values can be checked with a boolean.
*
* ``` php
* <?php
* $I->dontSeeInFormFields('#form-id', [
* 'checkbox1' => true, // fails if checked
* 'checkbox2' => false, // fails if unchecked
* ]);
* ?>
* ```
*
* @param $formSelector
* @param $params
* @see \Codeception\Lib\InnerBrowser::dontSeeInFormFields()
*/
public function dontSeeInFormFields($formSelector, $params) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeInFormFields', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Submits the given form on the page, optionally with the given form values.
* Give the form fields values as an array.
*
* Skipped fields will be filled by their values from the page.
* You don't need to click the 'Submit' button afterwards.
* This command itself triggers the request to form's action.
*
* You can optionally specify what button's value to include
* in the request with the last parameter as an alternative to
* explicitly setting its value in the second parameter, as
* button values are not otherwise included in the request.
*
* Examples:
*
* ``` php
* <?php
* $I->submitForm('#login', array('login' => 'davert', 'password' => '123456'));
* // or
* $I->submitForm('#login', array('login' => 'davert', 'password' => '123456'), 'submitButtonName');
*
* ```
*
* For example, given this sample "Sign Up" form:
*
* ``` html
* <form action="/sign_up">
* Login: <input type="text" name="user[login]" /><br/>
* Password: <input type="password" name="user[password]" /><br/>
* Do you agree to out terms? <input type="checkbox" name="user[agree]" /><br/>
* Select pricing plan <select name="plan"><option value="1">Free</option><option value="2" selected="selected">Paid</option></select>
* <input type="submit" name="submitButton" value="Submit" />
* </form>
* ```
*
* You could write the following to submit it:
*
* ``` php
* <?php
* $I->submitForm('#userForm', array('user' => array('login' => 'Davert', 'password' => '123456', 'agree' => true)), 'submitButton');
*
* ```
* Note that "2" will be the submitted value for the "plan" field, as it is the selected option.
*
* You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
*
* ```php
* <?php
* $I->submitForm('#userForm', array('user' => array('login' => 'Davert', 'password' => '123456', 'agree' => true)));
*
* ```
*
* Pair this with seeInFormFields for quick testing magic.
*
* ``` php
* <?php
* $form = [
* 'field1' => 'value',
* 'field2' => 'another value',
* 'checkbox1' => true,
* // ...
* ];
* $I->submitForm('//form[@id=my-form]', $form, 'submitButton');
* // $I->amOnPage('/path/to/form-page') may be needed
* $I->seeInFormFields('//form[@id=my-form]', $form);
* ?>
* ```
*
* Parameter values can be set to arrays for multiple input fields
* of the same name, or multi-select combo boxes. For checkboxes,
* either the string value can be used, or boolean values which will
* be replaced by the checkbox's value in the DOM.
*
* ``` php
* <?php
* $I->submitForm('#my-form', [
* 'field1' => 'value',
* 'checkbox' => [
* 'value of first checkbox',
* 'value of second checkbox,
* ],
* 'otherCheckboxes' => [
* true,
* false,
* false
* ],
* 'multiselect' => [
* 'first option value',
* 'second option value'
* ]
* ]);
* ?>
* ```
*
* Mixing string and boolean values for a checkbox's value is not
* supported and may produce unexpected results.
*
* @param $selector
* @param $params
* @param $button
* @see \Codeception\Lib\InnerBrowser::submitForm()
*/
public function submitForm($selector, $params, $button = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('submitForm', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Fills a text field or textarea with the given string.
*
* ``` php
* <?php
* $I->fillField("//input[@type='text']", "Hello World!");
* $I->fillField(['name' => 'email'], 'jon@mail.com');
* ?>
* ```
*
* @param $field
* @param $value
* @see \Codeception\Lib\InnerBrowser::fillField()
*/
public function fillField($field, $value) {
return $this->scenario->runStep(new \Codeception\Step\Action('fillField', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Selects an option in a select tag or in radio button group.
*
* ``` php
* <?php
* $I->selectOption('form select[name=account]', 'Premium');
* $I->selectOption('form input[name=payment]', 'Monthly');
* $I->selectOption('//form/select[@name=account]', 'Monthly');
* ?>
* ```
*
* Provide an array for the second argument to select multiple options:
*
* ``` php
* <?php
* $I->selectOption('Which OS do you use?', array('Windows','Linux'));
* ?>
* ```
*
* @param $select
* @param $option
* @see \Codeception\Lib\InnerBrowser::selectOption()
*/
public function selectOption($select, $option) {
return $this->scenario->runStep(new \Codeception\Step\Action('selectOption', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
*
* ``` php
* <?php
* $I->checkOption('#agree');
* ?>
* ```
*
* @param $option
* @see \Codeception\Lib\InnerBrowser::checkOption()
*/
public function checkOption($option) {
return $this->scenario->runStep(new \Codeception\Step\Action('checkOption', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Unticks a checkbox.
*
* ``` php
* <?php
* $I->uncheckOption('#notify');
* ?>
* ```
*
* @param $option
* @see \Codeception\Lib\InnerBrowser::uncheckOption()
*/
public function uncheckOption($option) {
return $this->scenario->runStep(new \Codeception\Step\Action('uncheckOption', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Attaches a file relative to the Codeception data directory to the given file upload field.
*
* ``` php
* <?php
* // file is stored in 'tests/_data/prices.xls'
* $I->attachFile('input[@type="file"]', 'prices.xls');
* ?>
* ```
*
* @param $field
* @param $filename
* @see \Codeception\Lib\InnerBrowser::attachFile()
*/
public function attachFile($field, $filename) {
return $this->scenario->runStep(new \Codeception\Step\Action('attachFile', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* If your page triggers an ajax request, you can perform it manually.
* This action sends a GET ajax request with specified params.
*
* See ->sendAjaxPostRequest for examples.
*
* @param $uri
* @param $params
* @see \Codeception\Lib\InnerBrowser::sendAjaxGetRequest()
*/
public function sendAjaxGetRequest($uri, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('sendAjaxGetRequest', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* If your page triggers an ajax request, you can perform it manually.
* This action sends a POST ajax request with specified params.
* Additional params can be passed as array.
*
* Example:
*
* Imagine that by clicking checkbox you trigger ajax request which updates user settings.
* We emulate that click by running this ajax request manually.
*
* ``` php
* <?php
* $I->sendAjaxPostRequest('/updateSettings', array('notifications' => true)); // POST
* $I->sendAjaxGetRequest('/updateSettings', array('notifications' => true)); // GET
*
* ```
*
* @param $uri
* @param $params
* @see \Codeception\Lib\InnerBrowser::sendAjaxPostRequest()
*/
public function sendAjaxPostRequest($uri, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('sendAjaxPostRequest', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* If your page triggers an ajax request, you can perform it manually.
* This action sends an ajax request with specified method and params.
*
* Example:
*
* You need to perform an ajax request specifying the HTTP method.
*
* ``` php
* <?php
* $I->sendAjaxRequest('PUT', '/posts/7', array('title' => 'new title'));
*
* ```
*
* @param $method
* @param $uri
* @param $params
* @see \Codeception\Lib\InnerBrowser::sendAjaxRequest()
*/
public function sendAjaxRequest($method, $uri, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('sendAjaxRequest', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Finds and returns the text contents of the given element.
* If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
*
* ``` php
* <?php
* $heading = $I->grabTextFrom('h1');
* $heading = $I->grabTextFrom('descendant-or-self::h1');
* $value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
* ?>
* ```
*
* @param $cssOrXPathOrRegex
*
* @return mixed
* @see \Codeception\Lib\InnerBrowser::grabTextFrom()
*/
public function grabTextFrom($cssOrXPathOrRegex) {
return $this->scenario->runStep(new \Codeception\Step\Action('grabTextFrom', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Grabs the value of the given attribute value from the given element.
* Fails if element is not found.
*
* ``` php
* <?php
* $I->grabAttributeFrom('#tooltip', 'title');
* ?>
* ```
*
*
* @param $cssOrXpath
* @param $attribute
* @internal param $element
* @return mixed
* @see \Codeception\Lib\InnerBrowser::grabAttributeFrom()
*/
public function grabAttributeFrom($cssOrXpath, $attribute) {
return $this->scenario->runStep(new \Codeception\Step\Action('grabAttributeFrom', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $field
*
* @return array|mixed|null|string
* @see \Codeception\Lib\InnerBrowser::grabValueFrom()
*/
public function grabValueFrom($field) {
return $this->scenario->runStep(new \Codeception\Step\Action('grabValueFrom', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Sets a cookie with the given name and value.
* You can set additional cookie params like `domain`, `path`, `expire`, `secure` in array passed as last argument.
*
* ``` php
* <?php
* $I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
* ?>
* ```
*
* @param $name
* @param $val
* @param array $params
* @internal param $cookie
* @internal param $value
*
* @return mixed
* @see \Codeception\Lib\InnerBrowser::setCookie()
*/
public function setCookie($name, $val, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('setCookie', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Grabs a cookie value.
* You can set additional cookie params like `domain`, `path` in array passed as last argument.
*
* @param $cookie
*
* @param array $params
* @return mixed
* @see \Codeception\Lib\InnerBrowser::grabCookie()
*/
public function grabCookie($cookie, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('grabCookie', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that a cookie with the given name is set.
* You can set additional cookie params like `domain`, `path` as array passed in last argument.
*
* ``` php
* <?php
* $I->seeCookie('PHPSESSID');
* ?>
* ```
*
* @param $cookie
* @param array $params
* @return mixed
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeCookie()
*/
public function canSeeCookie($cookie, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeCookie', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that a cookie with the given name is set.
* You can set additional cookie params like `domain`, `path` as array passed in last argument.
*
* ``` php
* <?php
* $I->seeCookie('PHPSESSID');
* ?>
* ```
*
* @param $cookie
* @param array $params
* @return mixed
* @see \Codeception\Lib\InnerBrowser::seeCookie()
*/
public function seeCookie($cookie, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeCookie', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that there isn't a cookie with the given name.
* You can set additional cookie params like `domain`, `path` as array passed in last argument.
*
* @param $cookie
*
* @param array $params
* @return mixed
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeCookie()
*/
public function cantSeeCookie($cookie, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeCookie', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that there isn't a cookie with the given name.
* You can set additional cookie params like `domain`, `path` as array passed in last argument.
*
* @param $cookie
*
* @param array $params
* @return mixed
* @see \Codeception\Lib\InnerBrowser::dontSeeCookie()
*/
public function dontSeeCookie($cookie, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeCookie', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Unsets cookie with the given name.
* You can set additional cookie params like `domain`, `path` in array passed as last argument.
*
* @param $cookie
*
* @param array $params
* @return mixed
* @see \Codeception\Lib\InnerBrowser::resetCookie()
*/
public function resetCookie($name, $params = null) {
return $this->scenario->runStep(new \Codeception\Step\Action('resetCookie', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given element exists on the page and is visible.
* You can also specify expected attributes of this element.
*
* ``` php
* <?php
* $I->seeElement('.error');
* $I->seeElement('//form/input[1]');
* $I->seeElement('input', ['name' => 'login']);
* $I->seeElement('input', ['value' => '123456']);
*
* // strict locator in first arg, attributes in second
* $I->seeElement(['css' => 'form input'], ['name' => 'login']);
* ?>
* ```
*
* @param $selector
* @param array $attributes
* @return
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeElement()
*/
public function canSeeElement($selector, $attributes = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeElement', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given element exists on the page and is visible.
* You can also specify expected attributes of this element.
*
* ``` php
* <?php
* $I->seeElement('.error');
* $I->seeElement('//form/input[1]');
* $I->seeElement('input', ['name' => 'login']);
* $I->seeElement('input', ['value' => '123456']);
*
* // strict locator in first arg, attributes in second
* $I->seeElement(['css' => 'form input'], ['name' => 'login']);
* ?>
* ```
*
* @param $selector
* @param array $attributes
* @return
* @see \Codeception\Lib\InnerBrowser::seeElement()
*/
public function seeElement($selector, $attributes = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeElement', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given element is invisible or not present on the page.
* You can also specify expected attributes of this element.
*
* ``` php
* <?php
* $I->dontSeeElement('.error');
* $I->dontSeeElement('//form/input[1]');
* $I->dontSeeElement('input', ['name' => 'login']);
* $I->dontSeeElement('input', ['value' => '123456']);
* ?>
* ```
*
* @param $selector
* @param array $attributes
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeElement()
*/
public function cantSeeElement($selector, $attributes = null) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeElement', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given element is invisible or not present on the page.
* You can also specify expected attributes of this element.
*
* ``` php
* <?php
* $I->dontSeeElement('.error');
* $I->dontSeeElement('//form/input[1]');
* $I->dontSeeElement('input', ['name' => 'login']);
* $I->dontSeeElement('input', ['value' => '123456']);
* ?>
* ```
*
* @param $selector
* @param array $attributes
* @see \Codeception\Lib\InnerBrowser::dontSeeElement()
*/
public function dontSeeElement($selector, $attributes = null) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeElement', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that there are a certain number of elements matched by the given locator on the page.
*
* ``` php
* <?php
* $I->seeNumberOfElements('tr', 10);
* $I->seeNumberOfElements('tr', [0,10]); //between 0 and 10 elements
* ?>
* ```
* @param $selector
* @param mixed $expected:
* - string: strict number
* - array: range of numbers [0,10]
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeNumberOfElements()
*/
public function canSeeNumberOfElements($selector, $expected) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeNumberOfElements', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that there are a certain number of elements matched by the given locator on the page.
*
* ``` php
* <?php
* $I->seeNumberOfElements('tr', 10);
* $I->seeNumberOfElements('tr', [0,10]); //between 0 and 10 elements
* ?>
* ```
* @param $selector
* @param mixed $expected:
* - string: strict number
* - array: range of numbers [0,10]
* @see \Codeception\Lib\InnerBrowser::seeNumberOfElements()
*/
public function seeNumberOfElements($selector, $expected) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeNumberOfElements', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given option is selected.
*
* ``` php
* <?php
* $I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
* ?>
* ```
*
* @param $selector
* @param $optionText
*
* @return mixed
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeOptionIsSelected()
*/
public function canSeeOptionIsSelected($selector, $optionText) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeOptionIsSelected', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given option is selected.
*
* ``` php
* <?php
* $I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
* ?>
* ```
*
* @param $selector
* @param $optionText
*
* @return mixed
* @see \Codeception\Lib\InnerBrowser::seeOptionIsSelected()
*/
public function seeOptionIsSelected($selector, $optionText) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeOptionIsSelected', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given option is not selected.
*
* ``` php
* <?php
* $I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
* ?>
* ```
*
* @param $selector
* @param $optionText
*
* @return mixed
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeOptionIsSelected()
*/
public function cantSeeOptionIsSelected($selector, $optionText) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeOptionIsSelected', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the given option is not selected.
*
* ``` php
* <?php
* $I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
* ?>
* ```
*
* @param $selector
* @param $optionText
*
* @return mixed
* @see \Codeception\Lib\InnerBrowser::dontSeeOptionIsSelected()
*/
public function dontSeeOptionIsSelected($selector, $optionText) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeOptionIsSelected', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Asserts that current page has 404 response status code.
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seePageNotFound()
*/
public function canSeePageNotFound() {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seePageNotFound', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Asserts that current page has 404 response status code.
* @see \Codeception\Lib\InnerBrowser::seePageNotFound()
*/
public function seePageNotFound() {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seePageNotFound', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that response code is equal to value provided.
*
* @param $code
*
* @return mixed
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeResponseCodeIs()
*/
public function canSeeResponseCodeIs($code) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeResponseCodeIs', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that response code is equal to value provided.
*
* @param $code
*
* @return mixed
* @see \Codeception\Lib\InnerBrowser::seeResponseCodeIs()
*/
public function seeResponseCodeIs($code) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeResponseCodeIs', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the page title contains the given string.
*
* ``` php
* <?php
* $I->seeInTitle('Blog - Post #1');
* ?>
* ```
*
* @param $title
*
* @return mixed
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::seeInTitle()
*/
public function canSeeInTitle($title) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('seeInTitle', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the page title contains the given string.
*
* ``` php
* <?php
* $I->seeInTitle('Blog - Post #1');
* ?>
* ```
*
* @param $title
*
* @return mixed
* @see \Codeception\Lib\InnerBrowser::seeInTitle()
*/
public function seeInTitle($title) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('seeInTitle', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the page title does not contain the given string.
*
* @param $title
*
* @return mixed
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSeeInTitle()
*/
public function cantSeeInTitle($title) {
return $this->scenario->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeInTitle', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that the page title does not contain the given string.
*
* @param $title
*
* @return mixed
* @see \Codeception\Lib\InnerBrowser::dontSeeInTitle()
*/
public function dontSeeInTitle($title) {
return $this->scenario->runStep(new \Codeception\Step\Assertion('dontSeeInTitle', func_get_args()));
}
}
| {
"content_hash": "4fb0ccc6a4c586bbd0df747bf0f9ef60",
"timestamp": "",
"source": "github",
"line_count": 1918,
"max_line_length": 143,
"avg_line_length": 33.00052137643379,
"alnum_prop": 0.5878821391895095,
"repo_name": "hamidgoharjoo/test",
"id": "cdf0ae3a593cc6053f24b47e305a8ce093e656e4",
"size": "63295",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/acceptance/AcceptanceTester.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "1560"
},
{
"name": "PHP",
"bytes": "139450"
}
],
"symlink_target": ""
} |
var Helper = {};
//Function for getting the radians on an angle
Helper.radians = function(degrees) {
return (Math.PI / 180) * degrees;
}
// Returns an array with the amount of days in every month
// and the count of days of december last year in week 1 as
// the first value in the array.
Helper.getMonthDayCount = function(year){
var dayCounts = [];
var firstDateOfTheYear = new Date(year, 0, 0);
var numberOfWeekDay = firstDateOfTheYear.getDay();
dayCounts.push(numberOfWeekDay);
// Pushes the day-count of all the months into the array
for (var i = 1; i <= 12; i++) {
dayCounts.push(new Date(year, i, 0).getDate());
}
return dayCounts;
}
Helper.objectSize = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
}
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.toFnName = function() {
var arr = this.split("-"),
ret = arr[0];
for (var i = 1; child = arr[i++];) {
ret += child.capitalizeFirstLetter();
}
return ret;
}
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
}
Array.prototype.except = function(remove) {
if (!(remove instanceof Array)) remove = [];
var ret = this.filter(function(item) {
return remove.indexOf(item) === -1;
});
return ret;
} | {
"content_hash": "8bc1e0eee23dbeed1cdf7451ce32f641",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 60,
"avg_line_length": 24.81967213114754,
"alnum_prop": 0.6036988110964333,
"repo_name": "Ice-A-Slice/kvalitetshjulet",
"id": "d53dad010dcf708e6d4155864065a9b20d89c8cb",
"size": "1514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/assets/javascripts/wheel/classes/Helper.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "33126"
},
{
"name": "CSS",
"bytes": "731438"
},
{
"name": "CoffeeScript",
"bytes": "1997"
},
{
"name": "HTML",
"bytes": "96550"
},
{
"name": "JavaScript",
"bytes": "3839223"
},
{
"name": "Ruby",
"bytes": "114601"
}
],
"symlink_target": ""
} |
<!doctype>
<html>
<head>
<meta charset="UTF-8">
<style>
body{
font-family: arial;font-size:12px;
}
</style>
</head>
<body>
<h1>Getting Start</h1>
Nouveau framework PHP basé sur un concept MVC solide et très malléable.<br/><br/>
Pour afficher Hello World, voici le Vhost apache Type à mettre en place :
<pre>
<VirtualHost *:80>
ServerName localhost
DocumentRoot E:/venus/public/Demo/
<Directory E:/venus/public/Demo/>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
</pre>
N'oubliez pas de redémarrer Apache pour que les modifications soient prises en compte.<br/><br/>
Vous pouvez également utiliser le serveur interne proposé par Venus en faisant php bin/console server:run
<br/><br/>
Pour vori votre page, vous pouvez à présent faire http://localhost/ dans votre navigateur Internet.<br/><br/>
<a href="mon-premier-bundle.html">[suivant]</a>
</body>
</html>
| {
"content_hash": "5e85ff58deb3b926de79c9abed2ed659",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 117,
"avg_line_length": 34,
"alnum_prop": 0.624777183600713,
"repo_name": "las93/venus3",
"id": "a9f9f8b36d5b83b9b0d5f8fc43d50429d175b3e4",
"size": "1131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "124"
},
{
"name": "CSS",
"bytes": "39"
},
{
"name": "PHP",
"bytes": "269951"
},
{
"name": "Smarty",
"bytes": "415"
}
],
"symlink_target": ""
} |
import * as React from 'react';
import { defineMessages } from 'react-intl';
import {
Boundary,
Button,
Divider,
Menu,
OverflowList,
} from '@blueprintjs/core';
import { Popover2 as Popover } from '@blueprintjs/popover2';
import c from 'classnames';
import { GraphContext } from 'react-ftm/components/NetworkDiagram/GraphContext';
import {
IToolbarButtonGroup,
ToolbarButtonGroup,
SearchBox,
} from 'react-ftm/components/NetworkDiagram/toolbox';
import { modes } from 'react-ftm/components/NetworkDiagram/utils';
import {
Point,
centerAround,
positionSelection,
type PositionType,
} from 'react-ftm/components/NetworkDiagram/layout';
import { History } from 'react-ftm/components/NetworkDiagram/History';
import './Toolbar.scss';
const messages = defineMessages({
tooltip_undo: {
id: 'tooltip.undo',
defaultMessage: 'Undo',
},
tooltip_redo: {
id: 'tooltip.redo',
defaultMessage: 'Redo',
},
tooltip_add_entities: {
id: 'tooltip.add_entities',
defaultMessage: 'Add entities',
},
tooltip_add_edges: {
id: 'tooltip.add_edges',
defaultMessage: 'Add link',
},
tooltip_expand: {
id: 'tooltip.expand',
defaultMessage: 'Discover links',
},
tooltip_delete: {
id: 'tooltip.delete',
defaultMessage: 'Delete selected',
},
tooltip_group: {
id: 'tooltip.group',
defaultMessage: 'Group selected',
},
tooltip_ungroup: {
id: 'tooltip.ungroup',
defaultMessage: 'Ungroup selected',
},
tooltip_select_mode: {
id: 'tooltip.select_mode',
defaultMessage: 'Toggle select mode',
},
tooltip_pan_mode: {
id: 'tooltip.pan_mode',
defaultMessage: 'Toggle pan mode',
},
tooltip_layouts: {
id: 'tooltip.layouts',
defaultMessage: 'Layouts',
},
tooltip_layout_horizontal: {
id: 'tooltip.layout_horizontal',
defaultMessage: 'Align horizontal',
},
tooltip_layout_vertical: {
id: 'tooltip.layout_vertical',
defaultMessage: 'Align vertical',
},
tooltip_layout_circle: {
id: 'tooltip.layout_circle',
defaultMessage: 'Arrange as circle',
},
tooltip_layout_hierarchy: {
id: 'tooltip.layout_hierarchy',
defaultMessage: 'Arrange as hierarchy',
},
tooltip_layout_auto: {
id: 'tooltip.layout_auto',
defaultMessage: 'Auto-layout',
},
tooltip_layout_center: {
id: 'tooltip.layout_center',
defaultMessage: 'Center',
},
tooltip_sidebar_view: {
id: 'tooltip.sidebar_view',
defaultMessage: 'Show sidebar',
},
tooltip_table_view: {
id: 'tooltip.table_view',
defaultMessage: 'Show table',
},
tooltip_export_svg: {
id: 'tooltip.export_svg',
defaultMessage: 'Export as SVG',
},
tooltip_settings: {
id: 'tooltip.settings',
defaultMessage: 'Settings',
},
});
interface IToolbarProps {
actions: any;
history: History;
showEditingButtons: boolean;
searchText: string;
tableView: boolean;
}
export class Toolbar extends React.Component<IToolbarProps> {
static contextType = GraphContext;
constructor(props: Readonly<IToolbarProps>) {
super(props);
this.onSetInteractionMode = this.onSetInteractionMode.bind(this);
this.onPosition = this.onPosition.bind(this);
this.itemRenderer = this.itemRenderer.bind(this);
this.overflowListRenderer = this.overflowListRenderer.bind(this);
}
onSetInteractionMode(newMode: string) {
const { layout, updateLayout } = this.context;
const { actions } = this.props;
actions.setInteractionMode(newMode);
updateLayout(layout);
}
onPosition(type: PositionType) {
const { layout, updateLayout } = this.context;
const { actions } = this.props;
updateLayout(positionSelection(layout, type), null, {
modifyHistory: true,
});
actions.fitToSelection();
}
itemRenderer(buttonGroup: IToolbarButtonGroup, visible: boolean) {
const { layout } = this.context;
const { showEditingButtons } = this.props;
const filteredGroup = showEditingButtons
? buttonGroup
: buttonGroup.filter((b: any) => !b.writeableOnly);
if (!filteredGroup.length) {
return <></>;
}
return (
<React.Fragment key={filteredGroup[0]?.helpText}>
<Divider />
<ToolbarButtonGroup
buttonGroup={filteredGroup}
visible={visible}
editorTheme={layout.config.editorTheme}
/>
</React.Fragment>
);
}
overflowListRenderer(overflowItems: Array<IToolbarButtonGroup>) {
const { config } = this.context.layout;
const menuContent = overflowItems.map((item: IToolbarButtonGroup) =>
this.itemRenderer(item, false)
);
return (
<Popover
content={<Menu>{menuContent}</Menu>}
position="bottom"
minimal
popoverClassName={c('Toolbar__menu', `theme-${config.editorTheme}`)}
rootBoundary="viewport"
>
<Button icon="double-chevron-right" />
</Popover>
);
}
render() {
const { entityManager, interactionMode, intl, layout, updateLayout } =
this.context;
const { actions, history, searchText, tableView } = this.props;
const vertices = layout.getSelectedVertices();
const hasSelection = layout.hasSelection();
const canAddEdge = vertices.length > 0 && vertices.length <= 2;
const canExpandSelection =
entityManager.hasExpand && layout.getSelectedVertices().length === 1;
const canGroupSelection = layout.getSelectedVertices().length > 1;
const canUngroupSelection = layout.getSelectedGroupings().length >= 1;
const showSearch = layout.vertices && layout.vertices.size > 0;
const { logo } = layout.config;
const buttons: Array<IToolbarButtonGroup> = [
[
{
helpText: intl.formatMessage(messages.tooltip_undo),
icon: 'undo',
onClick: () => actions.navigateHistory(History.BACK),
disabled: !history.canGoTo(History.BACK),
writeableOnly: true,
},
{
helpText: intl.formatMessage(messages.tooltip_redo),
icon: 'redo',
onClick: () => actions.navigateHistory(History.FORWARD),
disabled: !history.canGoTo(History.FORWARD),
writeableOnly: true,
},
],
[
{
helpText: intl.formatMessage(messages.tooltip_add_entities),
icon: 'new-object',
onClick: () => this.onSetInteractionMode(modes.VERTEX_CREATE),
writeableOnly: true,
},
{
helpText: intl.formatMessage(messages.tooltip_add_edges),
icon: 'new-link',
onClick: () => this.onSetInteractionMode(modes.EDGE_CREATE),
disabled: !canAddEdge,
writeableOnly: true,
},
{
helpText: intl.formatMessage(messages.tooltip_delete),
icon: 'trash',
onClick: () => actions.removeSelection(),
disabled: !hasSelection,
writeableOnly: true,
},
...(entityManager.hasExpand
? [
{
helpText: intl.formatMessage(messages.tooltip_expand),
icon: 'search-around',
onClick: (e: React.MouseEvent) => {
const selectedVertex = vertices[0];
if (selectedVertex.isEntity()) {
const isTopToolbar =
layout.config.toolbarPosition === 'top';
const posX = isTopToolbar ? e.clientX - 10 : 70;
const posY = isTopToolbar ? 40 : e.clientY - 10;
actions.showVertexMenu(
selectedVertex,
new Point(posX, posY),
true
);
}
},
disabled: !canExpandSelection,
writeableOnly: true,
},
]
: []),
],
[
{
helpText: intl.formatMessage(messages.tooltip_group),
icon: 'group-objects',
onClick: () => this.onSetInteractionMode(modes.GROUPING_CREATE),
disabled: !canGroupSelection,
writeableOnly: true,
},
{
helpText: intl.formatMessage(messages.tooltip_ungroup),
icon: 'ungroup-objects',
onClick: () => actions.ungroupSelection(),
disabled: !canUngroupSelection,
writeableOnly: true,
},
],
[
{
helpText: intl.formatMessage(messages.tooltip_select_mode),
icon: 'select',
disabled: interactionMode !== modes.PAN,
onClick: () => this.onSetInteractionMode(modes.SELECT),
},
{
helpText: intl.formatMessage(messages.tooltip_pan_mode),
icon: 'hand',
disabled: interactionMode === modes.PAN,
onClick: () => this.onSetInteractionMode(modes.PAN),
},
],
[
{
helpText: intl.formatMessage(messages.tooltip_sidebar_view),
icon: 'panel-stats',
disabled: !tableView,
onClick: () => actions.toggleTableView(),
},
{
helpText: intl.formatMessage(messages.tooltip_table_view),
icon: 'th',
disabled: tableView,
onClick: () => actions.toggleTableView(),
},
],
[
{
helpText: intl.formatMessage(messages.tooltip_layouts),
icon: 'layout',
writeableOnly: true,
subItems: [
{
helpText: intl.formatMessage(messages.tooltip_layout_horizontal),
icon: 'layout-linear',
onClick: () => this.onPosition('alignHorizontal'),
},
{
helpText: intl.formatMessage(messages.tooltip_layout_vertical),
icon: 'drag-handle-vertical',
onClick: () => this.onPosition('alignVertical'),
},
{
helpText: intl.formatMessage(messages.tooltip_layout_circle),
icon: 'layout-circle',
onClick: () => this.onPosition('alignCircle'),
},
{
helpText: intl.formatMessage(messages.tooltip_layout_hierarchy),
icon: 'layout-hierarchy',
onClick: () => this.onPosition('arrangeTree'),
},
{
helpText: intl.formatMessage(messages.tooltip_layout_auto),
icon: 'layout',
onClick: () => this.onPosition('forceLayout'),
},
{
helpText: intl.formatMessage(messages.tooltip_layout_center),
icon: 'layout-auto',
disabled: !hasSelection,
onClick: () =>
updateLayout(centerAround(layout), null, {
modifyHistory: true,
}),
},
],
},
],
[
{
helpText: intl.formatMessage(messages.tooltip_settings),
icon: 'cog',
onClick: () => actions.toggleSettingsDialog(),
writeableOnly: true,
},
],
];
return (
<div className="Toolbar">
{logo && (
<div className="Toolbar__logo-container">
<div className="Toolbar__logo">
{logo.image && (
<img
className="Toolbar__logo__image"
src={logo.image}
alt="OCCRP Data"
></img>
)}
{logo.text && (
<h5 className="Toolbar__logo__text">{logo.text}</h5>
)}
</div>
</div>
)}
<div className="Toolbar__main">
<OverflowList
items={buttons}
collapseFrom={Boundary.END}
visibleItemRenderer={(buttonGroup: IToolbarButtonGroup) =>
this.itemRenderer(buttonGroup, true)
}
overflowRenderer={this.overflowListRenderer}
className="Toolbar__button-group-container"
observeParents
/>
</div>
{showSearch && (
<div className="Toolbar__search-container">
<SearchBox
onChangeSearch={actions.onChangeSearch}
onSubmitSearch={actions.onSubmitSearch}
searchText={searchText}
/>
</div>
)}
</div>
);
}
}
| {
"content_hash": "30254c1d804523bbed5f0d6a1ddcdae4",
"timestamp": "",
"source": "github",
"line_count": 413,
"max_line_length": 80,
"avg_line_length": 29.946731234866828,
"alnum_prop": 0.569372574385511,
"repo_name": "alephdata/aleph",
"id": "c1e48b4ee7e546fa2f158f4972937567a2d74155",
"size": "12368",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "ui/src/react-ftm/components/NetworkDiagram/toolbox/Toolbar.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2610"
},
{
"name": "HTML",
"bytes": "4162"
},
{
"name": "JavaScript",
"bytes": "882037"
},
{
"name": "Makefile",
"bytes": "7861"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "618821"
},
{
"name": "SCSS",
"bytes": "140491"
},
{
"name": "Shell",
"bytes": "3215"
},
{
"name": "TypeScript",
"bytes": "308454"
}
],
"symlink_target": ""
} |
package org.kuali.rice.kew.engine.node;
import java.util.HashMap;
import java.util.Map;
/**
* The current context of a search process within a node graph.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class NodeGraphContext {
private RouteNodeInstance previousNodeInstance;
private RouteNodeInstance currentNodeInstance;
private RouteNodeInstance resultNodeInstance;
private Map<String, RouteNodeInstance> visited = new HashMap<String, RouteNodeInstance>();
private Map<String, Integer> splitState = new HashMap<String, Integer>();
public RouteNodeInstance getCurrentNodeInstance() {
return currentNodeInstance;
}
public void setCurrentNodeInstance(RouteNodeInstance currentNodeInstance) {
this.currentNodeInstance = currentNodeInstance;
}
public RouteNodeInstance getPreviousNodeInstance() {
return previousNodeInstance;
}
public void setPreviousNodeInstance(RouteNodeInstance previousNodeInstance) {
this.previousNodeInstance = previousNodeInstance;
}
public RouteNodeInstance getResultNodeInstance() {
return resultNodeInstance;
}
public void setResultNodeInstance(RouteNodeInstance resultNodeInstance) {
this.resultNodeInstance = resultNodeInstance;
}
public Map<String, Integer> getSplitState() {
return splitState;
}
public void setSplitState(Map<String, Integer> splitState) {
this.splitState = splitState;
}
public Map<String, RouteNodeInstance> getVisited() {
return visited;
}
public void setVisited(Map<String, RouteNodeInstance> visited) {
this.visited = visited;
}
}
| {
"content_hash": "5dddf79505734ac60a892cd62f15fe7e",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 94,
"avg_line_length": 33.07843137254902,
"alnum_prop": 0.7296976882039122,
"repo_name": "gathreya/rice-kc",
"id": "32b5187ffcbed0482a05f5d9e842312cc8aad61c",
"size": "2308",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "rice-middleware/impl/src/main/java/org/kuali/rice/kew/engine/node/NodeGraphContext.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "582087"
},
{
"name": "Groovy",
"bytes": "2237525"
},
{
"name": "HTML",
"bytes": "3275588"
},
{
"name": "Java",
"bytes": "36174377"
},
{
"name": "JavaScript",
"bytes": "2676356"
},
{
"name": "PHP",
"bytes": "15766"
},
{
"name": "PLSQL",
"bytes": "318774"
},
{
"name": "SQLPL",
"bytes": "101667"
},
{
"name": "Shell",
"bytes": "13217"
},
{
"name": "XSLT",
"bytes": "107818"
}
],
"symlink_target": ""
} |
package com.bazaarvoice.commons.data.model.json;
import org.json.JSONArray;
import javax.annotation.Nullable;
public class StringJSONArrayList extends AbstractJSONArrayList<String> {
public StringJSONArrayList(@Nullable JSONArray jsonArray) {
super(jsonArray);
}
@Nullable
@Override
protected String getFromJSONArray(JSONArray jsonArray, int index) {
return (String) jsonArray.opt(index);
}
}
| {
"content_hash": "0a8f1853707d256b4450351cb098b73a",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 72,
"avg_line_length": 25.705882352941178,
"alnum_prop": 0.7391304347826086,
"repo_name": "bazaarvoice/commons-data-dao",
"id": "7e60203b0bf593c339f363b073615766f37360d9",
"size": "437",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "json/src/main/java/com/bazaarvoice/commons/data/model/json/StringJSONArrayList.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "342291"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "68e2d0e364734fd9d952371d6d8ded17",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "61f22fc46c2954931632c79814b764ec47ad86af",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Phlomis/Phlomis hypoleuca/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Prime Numbers</title>
<link rel="stylesheet" href="../../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../../index.html" title="Math Toolkit 2.3.0">
<link rel="up" href="../number_series.html" title="Number Series">
<link rel="prev" href="tangent_numbers.html" title="Tangent Numbers">
<link rel="next" href="../sf_gamma.html" title="Gamma Functions">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="tangent_numbers.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../number_series.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../sf_gamma.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="math_toolkit.number_series.primes"></a><a class="link" href="primes.html" title="Prime Numbers">Prime Numbers</a>
</h3></div></div></div>
<h5>
<a name="math_toolkit.number_series.primes.h0"></a>
<span class="phrase"><a name="math_toolkit.number_series.primes.synopsis"></a></span><a class="link" href="primes.html#math_toolkit.number_series.primes.synopsis">Synopsis</a>
</h5>
<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">math</span><span class="special">/</span><span class="identifier">special_functions</span><span class="special">/</span><span class="identifier">prime</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
</pre>
<pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">boost</span> <span class="special">{</span> <span class="keyword">namespace</span> <span class="identifier">math</span> <span class="special">{</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Policy</span><span class="special">></span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint32_t</span> <span class="identifier">prime</span><span class="special">(</span><span class="keyword">unsigned</span> <span class="identifier">n</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">Policy</span><span class="special">&</span> <span class="identifier">pol</span><span class="special">);</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint32_t</span> <span class="identifier">prime</span><span class="special">(</span><span class="keyword">unsigned</span> <span class="identifier">n</span><span class="special">);</span>
<span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">unsigned</span> <span class="identifier">max_prime</span> <span class="special">=</span> <span class="number">10000</span><span class="special">;</span>
<span class="special">}}</span> <span class="comment">// namespaces</span>
</pre>
<h5>
<a name="math_toolkit.number_series.primes.h1"></a>
<span class="phrase"><a name="math_toolkit.number_series.primes.description"></a></span><a class="link" href="primes.html#math_toolkit.number_series.primes.description">Description</a>
</h5>
<p>
The function <code class="computeroutput"><span class="identifier">prime</span></code> provides
fast table lookup to the first 10000 prime numbers (starting from 2 as the
zeroth prime: as 1 isn't terribly useful in practice). There are two function
signatures one of which takes an optional <a class="link" href="../../policy.html" title="Chapter 15. Policies: Controlling Precision, Error Handling etc">Policy</a>
as the second parameter to control error handling.
</p>
<p>
The constant <code class="computeroutput"><span class="identifier">max_prime</span></code> is
the largest value you can pass to <code class="computeroutput"><span class="identifier">prime</span></code>
without incurring an error.
</p>
<p>
Passing a value greater than <code class="computeroutput"><span class="identifier">max_prime</span></code>
results in a <a class="link" href="../error_handling.html#math_toolkit.error_handling.domain_error">domain_error</a>
being raised.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2006-2010, 2012-2014 Nikhar Agrawal,
Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert
Holin, Bruno Lalande, John Maddock, Johan Råde, Gautam Sewani, Benjamin Sobotta,
Thijs van den Berg, Daryle Walker and Xiaogang Zhang<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="tangent_numbers.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../number_series.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../sf_gamma.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "374ad63c2f04062085d805df831bd360",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 452,
"avg_line_length": 79.88095238095238,
"alnum_prop": 0.6536512667660208,
"repo_name": "zjutjsj1004/third",
"id": "3963287ade0f2d7821c082fce6c8675d652b1429",
"size": "6710",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "boost/libs/math/doc/html/math_toolkit/number_series/primes.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "224158"
},
{
"name": "Batchfile",
"bytes": "33175"
},
{
"name": "C",
"bytes": "5576593"
},
{
"name": "C#",
"bytes": "41850"
},
{
"name": "C++",
"bytes": "179595990"
},
{
"name": "CMake",
"bytes": "28348"
},
{
"name": "CSS",
"bytes": "331303"
},
{
"name": "Cuda",
"bytes": "26521"
},
{
"name": "FORTRAN",
"bytes": "1856"
},
{
"name": "Groff",
"bytes": "1305458"
},
{
"name": "HTML",
"bytes": "159660377"
},
{
"name": "IDL",
"bytes": "15"
},
{
"name": "JavaScript",
"bytes": "285786"
},
{
"name": "Lex",
"bytes": "1290"
},
{
"name": "Makefile",
"bytes": "1202020"
},
{
"name": "Max",
"bytes": "37424"
},
{
"name": "Objective-C",
"bytes": "3674"
},
{
"name": "Objective-C++",
"bytes": "651"
},
{
"name": "PHP",
"bytes": "60249"
},
{
"name": "Perl",
"bytes": "37297"
},
{
"name": "Perl6",
"bytes": "2130"
},
{
"name": "Python",
"bytes": "1833677"
},
{
"name": "QML",
"bytes": "613"
},
{
"name": "QMake",
"bytes": "17385"
},
{
"name": "Rebol",
"bytes": "372"
},
{
"name": "Shell",
"bytes": "1144162"
},
{
"name": "Tcl",
"bytes": "1205"
},
{
"name": "TeX",
"bytes": "38313"
},
{
"name": "XSLT",
"bytes": "564356"
},
{
"name": "Yacc",
"bytes": "20341"
}
],
"symlink_target": ""
} |
package org.carlspring.strongbox.authentication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author Przemyslaw Fusik
*/
@Configuration
@ComponentScan
public class AuthenticationConfig
{
}
| {
"content_hash": "f9bd06e581dc80c08ecee5353965ef87",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 60,
"avg_line_length": 19.857142857142858,
"alnum_prop": 0.8237410071942446,
"repo_name": "strongbox/strongbox",
"id": "4d87c23ff6350291062014dedf9c25be218c5338",
"size": "278",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "strongbox-security/strongbox-authentication-registry/src/main/java/org/carlspring/strongbox/authentication/AuthenticationConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "808"
},
{
"name": "Groovy",
"bytes": "4637"
},
{
"name": "HTML",
"bytes": "8895"
},
{
"name": "Java",
"bytes": "4154989"
},
{
"name": "JavaScript",
"bytes": "4698"
},
{
"name": "Shell",
"bytes": "570"
}
],
"symlink_target": ""
} |
#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include <string>
#include <vector>
#include <QClipboard>
SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0)
{
ui->setupUi(this);
#if (QT_VERSION >= 0x040700)
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addressIn_SM->setPlaceholderText(tr("Enter a Apollocoin address (e.g. WNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
ui->addressIn_VM->setPlaceholderText(tr("Enter a Apollocoin address (e.g. WNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->signatureIn_VM->setPlaceholderText(tr("Enter Apollocoin signature"));
#endif
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(QString address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(QString address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was canceled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CBitcoinAddress(key.GetPubKey().GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
| {
"content_hash": "7c8d7bd95e379081c1c536e132c56f81",
"timestamp": "",
"source": "github",
"line_count": 274,
"max_line_length": 156,
"avg_line_length": 32.06934306569343,
"alnum_prop": 0.6432229429839535,
"repo_name": "fubendong2/apollocoin",
"id": "88f6b7b9f6a226b64167e670a7761761c5558015",
"size": "8787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/signverifymessagedialog.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "78622"
},
{
"name": "C++",
"bytes": "1374539"
},
{
"name": "IDL",
"bytes": "11538"
},
{
"name": "Objective-C",
"bytes": "2463"
},
{
"name": "Python",
"bytes": "18144"
},
{
"name": "Shell",
"bytes": "1143"
},
{
"name": "TypeScript",
"bytes": "3810608"
}
],
"symlink_target": ""
} |
BU Analytics plugin for C# and Unity written in .NET.
Please visit our [BU Analytics](http://bu-games.bmth.ac.uk) website for more information.
## Installation
For Unity you must install the BUAnalytics package into your project by navigating to `Edit > Import Package > Custom Package`.
For native C# you must copy the BUAnalytics library from the [BUAnalytics](src/Assets/Plugins) folder into your Visual Studio project.
## Authentication
To authenticate with the backend you must first create an access key through the web management interface.
Then pass these details into the api singleton instance.
```csharp
BUAPI.Instance.Auth = new BUAccessKey("58ac40cd126553000c426f91", "06239e3a1401ba6d7250260d0f8fd680e52ff1e754ebe10a250297ebda2bac41");
```
## Getting Started
You can use the convenience method to quickly add a document to a collection which will be created and uploaded automatically.
```csharp
BUCollectionManager.Instance.Add("Users", new Dictionary<string, object>(){
{ "userId", .. },
{ "name", .. },
{ "age", .. },
{ "gender", .. },
{ "device", new Dictionary<string, string>{
{ "type", .. },
{ "name", .. },
{ "model", .. },
} }
});
```
If you would like to manage your own collections and documents please see below.
## Creating Collections
We must then create the collections that we would like to use throughout the application.
This can be done at any point and as many times as needed however collections will not be overwritten if created with a duplicate names.
```csharp
BUCollectionManager.Instance.Create(new string[]{
"Users",
"Sessions",
"Clicks"
});
```
## Creating a Document
We can create a document using a dictionary literal that allows for as many nested values as needed.
Documents support nested dictionaries, arrays and will encode literal data types when uploading to the backend server.
```csharp
var userDoc = new BUDocument(new Dictionary<string, object>(){
{ "userId", .. },
{ "name", .. },
{ "age", .. },
{ "gender", .. },
{ "device", new Dictionary<string, string>{
{ "type", .. },
{ "name", .. },
{ "model", .. },
} }
});
```
You can also create documents through the add method or can access the raw dictionary object through the contents property.
```csharp
var userDoc = new BUDocument();
userDoc.Add("userId", ..);
userDoc.Add("name", ..);
userDoc.Contents["age"] = ..;
userDoc.Contents["gender"] = ..;
```
## Adding a Document to Collection
You can then add one or more documents to a collection through the collection manager.
```csharp
BUCollectionManager.Instance.Collections["Users"].Add(userDoc);
BUCollectionManager.Instance.Collections["Users"].AddRange(new BUDocument[]{ userDoc1, userDoc2, userDoc3 });
```
Collections will automatically push all documents to the backend server every two seconds if not empty.
You can also manually initiate an upload either on all or a specific collection.
```csharp
BUCollectionManager.Instance.UploadAll();
BUCollectionManager.Instance.Collections["Users"].Upload();
```
You can also use the interval property to configure how often collections are uploaded in milliseconds.
The default is 2000 milliseconds and setting it to 0 will disable automatic uploads.
```csharp
BUCollectionManager.Instance.Interval = 4000;
```
## Error Handling
You can subscribe to actions in the collection manager to notify you when collections upload successfully or return errors.
```csharp
BUCollectionManager.Instance.Error = (collection, errorCode) => {
//...
};
BUCollectionManager.Instance.Success = (collection, successCount) => {
//...
};
```
You can also provide error and success actions to an individual collection using the upload method.
## Unique Identifiers
You can use our backend to generate unique identifiers for use inside documents.
Setup the cache at startup specifying how many identifiers you'd like to hold.
```csharp
BUID.Instance.Start(200);
```
Once the cache has been marked as ready you can generate identifiers at any time.
```csharp
if (BUID.Instance.IsReady){
userDoc.Add("userId", BUID.Instance.Generate());
}
```
You can modify the refresh frequency or size of the cache depending on how many identifiers you require.
GUIDs will be generated as a backup should the cache become empty.
```csharp
BUID.Instance.Interval = 4000;
BUID.Instance.Size = 100;
```
## Advanced
The hostname defaults to the university server although we can change this if necessary.
```csharp
BUAPI.Instance.URL = "https://192.168.0.x";
BUAPI.Instance.Path = "/api/v1";
``` | {
"content_hash": "db84d45d458320644898b2a54c79cbb0",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 136,
"avg_line_length": 29.67948717948718,
"alnum_prop": 0.7224622030237581,
"repo_name": "BUAnalytics/C-Sharp",
"id": "e9c691e3c0e69a98f2264f34b6f36f9657334c32",
"size": "4653",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "59445"
}
],
"symlink_target": ""
} |
import requests
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from django.test import LiveServerTestCase
class LoginTestCase(LiveServerTestCase):
@override_settings(DEBUG=True)
def test_login(self):
response = requests.get(self.live_server_url + reverse('test-error'))
self.assertEqual(response.status_code, 500)
| {
"content_hash": "342d18b36bd67123ff09ff4c4a8240b0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 77,
"avg_line_length": 29.846153846153847,
"alnum_prop": 0.7654639175257731,
"repo_name": "fjsj/liveservererror",
"id": "18880de85cee19c089578955f1e69283379932c3",
"size": "388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "liveservererror/tests/test_error_view.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3564"
}
],
"symlink_target": ""
} |
Tinytest.add('jss:admin-settings - test environment', function (test) {
test.isTrue(
typeof AdminSettings !== 'undefined',
'test environment not initialized AdminSettings'
);
test.isTrue(
typeof AdminSettingsTypes !== 'undefined',
'test environment not initialized AdminSettingsTypes'
);
}); | {
"content_hash": "5e05f12f804467bcf31c1e64448daf5e",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 71,
"avg_line_length": 31.5,
"alnum_prop": 0.7111111111111111,
"repo_name": "JSSolutions/meteor-admin-settings",
"id": "0934e3fdb9c56c55fe9bf8ecdd63f4d9e9003a81",
"size": "315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "admin-settings-tests.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "3236"
},
{
"name": "HTML",
"bytes": "1873"
},
{
"name": "JavaScript",
"bytes": "1437"
}
],
"symlink_target": ""
} |
#include "abstracttwitter4qmltest.h"
#include <userssuggestions.h>
class UsersSuggestionsTest : public AbstractTwitter4QMLTest
{
Q_OBJECT
private Q_SLOTS:
void lang();
void lang_data();
};
void UsersSuggestionsTest::lang()
{
QFETCH(QString, data);
UsersSuggestions usersSuggestions;
QCOMPARE(usersSuggestions.lang(), QString());
usersSuggestions.lang(data);
QCOMPARE(usersSuggestions.lang(), data);
QVERIFY2(reload(&usersSuggestions), "UsersSuggestions::reload()");
QVERIFY2(usersSuggestions.rowCount() > 0, "contains data");
// for (int i = 0; i < 2; i++) {
// qDebug() << data << slugs.get(i).value("name").toString();
// }
}
void UsersSuggestionsTest::lang_data()
{
QTest::addColumn<QString>("data");
QTest::newRow("English") << "en";
QTest::newRow("Spanish") << "es";
QTest::newRow("Japanese") << "ja";
}
QTEST_MAIN(UsersSuggestionsTest)
#include "tst_userssuggestions.moc"
| {
"content_hash": "42c59d42474901cd93f1772eb9b9b39d",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 70,
"avg_line_length": 21.355555555555554,
"alnum_prop": 0.6628511966701353,
"repo_name": "yuntan/twitter4qml",
"id": "e0742e2b983fa613d9fdd1e88c168971f1ae4217",
"size": "2535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/auto/cpp/users/tst_userssuggestions/tst_userssuggestions.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "702132"
},
{
"name": "IDL",
"bytes": "7598"
},
{
"name": "Ruby",
"bytes": "939"
}
],
"symlink_target": ""
} |
namespace Microsoft.Protocols.TestSuites.MS_OXORULE
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Protocols.TestSuites.Common;
/// <summary>
/// Address book EntryIDs can represent several types of Address Book objects including individual users, distribution lists, containers, and templates.
/// </summary>
public class AddressBookEntryID
{
/// <summary>
/// MUST be 0x00000000.
/// </summary>
public readonly uint Flags = 0x00000000;
/// <summary>
/// The ProviderUID value that MUST be %xDC.A7.40.C8.C0.42.10.1A.B4.B9.08.00.2B.2F.E1.82.
/// </summary>
public readonly byte[] ProviderUID = new byte[] { 0xDC, 0xA7, 0x40, 0xC8, 0xC0, 0x42, 0x10, 0x1A, 0xB4, 0xB9, 0x08, 0x00, 0x2B, 0x2F, 0xE1, 0x82 };
/// <summary>
/// MUST be set to %x01.00.00.00.
/// </summary>
public readonly uint Version = 0x00000001;
/// <summary>
/// A 32-bit integer representing the type of the object.
/// </summary>
private ObjectTypes type;
/// <summary>
/// The X500 DN of the Address Book object. X500DN is a null-terminated string of 8-bit characters.
/// </summary>
private string valueOfX500DN;
/// <summary>
/// Initializes a new instance of the AddressBookEntryID class.
/// </summary>
public AddressBookEntryID()
{
}
/// <summary>
/// Initializes a new instance of the AddressBookEntryID class.
/// </summary>
/// <param name="valueOfx500DN">The X500 DN of the Address Book object. This must not be a null-terminated string.</param>
public AddressBookEntryID(string valueOfx500DN)
{
this.Type = ObjectTypes.LocalMailUser;
this.valueOfX500DN = valueOfx500DN;
}
/// <summary>
/// Initializes a new instance of the AddressBookEntryID class.
/// </summary>
/// <param name="valueOfx500DN">The X500 DN of the Address Book object. This must not be a null-terminated string.</param>
/// <param name="types">Type of object.</param>
public AddressBookEntryID(string valueOfx500DN, ObjectTypes types)
{
this.Type = types;
this.valueOfX500DN = valueOfx500DN;
}
/// <summary>
/// A 32-bit integer representing the type of the object.
/// </summary>
public enum ObjectTypes : uint
{
/// <summary>
/// Local mail user type
/// </summary>
LocalMailUser = 0x0000,
/// <summary>
/// Distribution list type
/// </summary>
DistributionList = 0x0001,
/// <summary>
/// Bulletin board or public folder type
/// </summary>
BulletinBoardOrPublicFolder = 0x0002,
/// <summary>
/// Automated mailbox type
/// </summary>
AutomatedMailbox = 0x0003,
/// <summary>
/// Organizational mailbox type
/// </summary>
OrganizationalMailbox = 0x0004,
/// <summary>
/// Private distribution list type
/// </summary>
PrivateDistributionList = (ushort)PropertyId.PidTagAutoForwarded,
/// <summary>
/// Remote mail user type
/// </summary>
RemoteMailUser = 0x0006,
/// <summary>
/// Container type
/// </summary>
Container = 0x0100,
/// <summary>
/// Template type
/// </summary>
Template = 0x0101,
/// <summary>
/// One-off user type
/// </summary>
OneOffUser = 0x0102,
/// <summary>
/// Search type
/// </summary>
Search = 0x0200
}
/// <summary>
/// Gets or sets the X500 DN of the Address Book object. X500DN is a null-terminated string of 8-bit characters.
/// </summary>
public string ValueOfX500DN
{
get { return this.valueOfX500DN; }
set { this.valueOfX500DN = value; }
}
/// <summary>
/// Gets or sets a 32-bit integer representing the type of the object.
/// </summary>
public ObjectTypes Type
{
get { return this.type; }
set { this.type = value; }
}
/// <summary>
/// Get size of this class
/// </summary>
/// <returns>Size in byte of this class.</returns>
public int Size()
{
return this.Serialize().Length;
}
/// <summary>
/// Get serialized byte array for this struct
/// </summary>
/// <returns>Serialized byte array.</returns>
public byte[] Serialize()
{
List<byte> bytes = new List<byte>();
bytes.AddRange(BitConverter.GetBytes(this.Flags));
bytes.AddRange(this.ProviderUID);
bytes.AddRange(BitConverter.GetBytes(this.Version));
bytes.AddRange(BitConverter.GetBytes((uint)this.Type));
bytes.AddRange(Encoding.ASCII.GetBytes(this.valueOfX500DN + "\0"));
return bytes.ToArray();
}
/// <summary>
/// Deserialized byte array to an ActionBlock instance
/// </summary>
/// <param name="buffer">Byte array contain data of an ActionBlock instance.</param>
/// <returns>Bytes count that deserialized in buffer.</returns>
public uint Deserialize(byte[] buffer)
{
BufferReader reader = new BufferReader(buffer);
uint flags = reader.ReadUInt32();
if (this.Flags != flags)
{
throw new ParseException("Flags MUST be 0x00000000.");
}
byte[] providerUID = reader.ReadBytes(16);
if (!Common.CompareByteArray(this.ProviderUID, providerUID))
{
throw new ParseException("ProviderUID MUST be %xDC.A7.40.C8.C0.42.10.1A.B4.B9.08.00.2B.2F.E1.82.");
}
uint version = reader.ReadUInt32();
if (this.Version != version)
{
throw new ParseException("Version MUST be 0x00000001.");
}
this.Type = (ObjectTypes)reader.ReadUInt32();
this.valueOfX500DN = reader.ReadASCIIString();
return reader.Position;
}
}
} | {
"content_hash": "19e4456b1cf338c57f29e156e28c3cb1",
"timestamp": "",
"source": "github",
"line_count": 201,
"max_line_length": 156,
"avg_line_length": 34.124378109452735,
"alnum_prop": 0.5207756232686981,
"repo_name": "XinwLi/Interop-TestSuites-1",
"id": "43f15ca69125557f0ee584b6b0538419bc390f25",
"size": "6859",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ExchangeMAPI/Source/MS-OXORULE/Adapter/Helper/DataTypes/AddressBookEntryID.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1421"
},
{
"name": "Batchfile",
"bytes": "1149773"
},
{
"name": "C",
"bytes": "154398"
},
{
"name": "C#",
"bytes": "160448942"
},
{
"name": "C++",
"bytes": "26321"
},
{
"name": "PowerShell",
"bytes": "1499733"
}
],
"symlink_target": ""
} |
/* global chai */
'use strict';
import Selector from '../src/converter/Selector';
const expect = chai.expect;
describe('Selector', () => {
it('jest klasą', () => {
expect(Selector).to.be.a('function');
});
it('tworzy własności na podstawie parametrów', () => {
const selector = new Selector('bem', 'css');
expect(selector.BEM).to.equal('bem');
expect(selector.CSS).to.equal('css');
});
it('tworzy niezmienną instację', () => {
const selector = new Selector('bem', 'css');
expect(selector).to.be.fronzen;
});
}); | {
"content_hash": "e7dd1a3a31b1981da4f1f69a5e816004",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 58,
"avg_line_length": 25.565217391304348,
"alnum_prop": 0.5697278911564626,
"repo_name": "bmil/bse",
"id": "132affa15c91c78888c998fe2a46cc3fab738003",
"size": "594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Selector.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "145"
},
{
"name": "JavaScript",
"bytes": "13732"
}
],
"symlink_target": ""
} |
<?php
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/View/Pages/home.ctp)...
*/
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
/**
* Load all plugin routes. See the CakePlugin documentation on
* how to customize the loading of plugin routes.
*/
CakePlugin::routes();
/**
* Load the CakePHP default routes. Only remove this if you do not want to use
* the built-in default routes.
*/
require CAKE . 'Config' . DS . 'routes.php';
| {
"content_hash": "fafcefa0bd00d7f419766bc86dc68070",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 85,
"avg_line_length": 31.875,
"alnum_prop": 0.6509803921568628,
"repo_name": "nickpack/Methadone",
"id": "ff325f5af0fcb9c2801b1fe45037132ec4494eda",
"size": "1654",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "src/app/Config/routes.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6672"
},
{
"name": "PHP",
"bytes": "7652190"
},
{
"name": "Perl",
"bytes": "6460"
},
{
"name": "Puppet",
"bytes": "3905"
},
{
"name": "Ruby",
"bytes": "536"
},
{
"name": "Shell",
"bytes": "7626"
}
],
"symlink_target": ""
} |
var app = require('express')(),
wizard = require('hmpo-form-wizard'),
steps = require('./steps'),
fields = require('./fields');
app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' }));
app.use(wizard(steps, fields, { templatePath: 'priority_service_170705/startpage-overseas' }));
module.exports = app;
| {
"content_hash": "d2b1a4bd22fb82369713424ace0ea0d9",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 95,
"avg_line_length": 35,
"alnum_prop": 0.68,
"repo_name": "UKHomeOffice/passports-prototype",
"id": "068e2860eb7935a221ddf2eb7c939cd8f1107be2",
"size": "350",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "routes/priority_service_170705/startpage-overseas/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39324"
},
{
"name": "HTML",
"bytes": "6619551"
},
{
"name": "JavaScript",
"bytes": "1250249"
}
],
"symlink_target": ""
} |
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/effect.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/identify.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/magick.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/segment.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e B o u n d i n g B o x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageBoundingBox() returns the bounding box of an image canvas.
%
% The format of the GetImageBoundingBox method is:
%
% RectangleInfo GetImageBoundingBox(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o bounds: Method GetImageBoundingBox returns the bounding box of an
% image canvas.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport RectangleInfo GetImageBoundingBox(const Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
target[3],
zero;
RectangleInfo
bounds;
register const Quantum
*r;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
bounds.width=0;
bounds.height=0;
bounds.x=(ssize_t) image->columns;
bounds.y=(ssize_t) image->rows;
GetPixelInfo(image,&target[0]);
image_view=AcquireVirtualCacheView(image,exception);
r=GetCacheViewVirtualPixels(image_view,0,0,1,1,exception);
if (r == (const Quantum *) NULL)
{
image_view=DestroyCacheView(image_view);
return(bounds);
}
GetPixelInfoPixel(image,r,&target[0]);
GetPixelInfo(image,&target[1]);
r=GetCacheViewVirtualPixels(image_view,(ssize_t) image->columns-1,0,1,1,
exception);
if (r != (const Quantum *) NULL)
GetPixelInfoPixel(image,r,&target[1]);
GetPixelInfo(image,&target[2]);
r=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-1,1,1,
exception);
if (r != (const Quantum *) NULL)
GetPixelInfoPixel(image,r,&target[2]);
status=MagickTrue;
GetPixelInfo(image,&zero);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
RectangleInfo
bounding_box;
register const Quantum
*restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
# pragma omp critical (MagickCore_GetImageBoundingBox)
#endif
bounding_box=bounds;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,p,&pixel);
if ((x < bounding_box.x) &&
(IsFuzzyEquivalencePixelInfo(&pixel,&target[0]) == MagickFalse))
bounding_box.x=x;
if ((x > (ssize_t) bounding_box.width) &&
(IsFuzzyEquivalencePixelInfo(&pixel,&target[1]) == MagickFalse))
bounding_box.width=(size_t) x;
if ((y < bounding_box.y) &&
(IsFuzzyEquivalencePixelInfo(&pixel,&target[0]) == MagickFalse))
bounding_box.y=y;
if ((y > (ssize_t) bounding_box.height) &&
(IsFuzzyEquivalencePixelInfo(&pixel,&target[2]) == MagickFalse))
bounding_box.height=(size_t) y;
p+=GetPixelChannels(image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
# pragma omp critical (MagickCore_GetImageBoundingBox)
#endif
{
if (bounding_box.x < bounds.x)
bounds.x=bounding_box.x;
if (bounding_box.y < bounds.y)
bounds.y=bounding_box.y;
if (bounding_box.width > bounds.width)
bounds.width=bounding_box.width;
if (bounding_box.height > bounds.height)
bounds.height=bounding_box.height;
}
}
image_view=DestroyCacheView(image_view);
if ((bounds.width == 0) && (bounds.height == 0))
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
else
{
bounds.width-=(bounds.x-1);
bounds.height-=(bounds.y-1);
}
return(bounds);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDepth() returns the depth of a particular image channel.
%
% The format of the GetImageDepth method is:
%
% size_t GetImageDepth(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport size_t GetImageDepth(const Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
register ssize_t
i;
size_t
*current_depth,
depth,
number_threads;
ssize_t
y;
/*
Compute image depth.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
current_depth=(size_t *) AcquireQuantumMemory(number_threads,
sizeof(*current_depth));
if (current_depth == (size_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
status=MagickTrue;
for (i=0; i < (ssize_t) number_threads; i++)
current_depth[i]=1;
if ((image->storage_class == PseudoClass) &&
(image->alpha_trait == UndefinedPixelTrait))
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
if ((image->colors) > 256) \
num_threads(GetMagickResourceLimit(ThreadResource))
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
const int
id = GetOpenMPThreadId();
while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH)
{
MagickBooleanType
atDepth;
QuantumAny
range;
atDepth=MagickTrue;
range=GetQuantumRange(current_depth[id]);
if ((atDepth != MagickFalse) &&
(GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
if (IsPixelAtDepth(image->colormap[i].red,range) == MagickFalse)
atDepth=MagickFalse;
if ((atDepth != MagickFalse) &&
(GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
if (IsPixelAtDepth(image->colormap[i].green,range) == MagickFalse)
atDepth=MagickFalse;
if ((atDepth != MagickFalse) &&
(GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
if (IsPixelAtDepth(image->colormap[i].blue,range) == MagickFalse)
atDepth=MagickFalse;
if ((atDepth != MagickFalse))
break;
current_depth[id]++;
}
}
depth=current_depth[0];
for (i=1; i < (ssize_t) number_threads; i++)
if (depth < current_depth[i])
depth=current_depth[i];
current_depth=(size_t *) RelinquishMagickMemory(current_depth);
return(depth);
}
image_view=AcquireVirtualCacheView(image,exception);
#if !defined(MAGICKCORE_HDRI_SUPPORT)
if (QuantumRange <= MaxMap)
{
size_t
*depth_map;
/*
Scale pixels to desired (optimized with depth map).
*/
depth_map=(size_t *) AcquireQuantumMemory(MaxMap+1,sizeof(*depth_map));
if (depth_map == (size_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
for (i=0; i <= (ssize_t) MaxMap; i++)
{
unsigned int
depth;
for (depth=1; depth < MAGICKCORE_QUANTUM_DEPTH; depth++)
{
Quantum
pixel;
QuantumAny
range;
range=GetQuantumRange(depth);
pixel=(Quantum) i;
if (pixel == ScaleAnyToQuantum(ScaleQuantumToAny(pixel,range),range))
break;
}
depth_map[i]=depth;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register const Quantum
*restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
continue;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
(channel == IndexPixelChannel) ||
(channel == ReadMaskPixelChannel) ||
(channel == MetaPixelChannel))
continue;
if (depth_map[ScaleQuantumToMap(p[i])] > current_depth[id])
current_depth[id]=depth_map[ScaleQuantumToMap(p[i])];
}
p+=GetPixelChannels(image);
}
if (current_depth[id] == MAGICKCORE_QUANTUM_DEPTH)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
depth=current_depth[0];
for (i=1; i < (ssize_t) number_threads; i++)
if (depth < current_depth[i])
depth=current_depth[i];
depth_map=(size_t *) RelinquishMagickMemory(depth_map);
current_depth=(size_t *) RelinquishMagickMemory(current_depth);
return(depth);
}
#endif
/*
Compute pixel depth.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register const Quantum
*restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
continue;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel
channel;
PixelTrait
traits;
channel=GetPixelChannelChannel(image,i);
traits=GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) || (channel == IndexPixelChannel) ||
(channel == ReadMaskPixelChannel))
continue;
while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH)
{
QuantumAny
range;
range=GetQuantumRange(current_depth[id]);
if (p[i] == ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range),range))
break;
current_depth[id]++;
}
}
p+=GetPixelChannels(image);
}
if (current_depth[id] == MAGICKCORE_QUANTUM_DEPTH)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
depth=current_depth[0];
for (i=1; i < (ssize_t) number_threads; i++)
if (depth < current_depth[i])
depth=current_depth[i];
current_depth=(size_t *) RelinquishMagickMemory(current_depth);
return(depth);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e Q u a n t u m D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageQuantumDepth() returns the depth of the image rounded to a legal
% quantum depth: 8, 16, or 32.
%
% The format of the GetImageQuantumDepth method is:
%
% size_t GetImageQuantumDepth(const Image *image,
% const MagickBooleanType constrain)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o constrain: A value other than MagickFalse, constrains the depth to
% a maximum of MAGICKCORE_QUANTUM_DEPTH.
%
*/
MagickExport size_t GetImageQuantumDepth(const Image *image,
const MagickBooleanType constrain)
{
size_t
depth;
depth=image->depth;
if (depth <= 8)
depth=8;
else
if (depth <= 16)
depth=16;
else
if (depth <= 32)
depth=32;
else
if (depth <= 64)
depth=64;
if (constrain != MagickFalse)
depth=(size_t) MagickMin((double) depth,(double) MAGICKCORE_QUANTUM_DEPTH);
return(depth);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageType() returns the type of image:
%
% Bilevel Grayscale GrayscaleMatte
% Palette PaletteMatte TrueColor
% TrueColorMatte ColorSeparation ColorSeparationMatte
%
% The format of the GetImageType method is:
%
% ImageType GetImageType(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport ImageType GetImageType(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->colorspace == CMYKColorspace)
{
if (image->alpha_trait == UndefinedPixelTrait)
return(ColorSeparationType);
return(ColorSeparationAlphaType);
}
if (IsImageMonochrome(image) != MagickFalse)
return(BilevelType);
if (IsImageGray(image) != MagickFalse)
{
if (image->alpha_trait != UndefinedPixelTrait)
return(GrayscaleAlphaType);
return(GrayscaleType);
}
if (IsPaletteImage(image) != MagickFalse)
{
if (image->alpha_trait != UndefinedPixelTrait)
return(PaletteAlphaType);
return(PaletteType);
}
if (image->alpha_trait != UndefinedPixelTrait)
return(TrueColorAlphaType);
return(TrueColorType);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I d e n t i f y I m a g e G r a y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IdentifyImageGray() returns grayscale if all the pixels in the image have
% the same red, green, and blue intensities, and bi-level is the intensity is
% either 0 or QuantumRange. Otherwise undefined is returned.
%
% The format of the IdentifyImageGray method is:
%
% ImageType IdentifyImageGray(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ImageType IdentifyImageGray(const Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
ImageType
type;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->type == BilevelType) || (image->type == GrayscaleType) ||
(image->type == GrayscaleAlphaType))
return(image->type);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
return(UndefinedType);
type=BilevelType;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
{
type=UndefinedType;
break;
}
if ((type == BilevelType) &&
(IsPixelMonochrome(image,p) == MagickFalse))
type=GrayscaleType;
p+=GetPixelChannels(image);
}
if (type == UndefinedType)
break;
}
image_view=DestroyCacheView(image_view);
if ((type == GrayscaleType) && (image->alpha_trait != UndefinedPixelTrait))
type=GrayscaleAlphaType;
return(type);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I d e n t i f y I m a g e M o n o c h r o m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IdentifyImageMonochrome() returns MagickTrue if all the pixels in the image
% have the same red, green, and blue intensities and the intensity is either
% 0 or QuantumRange.
%
% The format of the IdentifyImageMonochrome method is:
%
% MagickBooleanType IdentifyImageMonochrome(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType IdentifyImageMonochrome(const Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
ImageType
type;
register ssize_t
x;
register const Quantum
*p;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->type == BilevelType)
return(MagickTrue);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
return(MagickFalse);
type=BilevelType;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelMonochrome(image,p) == MagickFalse)
{
type=UndefinedType;
break;
}
p+=GetPixelChannels(image);
}
if (type == UndefinedType)
break;
}
image_view=DestroyCacheView(image_view);
if (type == BilevelType)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I d e n t i f y I m a g e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IdentifyImageType() returns the potential type of image:
%
% Bilevel Grayscale GrayscaleMatte
% Palette PaletteMatte TrueColor
% TrueColorMatte ColorSeparation ColorSeparationMatte
%
% To ensure the image type matches its potential, use SetImageType():
%
% (void) SetImageType(image,IdentifyImageType(image,exception),exception);
%
% The format of the IdentifyImageType method is:
%
% ImageType IdentifyImageType(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ImageType IdentifyImageType(const Image *image,
ExceptionInfo *exception)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->colorspace == CMYKColorspace)
{
if (image->alpha_trait == UndefinedPixelTrait)
return(ColorSeparationType);
return(ColorSeparationAlphaType);
}
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
return(BilevelType);
if (IdentifyImageGray(image,exception) != UndefinedType)
{
if (image->alpha_trait != UndefinedPixelTrait)
return(GrayscaleAlphaType);
return(GrayscaleType);
}
if (IdentifyPaletteImage(image,exception) != MagickFalse)
{
if (image->alpha_trait != UndefinedPixelTrait)
return(PaletteAlphaType);
return(PaletteType);
}
if (image->alpha_trait != UndefinedPixelTrait)
return(TrueColorAlphaType);
return(TrueColorType);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e G r a y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImageGray() returns MagickTrue if the type of the image is grayscale or
% bi-level.
%
% The format of the IsImageGray method is:
%
% MagickBooleanType IsImageGray(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsImageGray(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if ((image->type == BilevelType) || (image->type == GrayscaleType) ||
(image->type == GrayscaleAlphaType))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e M o n o c h r o m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImageMonochrome() returns MagickTrue if type of the image is bi-level.
%
% The format of the IsImageMonochrome method is:
%
% MagickBooleanType IsImageMonochrome(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsImageMonochrome(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->type == BilevelType)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e O p a q u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImageOpaque() returns MagickTrue if none of the pixels in the image have
% an alpha value other than OpaqueAlpha (QuantumRange).
%
% Will return true immediatally is alpha channel is not available.
%
% The format of the IsImageOpaque method is:
%
% MagickBooleanType IsImageOpaque(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType IsImageOpaque(const Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Determine if image is opaque.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->alpha_trait == UndefinedPixelTrait)
return(MagickTrue);
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,p) != OpaqueAlpha)
break;
p+=GetPixelChannels(image);
}
if (x < (ssize_t) image->columns)
break;
}
image_view=DestroyCacheView(image_view);
return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageDepth() sets the depth of the image.
%
% The format of the SetImageDepth method is:
%
% MagickBooleanType SetImageDepth(Image *image,const size_t depth,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o depth: the image depth.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageDepth(Image *image,
const size_t depth,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
QuantumAny
range;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (depth >= MAGICKCORE_QUANTUM_DEPTH)
{
image->depth=depth;
return(MagickTrue);
}
range=GetQuantumRange(depth);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) ScaleAnyToQuantum(ScaleQuantumToAny(
ClampPixel(image->colormap[i].red),range),range);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) ScaleAnyToQuantum(ScaleQuantumToAny(
ClampPixel(image->colormap[i].green),range),range);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) ScaleAnyToQuantum(ScaleQuantumToAny(
ClampPixel(image->colormap[i].blue),range),range);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) ScaleAnyToQuantum(ScaleQuantumToAny(
ClampPixel(image->colormap[i].alpha),range),range);
}
}
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if !defined(MAGICKCORE_HDRI_SUPPORT)
if (QuantumRange <= MaxMap)
{
Quantum
*depth_map;
register ssize_t
i;
/*
Scale pixels to desired (optimized with depth map).
*/
depth_map=(Quantum *) AcquireQuantumMemory(MaxMap+1,sizeof(*depth_map));
if (depth_map == (Quantum *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
for (i=0; i <= (ssize_t) MaxMap; i++)
depth_map[i]=ScaleAnyToQuantum(ScaleQuantumToAny((Quantum) i,range),
range);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel
channel;
PixelTrait
traits;
channel=GetPixelChannelChannel(image,i);
traits=GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
(channel == IndexPixelChannel) ||
(channel == ReadMaskPixelChannel))
continue;
q[i]=depth_map[ScaleQuantumToMap(q[i])];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
{
status=MagickFalse;
continue;
}
}
image_view=DestroyCacheView(image_view);
depth_map=(Quantum *) RelinquishMagickMemory(depth_map);
if (status != MagickFalse)
image->depth=depth;
return(status);
}
#endif
/*
Scale pixels to desired depth.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel
channel;
PixelTrait
traits;
channel=GetPixelChannelChannel(image,i);
traits=GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) || (channel == IndexPixelChannel) ||
(channel == ReadMaskPixelChannel))
continue;
q[i]=ScaleAnyToQuantum(ScaleQuantumToAny(ClampPixel(q[i]),range),range);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
{
status=MagickFalse;
continue;
}
}
image_view=DestroyCacheView(image_view);
if (status != MagickFalse)
image->depth=depth;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageType() sets the type of image. Choose from these types:
%
% Bilevel Grayscale GrayscaleMatte
% Palette PaletteMatte TrueColor
% TrueColorMatte ColorSeparation ColorSeparationMatte
% OptimizeType
%
% The format of the SetImageType method is:
%
% MagickBooleanType SetImageType(Image *image,const ImageType type,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: Image type.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type,
ExceptionInfo *exception)
{
const char
*artifact;
ImageInfo
*image_info;
MagickBooleanType
status;
QuantizeInfo
*quantize_info;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
status=MagickTrue;
image_info=AcquireImageInfo();
image_info->dither=image->dither;
artifact=GetImageArtifact(image,"dither");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"dither",artifact);
switch (type)
{
case BilevelType:
{
if (SetImageMonochrome(image,exception) == MagickFalse)
{
status=TransformImageColorspace(image,GRAYColorspace,exception);
(void) NormalizeImage(image,exception);
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->number_colors=2;
quantize_info->colorspace=GRAYColorspace;
status=QuantizeImage(quantize_info,image,exception);
quantize_info=DestroyQuantizeInfo(quantize_info);
}
image->colors=2;
image->alpha_trait=UndefinedPixelTrait;
break;
}
case GrayscaleType:
{
if (SetImageGray(image,exception) == MagickFalse)
status=TransformImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=UndefinedPixelTrait;
break;
}
case GrayscaleAlphaType:
{
if (SetImageGray(image,exception) == MagickFalse)
status=TransformImageColorspace(image,GRAYColorspace,exception);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
break;
}
case PaletteType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace,exception);
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->number_colors=256;
status=QuantizeImage(quantize_info,image,exception);
quantize_info=DestroyQuantizeInfo(quantize_info);
}
image->alpha_trait=UndefinedPixelTrait;
break;
}
case PaletteBilevelAlphaType:
{
ChannelType
channel_mask;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace,exception);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
channel_mask=SetImageChannelMask(image,AlphaChannel);
(void) BilevelImage(image,(double) QuantumRange/2.0,exception);
(void) SetImageChannelMask(image,channel_mask);
quantize_info=AcquireQuantizeInfo(image_info);
status=QuantizeImage(quantize_info,image,exception);
quantize_info=DestroyQuantizeInfo(quantize_info);
break;
}
case PaletteAlphaType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace,exception);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
quantize_info=AcquireQuantizeInfo(image_info);
quantize_info->colorspace=TransparentColorspace;
status=QuantizeImage(quantize_info,image,exception);
quantize_info=DestroyQuantizeInfo(quantize_info);
break;
}
case TrueColorType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace,exception);
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass,exception);
image->alpha_trait=UndefinedPixelTrait;
break;
}
case TrueColorAlphaType:
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace,exception);
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass,exception);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
break;
}
case ColorSeparationType:
{
if (image->colorspace != CMYKColorspace)
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace,exception);
status=TransformImageColorspace(image,CMYKColorspace,exception);
}
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass,exception);
image->alpha_trait=UndefinedPixelTrait;
break;
}
case ColorSeparationAlphaType:
{
if (image->colorspace != CMYKColorspace)
{
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
status=TransformImageColorspace(image,sRGBColorspace,exception);
status=TransformImageColorspace(image,CMYKColorspace,exception);
}
if (image->storage_class != DirectClass)
status=SetImageStorageClass(image,DirectClass,exception);
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
break;
}
case OptimizeType:
case UndefinedType:
break;
}
image_info=DestroyImageInfo(image_info);
if (status == MagickFalse)
return(status);
image->type=type;
return(MagickTrue);
}
| {
"content_hash": "62f58879132b48bc6acad3f518dc6c68",
"timestamp": "",
"source": "github",
"line_count": 1360,
"max_line_length": 80,
"avg_line_length": 32.775,
"alnum_prop": 0.5266747431237941,
"repo_name": "kwm81/ImageMagick",
"id": "e8430d1494e362a1b5d469aa1680801eb14f2047",
"size": "47225",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "MagickCore/attribute.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "16933529"
},
{
"name": "C++",
"bytes": "787684"
},
{
"name": "CSS",
"bytes": "31314"
},
{
"name": "DIGITAL Command Language",
"bytes": "17790"
},
{
"name": "Groff",
"bytes": "125941"
},
{
"name": "HTML",
"bytes": "3446719"
},
{
"name": "Makefile",
"bytes": "912"
},
{
"name": "PHP",
"bytes": "1134169"
},
{
"name": "Perl",
"bytes": "216198"
},
{
"name": "Shell",
"bytes": "400855"
},
{
"name": "Tcl",
"bytes": "20736"
},
{
"name": "XS",
"bytes": "481439"
}
],
"symlink_target": ""
} |
package jwt
import "time"
// Mapper is the interface used internally to map key-value pairs
type Mapper interface {
ToMap() map[string]interface{}
Add(key string, value interface{})
Get(key string) interface{}
}
// ToString will return a string representation of a map
func ToString(i interface{}) string {
if i == nil {
return ""
}
if s, ok := i.(string); ok {
return s
}
if sl, ok := i.([]string); ok {
if len(sl) == 1 {
return sl[0]
}
}
return ""
}
// ToTime will try to convert a given input to a time.Time structure
func ToTime(i interface{}) time.Time {
if i == nil {
return time.Time{}
}
if t, ok := i.(int64); ok {
return time.Unix(t, 0)
} else if t, ok := i.(float64); ok {
return time.Unix(int64(t), 0)
}
return time.Time{}
}
// Filter will filter out elemets based on keys in a given input map na key-slice
func Filter(elements map[string]interface{}, keys ...string) map[string]interface{} {
var keyIdx = make(map[string]bool)
var result = make(map[string]interface{})
for _, key := range keys {
keyIdx[key] = true
}
for k, e := range elements {
if _, ok := keyIdx[k]; !ok {
result[k] = e
}
}
return result
}
// Copy will copy all elements in a map and return a new representational map
func Copy(elements map[string]interface{}) (result map[string]interface{}) {
result = make(map[string]interface{}, len(elements))
for k, v := range elements {
result[k] = v
}
return result
}
| {
"content_hash": "a660c0b6a4b925b2e8d705078ad65617",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 85,
"avg_line_length": 20.27777777777778,
"alnum_prop": 0.6493150684931507,
"repo_name": "janekolszak/fosite",
"id": "6e0513f19cda15127ea3034b0b6d22f78efbbfd3",
"size": "1460",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "token/jwt/claims.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "397796"
},
{
"name": "Shell",
"bytes": "3438"
}
],
"symlink_target": ""
} |
namespace System.Web.UI.WebControls {
using System.ComponentModel;
using System.Security.Permissions;
[
ToolboxItem(false),
SupportsEventValidation,
]
/// <devdoc>
/// <para>Constructs a table used for pager rows for DetailsView, GridView, and FormView</para>
/// </devdoc>
internal sealed class PagerTable : Table {
}
} | {
"content_hash": "24241c3d48a1a5f21bf93ace4bf5dfb4",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 102,
"avg_line_length": 24.6,
"alnum_prop": 0.6612466124661247,
"repo_name": "mono/referencesource",
"id": "f55e26d655b39e41ea94b96ce050f7aea7766ffc",
"size": "670",
"binary": false,
"copies": "7",
"ref": "refs/heads/mono",
"path": "System.Web/UI/WebControls/PagerTable.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "155045910"
}
],
"symlink_target": ""
} |
package org.hoteia.qalingo.core.dao;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.hoteia.qalingo.core.domain.CatalogCategoryMaster;
import org.hoteia.qalingo.core.domain.CatalogCategoryVirtual;
import org.hoteia.qalingo.core.fetchplan.FetchPlan;
import org.hoteia.qalingo.core.fetchplan.catalog.FetchPlanGraphCategory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
@Repository("catalogCategoryDao")
public class CatalogCategoryDao extends AbstractGenericDao {
private final Logger logger = LoggerFactory.getLogger(getClass());
// MASTER
public CatalogCategoryMaster getMasterCatalogCategoryById(final Long catalogCategoryId, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryMaster.class);
FetchPlan fetchPlan = handleSpecificFetchMasterCategoryMode(criteria, params);
criteria.add(Restrictions.eq("id", catalogCategoryId));
CatalogCategoryMaster catalogCategory = (CatalogCategoryMaster) criteria.uniqueResult();
if(catalogCategory != null){
catalogCategory.setFetchPlan(fetchPlan);
}
return catalogCategory;
}
public CatalogCategoryMaster getMasterCatalogCategoryByCode(final String catalogCategoryCode, final String catalogMasterCode, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryMaster.class);
FetchPlan fetchPlan = handleSpecificFetchMasterCategoryMode(criteria, params);
criteria.add(Restrictions.eq("code", handleCodeValue(catalogCategoryCode)));
criteria.createAlias("catalog", "catalog", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalog.code", handleCodeValue(catalogMasterCode)));
CatalogCategoryMaster catalogCategory = (CatalogCategoryMaster) criteria.uniqueResult();
if(catalogCategory != null){
catalogCategory.setFetchPlan(fetchPlan);
}
return catalogCategory;
}
public List<CatalogCategoryMaster> findRootMasterCatalogCategoriesByCatalogCode(final String catalogMasterCode, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryMaster.class);
handleSpecificFetchMasterCategoryMode(criteria, params);
criteria.createAlias("catalog", "catalog", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalog.code", handleCodeValue(catalogMasterCode)));
criteria.add(Restrictions.isNull("parentCatalogCategory"));
criteria.addOrder(Order.asc("id"));
@SuppressWarnings("unchecked")
List<CatalogCategoryMaster> categories = criteria.list();
return categories;
}
public List<CatalogCategoryMaster> findAllMasterCatalogCategoriesByCatalogCode(final String catalogMasterCode, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryMaster.class);
handleSpecificFetchMasterCategoryMode(criteria, params);
criteria.createAlias("catalog", "catalog", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalog.code", handleCodeValue(catalogMasterCode)));
criteria.addOrder(Order.asc("id"));
@SuppressWarnings("unchecked")
List<CatalogCategoryMaster> categories = criteria.list();
return categories;
}
public List<CatalogCategoryMaster> findMasterCategoriesByProductSkuId(final Long productSkuId, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryMaster.class);
handleSpecificFetchVirtualCategoryMode(criteria, params);
criteria.createAlias("catalogCategoryProductSkuRels", "catalogCategoryProductSkuRel", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalogCategoryProductSkuRel.pk.productSku.id", productSkuId));
criteria.addOrder(Order.asc("id"));
@SuppressWarnings("unchecked")
List<CatalogCategoryMaster> categories = criteria.list();
return categories;
}
public CatalogCategoryMaster saveOrUpdateCatalogCategory(final CatalogCategoryMaster catalogCategory) {
// TODO : Denis : child object dates ?
if(catalogCategory.getDateCreate() == null){
catalogCategory.setDateCreate(new Date());
}
catalogCategory.setDateUpdate(new Date());
if (catalogCategory.getId() != null) {
if(em.contains(catalogCategory)){
em.refresh(catalogCategory);
}
CatalogCategoryMaster mergedCatalogCategoryMaster = em.merge(catalogCategory);
em.flush();
return mergedCatalogCategoryMaster;
} else {
em.persist(catalogCategory);
return catalogCategory;
}
}
public void deleteCatalogCategory(final CatalogCategoryMaster catalogCategory) {
em.remove(catalogCategory);
}
protected FetchPlan handleSpecificFetchMasterCategoryMode(Criteria criteria, Object... params) {
if (params != null && params.length > 0) {
return super.handleSpecificFetchMode(criteria, params);
} else {
return super.handleSpecificFetchMode(criteria, FetchPlanGraphCategory.defaultMasterCatalogCategoryFetchPlan());
}
}
// VIRTUAL
public CatalogCategoryVirtual getVirtualCatalogCategoryById(final Long catalogCategoryId, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
FetchPlan fetchPlan = handleSpecificFetchVirtualCategoryMode(criteria, params);
criteria.add(Restrictions.eq("id", catalogCategoryId));
CatalogCategoryVirtual catalogCategory = (CatalogCategoryVirtual) criteria.uniqueResult();
if(catalogCategory != null){
catalogCategory.setFetchPlan(fetchPlan);
}
return catalogCategory;
}
public CatalogCategoryVirtual getVirtualCatalogCategoryByVirtualCategoryCode(final String catalogCategoryCode, final String catalogVirtualCode, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
FetchPlan fetchPlan = handleSpecificFetchVirtualCategoryMode(criteria, params);
criteria.createAlias("catalog", "catalog", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalog.code", handleCodeValue(catalogVirtualCode)));
criteria.add(Restrictions.eq("code", handleCodeValue(catalogCategoryCode)));
CatalogCategoryVirtual catalogCategory = (CatalogCategoryVirtual) criteria.uniqueResult();
if(catalogCategory != null){
catalogCategory.setFetchPlan(fetchPlan);
}
return catalogCategory;
}
public CatalogCategoryVirtual getVirtualCatalogCategoryByMasterCategoryCode(final String catalogCategoryCode, final String catalogVirtualCode, final String catalogMasterCode, Object... params) {
try {
Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
FetchPlan fetchPlan = handleSpecificFetchVirtualCategoryMode(criteria, params);
criteria.createAlias("catalog", "catalog", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalog.code", handleCodeValue(catalogVirtualCode)));
criteria.createAlias("categoryMaster", "categoryMaster", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("categoryMaster.code", handleCodeValue(catalogCategoryCode)));
criteria.createAlias("categoryMaster.catalog", "catalogMaster", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalogMaster.code", handleCodeValue(catalogMasterCode)));
CatalogCategoryVirtual catalogCategory = (CatalogCategoryVirtual) criteria.uniqueResult();
if(catalogCategory != null){
catalogCategory.setFetchPlan(fetchPlan);
}
return catalogCategory;
} catch (Exception e) {
logger.error("Can't load VirtualCategory by MasterCode, catalogCategoryCode: '" + catalogCategoryCode + "', catalogVirtualCode: '" + catalogVirtualCode + "', catalogMasterCode: '" + catalogMasterCode, e);
}
return null;
}
public List<CatalogCategoryVirtual> findRootVirtualCatalogCategoriesByCatalogCode(final String catalogVirtualCode, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
handleSpecificFetchVirtualCategoryMode(criteria, params);
criteria.createAlias("catalog", "catalog", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalog.code", handleCodeValue(catalogVirtualCode)));
criteria.add(Restrictions.isNull("parentCatalogCategory"));
criteria.addOrder(Order.asc("id"));
@SuppressWarnings("unchecked")
List<CatalogCategoryVirtual> categories = criteria.list();
return categories;
}
public List<CatalogCategoryVirtual> findAllVirtualCatalogCategoriesByCatalogCode(final String catalogVirtualCode, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
handleSpecificFetchVirtualCategoryMode(criteria, params);
criteria.createAlias("catalog", "catalog", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalog.code", handleCodeValue(catalogVirtualCode)));
criteria.addOrder(Order.asc("id"));
@SuppressWarnings("unchecked")
List<CatalogCategoryVirtual> categories = criteria.list();
return categories;
}
// public List<CatalogCategoryVirtual> findVirtualCategories(Object... params) {
// Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
//
// handleSpecificFetchVirtualCategoryMode(criteria, params);
//
// criteria.addOrder(Order.asc("id"));
//
// @SuppressWarnings("unchecked")
// List<CatalogCategoryVirtual> categories = criteria.list();
// return categories;
// }
public List<CatalogCategoryVirtual> findVirtualCategoriesByProductSkuId(final Long productSkuId, Object... params) {
Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
handleSpecificFetchVirtualCategoryMode(criteria, params);
criteria.createAlias("catalogCategoryProductSkuRels", "catalogCategoryProductSkuRel", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("catalogCategoryProductSkuRel.pk.productSku.id", productSkuId));
criteria.addOrder(Order.asc("id"));
@SuppressWarnings("unchecked")
List<CatalogCategoryVirtual> categories = criteria.list();
return categories;
}
// public List<CatalogCategoryVirtual> findVirtualCategoriesByProductMarketingId(final Long productMarketingId, Object... params) {
// Criteria criteria = createDefaultCriteria(CatalogCategoryVirtual.class);
//
// handleSpecificFetchVirtualCategoryMode(criteria, params);
//
// criteria.createAlias("catalogCategoryProductSkuRels", "catalogCategoryProductSkuRel", JoinType.LEFT_OUTER_JOIN);
// criteria.createAlias("productSku", "catalogCategoryProductSkuRel.pk.productSku", JoinType.LEFT_OUTER_JOIN);
// criteria.add(Restrictions.eq("productSku.productMarketing.id", productMarketingId));
//
// criteria.addOrder(Order.asc("id"));
//
// @SuppressWarnings("unchecked")
// List<CatalogCategoryVirtual> categories = criteria.list();
// return categories;
// }
public CatalogCategoryVirtual saveOrUpdateCatalogCategory(final CatalogCategoryVirtual catalogCategory) {
if(catalogCategory.getDateCreate() == null){
catalogCategory.setDateCreate(new Date());
}
catalogCategory.setDateUpdate(new Date());
if (catalogCategory.getId() != null) {
if(em.contains(catalogCategory)){
em.refresh(catalogCategory);
}
CatalogCategoryVirtual mergedCatalogCategoryVirtual = em.merge(catalogCategory);
em.flush();
return mergedCatalogCategoryVirtual;
} else {
em.persist(catalogCategory);
return catalogCategory;
}
}
public void deleteCatalogCategory(final CatalogCategoryVirtual catalogCategory) {
em.remove(catalogCategory);
}
protected FetchPlan handleSpecificFetchVirtualCategoryMode(Criteria criteria, Object... params){
if (params != null && params.length > 0) {
return super.handleSpecificFetchMode(criteria, params);
} else {
return super.handleSpecificFetchMode(criteria, FetchPlanGraphCategory.defaultVirtualCatalogCategoryFetchPlan());
}
}
} | {
"content_hash": "dc779311e8eab5d50180c4b71c210bc3",
"timestamp": "",
"source": "github",
"line_count": 295,
"max_line_length": 216,
"avg_line_length": 44.722033898305085,
"alnum_prop": 0.7032517243993026,
"repo_name": "cloudbearings/qalingo-engine",
"id": "75c34655554eb108384c4948cae64c49643c081b",
"size": "13537",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/dao/CatalogCategoryDao.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4385431"
}
],
"symlink_target": ""
} |
using BizHawk.Emulation.Common;
namespace BizHawk.Emulation.Cores.Atari.A7800Hawk
{
public partial class A7800Hawk : IInputPollable
{
public int LagCount
{
get { return _lagcount; }
set { _lagcount = value; }
}
public bool IsLagFrame
{
get { return _islag; }
set { _islag = value; }
}
public IInputCallbackSystem InputCallbacks { get; } = new InputCallbackSystem();
public bool _islag = true;
private int _lagcount;
}
}
| {
"content_hash": "e0e2c57b477fbe391309e20098852224",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 82,
"avg_line_length": 19.083333333333332,
"alnum_prop": 0.6790393013100436,
"repo_name": "ircluzar/RTC3",
"id": "7271981aec497d05e0d72973d6cefdec45186664",
"size": "460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IInputPollable.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "77250"
},
{
"name": "Batchfile",
"bytes": "11077"
},
{
"name": "C",
"bytes": "10464062"
},
{
"name": "C#",
"bytes": "14062504"
},
{
"name": "C++",
"bytes": "15252473"
},
{
"name": "CSS",
"bytes": "74"
},
{
"name": "GLSL",
"bytes": "6610"
},
{
"name": "HTML",
"bytes": "426873"
},
{
"name": "Limbo",
"bytes": "15313"
},
{
"name": "Lua",
"bytes": "312676"
},
{
"name": "Makefile",
"bytes": "127427"
},
{
"name": "Objective-C",
"bytes": "40789"
},
{
"name": "PHP",
"bytes": "863004"
},
{
"name": "POV-Ray SDL",
"bytes": "206"
},
{
"name": "Python",
"bytes": "27842"
},
{
"name": "Shell",
"bytes": "19693"
},
{
"name": "Smalltalk",
"bytes": "1719"
}
],
"symlink_target": ""
} |
package lejos.internal.ev3;
import lejos.hardware.LED;
import lejos.internal.io.NativeDevice;
public class EV3LED implements LED {
private static NativeDevice dev = new NativeDevice("/dev/lms_ui");
public static int COLOR_NONE = 0;
public static int COLOR_GREEN = 1;
public static int COLOR_RED = 2;
public static int COLOR_ORANGE = 3;
public static int PATTERN_ON = 0;
public static int PATTERN_BLINK = 1;
public static int PATTERN_HEARTBEAT = 2;
@Override
public void setPattern(int pattern) {
byte [] cmd = new byte[2];
cmd[0] = (byte)('0' + pattern);
dev.write(cmd, cmd.length);
}
public void setPattern(int color, int pattern) {
if (color == 0 ) {
setPattern(0);
}
else {
setPattern(pattern * 3 + color);
}
}
}
| {
"content_hash": "5eb053384f88d099f5fafc97d1820de2",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 67,
"avg_line_length": 23.636363636363637,
"alnum_prop": 0.6653846153846154,
"repo_name": "antoniardot/DockBot-Eve",
"id": "867fde13b011ee0b4741e5ac21eaa49c80bcc468",
"size": "780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/lejos/internal/ev3/EV3LED.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2139498"
}
],
"symlink_target": ""
} |
@implementation TweetingViewController
@synthesize tweetLabel, attachedImage;
#pragma mark - View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidUnload {
[self setTweetLabel:nil];
[super viewDidUnload];
}
- (IBAction)tweet:(id)sender {
if ([TWTweetComposeViewController canSendTweet]) {
TWTweetComposeViewController *tweetComposerViewController = [[TWTweetComposeViewController alloc] init];
[tweetComposerViewController setInitialText:self.tweetLabel.text];
if (self.attachedImage) {
[tweetComposerViewController addImage:self.attachedImage];
}
[self presentModalViewController:tweetComposerViewController animated:YES];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"PickImage"]) {
ImagePickerViewController *imagePickerVC = (ImagePickerViewController *)segue.destinationViewController;
imagePickerVC.delegate = self;
}
}
- (void)dismissThisController:(UIViewController *)controller {
[self.view setHidden:NO];
[UIView animateWithDuration:0.5
animations:^{
[controller.view setAlpha:0.0];
}
completion:^(BOOL finished) {
[controller willMoveToParentViewController:nil];
[controller removeFromParentViewController];
[controller.view removeFromSuperview];
}];
}
- (void)imagePickerController:(ImagePickerViewController *)controller didSelectImage:(UIImage *)image {
[self dismissThisController:controller];
self.attachedImage = image;
}
@end
| {
"content_hash": "90a0ffe8b23ab012e0d706c501faca14",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 112,
"avg_line_length": 32.71666666666667,
"alnum_prop": 0.6622516556291391,
"repo_name": "3kunci/IdocTwit",
"id": "ef17e26ff0701c7357915305aefd2ba794a293d3",
"size": "2206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IdocTwit/TweetingViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "27936"
}
],
"symlink_target": ""
} |
/**
* A package for meal analysis algorithms.
*/
/**
* @author master
*
*/
package com.visionarysoftwaresolutions.smacker.api.nutrition.analysis; | {
"content_hash": "ef8e2b641b8cf5b82af6f70aea7c59bd",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 70,
"avg_line_length": 18.75,
"alnum_prop": 0.72,
"repo_name": "Byter/smacker",
"id": "125ca6d827a177b8e002aee7c5fd1df7cbdbdd5f",
"size": "150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/visionarysoftwaresolutions/smacker/api/nutrition/analysis/package-info.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "80453"
},
{
"name": "Java",
"bytes": "14791"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Shell;
using System.Diagnostics;
using EnvDTE;
using VisualLocalizer.Editor;
using Microsoft.VisualStudio.Shell.Interop;
using System.IO;
using System.Text.RegularExpressions;
using VisualLocalizer.Gui;
using EnvDTE80;
using Microsoft.VisualStudio.OLE.Interop;
using VisualLocalizer.Components;
using VisualLocalizer.Library;
using Microsoft.VisualStudio;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using VisualLocalizer.Components.Code;
using VisualLocalizer.Library.Extensions;
using VisualLocalizer.Library.Components;
using VisualLocalizer.Components.UndoUnits;
namespace VisualLocalizer.Commands.Move {
/// <summary>
/// Ancestor of C#, VB and ASP .NET "move to resources" commands. It provides functionality from the moment where
/// the string literal has already been located.
/// </summary>
/// <typeparam name="T">Type of result items this class handles.</typeparam>
internal abstract class MoveToResourcesCommand<T> : AbstractCommand where T:CodeStringResultItem, new() {
/// <summary>
/// Gets result item from current selection. Returns null in any case of errors and exceptions.
/// </summary>
protected abstract T GetReplaceStringItem();
/// <summary>
/// Called on click - when overriden, finds object in current selection and displayes dialog offering to move it.
/// </summary>
public override void Process() {
base.Process(); // initialize basic variables
T resultItem = GetReplaceStringItem(); // get result item (language specific)
if (resultItem != null) { // result item found and ok - proceed
TextSpan replaceSpan = resultItem.ReplaceSpan;
string referencedCodeText = resultItem.Value;
resultItem.SourceItem = currentDocument.ProjectItem; // set origin project item of the result item
// display dialog enabling user to modify resource key, select destination resource file etc.
// also enables user to resolve conflicts (duplicate key entries)
SelectResourceFileForm f = new SelectResourceFileForm(currentDocument.ProjectItem, resultItem);
System.Windows.Forms.DialogResult result = f.ShowDialog();
resultItem.DestinationItem = f.SelectedItem; // set destination project item - ResX file
if (result == System.Windows.Forms.DialogResult.OK) {
bool removeConst = false;
if (resultItem.IsConst) {
var deleteConst = VisualLocalizer.Library.Components.MessageBox.Show("This field is marked as 'const'. In order to continue with this operation, this modifier must be removed. Continue?", "Const", OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_WARNING);
if (deleteConst == DialogResult.Yes) {
removeConst = true;
} else {
return;
}
}
bool unitsFromStackRemoved = false;
bool unitMovedToResource = false;
ReferenceString referenceText;
bool addUsing = false;
// Now we must resolve the namespaces issue. If user selected the "use full name" in previous dialog,
// there's no trouble. Otherwise we must find out, if necessary namespace has already been included (using)
// and if not, create new using block with the namespace name.
try {
resultItem.DestinationItem = f.SelectedItem;
if (resultItem.DestinationItem == null) throw new InvalidOperationException("Destination item must be selected.");
if (resultItem.DestinationItem.InternalProjectItem == null) throw new InvalidOperationException("Destination item must be selected.");
if (!File.Exists(resultItem.DestinationItem.InternalProjectItem.GetFullPath())) throw new InvalidOperationException("Destination item file does not exist.");
if (f.UsingFullName || resultItem.MustUseFullName || (resultItem.Language==LANGUAGE.VB && resultItem.DestinationItem.IsProjectDefault(resultItem.SourceItem.ContainingProject))) {
referenceText = new ReferenceString(f.SelectedItem.Namespace, f.SelectedItem.Class, f.Key);
addUsing = false;
} else {
NamespacesList usedNamespaces = resultItem.GetUsedNamespaces();
addUsing = usedNamespaces.ResolveNewElement(f.SelectedItem.Namespace, f.SelectedItem.Class, f.Key,
currentDocument.ProjectItem.ContainingProject, out referenceText);
}
string newText = resultItem.GetReferenceText(referenceText);
// perform actual replace
int hr = textLines.ReplaceLines(replaceSpan.iStartLine, replaceSpan.iStartIndex, replaceSpan.iEndLine, replaceSpan.iEndIndex,
Marshal.StringToBSTR(newText), newText.Length, new TextSpan[] { replaceSpan });
Marshal.ThrowExceptionForHR(hr);
// set selection to the new text
hr = textView.SetSelection(replaceSpan.iStartLine, replaceSpan.iStartIndex,
replaceSpan.iStartLine, replaceSpan.iStartIndex + newText.Length);
Marshal.ThrowExceptionForHR(hr);
if (removeConst) {
CodeVariable2 codeVar = (CodeVariable2)resultItem.CodeModelSource;
codeVar.ConstKind = vsCMConstKind.vsCMConstKindNone;
}
if (addUsing) {
resultItem.AddUsingBlock(textLines);
}
if (f.Result == SELECT_RESOURCE_FILE_RESULT.INLINE) {
// conflict -> user chooses to reference existing key
unitsFromStackRemoved = CreateMoveToResourcesReferenceUndoUnit(f.Key, addUsing, removeConst);
} else if (f.Result == SELECT_RESOURCE_FILE_RESULT.OVERWRITE) {
// conflict -> user chooses to overwrite existing key and reference the new one
f.SelectedItem.AddString(f.Key, f.Value);
unitMovedToResource = true;
unitsFromStackRemoved = CreateMoveToResourcesOverwriteUndoUnit(f.Key, f.Value, f.OverwrittenValue, f.SelectedItem, addUsing, removeConst);
} else {
// no conflict occured
f.SelectedItem.AddString(f.Key, f.Value);
unitMovedToResource = true;
unitsFromStackRemoved = CreateMoveToResourcesUndoUnit(f.Key, f.Value, f.SelectedItem, addUsing, removeConst);
}
} catch (Exception) {
// exception occured - rollback all already performed actions in order to restore original state
VLOutputWindow.VisualLocalizerPane.WriteLine("Exception caught, rolling back...");
if (!unitsFromStackRemoved) {
int unitsToRemoveCount = (addUsing && removeConst) ? 3 : (addUsing || removeConst ? 2 : 1);
List<IOleUndoUnit> units = undoManager.RemoveTopFromUndoStack(unitsToRemoveCount);
foreach (var unit in units) {
unit.Do(undoManager);
}
undoManager.RemoveTopFromUndoStack(units.Count);
if (unitMovedToResource) {
f.SelectedItem.RemoveKey(f.Key);
}
} else {
AbstractUndoUnit unit = (AbstractUndoUnit)undoManager.RemoveTopFromUndoStack(1)[0];
int unitsToRemove = unit.AppendUnits.Count + 1;
unit.Do(undoManager);
undoManager.RemoveTopFromUndoStack(unitsToRemove);
}
throw;
}
}
} else throw new Exception("This part of code cannot be referenced");
}
/// <summary>
/// Adds a new undo unit to the undo stack, representing the "move to resources" action.
/// Text replacement and adding new using block is already in the undo stack -
/// these items are removed and merged into one atomic action.
/// </summary>
/// <param name="key">Resource file key</param>
/// <param name="value">Resource value</param>
/// <param name="resXProjectItem">Destination ResX project item</param>
/// <param name="addNamespace">Whether new using block has been added</param>
/// <returns>True, if original undo units has been successfully removed from the undo stack</returns>
private bool CreateMoveToResourcesUndoUnit(string key,string value, ResXProjectItem resXProjectItem,bool addNamespace, bool removeConst) {
bool unitsRemoved = false;
int unitsToRemoveCount = (addNamespace && removeConst) ? 3 : (addNamespace || removeConst ? 2 : 1);
List<IOleUndoUnit> units = undoManager.RemoveTopFromUndoStack(unitsToRemoveCount);
unitsRemoved = true;
MoveToResourcesUndoUnit newUnit = new MoveToResourcesUndoUnit(key, value, resXProjectItem);
newUnit.AppendUnits.AddRange(units);
undoManager.Add(newUnit);
return unitsRemoved;
}
/// <summary>
/// Adds a new undo unit to the undo stack, representing the "overwrite" action.
/// </summary>
/// <param name="key">Resource file key</param>
/// <param name="newValue">New (overwriting) resource value</param>
/// <param name="oldValue">Old (overwritten) resource value</param>
/// <param name="resXProjectItem">Destination ResX project item</param>
/// <param name="addNamespace">Whether new using block has been added</param>
/// <returns>True, if original undo units has been successfully removed from the undo stack</returns>
private bool CreateMoveToResourcesOverwriteUndoUnit(string key, string newValue, string oldValue, ResXProjectItem resXProjectItem, bool addNamespace, bool removeConst) {
bool unitsRemoved = false;
int unitsToRemoveCount = (addNamespace && removeConst) ? 3 : (addNamespace || removeConst ? 2 : 1);
List<IOleUndoUnit> units = undoManager.RemoveTopFromUndoStack(unitsToRemoveCount);
unitsRemoved = true;
MoveToResourcesOverwriteUndoUnit newUnit = new MoveToResourcesOverwriteUndoUnit(key, oldValue, newValue, resXProjectItem);
newUnit.AppendUnits.AddRange(units);
undoManager.Add(newUnit);
return unitsRemoved;
}
/// <summary>
/// Adds a new undo unit to the undo stack, representing the "inline" action.
/// </summary>
/// <param name="key">Key that it being referenced</param>
/// <param name="addNamespace">Whether new using block has been added</param>
/// <returns>True, if original undo units has been successfully removed from the undo stack</returns>
private bool CreateMoveToResourcesReferenceUndoUnit(string key, bool addNamespace, bool removeConst) {
bool unitsRemoved = false;
int unitsToRemoveCount = (addNamespace && removeConst) ? 3 : (addNamespace || removeConst ? 2 : 1);
List<IOleUndoUnit> units = undoManager.RemoveTopFromUndoStack(unitsToRemoveCount);
unitsRemoved = true;
MoveToResourcesReferenceUndoUnit newUnit = new MoveToResourcesReferenceUndoUnit(key);
newUnit.AppendUnits.AddRange(units);
undoManager.Add(newUnit);
return unitsRemoved;
}
}
}
| {
"content_hash": "9b77089dc9e7ccb409f843267f89efb4",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 324,
"avg_line_length": 58.82222222222222,
"alnum_prop": 0.5845107669059313,
"repo_name": "ostumpf/visuallocalizer",
"id": "eaf0ea2800f3ec7ef20f27ad4b571e080eef631e",
"size": "13237",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VisualLocalizer/VisualLocalizer/Commands/Move/MoveToResourcesCommand.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "8375"
},
{
"name": "C#",
"bytes": "1682006"
},
{
"name": "Visual Basic",
"bytes": "46162"
}
],
"symlink_target": ""
} |
.class public final Landroid/webkit/CookieSyncManager;
.super Landroid/webkit/WebSyncManager;
.source "CookieSyncManager.java"
# static fields
.field private static sRef:Landroid/webkit/CookieSyncManager;
# direct methods
.method private constructor <init>(Landroid/content/Context;)V
.locals 1
.parameter "context"
.prologue
.line 63
const-string v0, "CookieSyncManager"
invoke-direct {p0, p1, v0}, Landroid/webkit/WebSyncManager;-><init>(Landroid/content/Context;Ljava/lang/String;)V
.line 64
return-void
.end method
.method private static checkInstanceIsCreated()V
.locals 2
.prologue
.line 116
sget-object v0, Landroid/webkit/CookieSyncManager;->sRef:Landroid/webkit/CookieSyncManager;
if-nez v0, :cond_0
.line 117
new-instance v0, Ljava/lang/IllegalStateException;
const-string v1, "CookieSyncManager::createInstance() needs to be called before CookieSyncManager::getInstance()"
invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V
throw v0
.line 121
:cond_0
return-void
.end method
.method public static declared-synchronized createInstance(Landroid/content/Context;)Landroid/webkit/CookieSyncManager;
.locals 4
.parameter "context"
.prologue
.line 85
const-class v2, Landroid/webkit/CookieSyncManager;
monitor-enter v2
if-nez p0, :cond_0
.line 86
:try_start_0
new-instance v1, Ljava/lang/IllegalArgumentException;
const-string v3, "Invalid context argument"
invoke-direct {v1, v3}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V
throw v1
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
.line 85
:catchall_0
move-exception v1
monitor-exit v2
throw v1
.line 89
:cond_0
:try_start_1
invoke-static {p0}, Landroid/webkit/JniUtil;->setContext(Landroid/content/Context;)V
.line 90
invoke-virtual {p0}, Landroid/content/Context;->getApplicationContext()Landroid/content/Context;
move-result-object v0
.line 91
.local v0, appContext:Landroid/content/Context;
sget-object v1, Landroid/webkit/CookieSyncManager;->sRef:Landroid/webkit/CookieSyncManager;
if-nez v1, :cond_1
.line 92
new-instance v1, Landroid/webkit/CookieSyncManager;
invoke-direct {v1, v0}, Landroid/webkit/CookieSyncManager;-><init>(Landroid/content/Context;)V
sput-object v1, Landroid/webkit/CookieSyncManager;->sRef:Landroid/webkit/CookieSyncManager;
.line 94
:cond_1
sget-object v1, Landroid/webkit/CookieSyncManager;->sRef:Landroid/webkit/CookieSyncManager;
:try_end_1
.catchall {:try_start_1 .. :try_end_1} :catchall_0
monitor-exit v2
return-object v1
.end method
.method public static declared-synchronized getInstance()Landroid/webkit/CookieSyncManager;
.locals 2
.prologue
.line 74
const-class v1, Landroid/webkit/CookieSyncManager;
monitor-enter v1
:try_start_0
invoke-static {}, Landroid/webkit/CookieSyncManager;->checkInstanceIsCreated()V
.line 75
sget-object v0, Landroid/webkit/CookieSyncManager;->sRef:Landroid/webkit/CookieSyncManager;
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
monitor-exit v1
return-object v0
.line 74
:catchall_0
move-exception v0
monitor-exit v1
throw v0
.end method
# virtual methods
.method public bridge synthetic resetSync()V
.locals 0
.prologue
.line 58
invoke-super {p0}, Landroid/webkit/WebSyncManager;->resetSync()V
return-void
.end method
.method public bridge synthetic run()V
.locals 0
.prologue
.line 58
invoke-super {p0}, Landroid/webkit/WebSyncManager;->run()V
return-void
.end method
.method public bridge synthetic startSync()V
.locals 0
.prologue
.line 58
invoke-super {p0}, Landroid/webkit/WebSyncManager;->startSync()V
return-void
.end method
.method public bridge synthetic stopSync()V
.locals 0
.prologue
.line 58
invoke-super {p0}, Landroid/webkit/WebSyncManager;->stopSync()V
return-void
.end method
.method public bridge synthetic sync()V
.locals 0
.prologue
.line 58
invoke-super {p0}, Landroid/webkit/WebSyncManager;->sync()V
return-void
.end method
.method protected syncFromRamToFlash()V
.locals 2
.prologue
.line 102
invoke-static {}, Landroid/webkit/CookieManager;->getInstance()Landroid/webkit/CookieManager;
move-result-object v0
.line 104
.local v0, manager:Landroid/webkit/CookieManager;
invoke-virtual {v0}, Landroid/webkit/CookieManager;->acceptCookie()Z
move-result v1
if-nez v1, :cond_0
.line 113
:goto_0
return-void
.line 108
:cond_0
invoke-virtual {v0}, Landroid/webkit/CookieManager;->flushCookieStore()V
goto :goto_0
.end method
| {
"content_hash": "91bc2dd0b173d238d3a88398d168ce71",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 119,
"avg_line_length": 22.166666666666668,
"alnum_prop": 0.7002641739483845,
"repo_name": "baidurom/devices-g520",
"id": "6d534bbbf01ea6c2ef91d3c9fcf0a2a8fa61dabc",
"size": "4921",
"binary": false,
"copies": "4",
"ref": "refs/heads/coron-4.1",
"path": "framework.jar.out/smali/android/webkit/CookieSyncManager.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "12575"
},
{
"name": "Python",
"bytes": "1261"
},
{
"name": "Shell",
"bytes": "2159"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81a.cpp
Label Definition File: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close.label.xml
Template File: source-sinks-81a.tmpl.cpp
*/
/*
* @description
* CWE: 775 Missing Release of File Descriptor or Handle After Effective Lifetime
* BadSource: Open a file using CreateFile()
* Sinks:
* GoodSink: Close the file using CloseHandle()
* BadSink : Do not close file
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include "CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81.h"
namespace CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81
{
#ifndef OMITBAD
void bad()
{
HANDLE data;
/* Initialize data */
data = INVALID_HANDLE_VALUE;
/* POTENTIAL FLAW: Open a file without closing it */
data = CreateFile("BadSource_w32CreateFile.txt",
(GENERIC_WRITE|GENERIC_READ),
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
const CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_base& baseObject = CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_bad();
baseObject.action(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
HANDLE data;
/* Initialize data */
data = INVALID_HANDLE_VALUE;
/* POTENTIAL FLAW: Open a file without closing it */
data = CreateFile("BadSource_w32CreateFile.txt",
(GENERIC_WRITE|GENERIC_READ),
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
const CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_base& baseObject = CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_goodB2G();
baseObject.action(data);
}
void good()
{
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "6ae40d2c61993f89fe9d7465b22ea241",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 197,
"avg_line_length": 32.707070707070706,
"alnum_prop": 0.637739345274861,
"repo_name": "maurer/tiamat",
"id": "6c190d6484cba7e09e84e9022a1d03f5a5ef44b5",
"size": "3238",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE775_Missing_Release_of_File_Descriptor_or_Handle/CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81a.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class SampleList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, assistant_sid, task_sid):
"""
Initialize the SampleList
:param Version version: Version that contains the resource
:param assistant_sid: The unique ID of the Assistant.
:param task_sid: The unique ID of the Task associated with this Sample.
:returns: twilio.rest.preview.understand.assistant.task.sample.SampleList
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleList
"""
super(SampleList, self).__init__(version)
# Path Solution
self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, }
self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples'.format(**self._solution)
def stream(self, language=values.unset, limit=None, page_size=None):
"""
Streams SampleInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode language: An ISO language-country string of the sample.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.preview.understand.assistant.task.sample.SampleInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(language=language, page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'], limits['page_limit'])
def list(self, language=values.unset, limit=None, page_size=None):
"""
Lists SampleInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode language: An ISO language-country string of the sample.
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.preview.understand.assistant.task.sample.SampleInstance]
"""
return list(self.stream(language=language, limit=limit, page_size=page_size, ))
def page(self, language=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of SampleInstance records from the API.
Request is executed immediately
:param unicode language: An ISO language-country string of the sample.
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SamplePage
"""
params = values.of({
'Language': language,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(
'GET',
self._uri,
params=params,
)
return SamplePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of SampleInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SamplePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return SamplePage(self._version, response, self._solution)
def create(self, language, tagged_text, source_channel=values.unset):
"""
Create a new SampleInstance
:param unicode language: An ISO language-country string of the sample.
:param unicode tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks.
:param unicode source_channel: The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null
:returns: Newly created SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
"""
data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, })
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
)
def get(self, sid):
"""
Constructs a SampleContext
:param sid: A 34 character string that uniquely identifies this resource.
:returns: twilio.rest.preview.understand.assistant.task.sample.SampleContext
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleContext
"""
return SampleContext(
self._version,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a SampleContext
:param sid: A 34 character string that uniquely identifies this resource.
:returns: twilio.rest.preview.understand.assistant.task.sample.SampleContext
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleContext
"""
return SampleContext(
self._version,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Preview.Understand.SampleList>'
class SamplePage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the SamplePage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param assistant_sid: The unique ID of the Assistant.
:param task_sid: The unique ID of the Task associated with this Sample.
:returns: twilio.rest.preview.understand.assistant.task.sample.SamplePage
:rtype: twilio.rest.preview.understand.assistant.task.sample.SamplePage
"""
super(SamplePage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of SampleInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
"""
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Preview.Understand.SamplePage>'
class SampleContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, assistant_sid, task_sid, sid):
"""
Initialize the SampleContext
:param Version version: Version that contains the resource
:param assistant_sid: The unique ID of the Assistant.
:param task_sid: The unique ID of the Task associated with this Sample.
:param sid: A 34 character string that uniquely identifies this resource.
:returns: twilio.rest.preview.understand.assistant.task.sample.SampleContext
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleContext
"""
super(SampleContext, self).__init__(version)
# Path Solution
self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, 'sid': sid, }
self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch a SampleInstance
:returns: Fetched SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=self._solution['sid'],
)
def update(self, language=values.unset, tagged_text=values.unset,
source_channel=values.unset):
"""
Update the SampleInstance
:param unicode language: An ISO language-country string of the sample.
:param unicode tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks.
:param unicode source_channel: The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null
:returns: Updated SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
"""
data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, })
payload = self._version.update(
'POST',
self._uri,
data=data,
)
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=self._solution['sid'],
)
def delete(self):
"""
Deletes the SampleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete('delete', self._uri)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Preview.Understand.SampleContext {}>'.format(context)
class SampleInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, payload, assistant_sid, task_sid, sid=None):
"""
Initialize the SampleInstance
:returns: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
"""
super(SampleInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'task_sid': payload.get('task_sid'),
'language': payload.get('language'),
'assistant_sid': payload.get('assistant_sid'),
'sid': payload.get('sid'),
'tagged_text': payload.get('tagged_text'),
'url': payload.get('url'),
'source_channel': payload.get('source_channel'),
}
# Context
self._context = None
self._solution = {
'assistant_sid': assistant_sid,
'task_sid': task_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SampleContext for this SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleContext
"""
if self._context is None:
self._context = SampleContext(
self._version,
assistant_sid=self._solution['assistant_sid'],
task_sid=self._solution['task_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The unique ID of the Account that created this Sample.
:rtype: unicode
"""
return self._properties['account_sid']
@property
def date_created(self):
"""
:returns: The date that this resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date that this resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def task_sid(self):
"""
:returns: The unique ID of the Task associated with this Sample.
:rtype: unicode
"""
return self._properties['task_sid']
@property
def language(self):
"""
:returns: An ISO language-country string of the sample.
:rtype: unicode
"""
return self._properties['language']
@property
def assistant_sid(self):
"""
:returns: The unique ID of the Assistant.
:rtype: unicode
"""
return self._properties['assistant_sid']
@property
def sid(self):
"""
:returns: A 34 character string that uniquely identifies this resource.
:rtype: unicode
"""
return self._properties['sid']
@property
def tagged_text(self):
"""
:returns: The text example of how end-users may express this task. The sample may contain Field tag blocks.
:rtype: unicode
"""
return self._properties['tagged_text']
@property
def url(self):
"""
:returns: The url
:rtype: unicode
"""
return self._properties['url']
@property
def source_channel(self):
"""
:returns: The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null
:rtype: unicode
"""
return self._properties['source_channel']
def fetch(self):
"""
Fetch a SampleInstance
:returns: Fetched SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
"""
return self._proxy.fetch()
def update(self, language=values.unset, tagged_text=values.unset,
source_channel=values.unset):
"""
Update the SampleInstance
:param unicode language: An ISO language-country string of the sample.
:param unicode tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks.
:param unicode source_channel: The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null
:returns: Updated SampleInstance
:rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance
"""
return self._proxy.update(language=language, tagged_text=tagged_text, source_channel=source_channel, )
def delete(self):
"""
Deletes the SampleInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Preview.Understand.SampleInstance {}>'.format(context)
| {
"content_hash": "4bfc0d6578cf76cfe42cf4b6a2321272",
"timestamp": "",
"source": "github",
"line_count": 511,
"max_line_length": 192,
"avg_line_length": 36.76320939334638,
"alnum_prop": 0.620142659427233,
"repo_name": "tysonholub/twilio-python",
"id": "575ee7a68bc9ad4032d1cf483e0031a80a8a2ee7",
"size": "18801",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "twilio/rest/preview/understand/assistant/task/sample.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "173"
},
{
"name": "Makefile",
"bytes": "2081"
},
{
"name": "Python",
"bytes": "8063586"
}
],
"symlink_target": ""
} |
The aim of this first guide is to get a Phoenix application up and running as quickly as possible.
Before we begin, please take a minute to read the [Installation Guide](http://www.phoenixframework.org/docs/installation). By installing any necessary dependencies beforehand, we'll be able to get our application up and running smoothly.
At this point, we should have Elixir, Erlang, Hex, and the Phoenix archive installed. We should also have PostgreSQL and node.js installed to build a default application.
Ok, we're ready to go!
We can run `mix phoenix.new` from any directory in order to bootstrap our Phoenix application. Phoenix will accept either an absolute or relative path for the directory of our new project. Assuming that the name of our application is `hello_phoenix`, either of these will work.
```console
$ mix phoenix.new /Users/me/work/elixir-stuff/hello_phoenix
```
```console
$ mix phoenix.new hello_phoenix
```
> A note about [Brunch.io](http://brunch.io/) before we begin: Phoenix will use Brunch.io for asset management by default. Brunch.io's dependencies are installed via the node package manager, not mix. Phoenix will prompt us to install them at the end of the `mix phoenix.new` task. If we say "no" at that point, and if we don't install those dependencies later with `npm install`, our application will raise errors when we try to start it, and our assets may not load properly. If we don't want to use Brunch.io at all, we can simply pass `--no-brunch` to `mix phoenix.new`.
Now that we're ready, let's call `phoenix.new` with a relative path.
```console
$ mix phoenix.new hello_phoenix
* creating hello_phoenix/README.md
. . .
```
Phoenix generates the directory structure and all the files we will need for our application. When it's done, it will ask us if we want it to install our dependencies for us. Let's say yes to that.
```console
Fetch and install dependencies? [Yn] y
* running npm install && node node_modules/brunch/bin/brunch build
* running mix deps.get
```
Once our dependencies are installed, the task will prompt us to change into our project directory and start our application.
```console
We are all set! Run your Phoenix application:
$ cd hello_phoenix
$ mix ecto.create
$ mix phoenix.server
You can also run it inside IEx (Interactive Elixir) as:
$ iex -S mix phoenix.server
```
Phoenix assumes that our PostgreSQL database will have a `postgres` user account with the correct permissions and a password of "postgres". If that isn't the case, please see the instructions for the [ecto.create](http://www.phoenixframework.org/docs/mix-tasks#section--ecto-create-) mix task.
Ok, let's give it a try.
```console
$ cd hello_phoenix
$ mix ecto.create
$ mix phoenix.server
```
> Note: if this is the first time you are running this command, Phoenix may also ask to install Rebar. Go ahead with the installation as Rebar is used to build Erlang packages.
If we choose not to have Phoenix install our dependencies when we generate a new application, the `phoenix.new` task will prompt us to take the necessary steps when we do want to install them.
```console
Fetch and install dependencies? [Yn] n
Phoenix uses an optional assets build tool called brunch.io
that requires node.js and npm. Installation instructions for
node.js, which includes npm, can be found at http://nodejs.org.
After npm is installed, install your brunch dependencies by
running inside your app:
$ npm install
If you don't want brunch.io, you can re-run this generator
with the --no-brunch option.
We are all set! Run your Phoenix application:
$ cd hello_phoenix
$ mix deps.get
$ mix phoenix.server
You can also run it inside IEx (Interactive Elixir) as:
$ iex -S mix phoenix.server
```
By default Phoenix accepts requests on port 4000. If we point our favorite web browser at [http://localhost:4000](http://localhost:4000), we should see the Phoenix Framework welcome page.

If your screen looks like the image above, congratulations! You now have a working Phoenix application.
Locally, our application is running in an iex session. To stop it, we hit ctrl-c twice, just as we would to stop iex normally.
The next step is customizing our application just a bit to give us a sense of how a Phoenix app is put together.
| {
"content_hash": "bcfdb824f7212489d66e77828e71f887",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 574,
"avg_line_length": 43.54,
"alnum_prop": 0.7618282039503904,
"repo_name": "larrylv/phoenix_guides",
"id": "361c61815920e2544110fad017a9511d96fc988e",
"size": "4354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "A_up_and_running.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "271364"
},
{
"name": "HTML",
"bytes": "26450"
}
],
"symlink_target": ""
} |
#include "lib.h"
#include "array.h"
#include "ioloop.h"
#include "str.h"
#include "llist.h"
#include "mkdir-parents.h"
#include "unlink-directory.h"
#include "index-mail.h"
#include "mail-copy.h"
#include "mail-search.h"
#include "mailbox-list-private.h"
#include "virtual-plugin.h"
#include "virtual-transaction.h"
#include "virtual-storage.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#define VIRTUAL_DEFAULT_MAX_OPEN_MAILBOXES 64
extern struct mail_storage virtual_storage;
extern struct mailbox virtual_mailbox;
extern struct virtual_mailbox_vfuncs virtual_mailbox_vfuncs;
struct virtual_storage_module virtual_storage_module =
MODULE_CONTEXT_INIT(&mail_storage_module_register);
static bool ns_is_visible(struct mail_namespace *ns)
{
return (ns->flags & NAMESPACE_FLAG_LIST_PREFIX) != 0 ||
(ns->flags & NAMESPACE_FLAG_LIST_CHILDREN) != 0 ||
(ns->flags & NAMESPACE_FLAG_HIDDEN) == 0;
}
static const char *get_user_visible_mailbox_name(struct mailbox *box)
{
if (ns_is_visible(box->list->ns))
return box->vname;
else {
return t_strdup_printf("<hidden>%c%s",
mail_namespace_get_sep(box->list->ns),
box->vname);
}
}
void virtual_box_copy_error(struct mailbox *dest, struct mailbox *src)
{
const char *name, *str;
enum mail_error error;
name = get_user_visible_mailbox_name(src);
str = mailbox_get_last_error(src, &error);
str = t_strdup_printf("%s (for backend mailbox %s)", str, name);
mail_storage_set_error(dest->storage, error, str);
}
static struct mail_storage *virtual_storage_alloc(void)
{
struct virtual_storage *storage;
pool_t pool;
pool = pool_alloconly_create("virtual storage", 1024);
storage = p_new(pool, struct virtual_storage, 1);
storage->storage = virtual_storage;
storage->storage.pool = pool;
p_array_init(&storage->open_stack, pool, 8);
return &storage->storage;
}
static int
virtual_storage_create(struct mail_storage *_storage,
struct mail_namespace *ns ATTR_UNUSED,
const char **error_r)
{
struct virtual_storage *storage = (struct virtual_storage *)_storage;
const char *value;
value = mail_user_plugin_getenv(_storage->user, "virtual_max_open_mailboxes");
if (value == NULL)
storage->max_open_mailboxes = VIRTUAL_DEFAULT_MAX_OPEN_MAILBOXES;
else if (str_to_uint(value, &storage->max_open_mailboxes) < 0) {
*error_r = "Invalid virtual_max_open_mailboxes setting";
return -1;
}
return 0;
}
static void
virtual_storage_get_list_settings(const struct mail_namespace *ns ATTR_UNUSED,
struct mailbox_list_settings *set)
{
if (set->layout == NULL)
set->layout = MAILBOX_LIST_NAME_FS;
if (set->subscription_fname == NULL)
set->subscription_fname = VIRTUAL_SUBSCRIPTION_FILE_NAME;
}
struct virtual_backend_box *
virtual_backend_box_lookup_name(struct virtual_mailbox *mbox, const char *name)
{
struct virtual_backend_box *const *bboxes;
unsigned int i, count;
bboxes = array_get(&mbox->backend_boxes, &count);
for (i = 0; i < count; i++) {
if (strcmp(bboxes[i]->name, name) == 0)
return bboxes[i];
}
return NULL;
}
struct virtual_backend_box *
virtual_backend_box_lookup(struct virtual_mailbox *mbox, uint32_t mailbox_id)
{
struct virtual_backend_box *const *bboxes;
unsigned int i, count;
if (mailbox_id == 0)
return NULL;
bboxes = array_get(&mbox->backend_boxes, &count);
for (i = 0; i < count; i++) {
if (bboxes[i]->mailbox_id == mailbox_id)
return bboxes[i];
}
return NULL;
}
static bool virtual_mailbox_is_in_open_stack(struct virtual_storage *storage,
const char *name)
{
const char *const *names;
unsigned int i, count;
names = array_get(&storage->open_stack, &count);
for (i = 0; i < count; i++) {
if (strcmp(names[i], name) == 0)
return TRUE;
}
return FALSE;
}
static int virtual_backend_box_open_failed(struct virtual_mailbox *mbox,
struct virtual_backend_box *bbox)
{
enum mail_error error;
const char *str;
str = t_strdup_printf(
"Virtual mailbox open failed because of mailbox %s: %s",
get_user_visible_mailbox_name(bbox->box),
mailbox_get_last_error(bbox->box, &error));
mail_storage_set_error(mbox->box.storage, error, str);
mailbox_free(&bbox->box);
if (error == MAIL_ERROR_PERM && bbox->wildcard) {
/* this mailbox wasn't explicitly specified. just skip it. */
return 0;
}
return -1;
}
static int virtual_backend_box_alloc(struct virtual_mailbox *mbox,
struct virtual_backend_box *bbox,
enum mailbox_flags flags)
{
struct mail_user *user = mbox->storage->storage.user;
struct mail_namespace *ns;
const char *mailbox;
enum mailbox_existence existence;
i_assert(bbox->box == NULL);
if (!bbox->clear_recent)
flags &= ~MAILBOX_FLAG_DROP_RECENT;
mailbox = bbox->name;
ns = mail_namespace_find(user->namespaces, mailbox);
bbox->box = mailbox_alloc(ns->list, mailbox, flags);
if (mailbox_exists(bbox->box, TRUE, &existence) < 0)
return virtual_backend_box_open_failed(mbox, bbox);
if (existence != MAILBOX_EXISTENCE_SELECT) {
/* ignore this. it could be intentional. */
if (mbox->storage->storage.user->mail_debug) {
i_debug("virtual mailbox %s: "
"Skipping non-existing mailbox %s",
mbox->box.vname, bbox->box->vname);
}
mailbox_free(&bbox->box);
return 0;
}
i_array_init(&bbox->uids, 64);
i_array_init(&bbox->sync_pending_removes, 64);
/* we use modseqs for being able to check quickly if backend mailboxes
have changed. make sure the backend has them enabled. */
mailbox_enable(bbox->box, MAILBOX_FEATURE_CONDSTORE);
return 1;
}
static int virtual_mailboxes_open(struct virtual_mailbox *mbox,
enum mailbox_flags flags)
{
struct virtual_backend_box *const *bboxes;
unsigned int i, count;
int ret;
bboxes = array_get(&mbox->backend_boxes, &count);
for (i = 0; i < count; ) {
ret = virtual_backend_box_alloc(mbox, bboxes[i], flags);
if (ret <= 0) {
if (ret < 0)
break;
array_delete(&mbox->backend_boxes, i, 1);
bboxes = array_get(&mbox->backend_boxes, &count);
} else {
i++;
}
}
if (i == count)
return 0;
else {
/* failed */
for (; i > 0; i--) {
mailbox_free(&bboxes[i-1]->box);
array_free(&bboxes[i-1]->uids);
}
return -1;
}
}
static struct mailbox *
virtual_mailbox_alloc(struct mail_storage *_storage, struct mailbox_list *list,
const char *vname, enum mailbox_flags flags)
{
struct virtual_storage *storage = (struct virtual_storage *)_storage;
struct virtual_mailbox *mbox;
pool_t pool;
pool = pool_alloconly_create("virtual mailbox", 2048);
mbox = p_new(pool, struct virtual_mailbox, 1);
mbox->box = virtual_mailbox;
mbox->box.pool = pool;
mbox->box.storage = _storage;
mbox->box.list = list;
mbox->box.mail_vfuncs = &virtual_mail_vfuncs;
mbox->vfuncs = virtual_mailbox_vfuncs;
index_storage_mailbox_alloc(&mbox->box, vname, flags, MAIL_INDEX_PREFIX);
mbox->storage = storage;
mbox->virtual_ext_id = (uint32_t)-1;
return &mbox->box;
}
void virtual_backend_box_sync_mail_unset(struct virtual_backend_box *bbox)
{
struct mailbox_transaction_context *trans;
if (bbox->sync_mail != NULL) {
trans = bbox->sync_mail->transaction;
mail_free(&bbox->sync_mail);
(void)mailbox_transaction_commit(&trans);
}
}
static bool virtual_backend_box_can_close(struct virtual_backend_box *bbox)
{
if (bbox->box->notify_callback != NULL) {
/* FIXME: IMAP IDLE running - we should support closing this
also if mailbox_list_index=yes */
return FALSE;
}
if (array_count(&bbox->sync_pending_removes) > 0) {
/* FIXME: we could probably close this by making
syncing support it? */
return FALSE;
}
return TRUE;
}
static bool
virtual_backend_box_close_any_except(struct virtual_mailbox *mbox,
struct virtual_backend_box *except_bbox)
{
struct virtual_backend_box *bbox;
/* first try to close a mailbox without any transactions.
we'll also skip any mailbox that has notifications enabled (ideally
these would be handled by mailbox list index) */
for (bbox = mbox->open_backend_boxes_head; bbox != NULL; bbox = bbox->next_open) {
i_assert(bbox->box->opened);
if (bbox != except_bbox &&
bbox->box->transaction_count == 0 &&
virtual_backend_box_can_close(bbox)) {
i_assert(bbox->sync_mail == NULL);
virtual_backend_box_close(mbox, bbox);
return TRUE;
}
}
/* next try to close a mailbox that has sync_mail, but no
other transactions */
for (bbox = mbox->open_backend_boxes_head; bbox != NULL; bbox = bbox->next_open) {
if (bbox != except_bbox &&
bbox->sync_mail != NULL &&
bbox->box->transaction_count == 1 &&
virtual_backend_box_can_close(bbox)) {
virtual_backend_box_sync_mail_unset(bbox);
i_assert(bbox->box->transaction_count == 0);
virtual_backend_box_close(mbox, bbox);
return TRUE;
}
}
return FALSE;
}
void virtual_backend_box_opened(struct virtual_mailbox *mbox,
struct virtual_backend_box *bbox)
{
/* the backend mailbox was already opened. if we didn't get here
from virtual_backend_box_open() we may need to close a mailbox */
while (mbox->backends_open_count > mbox->storage->max_open_mailboxes &&
virtual_backend_box_close_any_except(mbox, bbox))
;
mbox->backends_open_count++;
DLLIST2_APPEND_FULL(&mbox->open_backend_boxes_head,
&mbox->open_backend_boxes_tail, bbox,
prev_open, next_open);
}
int virtual_backend_box_open(struct virtual_mailbox *mbox,
struct virtual_backend_box *bbox)
{
i_assert(!bbox->box->opened);
/* try to keep the number of open mailboxes below the threshold
before opening the mailbox */
while (mbox->backends_open_count >= mbox->storage->max_open_mailboxes &&
virtual_backend_box_close_any_except(mbox, bbox))
;
if (mailbox_open(bbox->box) < 0)
return -1;
virtual_backend_box_opened(mbox, bbox);
return 0;
}
void virtual_backend_box_close(struct virtual_mailbox *mbox,
struct virtual_backend_box *bbox)
{
i_assert(bbox->box->opened);
if (bbox->search_result != NULL)
mailbox_search_result_free(&bbox->search_result);
if (bbox->search_args != NULL &&
bbox->search_args_initialized) {
mail_search_args_deinit(bbox->search_args);
bbox->search_args_initialized = FALSE;
}
i_assert(mbox->backends_open_count > 0);
mbox->backends_open_count--;
DLLIST2_REMOVE_FULL(&mbox->open_backend_boxes_head,
&mbox->open_backend_boxes_tail, bbox,
prev_open, next_open);
mailbox_close(bbox->box);
}
void virtual_backend_box_accessed(struct virtual_mailbox *mbox,
struct virtual_backend_box *bbox)
{
DLLIST2_REMOVE_FULL(&mbox->open_backend_boxes_head,
&mbox->open_backend_boxes_tail, bbox,
prev_open, next_open);
DLLIST2_APPEND_FULL(&mbox->open_backend_boxes_head,
&mbox->open_backend_boxes_tail, bbox,
prev_open, next_open);
}
static void virtual_mailbox_close_internal(struct virtual_mailbox *mbox)
{
struct virtual_backend_box **bboxes;
unsigned int i, count;
bboxes = array_get_modifiable(&mbox->backend_boxes, &count);
for (i = 0; i < count; i++) {
if (bboxes[i]->box == NULL)
continue;
if (bboxes[i]->box->opened)
virtual_backend_box_close(mbox, bboxes[i]);
mailbox_free(&bboxes[i]->box);
if (array_is_created(&bboxes[i]->sync_outside_expunges))
array_free(&bboxes[i]->sync_outside_expunges);
array_free(&bboxes[i]->sync_pending_removes);
array_free(&bboxes[i]->uids);
}
i_assert(mbox->backends_open_count == 0);
}
static int
virtual_mailbox_exists(struct mailbox *box, bool auto_boxes ATTR_UNUSED,
enum mailbox_existence *existence_r)
{
return index_storage_mailbox_exists_full(box, VIRTUAL_CONFIG_FNAME,
existence_r);
}
static int virtual_mailbox_open(struct mailbox *box)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
bool broken;
int ret = 0;
if (virtual_mailbox_is_in_open_stack(mbox->storage, box->name)) {
mail_storage_set_critical(box->storage,
"Virtual mailbox loops: %s", box->name);
return -1;
}
if (!array_is_created(&mbox->backend_boxes))
ret = virtual_config_read(mbox);
if (ret == 0) {
array_append(&mbox->storage->open_stack, &box->name, 1);
ret = virtual_mailboxes_open(mbox, box->flags);
array_delete(&mbox->storage->open_stack,
array_count(&mbox->storage->open_stack)-1, 1);
}
if (ret < 0) {
virtual_mailbox_close_internal(mbox);
return -1;
}
if (index_storage_mailbox_open(box, FALSE) < 0)
return -1;
mbox->virtual_ext_id =
mail_index_ext_register(mbox->box.index, "virtual", 0,
sizeof(struct virtual_mail_index_record),
sizeof(uint32_t));
if (virtual_mailbox_ext_header_read(mbox, box->view, &broken) < 0) {
virtual_mailbox_close_internal(mbox);
index_storage_mailbox_close(box);
return -1;
}
return 0;
}
static void virtual_mailbox_close(struct mailbox *box)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
virtual_mailbox_close_internal(mbox);
index_storage_mailbox_close(box);
}
static void virtual_mailbox_free(struct mailbox *box)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
virtual_config_free(mbox);
index_storage_mailbox_free(box);
}
static int
virtual_mailbox_create(struct mailbox *box,
const struct mailbox_update *update ATTR_UNUSED,
bool directory ATTR_UNUSED)
{
mail_storage_set_error(box->storage, MAIL_ERROR_NOTPOSSIBLE,
"Can't create virtual mailboxes");
return -1;
}
static int
virtual_mailbox_update(struct mailbox *box,
const struct mailbox_update *update ATTR_UNUSED)
{
mail_storage_set_error(box->storage, MAIL_ERROR_NOTPOSSIBLE,
"Can't update virtual mailboxes");
return -1;
}
static int virtual_storage_set_have_guid_flags(struct virtual_mailbox *mbox)
{
struct virtual_backend_box *const *bboxes;
unsigned int i, count;
struct mailbox_status status;
bool opened;
mbox->have_guids = TRUE;
mbox->have_save_guids = TRUE;
bboxes = array_get(&mbox->backend_boxes, &count);
for (i = 0; i < count; i++) {
opened = bboxes[i]->box->opened;
if (mailbox_get_status(bboxes[i]->box, 0, &status) < 0) {
virtual_box_copy_error(&mbox->box, bboxes[i]->box);
return -1;
}
i_assert(bboxes[i]->box->opened == opened);
if (!status.have_guids)
mbox->have_guids = FALSE;
if (!status.have_save_guids)
mbox->have_save_guids = FALSE;
}
return 0;
}
static int
virtual_storage_get_status(struct mailbox *box,
enum mailbox_status_items items,
struct mailbox_status *status_r)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
if ((items & STATUS_LAST_CACHED_SEQ) != 0)
items |= STATUS_MESSAGES;
if (index_storage_get_status(box, items, status_r) < 0)
return -1;
if ((items & STATUS_LAST_CACHED_SEQ) != 0) {
/* Virtual mailboxes have no cached data of their own, so the
current value is always 0. The most important use for this
functionality is for "doveadm index" to do FTS indexing and
it doesn't really matter there if we set this value
correctly or not. So for now just assume that everything is
indexed. */
status_r->last_cached_seq = status_r->messages;
}
if (!mbox->have_guid_flags_set) {
if (virtual_storage_set_have_guid_flags(mbox) < 0)
return -1;
mbox->have_guid_flags_set = TRUE;
}
if (mbox->have_guids)
status_r->have_guids = TRUE;
if (mbox->have_save_guids)
status_r->have_save_guids = TRUE;
return 0;
}
static int
virtual_mailbox_get_metadata(struct mailbox *box,
enum mailbox_metadata_items items,
struct mailbox_metadata *metadata_r)
{
if (index_mailbox_get_metadata(box, items, metadata_r) < 0)
return -1;
if ((items & MAILBOX_METADATA_GUID) != 0) {
mail_storage_set_error(box->storage, MAIL_ERROR_NOTPOSSIBLE,
"Virtual mailboxes have no GUIDs");
return -1;
}
return 0;
}
static void
virtual_notify_callback(struct mailbox *bbox ATTR_UNUSED, struct mailbox *box)
{
box->notify_callback(box, box->notify_context);
}
static void virtual_notify_changes(struct mailbox *box)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
struct virtual_backend_box *const *bboxp;
if (box->notify_callback == NULL) {
array_foreach(&mbox->backend_boxes, bboxp)
mailbox_notify_changes_stop((*bboxp)->box);
return;
}
/* FIXME: if mailbox_list_index=yes, use mailbox-list-notify.h API
to wait for changes and avoid opening all mailboxes here. */
array_foreach(&mbox->backend_boxes, bboxp) {
if (!(*bboxp)->box->opened &&
virtual_backend_box_open(mbox, *bboxp) < 0) {
/* we can't report error in here, so do it later */
(*bboxp)->open_failed = TRUE;
continue;
}
mailbox_notify_changes((*bboxp)->box,
virtual_notify_callback, box);
}
}
static void
virtual_get_virtual_uids(struct mailbox *box,
struct mailbox *backend_mailbox,
const ARRAY_TYPE(seq_range) *backend_uids,
ARRAY_TYPE(seq_range) *virtual_uids_r)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
struct virtual_backend_box *bbox;
const struct virtual_backend_uidmap *uids;
struct seq_range_iter iter;
unsigned int n, i, count;
uint32_t uid;
if (mbox->lookup_prev_bbox != NULL &&
strcmp(mbox->lookup_prev_bbox->box->vname, backend_mailbox->vname) == 0)
bbox = mbox->lookup_prev_bbox;
else {
bbox = virtual_backend_box_lookup_name(mbox, backend_mailbox->vname);
mbox->lookup_prev_bbox = bbox;
}
if (bbox == NULL)
return;
uids = array_get(&bbox->uids, &count); i = 0;
seq_range_array_iter_init(&iter, backend_uids); n = 0;
while (seq_range_array_iter_nth(&iter, n++, &uid)) {
while (i < count && uids[i].real_uid < uid) i++;
if (i < count && uids[i].real_uid == uid) {
seq_range_array_add(virtual_uids_r,
uids[i].virtual_uid);
i++;
}
}
}
static void
virtual_get_virtual_uid_map(struct mailbox *box,
struct mailbox *backend_mailbox,
const ARRAY_TYPE(seq_range) *backend_uids,
ARRAY_TYPE(uint32_t) *virtual_uids_r)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
struct virtual_backend_box *bbox;
const struct virtual_backend_uidmap *uids;
struct seq_range_iter iter;
unsigned int n, i, count;
uint32_t uid;
if (mbox->lookup_prev_bbox != NULL &&
strcmp(mbox->lookup_prev_bbox->box->vname, backend_mailbox->vname) == 0)
bbox = mbox->lookup_prev_bbox;
else {
bbox = virtual_backend_box_lookup_name(mbox, backend_mailbox->vname);
mbox->lookup_prev_bbox = bbox;
}
if (bbox == NULL)
return;
uids = array_get(&bbox->uids, &count); i = 0;
seq_range_array_iter_init(&iter, backend_uids); n = 0;
while (seq_range_array_iter_nth(&iter, n++, &uid)) {
while (i < count && uids[i].real_uid < uid) i++;
if (i == count || uids[i].real_uid > uid) {
uint32_t zero = 0;
array_append(virtual_uids_r, &zero, 1);
} else {
array_append(virtual_uids_r, &uids[i].virtual_uid, 1);
i++;
}
}
}
static void
virtual_get_virtual_backend_boxes(struct mailbox *box,
ARRAY_TYPE(mailboxes) *mailboxes,
bool only_with_msgs)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
struct virtual_backend_box *const *bboxes;
unsigned int i, count;
bboxes = array_get(&mbox->backend_boxes, &count);
for (i = 0; i < count; i++) {
if (!only_with_msgs || array_count(&bboxes[i]->uids) > 0)
array_append(mailboxes, &bboxes[i]->box, 1);
}
}
static bool virtual_is_inconsistent(struct mailbox *box)
{
struct virtual_mailbox *mbox = (struct virtual_mailbox *)box;
if (mbox->inconsistent)
return TRUE;
return index_storage_is_inconsistent(box);
}
struct mail_storage virtual_storage = {
.name = VIRTUAL_STORAGE_NAME,
.class_flags = MAIL_STORAGE_CLASS_FLAG_NOQUOTA,
.v = {
NULL,
virtual_storage_alloc,
virtual_storage_create,
index_storage_destroy,
NULL,
virtual_storage_get_list_settings,
NULL,
virtual_mailbox_alloc,
NULL
}
};
struct mailbox virtual_mailbox = {
.v = {
index_storage_is_readonly,
index_storage_mailbox_enable,
virtual_mailbox_exists,
virtual_mailbox_open,
virtual_mailbox_close,
virtual_mailbox_free,
virtual_mailbox_create,
virtual_mailbox_update,
index_storage_mailbox_delete,
index_storage_mailbox_rename,
virtual_storage_get_status,
virtual_mailbox_get_metadata,
index_storage_set_subscribed,
index_storage_attribute_set,
index_storage_attribute_get,
index_storage_attribute_iter_init,
index_storage_attribute_iter_next,
index_storage_attribute_iter_deinit,
NULL,
NULL,
virtual_storage_sync_init,
index_mailbox_sync_next,
index_mailbox_sync_deinit,
NULL,
virtual_notify_changes,
virtual_transaction_begin,
virtual_transaction_commit,
virtual_transaction_rollback,
NULL,
virtual_mail_alloc,
virtual_search_init,
virtual_search_deinit,
virtual_search_next_nonblock,
virtual_search_next_update_seq,
virtual_save_alloc,
virtual_save_begin,
virtual_save_continue,
virtual_save_finish,
virtual_save_cancel,
mail_storage_copy,
NULL,
NULL,
NULL,
virtual_is_inconsistent
}
};
struct virtual_mailbox_vfuncs virtual_mailbox_vfuncs = {
virtual_get_virtual_uids,
virtual_get_virtual_uid_map,
virtual_get_virtual_backend_boxes
};
| {
"content_hash": "0a01c13d81625e4c6791a4cfc7a1273f",
"timestamp": "",
"source": "github",
"line_count": 772,
"max_line_length": 83,
"avg_line_length": 27.40414507772021,
"alnum_prop": 0.685195689166194,
"repo_name": "LTD-Beget/dovecot",
"id": "60ea3731fe59c284689f5b18578fe1556d7acf2a",
"size": "21232",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/plugins/virtual/virtual-storage.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "10591133"
},
{
"name": "C++",
"bytes": "89116"
},
{
"name": "Logos",
"bytes": "3470"
},
{
"name": "Objective-C",
"bytes": "1543"
},
{
"name": "Perl",
"bytes": "9273"
},
{
"name": "Python",
"bytes": "1626"
},
{
"name": "Shell",
"bytes": "7240"
}
],
"symlink_target": ""
} |
@class DBGCodeModule, DBGDataValue, DBGDisassemblyInstructionList, DBGThread, DVTObservingToken, DVTStackBacktrace, IDELaunchSession, NSArray, NSNumber, NSString, NSURL;
@interface DBGStackFrame : NSObject <IDEDebugNavigableModel, DVTInvalidation>
{
DVTObservingToken *_debugSessionStateObserver;
BOOL _hasSymbols;
BOOL _returnValueIsValid;
BOOL _recorded;
BOOL _settingDisassembly;
NSString *_displayName;
NSString *_filePath;
DBGDataValue *_returnValue;
DBGThread *_parentThread;
NSString *_name;
NSURL *_fileURL;
NSNumber *_lineNumber;
NSString *_instructionPointerAddressString;
NSNumber *_frameNumber;
NSNumber *_framePointer;
DBGCodeModule *_module;
NSArray *_locals;
NSArray *_arguments;
NSArray *_fileStatics;
NSArray *_registers;
DBGDisassemblyInstructionList *_disassembly;
}
+ (id)keyPathsForValuesAffectingDisplayName;
+ (id)stackFrameForDisassemblyURL:(id)arg1;
+ (id)disassemblyURLForStackFrame:(id)arg1 inDebugSession:(id)arg2;
+ (id)compressedStackFrames:(id)arg1 usingCompressionValue:(long long)arg2;
+ (void)initialize;
@property(nonatomic) BOOL settingDisassembly; // @synthesize settingDisassembly=_settingDisassembly;
@property(retain, nonatomic) DBGDisassemblyInstructionList *disassembly; // @synthesize disassembly=_disassembly;
@property(nonatomic, getter=isRecorded) BOOL recorded; // @synthesize recorded=_recorded;
@property(nonatomic) BOOL returnValueIsValid; // @synthesize returnValueIsValid=_returnValueIsValid;
@property(readonly, nonatomic) NSArray *registers; // @synthesize registers=_registers;
@property(readonly, nonatomic) NSArray *fileStatics; // @synthesize fileStatics=_fileStatics;
@property(readonly, nonatomic) NSArray *arguments; // @synthesize arguments=_arguments;
@property(readonly, nonatomic) NSArray *locals; // @synthesize locals=_locals;
@property(retain, nonatomic) DBGCodeModule *module; // @synthesize module=_module;
@property(copy, nonatomic) NSNumber *framePointer; // @synthesize framePointer=_framePointer;
@property(copy, nonatomic) NSNumber *frameNumber; // @synthesize frameNumber=_frameNumber;
@property(copy, nonatomic) NSString *instructionPointerAddressString; // @synthesize instructionPointerAddressString=_instructionPointerAddressString;
@property(copy, nonatomic) NSNumber *lineNumber; // @synthesize lineNumber=_lineNumber;
@property(copy, nonatomic) NSURL *fileURL; // @synthesize fileURL=_fileURL;
@property(nonatomic) BOOL hasSymbols; // @synthesize hasSymbols=_hasSymbols;
@property(copy, nonatomic) NSString *name; // @synthesize name=_name;
@property(readonly, nonatomic) DBGThread *parentThread; // @synthesize parentThread=_parentThread;
- (void).cxx_destruct;
- (void)primitiveInvalidate;
- (void)evaluateExpression:(id)arg1 options:(id)arg2 withResultBlock:(CDUnknownBlockType)arg3;
- (void)evaluateExpression:(id)arg1 withResultBlock:(CDUnknownBlockType)arg2;
- (void)requestDataValueForSymbol:(id)arg1 symbolKind:(id)arg2 atLocation:(id)arg3 onQueue:(id)arg4 withResultBlock:(CDUnknownBlockType)arg5;
- (id)dataValuesToInvalidate;
- (void)primitiveSetReturnValueIsValid:(BOOL)arg1;
- (void)primitiveSetReturnValue:(id)arg1;
@property(retain, nonatomic) DBGDataValue *returnValue; // @synthesize returnValue=_returnValue;
- (void)primitiveSetInstructionPointerAddressString:(id)arg1;
@property(readonly, nonatomic) NSString *filePath; // @synthesize filePath=_filePath;
@property(readonly, nonatomic) NSString *displayName; // @synthesize displayName=_displayName;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
- (BOOL)isEqual:(id)arg1;
@property(readonly) IDELaunchSession *launchSession;
@property(readonly, copy) NSString *associatedProcessUUID;
- (id)initWithParentThread:(id)arg1 frameNumber:(id)arg2 framePointer:(id)arg3 name:(id)arg4;
- (BOOL)hasSameDisassemblyURL:(id)arg1;
// Remaining properties
@property(retain) DVTStackBacktrace *creationBacktrace;
@property(readonly, copy) NSString *debugDescription;
@property(readonly) DVTStackBacktrace *invalidationBacktrace;
@property(readonly) Class superclass;
@property(readonly, nonatomic, getter=isValid) BOOL valid;
@end
| {
"content_hash": "b5a32ac90dc69dd9de59f336dc18f3f9",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 169,
"avg_line_length": 53.92307692307692,
"alnum_prop": 0.7912505943889682,
"repo_name": "wczekalski/Distraction-Free-Xcode-plugin",
"id": "1fb801a8360589bf0554d245709e69e2ef60c134",
"size": "4431",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/DebuggerFoundation/DBGStackFrame.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "81011"
},
{
"name": "C++",
"bytes": "588495"
},
{
"name": "DTrace",
"bytes": "1835"
},
{
"name": "Objective-C",
"bytes": "10151940"
},
{
"name": "Ruby",
"bytes": "1105"
}
],
"symlink_target": ""
} |
package com.intellij.openapi.keymap;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.KeyboardShortcut;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.keymap.impl.KeymapImpl;
import com.intellij.openapi.keymap.impl.MacOSDefaultKeymap;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.FactoryMap;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import junit.framework.TestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.*;
/**
* @author cdr
*/
public abstract class KeymapsTestCase extends PlatformTestCase {
private static final boolean OUTPUT_TEST_DATA = false;
public void testDuplicateShortcuts() {
StringBuilder failMessage = new StringBuilder();
Map<String, Map<String, List<String>>> knownDuplicates = getKnownDuplicates();
for (Keymap keymap : KeymapManagerEx.getInstanceEx().getAllKeymaps()) {
String failure = checkDuplicatesInKeymap(keymap, knownDuplicates);
if (failMessage.length() > 0) failMessage.append("\n");
failMessage.append(failure);
}
if (failMessage.length() > 0) {
TestCase.fail(failMessage +
"\n" +
"Please specify 'use-shortcut-of' attribute for your action if it is similar to another action (but it won't appear in Settings/Keymap),\n" +
"reassign shortcut or, if absolutely must, modify the 'known duplicates list'");
}
}
// @formatter:off
@NonNls @SuppressWarnings({"HardCodedStringLiteral"})
private static final Map<String, String[][]> DEFAULT_DUPLICATES = new THashMap<String, String[][]>(){{
put("$default", new String[][] {
{ "ADD", "ExpandTreeNode", "Graph.ZoomIn"},
{ "BACK_SPACE", "EditorBackSpace", "Images.Thumbnails.UpFolder"},
{ "ENTER", "EditorChooseLookupItem", "NextTemplateVariable", "EditorEnter", "Images.Thumbnails.EnterAction",
"PropertyInspectorActions.EditValue", "Console.Execute", "Console.TableResult.EditValue"},
{ "F2", "GotoNextError", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "Console.TableResult.EditValue"},
{ "alt ENTER", "ShowIntentionActions", "Console.TableResult.EditValue", "DatabaseView.PropertiesAction"},
{ "F5", "UML.ApplyCurrentLayout", "CopyElement"},
{ "F7", "NextDiff", "StepInto"},
{ "INSERT", "EditorToggleInsertState", "UsageView.Include", "DomElementsTreeView.AddElement", "DomCollectionControl.Add"},
{ "SUBTRACT", "CollapseTreeNode", "Graph.ZoomOut"},
{ "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection", "EditorTab", "NextTemplateParameter", "ExpandLiveTemplateByTab"},
{ "alt DOWN", "ShowContent", "MethodDown"},
{ "alt F1", "SelectIn", "ProjectViewChangeView"},
{ "alt INSERT", "FileChooser.NewFolder", "Generate", "NewElement"},
{ "control F10", "javaee.UpdateRunningApplication", "liveedit.UpdateRunningApplication"},
{ "control 1", "FileChooser.GotoHome", "GotoBookmark1", "DuplicatesForm.SendToLeft"},
{ "control 2", "FileChooser.GotoProject", "GotoBookmark2", "DuplicatesForm.SendToRight"},
{ "control 3", "GotoBookmark3", "FileChooser.GotoModule"},
{ "control ADD", "ExpandAll", "ExpandRegion"},
{ "control DIVIDE", "CommentByLineComment", "Images.Editor.ActualSize"},
{ "control DOWN", "EditorScrollDown", "EditorLookupDown"},
{ "control ENTER", "EditorSplitLine", "ViewSource", "Console.Execute.Multiline"},
{ "control EQUALS", "ExpandAll", "ExpandRegion"},
{ "control F5", "Refresh", "Rerun"},
{ "control D", "EditorDuplicate", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "control M", "EditorScrollToCenter", "Vcs.ShowMessageHistory"},
{ "control N", "FileChooser.NewFolder", "GotoClass", "GotoChangedFile"},
{ "control P", "FileChooser.TogglePathShowing", "ParameterInfo"},
{ "control R", "Replace", "Console.TableResult.Reload", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "control SLASH", "CommentByLineComment", "Images.Editor.ActualSize"},
{ "control U", "GotoSuperMethod", "CommanderSwapPanels"},
{ "control UP", "EditorScrollUp", "EditorLookupUp"},
{ "control alt A", "ChangesView.AddUnversioned", "Diagram.DeselectAll"},
{ "control alt E", "PerforceDirect.Edit", "Console.History.Browse"},
{ "control alt DOWN", "NextOccurence", "Console.TableResult.NextPage"},
{ "control alt G", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"},
{ "control alt R", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction", "Django.RunManageTaskAction"},
{ "control alt UP", "PreviousOccurence", "Console.TableResult.PreviousPage"},
{ "control alt N", "Inline", "Console.TableResult.SetNull"},
{ "control MINUS", "CollapseAll", "CollapseRegion"},
{ "control PERIOD", "EditorChooseLookupItemDot", "CollapseSelection"},
{ "shift DELETE", "$Cut", "Maven.Uml.Exclude"},
{ "shift ENTER", "EditorStartNewLine", "Console.TableResult.EditValueMaximized"},
{ "shift F4", "Debugger.EditTypeSource", "EditSourceInNewWindow"},
{ "shift F7", "PreviousDiff", "SmartStepInto"},
{ "shift TAB", "PreviousTemplateVariable", "PrevParameter", "EditorUnindentSelection", "PrevTemplateParameter"},
{ "shift alt L", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"},
{ "shift alt T", "tasks.switch", "tasks.switch.toolbar"},
{ "shift control D", "TagDocumentationNavigation", "Diff.ShowSettingsPopup", "Uml.ShowDiff"},
{ "shift control DOWN", "ResizeToolWindowDown", "MoveStatementDown"},
{ "shift control ENTER", "EditorChooseLookupItemCompleteStatement", "EditorCompleteStatement", "Console.Jpa.GenerateSql"},
{ "shift control F10", "Console.Open", "RunClass", "RunTargetAction"},
{ "shift control F8", "ViewBreakpoints", "EditBreakpoint"},
{ "shift control G", "ClassTemplateNavigation", "GoToClass"},
{ "shift control LEFT", "EditorPreviousWordWithSelection", "ResizeToolWindowLeft", },
{ "shift control RIGHT", "EditorNextWordWithSelection", "ResizeToolWindowRight", },
{ "shift control T", "GotoTest", "Images.ShowThumbnails"},
{ "shift control UP", "ResizeToolWindowUp", "MoveStatementUp"},
{ "shift control alt DOWN", "VcsShowNextChangeMarker", "HtmlTableCellNavigateDown"},
{ "shift control alt UP", "VcsShowPrevChangeMarker", "HtmlTableCellNavigateUp"},
{ "shift control alt D", "UML.ShowChanges", "Console.TableResult.CloneColumn"},
{ "shift control U", "ShelveChanges.UnshelveWithDialog", "EditorToggleCase"},
{ "control E", "RecentFiles", "Vcs.ShowMessageHistory"},
{ "control alt Z", "Vcs.RollbackChangedLines", "ChangesView.Revert"},
{ "control TAB", "Switcher", "Diff.FocusOppositePane"},
{ "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"},
});
put("Mac OS X 10.5+", new String[][] {
{ "F5", "CopyElement", "Console.TableResult.Reload", "UML.ApplyCurrentLayout"},
{ "BACK_SPACE", "$Delete", "EditorBackSpace", "Images.Thumbnails.UpFolder"},
{ "shift BACK_SPACE", "EditorBackSpace", "UsageView.Include"},
{ "meta BACK_SPACE", "EditorDeleteLine", "$Delete"},
{ "control DOWN", "ShowContent", "EditorLookupDown", "MethodDown"},
{ "control UP", "EditorLookupUp", "MethodUp"},
{ "control TAB", "Switcher", "Diff.FocusOppositePane"},
{ "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"},
{ "meta R", "Refresh", "Rerun", "Replace", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "control O", "ExportToTextFile", "OverrideMethods", },
{ "control ENTER", "Generate", "NewElement"},
{ "meta 1", "ActivateProjectToolWindow", "FileChooser.GotoHome", "DuplicatesForm.SendToLeft"},
{ "meta 2", "ActivateFavoritesToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"},
{ "meta 3", "ActivateFindToolWindow", "FileChooser.GotoModule"},
{ "meta N", "FileChooser.NewFolder", "Generate", "NewElement"},
{ "meta O", "GotoClass", "GotoChangedFile"},
{ "shift meta G", "ClassTemplateNavigation", "GoToClass", "FindPrevious"},
{ "shift meta LEFT", "EditorLineStartWithSelection", "ResizeToolWindowLeft", },
{ "shift meta RIGHT", "EditorLineEndWithSelection", "ResizeToolWindowRight", },
{ "meta E", "RecentFiles", "Vcs.ShowMessageHistory"},
{ "alt R", "Django.RunManageTaskAction", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction"},
});
put("Mac OS X", new String[][] {
{ "BACK_SPACE", "$Delete", "EditorBackSpace", "Images.Thumbnails.UpFolder"},
{ "control DOWN", "EditorLookupDown", "ShowContent", "MethodDown"},
{ "control UP", "EditorLookupUp", "MethodUp"},
{ "control ENTER", "Generate", "NewElement"},
{ "control F5", "Refresh", "Rerun"},
{ "control TAB", "Switcher", "Diff.FocusOppositePane"},
{ "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"},
{ "meta 1", "ActivateProjectToolWindow", "FileChooser.GotoHome", "DuplicatesForm.SendToLeft"},
{ "meta 2", "ActivateFavoritesToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"},
{ "meta 3", "ActivateFindToolWindow", "FileChooser.GotoModule"},
{ "meta E", "RecentFiles", "Vcs.ShowMessageHistory"},
{ "shift meta LEFT", "EditorLineStartWithSelection", "ResizeToolWindowLeft", },
{ "shift meta RIGHT", "EditorLineEndWithSelection", "ResizeToolWindowRight", },
{ "alt R", "Django.RunManageTaskAction", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction"},
});
put("Emacs", new String[][] {
{ "ENTER", "EditorChooseLookupItem", "NextTemplateVariable", "EditorEnter", "Images.Thumbnails.EnterAction",
"PropertyInspectorActions.EditValue", "Console.Execute", "Console.TableResult.EditValue"},
{ "F2", "GotoNextError", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "Console.TableResult.EditValue"},
{ "alt ENTER", "ShowIntentionActions", "Console.TableResult.EditValue", "DatabaseView.PropertiesAction"},
{ "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection",
"EmacsStyleIndent", "NextTemplateParameter", "ExpandLiveTemplateByTab"},
{ "alt DOWN", "ShowContent", "MethodDown"},
{ "alt SLASH", "CodeCompletion", "HippieCompletion"},
{ "control 1", "FileChooser.GotoHome", "GotoBookmark1", "DuplicatesForm.SendToLeft"},
{ "control 2", "FileChooser.GotoProject", "GotoBookmark2", "DuplicatesForm.SendToRight"},
{ "control 3", "GotoBookmark3", "FileChooser.GotoModule"},
{ "control D", "$Delete", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "control K", "EditorCutLineEnd", "CheckinProject"},
{ "control M", "EditorEnter", "EditorChooseLookupItem", "NextTemplateVariable", "Console.Execute"},
{ "control N", "EditorDown", "FileChooser.NewFolder"},
{ "control P", "EditorUp", "FileChooser.TogglePathShowing"},
{ "control R", "Console.TableResult.Reload", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "FindPrevious"},
{ "control SLASH", "$Undo", "Images.Editor.ActualSize"},
{ "control X", "GotoFile", "SaveAll", "NextTab", "PreviousTab", "CloseContent", "CloseAllEditors", "NextSplitter",
"GotoNextError", "NextProjectWindow", "EditorSwapSelectionBoundaries", "SplitVertically",
"SplitHorizontally", "UnsplitAll", "Switcher", "$SelectAll"},
{ "control UP", "EditorBackwardParagraph", "EditorLookupUp"},
{ "control DOWN", "EditorForwardParagraph", "EditorLookupDown"},
{ "control alt A", "MethodUp", "ChangesView.AddUnversioned", "Diagram.DeselectAll"},
{ "control alt E", "MethodDown", "PerforceDirect.Edit", "Console.History.Browse"},
{ "control alt G", "GotoDeclaration", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"},
{ "control alt S", "ShowSettings", "Find"},
{ "shift DELETE", "$Cut", "Maven.Uml.Exclude"},
{ "shift alt S", "FindUsages", "context.save"},
{ "shift alt G", "GotoChangedFile", "GotoClass", "hg4idea.QGotoFromPatches"},
{ "shift alt P", "ParameterInfo", "hg4idea.QPushAction"},
{ "shift control X", "GotoPreviousError", "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
});
put("Visual Studio", new String[][] {
{ "F5", "Resume", "UML.ApplyCurrentLayout"},
{ "F7", "NextDiff", "CompileDirty"},
{ "alt F2", "ShowBookmarks", "WebOpenInAction"},
{ "alt F8", "ReformatCode", "ForceStepInto", "EvaluateExpression"},
{ "alt INSERT", "FileChooser.NewFolder", "Generate", "NewElement"},
{ "control DIVIDE", "CommentByLineComment", "Images.Editor.ActualSize"},
{ "control COMMA", "GotoClass", "GotoChangedFile"},
{ "control F1", "ExternalJavaDoc", "ShowErrorDescription"},
{ "control F10", "RunToCursor", "javaee.UpdateRunningApplication", "liveedit.UpdateRunningApplication"},
{ "control F5", "Rerun", "Run"},
{ "control N", "FileChooser.NewFolder", "Generate", },
{ "control P", "FileChooser.TogglePathShowing", "Print"},
{ "control SLASH", "CommentByLineComment", "Images.Editor.ActualSize"},
{ "control alt F", "ReformatCode", "IntroduceField"},
{ "shift F1", "QuickJavaDoc", "ExternalJavaDoc"},
{ "shift F12", "RestoreDefaultLayout", "FindUsagesInFile"},
{ "shift F2", "GotoPreviousError", "GotoDeclaration"},
{ "shift control F7", "FindUsagesInFile", "HighlightUsagesInFile"},
{ "shift control I", "ImplementMethods", "QuickImplementations"},
{ "alt F9", "ViewBreakpoints", "EditBreakpoint"},
{ "alt MULTIPLY", "ShowExecutionPoint", "Images.Thumbnails.ToggleRecursive"},
});
put("Default for XWin", new String[][] {
});
put("Default for GNOME", new String[][] {
{ "alt F1", "SelectIn", "ProjectViewChangeView"},
{ "shift alt 1", "SelectIn", "ProjectViewChangeView"},
{ "shift alt 7", "IDEtalk.SearchUserHistory", "FindUsages"},
{ "shift alt LEFT", "PreviousEditorTab", "Back"},
{ "shift alt RIGHT", "NextEditorTab", "Forward"},
});
put("Default for KDE", new String[][] {
{ "control 1", "FileChooser.GotoHome", "ShowErrorDescription", "DuplicatesForm.SendToLeft"},
{ "control 2", "FileChooser.GotoProject", "Stop", "DuplicatesForm.SendToRight"},
{ "control 3", "FindWordAtCaret", "FileChooser.GotoModule"},
{ "control 5", "Refresh", "Rerun"},
{ "shift alt 1", "SelectIn", "ProjectViewChangeView"},
{ "shift alt 7", "IDEtalk.SearchUserHistory", "FindUsages"},
{ "shift alt L", "ReformatCode", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"},
});
put("Eclipse", new String[][] {
{ "F2", "Console.TableResult.EditValue", "QuickJavaDoc"},
{ "alt ENTER", "ShowIntentionActions", "Console.TableResult.EditValue", "DatabaseView.PropertiesAction"},
{ "F5", "UML.ApplyCurrentLayout", "StepInto"},
{ "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection", "EditorTab", "NextTemplateParameter", "ExpandLiveTemplateByTab"},
{ "alt DOWN", "ShowContent", "MoveStatementDown"},
{ "alt HOME", "ViewNavigationBar", "ShowNavBar"},
{ "control F10", "ShowPopupMenu", "javaee.UpdateRunningApplication", "liveedit.UpdateRunningApplication"},
{ "control F11", "Rerun", "ToggleBookmarkWithMnemonic"},
{ "control D", "EditorDeleteLine", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "control N", "ShowPopupMenu", "FileChooser.NewFolder"},
{ "control P", "FileChooser.TogglePathShowing", "Print"},
{ "control R", "RunToCursor", "Console.TableResult.Reload", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "control U", "EvaluateExpression", "CommanderSwapPanels"},
{ "control alt DOWN", "Console.TableResult.NextPage", "EditorDuplicateLines"},
{ "control alt E", "Console.History.Browse", "ExecuteInPyConsoleAction", "PerforceDirect.Edit"},
{ "control alt G", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"},
{ "shift alt D", "hg4idea.QFold", "Debug"},
{ "shift alt G", "RerunTests", "hg4idea.QGotoFromPatches"},
{ "shift alt L", "IntroduceVariable", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"},
{ "shift alt P", "hg4idea.QPushAction", "ImplementMethods"},
{ "shift alt S", "ShowPopupMenu", "context.save"},
{ "shift alt T", "ShowPopupMenu", "tasks.switch", "tasks.switch.toolbar"},
{ "shift control DOWN", "ResizeToolWindowDown", "MethodDown"},
{ "shift control E", "EditSource", "RecentChangedFiles", "Graph.Faces.OpenSelectedPages"},
{ "shift control F6", "PreviousTab", "ChangeTypeSignature"},
{ "shift control F11", "ToggleBookmark", "FocusTracer"},
{ "shift control G", "FindUsagesInFile", "ClassTemplateNavigation", "GoToClass"},
{ "shift control I", "QuickImplementations", "XDebugger.Inspect"},
{ "shift control LEFT", "EditorPreviousWordWithSelection", "ResizeToolWindowLeft", },
{ "shift control RIGHT", "EditorNextWordWithSelection", "ResizeToolWindowRight", },
{ "shift control UP", "ResizeToolWindowUp", "MethodUp"},
{ "shift control alt LEFT", "NextEditorTab", "HtmlTableCellNavigateLeft"},
{ "shift control alt RIGHT", "PreviousEditorTab", "HtmlTableCellNavigateRight"},
{ "shift control K", "Vcs.Push", "FindPrevious"},
{ "shift control X", "EditorToggleCase", "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
{ "shift control U", "ShelveChanges.UnshelveWithDialog", "EditorToggleCase"},
{ "shift control T", "GotoClass", "GotoChangedFile"},
});
put("NetBeans 6.5", new String[][] {
{ "F2", "GotoNextError", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "Console.TableResult.EditValue"},
{ "F4", "RunToCursor", "EditSource"},
{ "F5", "Debugger.ResumeThread", "Resume", "UML.ApplyCurrentLayout"},
{ "alt DOWN", "NextOccurence", "ShowContent"},
{ "alt INSERT", "FileChooser.NewFolder", "Generate", "NewElement"},
{ "control 1", "ActivateProjectToolWindow", "DuplicatesForm.SendToLeft"},
{ "control 2", "ActivateProjectToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"},
{ "control 3", "ActivateProjectToolWindow", "FileChooser.GotoModule"},
{ "control BACK_SPACE", "EditorDeleteToWordStart", "ToggleDockMode"},
{ "control DIVIDE", "CollapseRegionRecursively", "Images.Editor.ActualSize"},
{ "control D", "EditorDuplicate", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "control M", "Vcs.ShowMessageHistory", "Move"},
{ "control R", "RenameElement", "Console.TableResult.Reload", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "control SLASH", "CommentByLineComment", "Images.Editor.ActualSize"},
{ "control U", "EditorToggleCase", "CommanderSwapPanels"},
{ "control O", "GotoClass", "GotoChangedFile"},
{ "control PERIOD", "GotoNextError", "EditorChooseLookupItemDot"},
{ "control alt DOWN", "MethodDown", "Console.TableResult.NextPage"},
{ "control alt UP", "MethodUp", "Console.TableResult.PreviousPage"},
{ "shift F4", "RecentFiles", "Debugger.EditTypeSource", "Vcs.ShowMessageHistory", "EditSourceInNewWindow"},
{ "shift alt F9", "ChooseDebugConfiguration", "ValidateXml", "ValidateJsp"},
{ "shift alt D", "ToggleFloatingMode", "hg4idea.QFold"},
{ "shift control DOWN", "EditorDuplicate", "ResizeToolWindowDown", },
{ "shift control ENTER", "EditorChooseLookupItemCompleteStatement", "EditorCompleteStatement", "Console.Jpa.GenerateSql"},
{ "shift control F7", "HighlightUsagesInFile", "XDebugger.NewWatch"},
{ "shift control UP", "EditorDuplicate", "ResizeToolWindowUp", },
{ "shift control alt P", "Print", "Graph.Print"},
{ "shift control K", "HippieCompletion", "Vcs.Push"},
{ "control alt E", "Console.History.Browse", "ExecuteInPyConsoleAction", "PerforceDirect.Edit"},
{ "TAB", "NextTemplateVariable", "NextParameter", "EditorTab", "EditorChooseLookupItemReplace", "EditorIndentSelection", "NextTemplateParameter", "ExpandLiveTemplateByTab"},
{ "shift TAB", "EditorUnindentSelection", "PreviousTemplateVariable", "PrevParameter", "PrevTemplateParameter"},
});
put("JBuilder", new String[][] {
{ "F2", "EditorTab", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "Console.TableResult.EditValue"},
{ "F5", "ToggleBreakpointEnabled", "UML.ApplyCurrentLayout"},
{ "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection", "EmacsStyleIndent", "NextTemplateParameter", "ExpandLiveTemplateByTab"},
{ "control F6", "PreviousEditorTab", "PreviousTab", },
{ "control M", "Vcs.ShowMessageHistory", "OverrideMethods", },
{ "control N", "FileChooser.NewFolder", "GotoClass", "GotoChangedFile"},
{ "control P", "FileChooser.TogglePathShowing", "FindInPath"},
{ "shift control A", "SaveAll", "GotoAction"},
{ "shift control E", "RecentChangedFiles", "ExtractMethod"},
{ "shift control ENTER", "EditorChooseLookupItemCompleteStatement", "FindUsages", "Console.Jpa.GenerateSql"},
{ "shift control F6", "NextTab", "ChangeTypeSignature"},
{ "shift control G", "GotoSymbol", "ClassTemplateNavigation", "GoToClass"},
{ "control SUBTRACT", "CollapseAll", "CollapseRegion"},
{ "shift control X", "EditorToggleShowWhitespaces", "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
});
put("Eclipse (Mac OS X)", new String[][] {
{ "meta BACK_SPACE", "EditorDeleteToWordStart", "$Delete"},
{ "F2", "Console.TableResult.EditValue", "QuickJavaDoc"},
{ "F3", "GotoDeclaration", "EditSource"},
{ "F5", "StepInto", "Console.TableResult.Reload", "UML.ApplyCurrentLayout"},
{ "control PERIOD", "EditorChooseLookupItemDot", "HippieCompletion"},
{ "meta 1", "FileChooser.GotoHome", "ShowIntentionActions", "DuplicatesForm.SendToLeft"},
{ "meta 3", "FileChooser.GotoModule", "GotoAction"},
{ "meta D", "EditorDeleteLine", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "meta I", "DatabaseView.PropertiesAction", "AutoIndentLines"},
{ "meta P", "FileChooser.TogglePathShowing", "Print"},
{ "meta R", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "RunToCursor"},
{ "meta U", "CommanderSwapPanels", "EvaluateExpression"},
{ "meta W", "CloseContent", "CloseActiveTab"},
{ "shift meta T", "GotoClass", "GotoChangedFile"},
{ "meta alt DOWN", "Console.TableResult.NextPage", "EditorDuplicateLines"},
{ "shift meta F11", "Run", "FocusTracer"},
{ "shift meta G", "ClassTemplateNavigation", "GoToClass", "FindUsages"},
{ "shift meta K", "Vcs.Push", "FindPrevious"},
{ "shift meta X", "EditorToggleCase", "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
{ "shift meta U", "FindUsagesInFile", "ShelveChanges.UnshelveWithDialog"},
{ "control shift alt Z", "Vcs.RollbackChangedLines", "ChangesView.Revert"},
});
}};
// @formatter:on
private Map<String, Map<String, List<String>>> getKnownDuplicates() {
Map<String, Map<String, List<String>>> result = new LinkedHashMap<String, Map<String, List<String>>>();
collectKnownDuplicates(result);
return result;
}
protected void collectKnownDuplicates(Map<String, Map<String, List<String>>> result) {
appendKnownDuplicates(result, DEFAULT_DUPLICATES);
}
protected static void appendKnownDuplicates(Map<String, Map<String, List<String>>> result, Map<String, String[][]> duplicates) {
for (Map.Entry<String, String[][]> eachKeymap : duplicates.entrySet()) {
String keymapName = eachKeymap.getKey();
Map<String, List<String>> mapping = result.get(keymapName);
if (mapping == null) {
result.put(keymapName, mapping = new LinkedHashMap<String, List<String>>());
}
for (String[] shortcuts : eachKeymap.getValue()) {
TestCase.assertTrue("known duplicates list entry for '" + keymapName + "' must not contain empty array",
shortcuts.length > 0);
TestCase.assertTrue("known duplicates list entry for '" + keymapName + "', shortcut '" + shortcuts[0] +
"' must contain at least two conflicting action ids",
shortcuts.length > 2);
mapping.put(shortcuts[0], ContainerUtil.newArrayList(shortcuts, 1, shortcuts.length));
}
}
}
@NotNull
@SuppressWarnings({"HardCodedStringLiteral"})
private static String checkDuplicatesInKeymap(Keymap keymap, Map<String, Map<String, List<String>>> allKnownDuplicates) {
Set<Shortcut> shortcuts = new LinkedHashSet<Shortcut>();
Set<String> aids = new THashSet<String>(Arrays.asList(keymap.getActionIds()));
removeBoundActionIds(aids);
nextId:
for (String id : aids) {
Map<String, List<String>> knownDuplicates = allKnownDuplicates.get(keymap.getName());
if (knownDuplicates != null) {
for (List<String> actionsMapping : knownDuplicates.values()) {
for (String eachAction : actionsMapping) {
if (eachAction.equals(id)) continue nextId;
}
}
}
for (Shortcut shortcut : keymap.getShortcuts(id)) {
if (!(shortcut instanceof KeyboardShortcut)) {
continue;
}
shortcuts.add(shortcut);
}
}
List<Shortcut> sorted = new ArrayList<Shortcut>(shortcuts);
Collections.sort(sorted, new Comparator<Shortcut>() {
@Override
public int compare(Shortcut o1, Shortcut o2) {
return getText(o1).compareTo(getText(o2));
}
});
if (OUTPUT_TEST_DATA) {
System.out.println("put(\"" + keymap.getName() + "\", new String[][] {");
}
else {
System.out.println(keymap.getName());
}
StringBuilder failMessage = new StringBuilder();
for (Shortcut shortcut : sorted) {
if (!(shortcut instanceof KeyboardShortcut)) {
continue;
}
Set<String> ids = new THashSet<String>(Arrays.asList(keymap.getActionIds(shortcut)));
removeBoundActionIds(ids);
if (ids.size() == 1) continue;
Keymap parent = keymap.getParent();
if (parent != null) {
// ignore duplicates from default keymap
boolean differFromParent = false;
for (String id : ids) {
Shortcut[] here = keymap.getShortcuts(id);
Shortcut[] there = parent.getShortcuts(id);
if (keymap.getName().startsWith("Mac")) convertMac(there);
if (!new HashSet<Shortcut>(Arrays.asList(here)).equals(new HashSet<Shortcut>(Arrays.asList(there)))) {
differFromParent = true;
break;
}
}
if (!differFromParent) continue;
}
String def = "{ "
+ "\"" + getText(shortcut) + "\","
+ StringUtil.repeatSymbol(' ', 25- getText(shortcut).length())
+ StringUtil.join(ids, StringUtil.QUOTER, ", ")
+ "},";
if (OUTPUT_TEST_DATA) {
System.out.println(def);
}
else {
if (failMessage.length() == 0) {
failMessage.append("Shortcut '").append(getText(shortcut)).append("' conflicts found in keymap '")
.append(keymap.getName()).append("':\n");
}
failMessage.append(def).append("\n");
}
}
if (OUTPUT_TEST_DATA) {
System.out.println("});");
}
return failMessage.toString();
}
private static void removeBoundActionIds(Set<String> aids) {
// explicitly bound to another action
for (Iterator<String> it = aids.iterator(); it.hasNext();) {
String id = it.next();
String sourceId = KeymapManagerEx.getInstanceEx().getActionBinding(id);
if (sourceId != null) {
it.remove();
}
}
}
@NonNls private static final Set<String> unknownActionIds = new THashSet<String>(Arrays.asList(
"ActivateChangesToolWindow", "ActivateFavoritesToolWindow", "ActivateCommanderToolWindow", "ActivateDebugToolWindow", "ActivateFindToolWindow",
"ActivateHierarchyToolWindow", "ActivateMessagesToolWindow", "ActivateProjectToolWindow", "ActivateRunToolWindow",
"ActivateStructureToolWindow", "ActivateTODOToolWindow", "ActivateWebToolWindow","ActivatePaletteToolWindow",
"ActivateTerminalToolWindow",
"IDEtalk.SearchUserHistory", "IDEtalk.SearchUserHistory", "IDEtalk.Rename",
""
));
protected void collectUnknownActions(Set<String> result) {
result.addAll(unknownActionIds);
}
public void testValidActionIds() {
THashSet<String> unknownActions = new THashSet<String>();
collectUnknownActions(unknownActions);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
Map<String, List<String>> missingActions = new FactoryMap<String, List<String>>() {
@Override
protected Map<String, List<String>> createMap() {
return new LinkedHashMap<String, List<String>>();
}
@Nullable
@Override
protected List<String> create(String key) {
return new ArrayList<String>();
}
};
for (Keymap keymap : KeymapManagerEx.getInstanceEx().getAllKeymaps()) {
String[] ids = keymap.getActionIds();
Arrays.sort(ids);
Set<String> noDuplicates = new LinkedHashSet<String>(Arrays.asList(ids));
TestCase.assertEquals(new ArrayList<String>(Arrays.asList(ids)), new ArrayList<String>(noDuplicates));
for (String cid : ids) {
if (unknownActions.contains(cid)) continue;
AnAction action = ActionManager.getInstance().getAction(cid);
if (action == null) {
if (OUTPUT_TEST_DATA) {
System.out.print("\""+cid+"\", ");
}
else {
missingActions.get(keymap.getName()).add(cid);
}
}
}
}
List<String> reappearedAction = new ArrayList<String>();
for (String id : unknownActions) {
AnAction action = ActionManager.getInstance().getAction(id);
if (action != null) {
reappearedAction.add(id);
}
}
if (!missingActions.isEmpty() || !reappearedAction.isEmpty()) {
StringBuilder message = new StringBuilder();
if (!missingActions.isEmpty()) {
for (Map.Entry<String, List<String>> keymapAndActions : missingActions.entrySet()) {
message.append("Unknown actions in keymap ").append(keymapAndActions.getKey()).append(", add them to unknown actions list:\n");
for (String action : keymapAndActions.getValue()) {
message.append("\"").append(action).append("\",").append("\n");
}
}
}
if (!reappearedAction.isEmpty()) {
message.append("The following actions have reappeared, remove them from unknown action list:\n");
for (String action : reappearedAction) {
message.append(action).append("\n");
}
}
fail("\n" + message);
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public void testIdsListIsConsistent() {
Map<String, Map<String, List<String>>> duplicates = getKnownDuplicates();
THashSet<String> allMaps =
new THashSet<String>(ContainerUtil.map(KeymapManagerEx.getInstanceEx().getAllKeymaps(), new Function<Keymap, String>() {
@Override
public String fun(Keymap keymap) {
return keymap.getName();
}
}));
TestCase.assertTrue("Modify 'known duplicates list' test data. Keymaps were added: " +
ContainerUtil.subtract(allMaps, duplicates.keySet()),
ContainerUtil.subtract(allMaps, duplicates.keySet()).isEmpty()
);
TestCase.assertTrue("Modify 'known duplicates list' test data. Keymaps were removed: " +
ContainerUtil.subtract(duplicates.keySet(), allMaps),
ContainerUtil.subtract(duplicates.keySet(), allMaps).isEmpty()
);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
Map<Keymap, List<Shortcut>> reassignedShortcuts = new FactoryMap<Keymap, List<Shortcut>>() {
@Override
protected Map<Keymap, List<Shortcut>> createMap() {
return new LinkedHashMap<Keymap, List<Shortcut>>();
}
@Nullable
@Override
protected List<Shortcut> create(Keymap key) {
return new ArrayList<Shortcut>();
}
};
for (String name : duplicates.keySet()) {
Keymap keymap = KeymapManagerEx.getInstanceEx().getKeymap(name);
TestCase.assertNotNull("KeyMap " + name + " not found", keymap);
Map<String, List<String>> duplicateIdsList = duplicates.get(name);
Set<String> mentionedShortcuts = new THashSet<String>();
for (Map.Entry<String, List<String>> shortcutMappings : duplicateIdsList.entrySet()) {
String shortcutString = shortcutMappings.getKey();
if (!mentionedShortcuts.add(shortcutString)) {
TestCase.fail("Shortcut '" + shortcutString + "' duplicate in keymap '" + keymap + "'. Please modify 'known duplicates list'");
}
Shortcut shortcut = parse(shortcutString);
String[] ids = keymap.getActionIds(shortcut);
Set<String> actualSc = new HashSet<String>(Arrays.asList(ids));
removeBoundActionIds(actualSc);
Set<String> expectedSc = new HashSet<String>(shortcutMappings.getValue());
for (String s : actualSc) {
if (!expectedSc.contains(s)) {
reassignedShortcuts.get(keymap).add(shortcut);
}
}
for (String s : expectedSc) {
if (!actualSc.contains(s)) {
System.out.println("Expected action '" + s + "' does not reassign shortcut " + getText(shortcut) + " in keymap " + keymap + " or is not registered");
}
}
}
}
if (!reassignedShortcuts.isEmpty()) {
StringBuilder message = new StringBuilder();
for (Map.Entry<Keymap, List<Shortcut>> keymapToShortcuts : reassignedShortcuts.entrySet()) {
Keymap keymap = keymapToShortcuts.getKey();
message.append("The following shortcuts was reassigned in keymap ").append(keymap.getName())
.append(". Please modify known duplicates list:\n");
for (Shortcut eachShortcut : keymapToShortcuts.getValue()) {
message.append(" { ").append(StringUtil.wrapWithDoubleQuote(getText(eachShortcut))).append(",\t")
.append(StringUtil.join(keymap.getActionIds(eachShortcut), new Function<String, String>() {
@Override
public String fun(String s) {
return StringUtil.wrapWithDoubleQuote(s);
}
}, ", "))
.append("},\n");
}
}
TestCase.fail("\n" + message.toString());
}
}
private static Shortcut parse(String s) {
String[] sc = s.split(",");
KeyStroke fst = ActionManagerEx.getKeyStroke(sc[0]);
assert fst != null : s;
KeyStroke snd = null;
if (sc.length == 2) {
snd = ActionManagerEx.getKeyStroke(sc[1]);
}
return new KeyboardShortcut(fst, snd);
}
private static String getText(Shortcut shortcut) {
if (shortcut instanceof KeyboardShortcut) {
KeyStroke fst = ((KeyboardShortcut)shortcut).getFirstKeyStroke();
String s = KeymapImpl.getKeyShortcutString(fst);
KeyStroke snd = ((KeyboardShortcut)shortcut).getSecondKeyStroke();
if (snd != null) {
s += "," + KeymapImpl.getKeyShortcutString(snd);
}
return s;
}
return KeymapUtil.getShortcutText(shortcut);
}
private static void convertMac(Shortcut[] there) {
for (int i = 0; i < there.length; i++) {
there[i] = MacOSDefaultKeymap.convertShortcutFromParent(there[i]);
}
}
private static final Set<String> LINUX_KEYMAPS = ContainerUtil.newHashSet("Default for XWin", "Default for GNOME", "Default for KDE");
public void testLinuxShortcuts() {
for (Keymap keymap : KeymapManagerEx.getInstanceEx().getAllKeymaps()) {
if (LINUX_KEYMAPS.contains(keymap.getName())) {
checkLinuxKeymap(keymap);
}
}
}
private static void checkLinuxKeymap(final Keymap keymap) {
for (String actionId : keymap.getActionIds()) {
for (Shortcut shortcut : keymap.getShortcuts(actionId)) {
if (shortcut instanceof KeyboardShortcut) {
checkCtrlAltFn(keymap, shortcut, ((KeyboardShortcut)shortcut).getFirstKeyStroke());
checkCtrlAltFn(keymap, shortcut, ((KeyboardShortcut)shortcut).getSecondKeyStroke());
}
}
}
}
private static void checkCtrlAltFn(final Keymap keymap, final Shortcut shortcut, final KeyStroke stroke) {
if (stroke != null) {
final int modifiers = stroke.getModifiers();
final int keyCode = stroke.getKeyCode();
if (KeyEvent.VK_F1 <= keyCode && keyCode <= KeyEvent.VK_F12 &&
(modifiers & InputEvent.CTRL_MASK) != 0 && (modifiers & InputEvent.ALT_MASK) != 0 && (modifiers & InputEvent.SHIFT_MASK) == 0) {
final String message = "Invalid shortcut '" + shortcut + "' for action(s) " + Arrays.asList(keymap.getActionIds(shortcut)) +
" in keymap '" + keymap.getName() + "' " +
"(Ctrl-Alt-Fn shortcuts switch Linux virtual terminals (causes newbie panic), " +
"so either assign another shortcut, or remove it; see Keymap_XWin.xml for reference).";
TestCase.fail(message);
}
}
}
}
| {
"content_hash": "ce8c7463eaff9440058adb31086b1db0",
"timestamp": "",
"source": "github",
"line_count": 706,
"max_line_length": 205,
"avg_line_length": 59.17847025495751,
"alnum_prop": 0.610818573480134,
"repo_name": "orekyuu/intellij-community",
"id": "bd53a43138a49f6f5a08aaf4ab9c97e130a143f8",
"size": "42380",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "platform/testFramework/testSrc/com/intellij/openapi/keymap/KeymapsTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "63518"
},
{
"name": "C",
"bytes": "214180"
},
{
"name": "C#",
"bytes": "1538"
},
{
"name": "C++",
"bytes": "190455"
},
{
"name": "CSS",
"bytes": "111474"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Cucumber",
"bytes": "14382"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "FLUX",
"bytes": "57"
},
{
"name": "Groff",
"bytes": "35232"
},
{
"name": "Groovy",
"bytes": "2269171"
},
{
"name": "HTML",
"bytes": "1737110"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "150036769"
},
{
"name": "JavaScript",
"bytes": "125292"
},
{
"name": "Kotlin",
"bytes": "914570"
},
{
"name": "Lex",
"bytes": "166177"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "87464"
},
{
"name": "Objective-C",
"bytes": "28878"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6570"
},
{
"name": "Python",
"bytes": "21639462"
},
{
"name": "Ruby",
"bytes": "1213"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "63606"
},
{
"name": "Smalltalk",
"bytes": "64"
},
{
"name": "TeX",
"bytes": "60798"
},
{
"name": "TypeScript",
"bytes": "6152"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
module app.userManagement {
angular.module("app.userManagement", [
"app.common"
]).config([
"$componentLoaderProvider",
"apiEndpointProvider",
"featureComponentsMappingsProvider",
"routesProvider",
config
]);
function config($componentLoaderProvider: any,
apiEndpointProvider: common.IApiEndpointProvider,
featureComponentsMappingsProvider: common.IFeatureComponentsMappingsProvider,
routesProvider: common.IRoutesProvider) {
featureComponentsMappingsProvider.mappings.push(
{
feature: "userManagement",
components: [
"createAccount",
"myAccount",
"myProfile",
"personalization",
"profile"]
});
routesProvider.configure([
{ path: '/', redirectTo: '/login' },
{ path: '/createAccount', component: 'createAccount' },
{ path: '/myAccount', component: 'myAccount' },
{ path: '/myProfile', component: 'myProfile' },
{ path: '/personalization', component: 'personalization' }
]);
apiEndpointProvider.configure("/api","userManagement");
}
} | {
"content_hash": "f20a211d7b237be4cb810633314add28",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 85,
"avg_line_length": 30.547619047619047,
"alnum_prop": 0.5580670303975058,
"repo_name": "QuinntyneBrown/LearningOriented",
"id": "0c190bd03ae3eb5e2df55afa8a958c75bae74b1b",
"size": "1285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LearningOriented/src/app/userManagement/userManagement.module.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "99"
},
{
"name": "C#",
"bytes": "34445"
},
{
"name": "CSS",
"bytes": "5015"
},
{
"name": "HTML",
"bytes": "3758"
},
{
"name": "JavaScript",
"bytes": "727896"
},
{
"name": "TypeScript",
"bytes": "33686"
}
],
"symlink_target": ""
} |
namespace LayoutFarm.TestTextFlow
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 337);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(309, 20);
this.textBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(327, 337);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(94, 32);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(327, 375);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(94, 32);
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(804, 449);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}
| {
"content_hash": "45fcd3aefee0c94442e16d382492eb33",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 107,
"avg_line_length": 36.61904761904762,
"alnum_prop": 0.5520156046814044,
"repo_name": "LayoutFarm/PixelFarm",
"id": "9b9732a325f161e1d49ed30e38de93441f6e9999",
"size": "3078",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Tests/TestTextFlow/Form1.Designer.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C#",
"bytes": "16663734"
},
{
"name": "GLSL",
"bytes": "15555"
},
{
"name": "Smalltalk",
"bytes": "239"
}
],
"symlink_target": ""
} |
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import absolute_import
import os
import sys
import unittest
import lib_openshift
from lib_openshift.rest import ApiException
from lib_openshift.models.v1_role_binding import V1RoleBinding
class TestV1RoleBinding(unittest.TestCase):
""" V1RoleBinding unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1RoleBinding(self):
"""
Test V1RoleBinding
"""
model = lib_openshift.models.v1_role_binding.V1RoleBinding()
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "e27ac799f08c4ab04bfe005b4a03e905",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 76,
"avg_line_length": 24.568627450980394,
"alnum_prop": 0.6927374301675978,
"repo_name": "detiber/lib_openshift",
"id": "038c6460f87713748023f91017bd31c73e13852f",
"size": "1270",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/test_v1_role_binding.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "61305"
},
{
"name": "Python",
"bytes": "6202851"
},
{
"name": "Shell",
"bytes": "2825"
}
],
"symlink_target": ""
} |
'use strict';
var _inherits = require('babel-runtime/helpers/inherits')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _extends = require('babel-runtime/helpers/extends')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
exports.__esModule = true;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = require('./utils/ValidComponentChildren');
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var ListGroup = (function (_React$Component) {
_inherits(ListGroup, _React$Component);
function ListGroup() {
_classCallCheck(this, ListGroup);
_React$Component.apply(this, arguments);
}
ListGroup.prototype.render = function render() {
var _this = this;
var items = _utilsValidComponentChildren2['default'].map(this.props.children, function (item, index) {
return _react.cloneElement(item, { key: item.key ? item.key : index });
});
var childrenAnchors = false;
if (!this.props.children) {
return this.renderDiv(items);
} else {
_react2['default'].Children.forEach(this.props.children, function (child) {
if (_this.isAnchor(child.props)) {
childrenAnchors = true;
}
});
}
if (childrenAnchors) {
return this.renderDiv(items);
} else {
return this.renderUL(items);
}
};
ListGroup.prototype.isAnchor = function isAnchor(props) {
return props.href || props.onClick;
};
ListGroup.prototype.renderUL = function renderUL(items) {
var listItems = _utilsValidComponentChildren2['default'].map(items, function (item, index) {
return _react.cloneElement(item, { listItem: true });
});
return _react2['default'].createElement(
'ul',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, 'list-group') }),
listItems
);
};
ListGroup.prototype.renderDiv = function renderDiv(items) {
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, 'list-group') }),
items
);
};
return ListGroup;
})(_react2['default'].Component);
ListGroup.propTypes = {
className: _react2['default'].PropTypes.string,
id: _react2['default'].PropTypes.string
};
exports['default'] = ListGroup;
module.exports = exports['default']; | {
"content_hash": "97702af08dc86789672577250b22af31",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 106,
"avg_line_length": 27.88421052631579,
"alnum_prop": 0.6715741789354474,
"repo_name": "principle-systems/react-shopping-cart-starter-kit",
"id": "565e5d7d199fbb83de3c7438129548e7c6a17496",
"size": "2649",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/react-bootstrap/lib/ListGroup.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "11281"
}
],
"symlink_target": ""
} |
package jj.http.client;
import java.util.List;
import jj.configuration.Default;
import jj.configuration.DefaultProvider;
/**
* @author jason
*
*/
public interface HttpClientConfiguration {
/**
* the ip address of the local interface to use for http client communication
* if left null, will use the wildcard (all local interfaces)
* if the string "loopback" will use the loopback address
* otherwise it has to be a valid ipv4 or ipv6 address
*/
String localClientAddress();
/**
* the ip address of the local interface to use for name resolution
* if left null, will use the wildcard (all local interfaces)
* if the string "loopback" will use the loopback address
* otherwise it has to be a valid ipv4 or ipv6 address
*/
String localNameserverAddress();
/**
* 1 or more nameservers to use for domain name resolution. by default, attempts
* to read the system configuration. if that cannot be found, falls back to
* OpenDNS on 208.67.222.222 and 208.67.220.220
* all addresses must be valid ipv4 or ipv6 addresses
*/
@DefaultProvider(NameServersDefaultProvider.class)
List<String> nameservers();
@Default("JibbrJabbr") // hmmm want interpolations here. maybe
String userAgent();
}
| {
"content_hash": "80875b581d8197ae8be391ce57c5000c",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 81,
"avg_line_length": 29.38095238095238,
"alnum_prop": 0.7341977309562399,
"repo_name": "heinousjay/JibbrJabbr",
"id": "be0f9f79b9b40580ab87e328272641d839a79180",
"size": "1832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kernel/src/main/java/jj/http/client/HttpClientConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "22391"
},
{
"name": "HTML",
"bytes": "10972"
},
{
"name": "Java",
"bytes": "1483097"
},
{
"name": "JavaScript",
"bytes": "702814"
}
],
"symlink_target": ""
} |
import os
# Variables
__author__ = "Rodrigo 'ItsPaper' Muñoz"
__authoremail__ = "Rodrigo.mcuadrada@gmail.com"
__version__ = "Alpha"
# Functions
def welcome():
print("Welcome to IMES: Itspaper's Message Encryption System!")
print("Made by: {}. You are using Version: {}".format(__author__, __version__))
def fetch():
os.system("cls")
filename = input("Please enter file name...") + ".txt"
print("Fetching file...")
os.system("pause")
try:
file = open("{}".format(filename), "r")
file.close()
print("{} fetched!".format(filename))
os.system("pause")
return filename
except FileNotFoundError:
print("{} does not exist...".format(filename))
os.system("pause")
def contact_us():
print("Thank you for sending me your feedback at {}.".format(__authoremail__))
def grab_text(x):
file = open("{}".format(x))
txt = file.read()
file.close()
return txt
def replace(char):
if char == " ":
return 0
elif char.isalpha():
return ord(char.lower()) - 96
elif char.isnumeric() and int(char) < 10:
return chr(int(char) + 65)
def new_file(x, y):
try:
file = open("{}".format(x), "r")
file.close()
os.remove("{}".format(x))
new_file(x, y)
except FileNotFoundError:
file = open("{}".format(x), "w")
file.write("THIS FILE HAS BEEN ENCRYPTED USING IMES\n")
file.write(y)
file.close()
def get_code():
os.system("cls")
code = input("Please enter encryption code...")
if code == "":
os.system("cls")
code = input("Code must be at least one Character long...")
return code
def check_int(x):
# This Function Checks if character is a number or a letter.
try:
int(x)
y = True
except ValueError:
y = False
finally:
return y
def encrypt():
filename = fetch()
code = get_code()
original_code = len(code)
code = original_code
code_changed = 0
replaced = 0
if filename is None:
return
txt = grab_text(filename)
etext = ""
for char in txt:
# For Each Character in text file replace character
x = replace(char)
y = check_int(x)
if y is True:
x += code
while x > 26:
x -= 26
etext += str(x) + " "
"""Replaces each character in the text
with its corresponding number from the alphabet +
the number of letters in the code"""
replaced += 1
if replaced == original_code:
code = code + original_code
code_changed += 1
replaced = 0
"""After the amount of replaced letters is the same
of the number of letters in the code the number of letters
in the code doubles"""
if code_changed == original_code:
"""If the code has changed the same number of times
than the number of letters in the original_code
then the code goes back to its original form..."""
code = original_code
code_changed = 0
replaced = 0
imes_file = "IMES {}".format(filename)
new_file(imes_file, etext)
def find_char(x):
e_char = ""
txt = []
for char in x:
if char == " ":
txt.append(e_char)
e_char = ""
continue
e_char += char
return txt
def check_encrypted(x):
file = open("{}".format(x), "r")
x = file.readline()
if x == "THIS FILE HAS BEEN ENCRYPTED USING IMES\n":
y = file.read()
file.close()
return True, y
else:
print("File is Not encrypted!")
os.system("pause")
return False, False
def decrypt_char(char):
if char == 1:
dchar = "A"
elif char == 2:
dchar = "B"
elif char == 3:
dchar = "C"
elif char == 4:
dchar = "D"
elif char == 5:
dchar = "E"
elif char == 6:
dchar = "F"
elif char == 7:
dchar = "G"
elif char == 8:
dchar = "H"
elif char == 9:
dchar = "I"
elif char == 10:
dchar = "J"
elif char == 11:
dchar = "K"
elif char == 12:
dchar = "L"
elif char == 13:
dchar = "M"
elif char == 14:
dchar = "N"
elif char == 15:
dchar = "O"
elif char == 16:
dchar = "P"
elif char == 17:
dchar = "Q"
elif char == 18:
dchar = "R"
elif char == 19:
dchar = "S"
elif char == 20:
dchar = "T"
elif char == 21:
dchar = "U"
elif char == 22:
dchar = "V"
elif char == 23:
dchar = "W"
elif char == 24:
dchar = "X"
elif char == 25:
dchar = "Y"
elif char == 26:
dchar = "Z"
elif char == "A":
dchar = "0"
elif char == "B":
dchar = "1"
elif char == "C":
dchar = "2"
elif char == "D":
dchar = "3"
elif char == "E":
dchar = "4"
elif char == "F":
dchar = "5"
elif char == "G":
dchar = "6"
elif char == "H":
dchar = "7"
elif char == "I":
dchar = "8"
elif char == "J":
dchar = "9"
elif char == 0:
dchar = " "
else:
dchar = str(char)
return dchar
def decrypt():
filename = fetch()
code = get_code()
original_code = len(code)
code = original_code
replaced = 0
code_changed = 0
decrypt_code = []
if filename is None:
return
is_encrypted, txt = check_encrypted(filename)
if is_encrypted is False:
return
txt = find_char(txt)
for instance in txt:
is_int = check_int(instance)
if is_int is False:
decrypt_code.append(instance)
continue
else:
char = int(instance)
char -= code
replaced += 1
if replaced == original_code:
code += original_code
code_changed += 1
replaced = 0
if code_changed == original_code:
code = original_code
code_changed = 0
replaced = 0
if char < 0:
char += 26
decrypt_code.append(char)
dtxt = ""
for char in decrypt_code:
dchar = decrypt_char(char)
dtxt += dchar
new_filename = input("Please enter the name for the new file...") + ".txt"
while new_filename == ".txt":
new_filename = input("Please enter a valid file name...") + ".txt"
file = open("{}".format(new_filename), "w")
file.write(dtxt)
def menu():
os.system("cls")
welcome()
print("1.Encrypt File")
print("2.Decrypt file")
print("3.Send Feedback to author")
menusel = input("Please enter the number of the option, or type exit to quit...")
is_int = check_int(menusel)
if is_int is True:
if int(menusel) == 1:
encrypt()
elif int(menusel) == 2:
decrypt()
elif int(menusel) == 3:
contact_us()
elif menusel == "EXIT" or menusel == "exit" or menusel == "Exit":
exit()
else:
print("Option not recognized! Please try again!")
os.system("pause")
# Main Code
while True:
menu()
| {
"content_hash": "42284388206d72dbb4274f097171f2c6",
"timestamp": "",
"source": "github",
"line_count": 303,
"max_line_length": 85,
"avg_line_length": 24.31023102310231,
"alnum_prop": 0.5054303556882976,
"repo_name": "ItsPapermunoz/IMES",
"id": "13cc116f7a880c8288ca17052b5e0f27cee1cdd9",
"size": "7378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/IMES.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8241"
},
{
"name": "TeX",
"bytes": "42181"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>qarith: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.2 / qarith - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
qarith
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-24 11:01:54 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-24 11:01:54 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/qarith"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/QArith"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [
"keyword: Q"
"keyword: arithmetic"
"keyword: rational numbers"
"keyword: setoid"
"keyword: ring"
"category: Mathematics/Arithmetic and Number Theory/Rational numbers"
"category: Miscellaneous/Extracted Programs/Arithmetic"
]
authors: [ "Pierre Letouzey" ]
bug-reports: "https://github.com/coq-contribs/qarith/issues"
dev-repo: "git+https://github.com/coq-contribs/qarith.git"
synopsis: "A Library for Rational Numbers (QArith)"
description: """
This contribution is a proposition of a library formalizing
rational number in Coq."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/qarith/archive/v8.8.0.tar.gz"
checksum: "md5=ee44f341443451374cd1610fd6133bc9"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-qarith.8.8.0 coq.8.13.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.2).
The following dependencies couldn't be met:
- coq-qarith -> coq < 8.9~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-qarith.8.8.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "851ee70e2c4f38491ed5e2b8a2c65945",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 159,
"avg_line_length": 40.75581395348837,
"alnum_prop": 0.5439372325249643,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "cbcc631bdc82c8c0a50b9e5d766469ace151b885",
"size": "7035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.13.2/qarith/8.8.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example9-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
</head>
<body ng-app="">
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</body>
</html> | {
"content_hash": "d31734828be9220012a0ecb68e447eb6",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 89,
"avg_line_length": 22.55,
"alnum_prop": 0.647450110864745,
"repo_name": "johncol/angularjs",
"id": "4ce973f9a128d7361ea8ff9bb51586728648734b",
"size": "451",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "angular/docs/examples/example-example9/index-production.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "49442"
},
{
"name": "JavaScript",
"bytes": "199417"
}
],
"symlink_target": ""
} |
<?php
defined('_JEXEC') or die;
JHtml::_('behavior.keepalive');
?>
<form action="<?php echo JRoute::_('index.php', true, $params->get('usesecure')); ?>" method="post" id="form-login">
<fieldset class="loginform">
<label id="mod-login-username-lbl" for="mod-login-username"><?php echo JText::_('JGLOBAL_USERNAME'); ?></label>
<input name="username" id="mod-login-username" type="text" size="15" autofocus="true" />
<label id="mod-login-password-lbl" for="mod-login-password"><?php echo JText::_('JGLOBAL_PASSWORD'); ?></label>
<input name="passwd" id="mod-login-password" type="password" size="15" />
<?php if (count($twofactormethods) > 1): ?>
<div class="control-group">
<div class="controls">
<label for="mod-login-secretkey">
<?php echo JText::_('JGLOBAL_SECRETKEY'); ?>
</label>
<input name="secretkey" autocomplete="off" tabindex="3" id="mod-login-secretkey" type="text" class="input-medium" size="15"/>
</div>
</div>
<?php endif; ?>
<?php if (!empty ($langs)) : ?>
<label id="mod-login-language-lbl" for="lang"><?php echo JText::_('MOD_LOGIN_LANGUAGE'); ?></label>
<?php echo $langs; ?>
<?php endif; ?>
<div class="clr"></div>
<div class="button-holder">
<div class="button1">
<div class="next">
<a href="#" onclick="document.getElementById('form-login').submit();">
<?php echo JText::_('MOD_LOGIN_LOGIN'); ?></a>
</div>
</div>
</div>
<div class="clr"></div>
<input type="submit" class="hidebtn" value="<?php echo JText::_('MOD_LOGIN_LOGIN'); ?>" />
<input type="hidden" name="option" value="com_login" />
<input type="hidden" name="task" value="login" />
<input type="hidden" name="return" value="<?php echo $return; ?>" />
<?php echo JHtml::_('form.token'); ?>
</fieldset>
</form>
| {
"content_hash": "e1ab40d1f4ad3330eed546bd964b0d86",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 130,
"avg_line_length": 36.714285714285715,
"alnum_prop": 0.6086714841578654,
"repo_name": "Bluemit/EDirect",
"id": "993a3a976ace937faa4e34faabc40558ed781966",
"size": "2046",
"binary": false,
"copies": "136",
"ref": "refs/heads/master",
"path": "administrator/templates/hathor/html/mod_login/default.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1644803"
},
{
"name": "HTML",
"bytes": "5904"
},
{
"name": "JavaScript",
"bytes": "3841654"
},
{
"name": "PHP",
"bytes": "17076030"
},
{
"name": "PLpgSQL",
"bytes": "1056"
},
{
"name": "SQLPL",
"bytes": "17688"
}
],
"symlink_target": ""
} |
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_ARTICULATION_HELPER_H
#define PXS_ARTICULATION_HELPER_H
#include "PxcArticulation.h"
#include "PxcSpatial.h"
namespace physx
{
struct PxcArticulationSolverDesc;
struct PxcSolverConstraintDesc;
struct PxsBodyCore;
struct PxsArticulationJointCore;
class PxcConstraintBlockStream;
class PxcRigidBody;
class PxsConstraintBlockManager;
struct PxcSolverConstraint1DExt;
namespace Cm
{
class EventProfiler;
}
struct PxcArticulationJointTransforms
{
PxTransform cA2w; // joint parent frame in world space
PxTransform cB2w; // joint child frame in world space
PxTransform cB2cA; // joint relative pose in world space
};
class PxcArticulationHelper
{
public:
static PxU32 computeUnconstrainedVelocities(const PxcArticulationSolverDesc& desc,
PxReal dt,
PxcConstraintBlockStream& stream,
PxcSolverConstraintDesc* constraintDesc,
PxU32& acCount,
Cm::EventProfiler& profiler,
PxsConstraintBlockManager& constraintBlockManager);
static void updateBodies(const PxcArticulationSolverDesc& desc,
PxReal dt);
static void getImpulseResponse(const PxcFsData& matrix,
PxU32 linkID,
const PxcSIMDSpatial& impulse,
PxcSIMDSpatial& deltaV);
static PX_FORCE_INLINE
void getImpulseResponse(const PxcFsData& matrix,
PxU32 linkID,
const Cm::SpatialVector& impulse,
Cm::SpatialVector& deltaV)
{
getImpulseResponse(matrix, linkID, reinterpret_cast<const PxcSIMDSpatial&>(impulse), reinterpret_cast<PxcSIMDSpatial&>(deltaV));
}
static void getImpulseSelfResponse(const PxcFsData& matrix,
PxU32 linkID0,
const PxcSIMDSpatial& impulse0,
PxcSIMDSpatial& deltaV0,
PxU32 linkID1,
const PxcSIMDSpatial& impulse1,
PxcSIMDSpatial& deltaV1);
static void flushVelocity(PxcFsData& matrix);
static void saveVelocity(const PxcArticulationSolverDesc& m);
static PX_FORCE_INLINE
PxcSIMDSpatial getVelocityFast(const PxcFsData& matrix,PxU32 linkID)
{
return getVelocity(matrix)[linkID];
}
static void getDataSizes(PxU32 linkCount, PxU32 &solverDataSize, PxU32& totalSize, PxU32& scratchSize);
static void initializeDriveCache(PxcFsData &data,
PxU16 linkCount,
const PxsArticulationLink* links,
PxReal compliance,
PxU32 iterations,
char* scratchMemory,
PxU32 scratchMemorySize);
static void applyImpulses(const PxcFsData& matrix,
PxcSIMDSpatial* Z,
PxcSIMDSpatial* V);
private:
static PxU32 getLtbDataSize(PxU32 linkCount);
static PxU32 getFsDataSize(PxU32 linkCount);
static void prepareDataBlock(PxcFsData& fsData,
const PxsArticulationLink* links,
PxU16 linkCount,
PxTransform* poses,
PxcFsInertia *baseInertia,
PxcArticulationJointTransforms* jointTransforms,
PxU32 expectedSize);
static void setInertia(PxcFsInertia& inertia,
const PxsBodyCore& body,
const PxTransform& pose);
static void setJointTransforms(PxcArticulationJointTransforms& transforms,
const PxTransform& parentPose,
const PxTransform& childPose,
const PxsArticulationJointCore& joint);
static void prepareLtbMatrix(PxcFsData& fsData,
const PxcFsInertia* baseInertia,
const PxTransform* poses,
const PxcArticulationJointTransforms* jointTransforms,
PxReal recipDt);
static void prepareFsData(PxcFsData& fsData,
const PxsArticulationLink* links);
static PX_FORCE_INLINE PxReal getResistance(PxReal compliance);
static void createHardLimit(const PxcFsData& fsData,
const PxsArticulationLink* links,
PxU32 linkIndex,
PxcSolverConstraint1DExt& s,
const PxVec3& axis,
PxReal err,
PxReal recipDt);
static void createTangentialSpring(const PxcFsData& fsData,
const PxsArticulationLink* links,
PxU32 linkIndex,
PxcSolverConstraint1DExt& s,
const PxVec3& axis,
PxReal stiffness,
PxReal damping,
PxReal dt);
static PxU32 setupSolverConstraints(PxcFsData& fsData, PxU32 solverDataSize,
PxcConstraintBlockStream& stream,
PxcSolverConstraintDesc* constraintDesc,
const PxsArticulationLink* links,
const PxcArticulationJointTransforms* jointTransforms,
PxReal dt,
PxU32& acCount,
PxsConstraintBlockManager& constraintBlockManager);
static void computeJointDrives(PxcFsData& fsData,
Vec3V* drives,
const PxsArticulationLink* links,
const PxTransform* poses,
const PxcArticulationJointTransforms* transforms,
const Mat33V* loads,
PxReal dt);
};
}
#endif
| {
"content_hash": "c09337d799fb91024993f5f604239e5d",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 130,
"avg_line_length": 29.580459770114942,
"alnum_prop": 0.6831163784728969,
"repo_name": "PopCap/GameIdea",
"id": "f5c68b0fe2cb99adf7b66d2e6ef2e0336ca8a6d9",
"size": "5591",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Engine/Source/ThirdParty/PhysX/PhysX-3.3/Source/LowLevel/common/include/pipeline/PxcArticulationHelper.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "238055"
},
{
"name": "Assembly",
"bytes": "184134"
},
{
"name": "Batchfile",
"bytes": "116983"
},
{
"name": "C",
"bytes": "84264210"
},
{
"name": "C#",
"bytes": "9612596"
},
{
"name": "C++",
"bytes": "242290999"
},
{
"name": "CMake",
"bytes": "548754"
},
{
"name": "CSS",
"bytes": "134910"
},
{
"name": "GLSL",
"bytes": "96780"
},
{
"name": "HLSL",
"bytes": "124014"
},
{
"name": "HTML",
"bytes": "4097051"
},
{
"name": "Java",
"bytes": "757767"
},
{
"name": "JavaScript",
"bytes": "2742822"
},
{
"name": "Makefile",
"bytes": "1976144"
},
{
"name": "Objective-C",
"bytes": "75778979"
},
{
"name": "Objective-C++",
"bytes": "312592"
},
{
"name": "PAWN",
"bytes": "2029"
},
{
"name": "PHP",
"bytes": "10309"
},
{
"name": "PLSQL",
"bytes": "130426"
},
{
"name": "Pascal",
"bytes": "23662"
},
{
"name": "Perl",
"bytes": "218656"
},
{
"name": "Python",
"bytes": "21593012"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "2889614"
},
{
"name": "Tcl",
"bytes": "1452"
}
],
"symlink_target": ""
} |
--
-- image-user-index.sql
--
-- Add user/timestamp index to current image versions
--
ALTER TABLE /*$wgDBprefix*/image
ADD INDEX img_usertext_timestamp (img_user_text,img_timestamp);
| {
"content_hash": "99ea2b11a30402c0e5794aa3308e8a31",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 66,
"avg_line_length": 23.875,
"alnum_prop": 0.7120418848167539,
"repo_name": "AKFourSeven/antoinekougblenou",
"id": "db56b221f85070bd57f978dadccfca107d7a1d5b",
"size": "191",
"binary": false,
"copies": "92",
"ref": "refs/heads/master",
"path": "old/wiki/maintenance/archives/patch-image-user-index.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2564"
},
{
"name": "JavaScript",
"bytes": "1614651"
},
{
"name": "PHP",
"bytes": "63555075"
},
{
"name": "Perl",
"bytes": "27348"
},
{
"name": "Python",
"bytes": "46036"
},
{
"name": "Shell",
"bytes": "4214"
}
],
"symlink_target": ""
} |
package cc.nfscan.server.domain;
import java.io.Serializable;
/**
* Base POJO interface for all entities on the whole application
*
* @author Paulo Miguel Almeida <a href="http://github.com/PauloMigAlmeida">@PauloMigAlmeida</a>
*/
public interface IDomain extends Serializable {
}
| {
"content_hash": "a94719d53973e298050ef9537dda9aa3",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 96,
"avg_line_length": 24,
"alnum_prop": 0.7534722222222222,
"repo_name": "PauloMigAlmeida/nfscan",
"id": "be68829a6c2662d1b8d5c3dfef65fe8f9f7c129e",
"size": "288",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "02-Sourcecode/nfscan-server/src/main/java/cc/nfscan/server/domain/IDomain.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5774"
},
{
"name": "Java",
"bytes": "119141"
},
{
"name": "Shell",
"bytes": "89"
}
],
"symlink_target": ""
} |
package org.apache.airavata.workflow.engine.util;
///*
// *
// * 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.airavata.xbaya.util;
//
//import org.apache.http.HttpEntity;
//import org.apache.http.HttpHost;
//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.UsernamePasswordCredentials;
//import org.apache.http.client.AuthCache;
//import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.CredentialsProvider;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.protocol.HttpClientContext;
//import org.apache.http.impl.auth.BasicScheme;
//import org.apache.http.impl.client.BasicAuthCache;
//import org.apache.http.impl.client.BasicCredentialsProvider;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.util.EntityUtils;
//import org.globusonline.transfer.APIError;
//import org.globusonline.transfer.Authenticator;
//import org.globusonline.transfer.GoauthAuthenticator;
//import org.globusonline.transfer.JSONTransferAPIClient;
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.json.JSONTokener;
//
//import java.io.File;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.security.GeneralSecurityException;
//import java.security.KeyManagementException;
//import java.security.NoSuchAlgorithmException;
//import java.text.DateFormat;
//import java.text.SimpleDateFormat;
//import java.util.*;
//
//public class GlobusOnlineUtils {
// public static final String ACCESS_TOKEN = "access_token";
//
// private static String goUserName;
// private static String goPWD;
//
// public static void main(String[] args) {
//// String s = appendFileName("/~/Desktop/1.docx", "/~/");
//// System.out.println(s);
//
// }
//
// public GlobusOnlineUtils(String goUsername, String goPwd) {
// goUserName = goUsername;
// goPWD = goPwd;
// }
//
// public String getAuthenticationToken() {
// String token = null;
// HttpHost targetHost = new HttpHost(GOConstants.NEXUS_API_HOST, GOConstants.NEXUS_API_PORT, GOConstants.NEXUS_API_SCHEMA);
// CredentialsProvider credsProvider = new BasicCredentialsProvider();
// credsProvider.setCredentials(
// new AuthScope(targetHost.getHostName(), targetHost.getPort()),
// new UsernamePasswordCredentials(goUserName, goPWD));
//
// CloseableHttpClient httpclient = HttpClients.custom()
// .setDefaultCredentialsProvider(credsProvider).build();
// try {
//
// // Create AuthCache instance
// AuthCache authCache = new BasicAuthCache();
// // Generate BASIC scheme object and add it to the local
// // auth cache
// BasicScheme basicScheme = new BasicScheme();
// authCache.put(targetHost, basicScheme);
//
// // Add AuthCache to the execution context
// HttpClientContext localContext = HttpClientContext.create();
// localContext.setAuthCache(authCache);
//
// HttpGet httpget = new HttpGet(GOConstants.GOAUTH_TOKEN_REQ_URL);
// httpget.addHeader("accept", "application/json");
// System.out.println("executing request: " + httpget.getRequestLine());
// System.out.println("to target: " + targetHost);
//
// CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localContext);
// try {
// HttpEntity entity = response.getEntity();
// InputStream entityContent = entity.getContent();
// InputStreamReader reader = new InputStreamReader(entityContent);
// JSONTokener tokenizer = new JSONTokener(reader);
// JSONObject json = new JSONObject(tokenizer);
// token = (String)json.get(ACCESS_TOKEN);
// entityContent.close();
// EntityUtils.consume(entity);
//
// } catch (JSONException e) {
// e.printStackTrace();
// } finally {
// response.close();
// }
// //}
// } catch (ClientProtocolException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// httpclient.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return token;
// }
//
// public JSONTransferAPIClient getAuthenticated (){
// JSONTransferAPIClient jsonTransferAPIClient = null;
// try {
// String authenticationToken = getAuthenticationToken();
// Authenticator authenticator = new GoauthAuthenticator(authenticationToken);
// jsonTransferAPIClient = new JSONTransferAPIClient(goUserName,
// null, GOConstants.BASEURL);
// jsonTransferAPIClient.setAuthenticator(authenticator);
// } catch (KeyManagementException e) {
// e.printStackTrace();
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// return jsonTransferAPIClient;
// }
//
// public String transferFiles (TransferFile tf){
// String taskId = null;
// try {
// JSONTransferAPIClient apiClient = getAuthenticated();
// String submissionId = apiClient.getSubmissionId();
// tf.setSubmission_id(submissionId);
// JSONObject jsonObject = new JSONObject(tf);
// JSONTransferAPIClient.Result result = apiClient.transfer(jsonObject);
// taskId = (String)result.document.get("task_id");
// } catch (IOException e) {
// e.printStackTrace();
// } catch (GeneralSecurityException e) {
// e.printStackTrace();
// } catch (JSONException e) {
// e.printStackTrace();
// } catch (APIError apiError) {
// apiError.printStackTrace();
// }
// return taskId;
// }
//
// public TransferFile getTransferFile (String sourceEp,
// String destEp,
// String sourcePath,
// String destPath,
// String label){
//
// TransferFile transferFile = new TransferFile();
//
//
// transferFile.setPreserve_timestamp(false);
// transferFile.setDATA_TYPE("transfer");
// transferFile.setEncrypt_data(false);
// transferFile.setSync_level(null);
// transferFile.setSource_endpoint(sourceEp);
// transferFile.setLabel(label);
// transferFile.setDestination_endpoint(destEp);
// transferFile.setLength(2);
// transferFile.setDeadline(getDeadlineForTransfer());
// transferFile.setNotify_on_succeeded(true);
// transferFile.setNotify_on_failed(true);
// transferFile.setVerify_checksum(false);
// transferFile.setDelete_destination_extra(false);
// Data[] datas = new Data[1];
// Data data = new Data();
// data.setDATA_TYPE("transfer_item");
// data.setDestination_path(appendFileName(sourcePath, destPath));
// data.setVerify_size(null);
// data.setSource_path(sourcePath);
// data.setRecursive(false);
// datas[0] = data;
// transferFile.setDATA(datas);
// return transferFile;
// }
//
// private static String appendFileName(String sourcePath, String destPath){
// String[] split = sourcePath.split(File.separator);
// String fileName = split[split.length - 1];
// if (destPath.endsWith(File.separator)){
// destPath = destPath.concat(fileName);
// }else {
// destPath = destPath.concat("/" + fileName);
// }
// System.out.println(destPath);
// return destPath;
// }
//
// private String getDeadlineForTransfer (){
// DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Calendar calendar = Calendar.getInstance();
// calendar.add(calendar.DAY_OF_MONTH, 1);
// Date tomorrow = calendar.getTime();
// String date = dateFormat.format(tomorrow);
// System.out.println(date);
// return date;
// }
//
// public List<String> getEPList() throws IOException, APIError, GeneralSecurityException, JSONException {
// List<String> epList = new ArrayList<String>();
// Map<String, String> params = new HashMap<String, String>();
// params.put("limit", "0");
// JSONTransferAPIClient transferAPIClient = getAuthenticated();
// JSONTransferAPIClient.Result result = transferAPIClient.getResult("/endpoint_list", params);
// JSONObject document = result.document;
// JSONArray dataArray = document.getJSONArray("DATA");
// for (int i = 0; i < dataArray.length(); i++ ){
// JSONObject jsonObject = dataArray.getJSONObject(i);
// String epName = (String)jsonObject.get("canonical_name");
// epList.add(epName);
// }
// return epList;
// }
//
//}
| {
"content_hash": "29661206ca01fd81f05bf288d5f07104",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 131,
"avg_line_length": 41.53846153846154,
"alnum_prop": 0.6249512670565303,
"repo_name": "gouravshenoy/airavata",
"id": "d6a281cb977273c6f4bb9d0c337a765bf7d79a5c",
"size": "11071",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/workflow-model/workflow-engine/src/main/java/org/apache/airavata/workflow/engine/util/GlobusOnlineUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5598"
},
{
"name": "C",
"bytes": "53885"
},
{
"name": "C++",
"bytes": "7147253"
},
{
"name": "CSS",
"bytes": "26656"
},
{
"name": "HTML",
"bytes": "84328"
},
{
"name": "Java",
"bytes": "34853075"
},
{
"name": "PHP",
"bytes": "294193"
},
{
"name": "Python",
"bytes": "295765"
},
{
"name": "Shell",
"bytes": "58504"
},
{
"name": "Thrift",
"bytes": "423314"
},
{
"name": "XSLT",
"bytes": "34643"
}
],
"symlink_target": ""
} |
<?php
/**
* @namespace
*/
namespace Zend\Text\Table\Exception;
class OverflowException
extends \OverflowException
implements \Zend\Text\Exception
{
}
| {
"content_hash": "f0f85059bae0a723efbe2b1f4be214b9",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 36,
"avg_line_length": 14.636363636363637,
"alnum_prop": 0.7204968944099379,
"repo_name": "florian987/DemoSite",
"id": "a63928b9b92741e9deb8636dc37abbf00e89caab",
"size": "161",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/Zend/library/Zend/Text/Table/Exception/OverflowException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "305864"
},
{
"name": "PHP",
"bytes": "26924"
}
],
"symlink_target": ""
} |
package vizzini
/*
* File Generated by enaml generator
* !!! Please do not edit this file !!!
*/
type Ssh struct {
/*ProxyAddress - Descr: Host and port for the SSH proxy Default: ssh-proxy.service.cf.internal:2222
*/
ProxyAddress interface{} `yaml:"proxy_address,omitempty"`
/*ProxySecret - Descr: Shared secret for the SSH proxy's Diego authenticator Default: <nil>
*/
ProxySecret interface{} `yaml:"proxy_secret,omitempty"`
} | {
"content_hash": "b6ea5b5e4eb616374f7d14a9203e1192",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 100,
"avg_line_length": 27.25,
"alnum_prop": 0.7293577981651376,
"repo_name": "enaml-ops/omg-product-bundle",
"id": "d86a4478d7436b7059e0c62bc22e1bb9f82d7e2d",
"size": "436",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "products/oss_cf/enaml-gen/vizzini/ssh.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2065494"
},
{
"name": "Shell",
"bytes": "1679"
}
],
"symlink_target": ""
} |
#if !defined(CY_BOOT_CYSPC_H)
#define CY_BOOT_CYSPC_H
#include "cytypes.h"
#include "CyLib.h"
#include "cydevice_trm.h"
/***************************************
* Global Variables
***************************************/
extern uint8 SpcLockState;
/***************************************
* Function Prototypes
***************************************/
void CySpcStart(void);
void CySpcStop(void);
uint8 CySpcReadData(uint8 buffer[], uint8 size);
cystatus CySpcLoadMultiByte(uint8 array, uint16 address, const uint8 buffer[], uint8 size)\
;
cystatus CySpcLoadRow(uint8 array, const uint8 buffer[], uint16 size);
cystatus CySpcWriteRow(uint8 array, uint16 address, uint8 tempPolarity, uint8 tempMagnitude)\
;
cystatus CySpcEraseSector(uint8 array, uint8 sectorNumber);
cystatus CySpcGetTemp(uint8 numSamples);
cystatus CySpcLock(void);
void CySpcUnlock(void);
/***************************************
* API Constants
***************************************/
#define CY_SPC_LOCKED (0x01u)
#define CY_SPC_UNLOCKED (0x00u)
/*******************************************************************************
* The Array ID indicates the unique ID of the SONOS array being accessed:
* - 0x00-0x3E : Flash Arrays
* - 0x3F : Selects all Flash arrays simultaneously
* - 0x40-0x7F : Embedded EEPROM Arrays
*******************************************************************************/
#define CY_SPC_FIRST_FLASH_ARRAYID (0x00u)
#define CY_SPC_LAST_FLASH_ARRAYID (0x3Fu)
#define CY_SPC_FIRST_EE_ARRAYID (0x40u)
#define CY_SPC_LAST_EE_ARRAYID (0x7Fu)
#define CY_SPC_STATUS_DATA_READY_MASK (0x01u)
#define CY_SPC_STATUS_IDLE_MASK (0x02u)
#define CY_SPC_STATUS_CODE_MASK (0xFCu)
#define CY_SPC_STATUS_CODE_SHIFT (0x02u)
/* Status codes for SPC. */
#define CY_SPC_STATUS_SUCCESS (0x00u) /* Operation Successful */
#define CY_SPC_STATUS_INVALID_ARRAY_ID (0x01u) /* Invalid Array ID for given command */
#define CY_SPC_STATUS_INVALID_2BYTEKEY (0x02u) /* Invalid 2-byte key */
#define CY_SPC_STATUS_ARRAY_ASLEEP (0x03u) /* Addressed Array is Asleep */
#define CY_SPC_STATUS_EXTERN_ACCESS (0x04u) /* External Access Failure (SPC is not in external access mode) */
#define CY_SPC_STATUS_INVALID_NUMBER (0x05u) /* Invalid 'N' Value for given command */
#define CY_SPC_STATUS_TEST_MODE (0x06u) /* Test Mode Failure (SPC is not in test mode) */
#define CY_SPC_STATUS_ALG_CSUM (0x07u) /* Smart Write Algorithm Checksum Failure */
#define CY_SPC_STATUS_PARAM_CSUM (0x08u) /* Smart Write Parameter Checksum Failure */
#define CY_SPC_STATUS_PROTECTION (0x09u) /* Protection Check Failure */
#define CY_SPC_STATUS_ADDRESS_PARAM (0x0Au) /* Invalid Address parameter for the given command */
#define CY_SPC_STATUS_COMMAND_CODE (0x0Bu) /* Invalid Command Code */
#define CY_SPC_STATUS_ROW_ID (0x0Cu) /* Invalid Row ID parameter for given command */
#define CY_SPC_STATUS_TADC_INPUT (0x0Du) /* Invalid input value for Get Temp & Get ADC commands */
#define CY_SPC_STATUS_BUSY (0xFFu) /* SPC is busy */
#if(CY_PSOC5)
/* Wait-state pipeline */
#define CY_SPC_CPU_WAITPIPE_BYPASS ((uint32)0x01u)
#endif /* (CY_PSOC5) */
/***************************************
* Registers
***************************************/
/* SPC CPU Data Register */
#define CY_SPC_CPU_DATA_REG (* (reg8 *) CYREG_SPC_CPU_DATA )
#define CY_SPC_CPU_DATA_PTR ( (reg8 *) CYREG_SPC_CPU_DATA )
/* SPC Status Register */
#define CY_SPC_STATUS_REG (* (reg8 *) CYREG_SPC_SR )
#define CY_SPC_STATUS_PTR ( (reg8 *) CYREG_SPC_SR )
/* Active Power Mode Configuration Register 0 */
#define CY_SPC_PM_ACT_REG (* (reg8 *) CYREG_PM_ACT_CFG0 )
#define CY_SPC_PM_ACT_PTR ( (reg8 *) CYREG_PM_ACT_CFG0 )
/* Standby Power Mode Configuration Register 0 */
#define CY_SPC_PM_STBY_REG (* (reg8 *) CYREG_PM_STBY_CFG0 )
#define CY_SPC_PM_STBY_PTR ( (reg8 *) CYREG_PM_STBY_CFG0 )
#if(CY_PSOC5)
/* Wait State Pipeline */
#define CY_SPC_CPU_WAITPIPE_REG (* (reg32 *) CYREG_PANTHER_WAITPIPE )
#define CY_SPC_CPU_WAITPIPE_PTR ( (reg32 *) CYREG_PANTHER_WAITPIPE )
#endif /* (CY_PSOC5) */
/***************************************
* Macros
***************************************/
#define CY_SPC_IDLE (0u != (CY_SPC_STATUS_REG & CY_SPC_STATUS_IDLE_MASK))
#define CY_SPC_BUSY (0u == (CY_SPC_STATUS_REG & CY_SPC_STATUS_IDLE_MASK))
#define CY_SPC_DATA_READY (0u != (CY_SPC_STATUS_REG & CY_SPC_STATUS_DATA_READY_MASK))
/* SPC must be in idle state in order to obtain correct status */
#define CY_SPC_READ_STATUS (CY_SPC_IDLE ? \
((uint8)(CY_SPC_STATUS_REG >> CY_SPC_STATUS_CODE_SHIFT)) : \
((uint8) CY_SPC_STATUS_BUSY))
/*******************************************************************************
* The following code is OBSOLETE and must not be used.
*
* If the obsoleted macro definitions intended for use in the application use the
* following scheme, redefine your own versions of these definitions:
* #ifdef <OBSOLETED_DEFINE>
* #undef <OBSOLETED_DEFINE>
* #define <OBSOLETED_DEFINE> (<New Value>)
* #endif
*
* Note: Redefine obsoleted macro definitions with caution. They might still be
* used in the application and their modification might lead to unexpected
* consequences.
*******************************************************************************/
#define FIRST_FLASH_ARRAYID (CY_SPC_FIRST_FLASH_ARRAYID)
#define LAST_FLASH_ARRAYID (CY_SPC_LAST_FLASH_ARRAYID)
#define FIRST_EE_ARRAYID (CY_SPC_FIRST_EE_ARRAYID)
#define LAST_EE_ARRAYID (CY_SPC_LAST_EE_ARRAYID)
#define SIZEOF_ECC_ROW (CYDEV_ECC_ROW_SIZE)
#define SIZEOF_FLASH_ROW (CYDEV_FLS_ROW_SIZE)
#define SIZEOF_EEPROM_ROW (CYDEV_EEPROM_ROW_SIZE)
#endif /* (CY_BOOT_CYSPC_H) */
/* [] END OF FILE */
| {
"content_hash": "c40e6b4ff6c3195f28b4563fbc740d8d",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 120,
"avg_line_length": 41.70860927152318,
"alnum_prop": 0.5612892981899016,
"repo_name": "btodoroff/simaces",
"id": "0978a96b4c9e502e6b8da874120456eea1bbe35a",
"size": "7042",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Joystick.cydsn/Generated_Source/PSoC3/CySpc.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "114667"
},
{
"name": "Batchfile",
"bytes": "1589"
},
{
"name": "C",
"bytes": "3349011"
},
{
"name": "C++",
"bytes": "1442775"
},
{
"name": "HTML",
"bytes": "133746"
},
{
"name": "Pascal",
"bytes": "2274"
}
],
"symlink_target": ""
} |
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define('usuarioTipo', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
descripcion: {
type: DataTypes.STRING,
allowNull: true
}
}, {
tableName: 'usuarioTipo',
name: {
singular: 'usuarioTipo',
plural: 'usuarioTipo',
},
paranoid: true,
});
};
| {
"content_hash": "1865a77b70f06afcbd190b38a9280bf1",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 49,
"avg_line_length": 20.217391304347824,
"alnum_prop": 0.5763440860215053,
"repo_name": "ungs-pp1g2/delix",
"id": "85c5b64afea4801a9b9176c9e2bb8b1c0e2abe36",
"size": "465",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/db/models/usuario_tipo.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "285"
},
{
"name": "CSS",
"bytes": "802"
},
{
"name": "HTML",
"bytes": "1588"
},
{
"name": "Java",
"bytes": "5088"
},
{
"name": "JavaScript",
"bytes": "142035"
},
{
"name": "NSIS",
"bytes": "4519"
}
],
"symlink_target": ""
} |
//
// AudioController.h
//
//
// Created by Manuel Deneu on 16/08/14.
//
//
#ifndef ____AudioController__
#define ____AudioController__
#include <iostream>
class AudioController
{
public:
AudioController();
~AudioController();
private:
};
#endif /* defined(____AudioController__) */
| {
"content_hash": "ac5397c0d718e217e2b1fd5ecc150c10",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 43,
"avg_line_length": 11.142857142857142,
"alnum_prop": 0.6121794871794872,
"repo_name": "manu88/Celesta",
"id": "fd48175fe46564b896239a972e7d1285115e264b",
"size": "312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Core/Audio/AudioController.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "332079"
},
{
"name": "C++",
"bytes": "1765597"
},
{
"name": "JavaScript",
"bytes": "62211"
},
{
"name": "Makefile",
"bytes": "9949"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Mon Mar 14 23:47:29 UTC 2016 -->
<title>LinkAccountCard</title>
<meta name="date" content="2016-03-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="LinkAccountCard";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/amazon/speech/ui/Image.html" title="class in com.amazon.speech.ui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/amazon/speech/ui/OutputSpeech.html" title="class in com.amazon.speech.ui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/amazon/speech/ui/LinkAccountCard.html" target="_top">Frames</a></li>
<li><a href="LinkAccountCard.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_com.amazon.speech.ui.Card">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.amazon.speech.ui</div>
<h2 title="Class LinkAccountCard" class="title">Class LinkAccountCard</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../com/amazon/speech/ui/Card.html" title="class in com.amazon.speech.ui">com.amazon.speech.ui.Card</a></li>
<li>
<ul class="inheritance">
<li>com.amazon.speech.ui.LinkAccountCard</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">LinkAccountCard</span>
extends <a href="../../../../com/amazon/speech/ui/Card.html" title="class in com.amazon.speech.ui">Card</a></pre>
<div class="block">A card that lets the user link their Alexa account with an account for your service. Return this
card if the request requires a valid access token, but the token included in the request is null
or invalid.</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../com/amazon/speech/ui/Card.html" title="class in com.amazon.speech.ui"><code>Card</code></a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../com/amazon/speech/ui/LinkAccountCard.html#LinkAccountCard()">LinkAccountCard</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.amazon.speech.ui.Card">
<!-- -->
</a>
<h3>Methods inherited from class com.amazon.speech.ui.<a href="../../../../com/amazon/speech/ui/Card.html" title="class in com.amazon.speech.ui">Card</a></h3>
<code><a href="../../../../com/amazon/speech/ui/Card.html#getTitle()">getTitle</a>, <a href="../../../../com/amazon/speech/ui/Card.html#setTitle(java.lang.String)">setTitle</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="LinkAccountCard()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>LinkAccountCard</h4>
<pre>public LinkAccountCard()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/amazon/speech/ui/Image.html" title="class in com.amazon.speech.ui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/amazon/speech/ui/OutputSpeech.html" title="class in com.amazon.speech.ui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/amazon/speech/ui/LinkAccountCard.html" target="_top">Frames</a></li>
<li><a href="LinkAccountCard.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_com.amazon.speech.ui.Card">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "1eedac2f27e88e41cae5090c03b2b6a1",
"timestamp": "",
"source": "github",
"line_count": 242,
"max_line_length": 188,
"avg_line_length": 34.45454545454545,
"alnum_prop": 0.6295274646198129,
"repo_name": "Miniland1333/alexa-skills-kit-java",
"id": "78bcfc5b72675dc159d34b19a3c4afde708883c5",
"size": "8338",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "javadoc/com/amazon/speech/ui/LinkAccountCard.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "617"
},
{
"name": "C",
"bytes": "190572"
},
{
"name": "HTML",
"bytes": "5156773"
},
{
"name": "Java",
"bytes": "181687"
},
{
"name": "Makefile",
"bytes": "1758"
}
],
"symlink_target": ""
} |
package org.mifos.application.meeting.business;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.mifos.application.meeting.MeetingTemplate;
import org.mifos.application.meeting.exceptions.MeetingException;
import org.mifos.application.meeting.util.helpers.MeetingConstants;
import org.mifos.application.meeting.util.helpers.MeetingType;
import org.mifos.application.meeting.util.helpers.RankOfDay;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.application.meeting.util.helpers.WeekDay;
import org.mifos.config.FiscalCalendarRules;
import org.mifos.config.persistence.ConfigurationPersistence;
import org.mifos.dto.domain.MeetingDetailsDto;
import org.mifos.dto.domain.MeetingDto;
import org.mifos.dto.domain.MeetingTypeDto;
import org.mifos.framework.business.AbstractBusinessObject;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.schedule.ScheduledEvent;
import org.mifos.schedule.ScheduledEventFactory;
/**
* A better name for MeetingBO would be along the lines of "ScheduledEvent". To
* see what a "meeting" can be look at {@link MeetingType}. It encompasses not
* only a customer meeting, but also financial events like loan installments,
* interest posting and the like. This should be refactored, perhaps from a
* ScheduledEvent base class with subclasses that correspond to the different
* MeetingType entries. In this way a member like meetingPlace could be
* associated with the CustomerMeeting rather than all MeetingTypes.
*/
public class MeetingBO extends AbstractBusinessObject {
private Integer meetingId;
private MeetingDetailsEntity meetingDetails;
private MeetingTypeEntity meetingType;
private Date meetingStartDate;
private String meetingPlace;
private FiscalCalendarRules fiscalCalendarRules = null;
public FiscalCalendarRules getFiscalCalendarRules() {
if (fiscalCalendarRules == null) {
fiscalCalendarRules = new FiscalCalendarRules();
}
return this.fiscalCalendarRules;
}
public void setFiscalCalendarRules(FiscalCalendarRules fiscalCalendarRules) {
this.fiscalCalendarRules = fiscalCalendarRules;
}
/**
* default constructor for hibernate
*/
protected MeetingBO() {
}
/**
* minimal legal constructor
*/
public MeetingBO(final MeetingType meetingType, final Date startDate, final String meetingLocation) {
this.meetingType = new MeetingTypeEntity(meetingType);
this.meetingStartDate = startDate;
this.meetingPlace = meetingLocation;
}
public MeetingBO(final RecurrenceType recurrenceType, final Short recurAfter, final Date startDate, final MeetingType meetingType)
throws MeetingException {
this(recurrenceType, Short.valueOf("1"), WeekDay.MONDAY, null, recurAfter, startDate, meetingType, "meetingPlace");
}
public MeetingBO(final WeekDay weekDay, final RankOfDay rank, final Short recurAfter, final Date startDate, final MeetingType meetingType,
final String meetingPlace) throws MeetingException {
this(weekDay, rank, recurAfter, startDate, meetingType, meetingPlace, null);
}
public MeetingBO(final WeekDay weekDay, final RankOfDay rank, final Short recurAfter, final Date startDate, final MeetingType meetingType,
final String meetingPlace, @SuppressWarnings("unused") final Locale locale) throws MeetingException {
this(RecurrenceType.MONTHLY, null, weekDay, rank, recurAfter, startDate, meetingType, meetingPlace, null);
}
public MeetingBO(final Short dayNumber, final Short recurAfter, final Date startDate, final MeetingType meetingType, final String meetingPlace)
throws MeetingException {
this(RecurrenceType.MONTHLY, dayNumber, null, null, recurAfter, startDate, meetingType, meetingPlace);
}
public MeetingBO(final WeekDay weekDay, final Short recurAfter, final Date startDate, final MeetingType meetingType, final String meetingPlace)
throws MeetingException {
this(RecurrenceType.WEEKLY, null, weekDay, null, recurAfter, startDate, meetingType, meetingPlace);
}
public MeetingBO(final Short recurAfter, Date startDate, MeetingType meetingType, String meetingPlace)
throws MeetingException {
this(RecurrenceType.DAILY, null, null, null, recurAfter, startDate, meetingType, meetingPlace);
}
public MeetingBO(final MeetingTemplate template) throws MeetingException {
this(template.getReccurenceType(), template.getDateNumber(), template.getWeekDay(), template.getRankType(),
template.getRecurAfter(), template.getStartDate(), template.getMeetingType(), template
.getMeetingPlace());
}
private MeetingBO(final RecurrenceType recurrenceType, final Short dayNumber, final WeekDay weekDay, final RankOfDay rank, final Short recurAfter,
final Date startDate, final MeetingType meetingType, final String meetingPlace) throws MeetingException {
this(recurrenceType, dayNumber, weekDay, rank, recurAfter, startDate, meetingType, meetingPlace, null);
}
private MeetingBO(final RecurrenceType recurrenceType, final Short dayNumber, final WeekDay weekDay, final RankOfDay rank, final Short recurAfter,
final Date startDate, final MeetingType meetingType, final String meetingPlace, @SuppressWarnings("unused") final Locale locale) throws MeetingException {
this.validateFields(recurrenceType, startDate, meetingType, meetingPlace);
this.meetingDetails = new MeetingDetailsEntity(new RecurrenceTypeEntity(recurrenceType), dayNumber, weekDay,
rank, recurAfter, this);
if (meetingType != null) {
this.meetingType = new MeetingTypeEntity(meetingType);
}
this.meetingId = null;
this.meetingStartDate = DateUtils.getDateWithoutTimeStamp(startDate.getTime());
this.meetingPlace = meetingPlace;
}
public MeetingBO(final Short dayNumber, final Short recurAfter, final Date startDate, final MeetingType meetingType, final String meetingPlace,
final Short weekNumber) throws MeetingException {
this(RecurrenceType.MONTHLY, null, WeekDay.getWeekDay(dayNumber), RankOfDay.getRankOfDay(weekNumber), recurAfter,
startDate, meetingType, meetingPlace);
}
public MeetingBO(final int recurrenceId, final Short dayNumber, final Short recurAfter, final Date startDate, final MeetingType meetingType,
final String meetingPlace) throws MeetingException {
this(RecurrenceType.WEEKLY, null, WeekDay.getWeekDay(dayNumber), null, recurAfter, startDate, meetingType,
meetingPlace);
}
public MeetingDetailsEntity getMeetingDetails() {
return meetingDetails;
}
public Integer getMeetingId() {
return meetingId;
}
public String getMeetingPlace() {
return meetingPlace;
}
public void setMeetingPlace(final String meetingPlace) {
this.meetingPlace = meetingPlace;
}
public Date getMeetingStartDate() {
return meetingStartDate;
}
public void setMeetingStartDate(final Date meetingStartDate) {
this.meetingStartDate = DateUtils.getDateWithoutTimeStamp(meetingStartDate);
}
public void setStartDate(final Date startDate) {
this.meetingStartDate = startDate;
}
public final Date getStartDate() {
return meetingStartDate;
}
public MeetingTypeEntity getMeetingType() {
return meetingType;
}
public MeetingType getMeetingTypeEnum() {
return meetingType.asEnum();
}
public void setMeetingType(final MeetingTypeEntity meetingType) {
this.meetingType = meetingType;
}
public boolean isMonthlyOnDate() {
return getMeetingDetails().isMonthlyOnDate();
}
public boolean isWeekly() {
return getMeetingDetails().isWeekly();
}
public boolean isMonthly() {
return getMeetingDetails().isMonthly();
}
public boolean isDaily() {
return getMeetingDetails().isDaily();
}
public void update(final WeekDay weekDay, final String meetingPlace) throws MeetingException {
validateMeetingPlace(meetingPlace);
getMeetingDetails().getMeetingRecurrence().updateWeekDay(weekDay);
this.meetingPlace = meetingPlace;
}
public void update(final WeekDay weekDay, final RankOfDay rank, final String meetingPlace) throws MeetingException {
validateMeetingPlace(meetingPlace);
getMeetingDetails().getMeetingRecurrence().update(weekDay, rank);
this.meetingPlace = meetingPlace;
}
public void update(final Short dayNumber, final String meetingPlace) throws MeetingException {
validateMeetingPlace(meetingPlace);
getMeetingDetails().getMeetingRecurrence().updateDayNumber(dayNumber);
this.meetingPlace = meetingPlace;
}
public void update(final String meetingPlace) throws MeetingException {
validateMeetingPlace(meetingPlace);
this.meetingPlace = meetingPlace;
}
private void validateFields(final RecurrenceType recurrenceType, final Date startDate, final MeetingType meetingType,
final String meetingPlace) throws MeetingException {
if (recurrenceType == null) {
throw new MeetingException(MeetingConstants.INVALID_RECURRENCETYPE);
}
if (startDate == null) {
throw new MeetingException(MeetingConstants.INVALID_STARTDATE);
}
if (meetingType == null) {
throw new MeetingException(MeetingConstants.INVALID_MEETINGTYPE);
}
validateMeetingPlace(meetingPlace);
}
private void validateMeetingPlace(final String meetingPlace) throws MeetingException {
if (StringUtils.isBlank(meetingPlace)) {
throw new MeetingException(MeetingConstants.INVALID_MEETINGPLACE);
}
}
public boolean isValidMeetingDateUntilNextYear(final Date meetingDate) throws MeetingException {
return isValidMeetingDate(meetingDate, DateUtils.getLastDayOfNextYear());
}
public boolean isValidMeetingDate(final Date meetingDate, final Date endDate) throws MeetingException {
validateMeetingDate(meetingDate);
validateEndDate(endDate);
DateTime currentScheduleDateTime = findNearestMatchingDate(new DateTime(this.meetingStartDate));
Date currentScheduleDate = currentScheduleDateTime.toDate();
Calendar c = Calendar.getInstance();
c.setTime(currentScheduleDate);
currentScheduleDate = getNextWorkingDay(c).getTime();
Date meetingDateWOTimeStamp = DateUtils.getDateWithoutTimeStamp(meetingDate.getTime());
Date endDateWOTimeStamp = DateUtils.getDateWithoutTimeStamp(endDate.getTime());
if (meetingDateWOTimeStamp.compareTo(endDateWOTimeStamp) > 0) {
return false;
}
while (currentScheduleDate.compareTo(meetingDateWOTimeStamp) < 0
&& currentScheduleDate.compareTo(endDateWOTimeStamp) < 0) {
currentScheduleDate = findNextMatchingDate(new DateTime(currentScheduleDate)).toDate();
c.setTime(currentScheduleDate);
currentScheduleDate = getNextWorkingDay(c).getTime();
}
boolean isRepaymentIndepOfMeetingEnabled = new ConfigurationPersistence().isRepaymentIndepOfMeetingEnabled();
if (isRepaymentIndepOfMeetingEnabled) {
return currentScheduleDate.compareTo(endDateWOTimeStamp) <= 0;
}
// If repayment date is dependend on meeting date, then they need to
// match
return currentScheduleDate.compareTo(endDateWOTimeStamp) <= 0
&& currentScheduleDate.compareTo(meetingDateWOTimeStamp) == 0;
}
private Calendar getNextWorkingDay(final Calendar day) {
while (!new FiscalCalendarRules().isWorkingDay(day)) {
day.add(Calendar.DATE, 1);
}
return day;
}
public boolean isValidMeetingDate(final Date meetingDate, final int occurrences) throws MeetingException {
validateMeetingDate(meetingDate);
validateOccurences(occurrences);
DateTime currentScheduleDateTime = findNearestMatchingDate(new DateTime(this.meetingStartDate));
Date currentScheduleDate = currentScheduleDateTime.toDate();
Date meetingDateWOTimeStamp = DateUtils.getDateWithoutTimeStamp(meetingDate.getTime());
for (int currentNumber = 1; currentScheduleDate.compareTo(meetingDateWOTimeStamp) < 0
&& currentNumber < occurrences; currentNumber++) {
currentScheduleDate = findNextMatchingDate(new DateTime(currentScheduleDate)).toDate();
}
boolean isRepaymentIndepOfMeetingEnabled = new ConfigurationPersistence().isRepaymentIndepOfMeetingEnabled();
if (!isRepaymentIndepOfMeetingEnabled) {
// If repayment date is dependend on meeting date, then they need to
// match
return currentScheduleDate.compareTo(meetingDateWOTimeStamp) == 0;
}
return true;
}
public Date getNextScheduleDateAfterRecurrenceWithoutAdjustment(final Date afterDate) throws MeetingException {
validateMeetingDate(afterDate);
DateTime from = findNearestMatchingDate(new DateTime(this.meetingStartDate));
DateTime currentScheduleDate = findNextMatchingDate(from);
while (currentScheduleDate.toDate().compareTo(afterDate) <= 0) {
currentScheduleDate = findNextMatchingDate(currentScheduleDate);
}
return currentScheduleDate.toDate();
}
private DateTime findNearestMatchingDate(DateTime startingFrom) {
ScheduledEvent scheduledEvent = ScheduledEventFactory.createScheduledEventFrom(this);
return scheduledEvent.nearestMatchingDateBeginningAt(startingFrom);
}
public Date getPrevScheduleDateAfterRecurrence(final Date meetingDate) throws MeetingException {
validateMeetingDate(meetingDate);
DateTime prevScheduleDate = null;
/*
* Current schedule date as next meeting date after start date till this
* date is after given meeting date or increment current schedule date
* to next meeting date from current schedule date return the last but
* one current schedule date as prev schedule date
*/
DateTime currentScheduleDate = findNextMatchingDate(new DateTime(this.meetingStartDate));
while (currentScheduleDate.toDate().compareTo(meetingDate) < 0) {
prevScheduleDate = currentScheduleDate;
currentScheduleDate = findNextMatchingDate(currentScheduleDate);
}
if (prevScheduleDate != null) {
return prevScheduleDate.toDate();
}
return null;
}
private void validateMeetingDate(final Date meetingDate) throws MeetingException {
if (meetingDate == null) {
throw new MeetingException(MeetingConstants.INVALID_MEETINGDATE);
}
}
private void validateOccurences(final int occurrences) throws MeetingException {
if (occurrences <= 0) {
throw new MeetingException(MeetingConstants.INVALID_OCCURENCES);
}
}
private void validateEndDate(final Date endDate) throws MeetingException {
if (endDate == null || endDate.compareTo(getStartDate()) < 0) {
throw new MeetingException(MeetingConstants.INVALID_ENDDATE);
}
}
private DateTime findNextMatchingDate(DateTime startingFrom) {
ScheduledEvent scheduledEvent = ScheduledEventFactory.createScheduledEventFrom(this);
return scheduledEvent.nextEventDateAfter(startingFrom);
}
/*
* This seems like it is trying to answer the question of whether meetings
* for meetingToBeMatched and meetingToBeMatchedWith overlap. For example a
* weekly meeting occurring every 2 weeks potentially overlaps with a
* meeting occurring every 4 weeks.
*/
public static boolean isMeetingMatched(final MeetingBO meetingToBeMatched, final MeetingBO meetingToBeMatchedWith) {
return meetingToBeMatched != null
&& meetingToBeMatchedWith != null
&& meetingToBeMatched.getMeetingDetails().getRecurrenceType().getRecurrenceId().equals(
meetingToBeMatchedWith.getMeetingDetails().getRecurrenceType().getRecurrenceId())
&& isMultiple(meetingToBeMatchedWith.getMeetingDetails().getRecurAfter(), meetingToBeMatched
.getMeetingDetails().getRecurAfter());
}
private static boolean isMultiple(final Short valueToBeChecked, final Short valueToBeCheckedWith) {
return valueToBeChecked % valueToBeCheckedWith == 0;
}
public void setMeetingDetails(final MeetingDetailsEntity meetingDetails) {
this.meetingDetails = meetingDetails;
}
public RecurrenceType getRecurrenceType() {
return meetingDetails.getRecurrenceTypeEnum();
}
public Short getRecurAfter() {
return meetingDetails.getRecurAfter();
}
/*
* Get the start date of the "interval" surrounding a given date
* For example assume March 1 is a Monday and that weeks are defined to start on
* Monday. If this is a weekly meeting on a Wednesday then the "interval"
* for Wednesday March 10 is the week from Monday March 8 to Sunday March 14,
* and this method would return March 8.
*/
public LocalDate startDateForMeetingInterval(LocalDate date) {
LocalDate startOfMeetingInterval = date;
if (isWeekly()) {
int weekDay = WeekDay.getJodaDayOfWeekThatMatchesMifosWeekDay(getFiscalCalendarRules().getStartOfWeekWeekDay().getValue());
while (startOfMeetingInterval.getDayOfWeek() != weekDay) {
startOfMeetingInterval = startOfMeetingInterval.minusDays(1);
}
} else if (isMonthly()) {
int dayOfMonth = date.getDayOfMonth();
startOfMeetingInterval = startOfMeetingInterval.minusDays(dayOfMonth - 1);
} else {
// for days we return the same day
startOfMeetingInterval = date;
}
return startOfMeetingInterval;
}
public boolean queryDateIsInMeetingIntervalForFixedDate(LocalDate queryDate, LocalDate fixedDate) {
LocalDate startOfMeetingInterval = startDateForMeetingInterval(fixedDate);
LocalDate endOfMeetingInterval;
if (isWeekly()) {
endOfMeetingInterval = startOfMeetingInterval.plusWeeks(getRecurAfter());
} else if (isMonthly()) {
endOfMeetingInterval = startOfMeetingInterval.plusMonths(getRecurAfter());
} else {
// we don't handle meeting intervals in days
return false;
}
return (queryDate.isEqual(startOfMeetingInterval) ||
queryDate.isAfter(startOfMeetingInterval)) &&
queryDate.isBefore(endOfMeetingInterval);
}
public boolean hasSameRecurrenceAs(MeetingBO customerMeetingValue) {
return this.getRecurrenceType().equals(customerMeetingValue.getRecurrenceType());
}
public boolean recursOnMultipleOf(MeetingBO meeting) {
return meeting.getMeetingDetails().getRecurAfter().intValue() % this.meetingDetails.getRecurAfter().intValue() == 0;
}
public boolean isDayOfWeekDifferent(WeekDay dayOfWeek) {
return !dayOfWeek.equals(this.getMeetingDetails().getWeekDay());
}
public boolean isDayOfMonthDifferent(Short dayOfMonth) {
return !dayOfMonth.equals(this.getMeetingDetails().getDayNumber());
}
public boolean isWeekOfMonthDifferent(RankOfDay weekOfMonth, WeekDay dayOfWeekInWeekOfMonth) {
boolean isDifferent = false;
if (!weekOfMonth.equals(this.getMeetingDetails().getWeekRank())) {
isDifferent = true;
}
if (!dayOfWeekInWeekOfMonth.equals(this.getMeetingDetails().getWeekDay())) {
isDifferent = true;
}
return isDifferent;
}
public MeetingDto toDto() {
MeetingTypeDto meetingType = this.meetingType.toDto();
MeetingDetailsDto meetingDetailsDto = this.meetingDetails.toDto();
return new MeetingDto(new LocalDate(this.meetingStartDate), this.meetingPlace, meetingType, meetingDetailsDto);
}
} | {
"content_hash": "29b54782a36a7d35ef76c4db8ed2d27b",
"timestamp": "",
"source": "github",
"line_count": 479,
"max_line_length": 166,
"avg_line_length": 43.102296450939455,
"alnum_prop": 0.7138913106655043,
"repo_name": "madhav123/gkmaster",
"id": "94c83ea9c63eaeef65c11278664cc020947dc042",
"size": "21407",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "appdomain/src/main/java/org/mifos/application/meeting/business/MeetingBO.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "160631"
},
{
"name": "Java",
"bytes": "19827990"
},
{
"name": "JavaScript",
"bytes": "1140843"
},
{
"name": "Python",
"bytes": "37612"
},
{
"name": "Shell",
"bytes": "54460"
}
],
"symlink_target": ""
} |
class CardSetCard < ActiveRecord::Base
belongs_to :user
belongs_to :card_set
belongs_to :card
end
| {
"content_hash": "04b58e910a583ab0a1816d352cdb88ec",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 38,
"avg_line_length": 20.8,
"alnum_prop": 0.7403846153846154,
"repo_name": "kintner/enki",
"id": "497fd5ad44b2df796b35d8d63f661e1ac3e20fd2",
"size": "104",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/card_set_card.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1932"
},
{
"name": "CoffeeScript",
"bytes": "1477"
},
{
"name": "JavaScript",
"bytes": "641"
},
{
"name": "Ruby",
"bytes": "24880"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Gdbots\Bundle\PbjxBundle;
use Gdbots\Pbj\Message;
use Gdbots\Pbjx\Pbjx;
use Gdbots\Pbjx\RequestHandler;
use Gdbots\Schemas\Pbjx\Request\EchoResponseV1;
final class EchoRequestHandler implements RequestHandler
{
public static function handlesCuries(): array
{
return [
'gdbots:pbjx:request:echo-request',
];
}
public function handleRequest(Message $request, Pbjx $pbjx): Message
{
return EchoResponseV1::create()->set('msg', $request->get('msg'));
}
}
| {
"content_hash": "37c44430fc4a3574baa54acaa5ef1dc1",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 74,
"avg_line_length": 23.166666666666668,
"alnum_prop": 0.6870503597122302,
"repo_name": "gdbots/pbjx-bundle-php",
"id": "79548a12f24e5a27146220153e9f35feddb5ee9c",
"size": "556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/EchoRequestHandler.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "179098"
}
],
"symlink_target": ""
} |
'use strict';
angular.module('records').factory('Records', ['$resource',
function ($resource) {
return $resource('records/:recordId', {
recordId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
| {
"content_hash": "7a0c88abe26d1d3a5465b148b7034e74",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 58,
"avg_line_length": 21.46153846153846,
"alnum_prop": 0.4336917562724014,
"repo_name": "eric-marie/my-kitchen-garden",
"id": "a0d53e93f1e1e060b649cd64eaaf235ccf7e6265",
"size": "279",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mean/public/app/modules/records/services/records.client.service.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "80"
},
{
"name": "CSS",
"bytes": "570818"
},
{
"name": "HTML",
"bytes": "368342"
},
{
"name": "JavaScript",
"bytes": "231700"
},
{
"name": "PHP",
"bytes": "2967"
},
{
"name": "Shell",
"bytes": "2772"
}
],
"symlink_target": ""
} |
using Sensus.Shared.Exceptions;
using System;
using Xamarin.Forms;
using System.Reflection;
namespace Sensus.Shared.UI.UiProperties
{
/// <summary>
/// Decorated members should be rendered as display-only yes/no values.
/// </summary>
public class DisplayYesNoUiProperty : UiProperty
{
public class ValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return "";
return ((bool)value) ? "Yes" : "No";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
SensusException.Report("Invalid call to " + GetType().FullName + ".ConvertBack.");
return null;
}
}
public DisplayYesNoUiProperty(string labelText, int order)
: base(labelText, true, order)
{
}
public override View GetView(PropertyInfo property, object o, out BindableProperty targetProperty, out IValueConverter converter)
{
targetProperty = Label.TextProperty;
converter = new ValueConverter();
return new Label();
}
}
}
| {
"content_hash": "10f663abdf989df7f1a861ae4621dc3e",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 137,
"avg_line_length": 32.13953488372093,
"alnum_prop": 0.5955137481910275,
"repo_name": "wesbonelli/sensus",
"id": "9639e4e633a1c3215fc568f165ff9ef7c515b44e",
"size": "2011",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sensus.Shared/UI/UiProperties/DisplayYesNoUiProperty.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1225005"
},
{
"name": "Python",
"bytes": "3115"
},
{
"name": "R",
"bytes": "33402"
},
{
"name": "Shell",
"bytes": "19098"
}
],
"symlink_target": ""
} |
Fastest CSV class for MRI Ruby and JRuby. Faster than faster_csv and fasterer-csv.
Uses native C code to parse CSV lines in MRI Ruby and Java in JRuby.
Supports standard CSV according to RFC4180. Not the so-called "csv" from Excel.
The interface is a subset of the CSV interface in Ruby 1.9.3. The options parameter is not supported.
Originally developed to parse large CSV log files from PowerMTA.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'fastest-csv'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install fastest-csv
## Usage
Parse single line
```ruby
FastestCSV.parse_line("one,two,three")
=> ["one", "two", "three"]
"one,two,three".parse_csv
=> ["one", "two", "three"]
```
Parse file without header
```ruby
FastestCSV.foreach("path/to/file.csv") do |row|
# ...
end
```
Parse file with header
```ruby
FastestCSV.open("path/to/file.csv") do |csv|
fields = csv.shift
while values = csv.shift
# ...
end
end
```
Parse file in array of arrays
```ruby
rows = FastestCSV.read("path/to/file.csv")
```
Parse string in array of arrays
```ruby
rows = FastestCSV.parse(csv_data)
```
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {
"content_hash": "1d4bbb4fbee42e0b7692322b87516508",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 101,
"avg_line_length": 18.592105263157894,
"alnum_prop": 0.6963906581740976,
"repo_name": "brightcode/fastest-csv",
"id": "cc7796573a9dc321b9dc64e7fb41a59f7ea3a93b",
"size": "1427",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2520"
},
{
"name": "Java",
"bytes": "6718"
},
{
"name": "Ruby",
"bytes": "12759"
}
],
"symlink_target": ""
} |
@interface ZFCollectionViewListController : UIViewController
@end
| {
"content_hash": "30bf5445b8ebfc3c6689741f817055cc",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 60,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.8656716417910447,
"repo_name": "renzifeng/ZFPlayer",
"id": "845a4422df8c226aa5ea17a448f7dcb1d735fb13",
"size": "250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/ZFPlayer/CollectionView/Controller/ZFCollectionViewListController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4596"
},
{
"name": "Objective-C",
"bytes": "756572"
},
{
"name": "Ruby",
"bytes": "2358"
}
],
"symlink_target": ""
} |
#ifndef __MSG_TIMER_H
#define __MSG_TIMER_H
enum msg_timer
{
/**
* Register a timer to trigger in approximately N nanoseconds.
*
* arg1: timeout.
*/
MSG_REG_TIMER = MSG_USER,
/**
* A registered timer has triggered. The timer will not be triggered again
* unless you re-register a new timeout.
*/
MSG_TIMER_T,
/**
* Two-argument sendrcv.
*
* returns:
* arg1: milliseconds
* arg2: ticks
*/
MSG_TIMER_GETTIME,
};
#endif /* __MSG_TIMER_H */
| {
"content_hash": "607f30c3218ce91e68983f0c067692a0",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 75,
"avg_line_length": 17.444444444444443,
"alnum_prop": 0.6326963906581741,
"repo_name": "olsner/os",
"id": "abaea30045970160efe4bf7b6d2c96e3a93b4f78",
"size": "471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cuser/include/msg_timer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "153263"
},
{
"name": "C",
"bytes": "140457"
},
{
"name": "C++",
"bytes": "75522"
},
{
"name": "Makefile",
"bytes": "14981"
},
{
"name": "Python",
"bytes": "14725"
},
{
"name": "Shell",
"bytes": "6837"
}
],
"symlink_target": ""
} |
//jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
//jQuery for page scrolling feature - requires jQuery Easing plugin
// $(function() {
// $('a.page-scroll').bind('click', function(event) {
// var $anchor = $(this);
// $('html, body').stop().animate({
// scrollTop: $($anchor.attr('href')).offset().top
// }, 1500, 'easeInOutExpo');
// event.preventDefault();
// });
// });
$(function() {
$('#submit-button').hover(function(){
$(this).css("color","#42744D");
$(this).css("border-color","#42744D");
},function(){
$(this).css("color","#EC5536");
$(this).css("border-color","#EC5536");
});
});
/* */
var $logo1 = $('.navbar');
var $home = $('.navbar-home');
//var $logo2 = $('.navbar-home img');
$(document).scroll(function() {
if(window.location.href.endsWith('/') || window.location.href.endsWith('index.html')){
$home.css({background: $(this).scrollTop() > 150? "#transparent":"#ffffffA6"});
// $logo2.css(scale: 0.8);
} else{
$logo1.css({background: $(this).scrollTop() > 150? "#0e3737":"#0e3737"});
}
$logo1.css({"-webkit-box-shadow": $(this).scrollTop() > 150? "0px 2px 3px 0px rgba(0,0,0,0.25)":"none"});
$home.css({"-webkit-box-shadow": $(this).scrollTop() > 150? "0px 2px 3px 0px rgba(0,0,0,0.25)":"none"});
});
var $logo = $('#navbar-index');
$(document).scroll(function() {
$logo.css({background: $(this).scrollTop() > ($( window ).height() - 80)? "white":"transparent"});
$logo.css({"-webkit-box-shadow": $(this).scrollTop() > ($( window ).height() - 80)? "0px 2px 3px 0px rgba(0,0,0,0.25)":"none"});
});
// video resizing
$(function() {
var $hero = $(".intro-section");
var $video = $(".bg-video");
var videoRatio = 16/9;
function resizeBGVideo() {
var width = $hero.width();
var height = $hero.height();
var containerRatio = width/height;
if (containerRatio < videoRatio) {
// too narrow
$video.css("height", height);
$video.css("top", 0);
var newWidth = height * videoRatio;
var wDiff = (newWidth - width) / 2;
$video.css("width", newWidth);
$video.css("left", -wDiff);
} else {
// too wide
$video.css("width", width);
$video.css("left", 0);
var newHeight = width / videoRatio;
var hDiff = (newHeight - height) / 2;
$video.css("height", newHeight);
$video.css("top", -hDiff);
}
}
resizeBGVideo();
$(window).resize(resizeBGVideo);
}); | {
"content_hash": "e40494b8934eb2e6b645c1781b77fca1",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 132,
"avg_line_length": 32.146067415730336,
"alnum_prop": 0.5277874868926948,
"repo_name": "ivyfilmfestival/ivyfilmfestival.github.io",
"id": "4555c0c4915bf8fcbfaa06fcaefbd08fe88822b0",
"size": "2861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/scrolling-nav.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45892"
},
{
"name": "HTML",
"bytes": "305587"
},
{
"name": "JavaScript",
"bytes": "26019"
},
{
"name": "Python",
"bytes": "538"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
export { default } from './Typography';
export * from './TypographyProps';
export { default as typographyClasses } from './typographyClasses';
export * from './typographyClasses';
| {
"content_hash": "0b569a4f1785b9ac0f712b96f437b7e9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 67,
"avg_line_length": 45,
"alnum_prop": 0.7333333333333333,
"repo_name": "rscnt/material-ui",
"id": "bbaa51027683f6c57bf2622e4c18523395b5c7d7",
"size": "180",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "packages/mui-joy/src/Typography/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2126"
},
{
"name": "JavaScript",
"bytes": "3967457"
},
{
"name": "TypeScript",
"bytes": "2468380"
}
],
"symlink_target": ""
} |
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import * as restm from 'typed-rest-client/RestClient';
import vsom = require('./VsoClient');
import basem = require('./ClientApiBases');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import ProjectAnalysisInterfaces = require("./interfaces/ProjectAnalysisInterfaces");
export interface IProjectAnalysisApi extends basem.ClientApiBase {
getProjectLanguageAnalytics(project: string): Promise<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>;
getProjectActivityMetrics(project: string, fromDate: Date, aggregationType: ProjectAnalysisInterfaces.AggregationType): Promise<ProjectAnalysisInterfaces.ProjectActivityMetrics>;
getGitRepositoriesActivityMetrics(project: string, fromDate: Date, aggregationType: ProjectAnalysisInterfaces.AggregationType, skip: number, top: number): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>;
getRepositoryActivityMetrics(project: string, repositoryId: string, fromDate: Date, aggregationType: ProjectAnalysisInterfaces.AggregationType): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics>;
}
export class ProjectAnalysisApi extends basem.ClientApiBase implements IProjectAnalysisApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) {
super(baseUrl, handlers, 'node-ProjectAnalysis-api', options);
}
public static readonly RESOURCE_AREA_ID = "7658fa33-b1bf-4580-990f-fac5896773d3";
/**
* @param {string} project - Project ID or project name
*/
public async getProjectLanguageAnalytics(
project: string
): Promise<ProjectAnalysisInterfaces.ProjectLanguageAnalytics> {
return new Promise<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.0-preview.1",
"projectanalysis",
"5b02a779-1867-433f-90b7-d23ed5e33e57",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>;
res = await this.rest.get<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.ProjectLanguageAnalytics,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {string} project - Project ID or project name
* @param {Date} fromDate
* @param {ProjectAnalysisInterfaces.AggregationType} aggregationType
*/
public async getProjectActivityMetrics(
project: string,
fromDate: Date,
aggregationType: ProjectAnalysisInterfaces.AggregationType
): Promise<ProjectAnalysisInterfaces.ProjectActivityMetrics> {
if (fromDate == null) {
throw new TypeError('fromDate can not be null or undefined');
}
if (aggregationType == null) {
throw new TypeError('aggregationType can not be null or undefined');
}
return new Promise<ProjectAnalysisInterfaces.ProjectActivityMetrics>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
let queryValues: any = {
fromDate: fromDate,
aggregationType: aggregationType,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.0-preview.1",
"projectanalysis",
"e40ae584-9ea6-4f06-a7c7-6284651b466b",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.ProjectActivityMetrics>;
res = await this.rest.get<ProjectAnalysisInterfaces.ProjectActivityMetrics>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.ProjectActivityMetrics,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Retrieves git activity metrics for repositories matching a specified criteria.
*
* @param {string} project - Project ID or project name
* @param {Date} fromDate - Date from which, the trends are to be fetched.
* @param {ProjectAnalysisInterfaces.AggregationType} aggregationType - Bucket size on which, trends are to be aggregated.
* @param {number} skip - The number of repositories to ignore.
* @param {number} top - The number of repositories for which activity metrics are to be retrieved.
*/
public async getGitRepositoriesActivityMetrics(
project: string,
fromDate: Date,
aggregationType: ProjectAnalysisInterfaces.AggregationType,
skip: number,
top: number
): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]> {
if (fromDate == null) {
throw new TypeError('fromDate can not be null or undefined');
}
if (aggregationType == null) {
throw new TypeError('aggregationType can not be null or undefined');
}
if (skip == null) {
throw new TypeError('skip can not be null or undefined');
}
if (top == null) {
throw new TypeError('top can not be null or undefined');
}
return new Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
let queryValues: any = {
fromDate: fromDate,
aggregationType: aggregationType,
'$skip': skip,
'$top': top,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.0-preview.1",
"projectanalysis",
"df7fbbca-630a-40e3-8aa3-7a3faf66947e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>;
res = await this.rest.get<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.RepositoryActivityMetrics,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {string} project - Project ID or project name
* @param {string} repositoryId
* @param {Date} fromDate
* @param {ProjectAnalysisInterfaces.AggregationType} aggregationType
*/
public async getRepositoryActivityMetrics(
project: string,
repositoryId: string,
fromDate: Date,
aggregationType: ProjectAnalysisInterfaces.AggregationType
): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics> {
if (fromDate == null) {
throw new TypeError('fromDate can not be null or undefined');
}
if (aggregationType == null) {
throw new TypeError('aggregationType can not be null or undefined');
}
return new Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics>(async (resolve, reject) => {
let routeValues: any = {
project: project,
repositoryId: repositoryId
};
let queryValues: any = {
fromDate: fromDate,
aggregationType: aggregationType,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.0-preview.1",
"projectanalysis",
"df7fbbca-630a-40e3-8aa3-7a3faf66947e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.RepositoryActivityMetrics>;
res = await this.rest.get<ProjectAnalysisInterfaces.RepositoryActivityMetrics>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.RepositoryActivityMetrics,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
}
| {
"content_hash": "50a80e07aaff555f8a9b26a11efea570",
"timestamp": "",
"source": "github",
"line_count": 246,
"max_line_length": 222,
"avg_line_length": 42.333333333333336,
"alnum_prop": 0.5763395429229883,
"repo_name": "Microsoft/vso-node-api",
"id": "acccf5dc3de490d9b7b64e0797bfabdda871dfdf",
"size": "10760",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/ProjectAnalysisApi.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1912"
},
{
"name": "TypeScript",
"bytes": "1495370"
}
],
"symlink_target": ""
} |
'use strict';
// ==========================================================================
// Math Round
// ==========================================================================
// Syntax
Math.round(x);
// Returns the value 20
x = Math.round(20.49);
// Returns the value 21
x = Math.round(20.5);
// Returns the value -20
x = Math.round(-20.5);
// Returns the value -21
x = Math.round(-20.51);
// Returns the value 1 (!)
// Note the rounding error because of inaccurate floating point arithmetics
// Compare this with Math.round10(1.005, -2) from the example below
document.write( Math.round(1.005 * 100) / 100); // => 1
| {
"content_hash": "8ce5d85bf719ff73c653a46866e974f3",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 78,
"avg_line_length": 19.441176470588236,
"alnum_prop": 0.481089258698941,
"repo_name": "Renatodeluna/lab",
"id": "8a7b66c7f9fcbc27b27ebc22b681e3cdd6095e05",
"size": "661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javascript/fundamental/function/math/math.round.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "31639"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>frameset</title>
</head>
<frameset rows="50%,50%">
<frame src="a.html">
<frameset cols="25%,75%">
<frame src="b.html">
<frame src="c.html">
</frameset>
</frameset>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="../../js/frame.js" type="text/javascript"></script>
</html> | {
"content_hash": "b00aada66b2ca9a1729d8f20304dca78",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 100,
"avg_line_length": 23.473684210526315,
"alnum_prop": 0.600896860986547,
"repo_name": "future-team/fe-training",
"id": "1f76ea80921d27955f213ddbbdc1e7c2d3336bc4",
"size": "446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js基础之bom&dom/bom/html/framesets/frameset.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9568"
},
{
"name": "HTML",
"bytes": "83774"
},
{
"name": "JavaScript",
"bytes": "1045843"
}
],
"symlink_target": ""
} |
package abi10_0_0.host.exp.exponent.modules.api;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import abi10_0_0.com.facebook.react.bridge.Arguments;
import abi10_0_0.com.facebook.react.bridge.Promise;
import abi10_0_0.com.facebook.react.bridge.ReactApplicationContext;
import abi10_0_0.com.facebook.react.bridge.ReactContextBaseJavaModule;
import abi10_0_0.com.facebook.react.bridge.ReactMethod;
import abi10_0_0.com.facebook.react.bridge.ReadableMap;
import abi10_0_0.com.facebook.react.bridge.WritableMap;
import abi10_0_0.com.facebook.react.common.SystemClock;
import abi10_0_0.com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter;
import java.util.HashMap;
import java.util.Map;
import host.exp.exponentview.Exponent;
public class LocationModule extends ReactContextBaseJavaModule {
Map<Integer, LocationListener> mLocationListeners = new HashMap<>();
public LocationModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "ExponentLocation";
}
private static WritableMap locationToMap(Location location) {
WritableMap map = Arguments.createMap();
WritableMap coords = Arguments.createMap();
coords.putDouble("latitude", location.getLatitude());
coords.putDouble("longitude", location.getLongitude());
coords.putDouble("altitude", location.getAltitude());
coords.putDouble("accuracy", location.getAccuracy());
coords.putDouble("heading", location.getBearing());
coords.putDouble("speed", location.getSpeed());
map.putMap("coords", coords);
map.putDouble("timestamp", location.getTime());
return map;
}
private static String selectProvider(LocationManager locMgr, boolean highAccuracy) {
String provider = highAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER;
if (!locMgr.isProviderEnabled(provider)) {
provider = provider.equals(LocationManager.GPS_PROVIDER) ?
LocationManager.NETWORK_PROVIDER :
LocationManager.GPS_PROVIDER;
}
if (locMgr.isProviderEnabled(provider)) {
return provider;
}
return null;
}
@ReactMethod
public void getCurrentPositionAsync(final ReadableMap options, final Promise promise) {
// Need to run when experience activity visible
Activity activity = Exponent.getInstance().getCurrentActivity();
if (activity == null) {
promise.reject("E_ACTIVITY_DOES_NOT_EXIST", "No visible activity. Must request location when visible.");
return;
}
// Read options
final long timeout = options.hasKey("timeout") ? (long) options.getDouble("timeout") : Long.MAX_VALUE;
final double maximumAge = options.hasKey("maximumAge") ? options.getDouble("maximumAge") : Double.POSITIVE_INFINITY;
boolean highAccuracy = options.hasKey("enableHighAccuracy") && options.getBoolean("enableHighAccuracy");
// Select location provider
final LocationManager locMgr = (LocationManager)
getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
final String provider = selectProvider(locMgr, highAccuracy);
if (provider == null) {
promise.reject("E_NO_LOCATION_PROVIDER", "No location provider available.");
}
// Check for permissions
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
promise.reject("E_MISSING_PERMISSION", "Missing location permissions.");
return;
}
// Have location cached already?
Location location = locMgr.getLastKnownLocation(provider);
if (location != null && SystemClock.currentTimeMillis() - location.getTime() < maximumAge) {
promise.resolve(locationToMap(location));
return;
}
// No cached location, ask for one
final Handler handler = new Handler();
class SingleRequest {
private boolean mDone;
public void invoke() {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
promise.reject("E_MISSING_PERMISSION", "Missing location permissions.");
return;
}
locMgr.requestSingleUpdate(provider, mLocListener, null);
handler.postDelayed(mTimeoutRunnable, timeout);
}
// Called when location request fulfilled
private final LocationListener mLocListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
synchronized (SingleRequest.this) {
if (!mDone) {
promise.resolve(locationToMap(location));
handler.removeCallbacks(mTimeoutRunnable);
mDone = true;
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
// Called on timeout
private final Runnable mTimeoutRunnable = new Runnable() {
@Override
public void run() {
synchronized (SingleRequest.this) {
if (!mDone) {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
promise.reject("E_MISSING_PERMISSION", "Missing location permissions.");
return;
}
promise.reject("E_TIMEOUT", "Location request timed out.");
locMgr.removeUpdates(mLocListener);
mDone = true;
}
}
}
};
}
new SingleRequest().invoke();
}
@ReactMethod
public void watchPositionImplAsync(final int watchId, final ReadableMap options, final Promise promise) {
// Need to run when experience activity visible
Activity activity = Exponent.getInstance().getCurrentActivity();
if (activity == null) {
promise.reject("E_ACTIVITY_DOES_NOT_EXIST", "No visible activity. Must request location when visible.");
return;
}
// Read options
final boolean highAccuracy = options.hasKey("enableHighAccuracy") && options.getBoolean("enableHighAccuracy");
final int timeInterval = options.hasKey("timeInterval") ? options.getInt("timeInterval") : 1000;
final int distanceInterval = options.hasKey("distanceInterval") ? options.getInt("distanceInterval") : 100;
// Select location provider
final LocationManager locMgr = (LocationManager)
getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
final String provider = selectProvider(locMgr, highAccuracy);
if (provider == null) {
promise.reject("E_NO_LOCATION_PROVIDER", "No location provider available.");
return;
}
// Check for permissions
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
promise.reject("E_MISSING_PERMISSION", "Missing location permissions.");
return;
}
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
WritableMap response = Arguments.createMap();
response.putInt("watchId", watchId);
response.putMap("location", locationToMap(location));
getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
.emit("Exponent.locationChanged", response);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
};
locMgr.requestLocationUpdates(provider, timeInterval, distanceInterval, listener);
mLocationListeners.put(watchId, listener);
promise.resolve(null);
}
@ReactMethod
public void removeWatchAsync(final int watchId, final Promise promise) {
final LocationManager locMgr = (LocationManager)
getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
final LocationListener listener = mLocationListeners.get(watchId);
if (listener == null) {
promise.resolve(null);
return;
}
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getReactApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
promise.reject("E_MISSING_PERMISSION", "Missing location permissions.");
return;
}
locMgr.removeUpdates(listener);
mLocationListeners.remove(watchId);
promise.resolve(null);
}
}
| {
"content_hash": "8ee36768139be9e96bf9b79cfe428d3a",
"timestamp": "",
"source": "github",
"line_count": 238,
"max_line_length": 173,
"avg_line_length": 42.98739495798319,
"alnum_prop": 0.7096080539536702,
"repo_name": "jolicloud/exponent",
"id": "fba5ca1f4f31a82edc8c6c28f3d4a602a7c6661e",
"size": "10295",
"binary": false,
"copies": "1",
"ref": "refs/heads/desktop",
"path": "android/app/src/main/java/abi10_0_0/host/exp/exponent/modules/api/LocationModule.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "80716"
},
{
"name": "Batchfile",
"bytes": "382"
},
{
"name": "C",
"bytes": "774135"
},
{
"name": "C++",
"bytes": "856989"
},
{
"name": "CSS",
"bytes": "5610"
},
{
"name": "HTML",
"bytes": "128851"
},
{
"name": "IDL",
"bytes": "897"
},
{
"name": "Java",
"bytes": "4143855"
},
{
"name": "JavaScript",
"bytes": "7815629"
},
{
"name": "Makefile",
"bytes": "8740"
},
{
"name": "Objective-C",
"bytes": "8757070"
},
{
"name": "Objective-C++",
"bytes": "266657"
},
{
"name": "Perl",
"bytes": "5860"
},
{
"name": "Prolog",
"bytes": "287"
},
{
"name": "Python",
"bytes": "95109"
},
{
"name": "Ruby",
"bytes": "42676"
},
{
"name": "Shell",
"bytes": "6465"
}
],
"symlink_target": ""
} |
Nyyyyahhhhahaawwwwwwwwwwwww
| {
"content_hash": "49160a08a770445543ab0ce863b7e7cb",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 27,
"avg_line_length": 28,
"alnum_prop": 0.9642857142857143,
"repo_name": "musicglue/project-elephant",
"id": "3f3054d7b0aaeaabeb5e81d14102fb2baf3a64b9",
"size": "47",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "11516"
}
],
"symlink_target": ""
} |
import sys
import os
from gi.repository import GLib
realpath = GLib.get_current_dir()
sys.path.append(realpath + '/Modules/')
sys.path.append(realpath + '/Apps/')
from Apps.MenuBar import MenuBar
from Apps.AppsWindow import AppsWindow
os.system('python MenuBar_main.py &')
os.system('python AppsWindow_main.py &')
| {
"content_hash": "23b1f2d9b3a836f7ff1f6f8e4104adb2",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 40,
"avg_line_length": 21.266666666666666,
"alnum_prop": 0.7523510971786834,
"repo_name": "OlivierLarrieu/HYDV2",
"id": "176cb617655d1c820c4740bb0a34feec3cf4ba0e",
"size": "364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7519"
},
{
"name": "Python",
"bytes": "163525"
},
{
"name": "Shell",
"bytes": "72"
}
],
"symlink_target": ""
} |
#import "CAGradientLayer.h"
#import "IDENavigationHUDDisposableLayer-Protocol.h"
#import "IDENavigationHUDSelectableLayer-Protocol.h"
#import "IDENavigationHUDWindowLevelNavigableLayer-Protocol.h"
@class IDENavigationHUDController, IDENavigationHUDSelection;
@interface IDENavigationHUDAbstractWorkspaceWindowLayer : CAGradientLayer <IDENavigationHUDSelectableLayer, IDENavigationHUDWindowLevelNavigableLayer, IDENavigationHUDDisposableLayer>
{
IDENavigationHUDController *_navigationHUDController;
}
- (void)dispose;
- (id)initWithNavigationHUDController:(id)arg1;
@property(readonly) IDENavigationHUDController *navigationHUDController; // @synthesize navigationHUDController=_navigationHUDController;
@property(readonly) IDENavigationHUDSelection *representativeSelection;
@property(readonly) BOOL representativeSelectionIsFinalForSingleMouseUp;
- (id)selectionForNavigatingDown;
- (id)selectionForNavigatingLeft;
- (id)selectionForNavigatingLeftOneTab;
- (id)selectionForNavigatingRight;
- (id)selectionForNavigatingRightOneTab;
- (id)selectionForNavigatingUp;
@end
| {
"content_hash": "05274253c28323a98d4d063be785c66b",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 183,
"avg_line_length": 37.310344827586206,
"alnum_prop": 0.8595194085027726,
"repo_name": "djromero/ShowInGitHub",
"id": "988e0ab86875aaad8a4e81f748e891a916067d06",
"size": "1222",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Source/Libraries/XcodeFrameworks/IDEKit/IDENavigationHUDAbstractWorkspaceWindowLayer.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "2079"
},
{
"name": "Objective-C",
"bytes": "992254"
}
],
"symlink_target": ""
} |
namespace capnp {
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
class VatNetwork;
template <typename SturdyRefObjectId>
class SturdyRefRestorer;
template <typename VatId>
class BootstrapFactory: public _::BootstrapFactoryBase {
// Interface that constructs per-client bootstrap interfaces. Use this if you want each client
// who connects to see a different bootstrap interface based on their (authenticated) VatId.
// This allows an application to bootstrap off of the authentication performed at the VatNetwork
// level. (Typically VatId is some sort of public key.)
//
// This is only useful for multi-party networks. For TwoPartyVatNetwork, there's no reason to
// use a BootstrapFactory; just specify a single bootstrap capability in this case.
public:
virtual Capability::Client createFor(typename VatId::Reader clientId) = 0;
// Create a bootstrap capability appropriate for exposing to the given client. VatNetwork will
// have authenticated the client VatId before this is called.
private:
Capability::Client baseCreateFor(AnyStruct::Reader clientId) override;
};
template <typename VatId>
class RpcSystem: public _::RpcSystemBase {
// Represents the RPC system, which is the portal to objects available on the network.
//
// The RPC implementation sits on top of an implementation of `VatNetwork`. The `VatNetwork`
// determines how to form connections between vats -- specifically, two-way, private, reliable,
// sequenced datagram connections. The RPC implementation determines how to use such connections
// to manage object references and make method calls.
//
// See `makeRpcServer()` and `makeRpcClient()` below for convenient syntax for setting up an
// `RpcSystem` given a `VatNetwork`.
//
// See `ez-rpc.h` for an even simpler interface for setting up RPC in a typical two-party
// client/server scenario.
public:
template <typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
kj::Maybe<Capability::Client> bootstrapInterface,
kj::Maybe<RealmGateway<>::Client> gateway = nullptr);
template <typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
BootstrapFactory<VatId>& bootstrapFactory,
kj::Maybe<RealmGateway<>::Client> gateway = nullptr);
template <typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult,
typename LocalSturdyRefObjectId>
RpcSystem(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
SturdyRefRestorer<LocalSturdyRefObjectId>& restorer);
RpcSystem(RpcSystem&& other) = default;
Capability::Client bootstrap(typename VatId::Reader vatId);
// Connect to the given vat and return its bootstrap interface.
Capability::Client restore(typename VatId::Reader hostId, AnyPointer::Reader objectId)
KJ_DEPRECATED("Please transition to using a bootstrap interface instead.");
// ** DEPRECATED **
//
// Restores the given SturdyRef from the network and return the capability representing it.
//
// `hostId` identifies the host from which to request the ref, in the format specified by the
// `VatNetwork` in use. `objectId` is the object ID in whatever format is expected by said host.
//
// This method will be removed in a future version of Cap'n Proto. Instead, please transition
// to using bootstrap(), which is equivalent to calling restore() with a null `objectId`.
// You may emulate the old concept of object IDs by exporting a bootstrap interface which has
// methods that can be used to obtain other capabilities by ID.
void setFlowLimit(size_t words);
// Sets the incoming call flow limit. If more than `words` worth of call messages have not yet
// received responses, the RpcSystem will not read further messages from the stream. This can be
// used as a crude way to prevent a resource exhaustion attack (or bug) in which a peer makes an
// excessive number of simultaneous calls that consume the receiver's RAM.
//
// There are some caveats. When over the flow limit, all messages are blocked, including returns.
// If the outstanding calls are themselves waiting on calls going in the opposite direction, the
// flow limit may prevent those calls from completing, leading to deadlock. However, a
// sufficiently high limit should make this unlikely.
//
// Note that a call's parameter size counts against the flow limit until the call returns, even
// if the recipient calls releaseParams() to free the parameter memory early. This is because
// releaseParams() may simply indicate that the parameters have been forwarded to another
// machine, but are still in-memory there. For illustration, say that Alice made a call to Bob
// who forwarded the call to Carol. Bob has imposed a flow limit on Alice. Alice's calls are
// being forwarded to Carol, so Bob never keeps the parameters in-memory for more than a brief
// period. However, the flow limit counts all calls that haven't returned, even if Bob has
// already freed the memory they consumed. You might argue that the right solution here is
// instead for Carol to impose her own flow limit on Bob. This has a serious problem, though:
// Bob might be forwarding requests to Carol on behalf of many different parties, not just Alice.
// If Alice can pump enough data to hit the Bob -> Carol flow limit, then those other parties
// will be disrupted. Thus, we can only really impose the limit on the Alice -> Bob link, which
// only affects Alice. We need that one flow limit to limit Alice's impact on the whole system,
// so it has to count all in-flight calls.
//
// In Sandstorm, flow limits are imposed by the supervisor on calls coming out of a grain, in
// order to prevent a grain from inundating the system with in-flight calls. In practice, the
// main time this happens is when a grain is pushing a large file download and doesn't implement
// proper cooperative flow control.
};
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
Capability::Client bootstrapInterface);
// Make an RPC server. Typical usage (e.g. in a main() function):
//
// MyEventLoop eventLoop;
// kj::WaitScope waitScope(eventLoop);
// MyNetwork network;
// MyMainInterface::Client bootstrap = makeMain();
// auto server = makeRpcServer(network, bootstrap);
// kj::NEVER_DONE.wait(waitScope); // run forever
//
// See also ez-rpc.h, which has simpler instructions for the common case of a two-party
// client-server RPC connection.
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult, typename RealmGatewayClient,
typename InternalRef = _::InternalRefFromRealmGatewayClient<RealmGatewayClient>,
typename ExternalRef = _::ExternalRefFromRealmGatewayClient<RealmGatewayClient>>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
Capability::Client bootstrapInterface, RealmGatewayClient gateway);
// Make an RPC server for a VatNetwork that resides in a different realm from the application.
// The given RealmGateway is used to translate SturdyRefs between the app's ("internal") format
// and the network's ("external") format.
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
BootstrapFactory<VatId>& bootstrapFactory);
// Make an RPC server that can serve different bootstrap interfaces to different clients via a
// BootstrapInterface.
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult, typename RealmGatewayClient,
typename InternalRef = _::InternalRefFromRealmGatewayClient<RealmGatewayClient>,
typename ExternalRef = _::ExternalRefFromRealmGatewayClient<RealmGatewayClient>>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
BootstrapFactory<VatId>& bootstrapFactory, RealmGatewayClient gateway);
// Make an RPC server that can serve different bootstrap interfaces to different clients via a
// BootstrapInterface and communicates with a different realm than the application is in via a
// RealmGateway.
template <typename VatId, typename LocalSturdyRefObjectId,
typename ProvisionId, typename RecipientId, typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
SturdyRefRestorer<LocalSturdyRefObjectId>& restorer)
KJ_DEPRECATED("Please transition to using a bootstrap interface instead.");
// ** DEPRECATED **
//
// Create an RPC server which exports multiple main interfaces by object ID. The `restorer` object
// can be used to look up objects by ID.
//
// Please transition to exporting only one interface, which is known as the "bootstrap" interface.
// For backwards-compatibility with old clients, continue to implement SturdyRefRestorer, but
// return the new bootstrap interface when the request object ID is null. When new clients connect
// and request the bootstrap interface, they will get that interface. Eventually, once all clients
// are updated to request only the bootstrap interface, stop implementing SturdyRefRestorer and
// switch to passing the bootstrap capability itself as the second parameter to `makeRpcServer()`.
template <typename VatId, typename ProvisionId,
typename RecipientId, typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcClient(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network);
// Make an RPC client. Typical usage (e.g. in a main() function):
//
// MyEventLoop eventLoop;
// kj::WaitScope waitScope(eventLoop);
// MyNetwork network;
// auto client = makeRpcClient(network);
// MyCapability::Client cap = client.restore(hostId, objId).castAs<MyCapability>();
// auto response = cap.fooRequest().send().wait(waitScope);
// handleMyResponse(response);
//
// See also ez-rpc.h, which has simpler instructions for the common case of a two-party
// client-server RPC connection.
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult, typename RealmGatewayClient,
typename InternalRef = _::InternalRefFromRealmGatewayClient<RealmGatewayClient>,
typename ExternalRef = _::ExternalRefFromRealmGatewayClient<RealmGatewayClient>>
RpcSystem<VatId> makeRpcClient(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
RealmGatewayClient gateway);
// Make an RPC client for a VatNetwork that resides in a different realm from the application.
// The given RealmGateway is used to translate SturdyRefs between the app's ("internal") format
// and the network's ("external") format.
template <typename SturdyRefObjectId>
class SturdyRefRestorer: public _::SturdyRefRestorerBase {
// ** DEPRECATED **
//
// In Cap'n Proto 0.4.x, applications could export multiple main interfaces identified by
// object IDs. The callback used to map object IDs to objects was `SturdyRefRestorer`, as we
// imagined this would eventually be used for restoring SturdyRefs as well. In practice, it was
// never used for real SturdyRefs, only for exporting singleton objects under well-known names.
//
// The new preferred strategy is to export only a _single_ such interface, called the
// "bootstrap interface". That interface can itself have methods for obtaining other objects, of
// course, but that is up to the app. `SturdyRefRestorer` exists for backwards-compatibility.
//
// Hint: Use SturdyRefRestorer<capnp::Text> to define a server that exports services under
// string names.
public:
virtual Capability::Client restore(typename SturdyRefObjectId::Reader ref)
KJ_DEPRECATED(
"Please transition to using bootstrap interfaces instead of SturdyRefRestorer.") = 0;
// Restore the given object, returning a capability representing it.
private:
Capability::Client baseRestore(AnyPointer::Reader ref) override final;
};
// =======================================================================================
// VatNetwork
class OutgoingRpcMessage {
// A message to be sent by a `VatNetwork`.
public:
virtual AnyPointer::Builder getBody() = 0;
// Get the message body, which the caller may fill in any way it wants. (The standard RPC
// implementation initializes it as a Message as defined in rpc.capnp.)
virtual void send() = 0;
// Send the message, or at least put it in a queue to be sent later. Note that the builder
// returned by `getBody()` remains valid at least until the `OutgoingRpcMessage` is destroyed.
};
class IncomingRpcMessage {
// A message received from a `VatNetwork`.
public:
virtual AnyPointer::Reader getBody() = 0;
// Get the message body, to be interpreted by the caller. (The standard RPC implementation
// interprets it as a Message as defined in rpc.capnp.)
};
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
class VatNetwork: public _::VatNetworkBase {
// Cap'n Proto RPC operates between vats, where a "vat" is some sort of host of objects.
// Typically one Cap'n Proto process (in the Unix sense) is one vat. The RPC system is what
// allows calls between objects hosted in different vats.
//
// The RPC implementation sits on top of an implementation of `VatNetwork`. The `VatNetwork`
// determines how to form connections between vats -- specifically, two-way, private, reliable,
// sequenced datagram connections. The RPC implementation determines how to use such connections
// to manage object references and make method calls.
//
// The most common implementation of VatNetwork is TwoPartyVatNetwork (rpc-twoparty.h). Most
// simple client-server apps will want to use it. (You may even want to use the EZ RPC
// interfaces in `ez-rpc.h` and avoid all of this.)
//
// TODO(someday): Provide a standard implementation for the public internet.
public:
class Connection;
struct ConnectionAndProvisionId {
// Result of connecting to a vat introduced by another vat.
kj::Own<Connection> connection;
// Connection to the new vat.
kj::Own<OutgoingRpcMessage> firstMessage;
// An already-allocated `OutgoingRpcMessage` associated with `connection`. The RPC system will
// construct this as an `Accept` message and send it.
Orphan<ProvisionId> provisionId;
// A `ProvisionId` already allocated inside `firstMessage`, which the RPC system will use to
// build the `Accept` message.
};
class Connection: public _::VatNetworkBase::Connection {
// A two-way RPC connection.
//
// This object may represent a connection that doesn't exist yet, but is expected to exist
// in the future. In this case, sent messages will automatically be queued and sent once the
// connection is ready, so that the caller doesn't need to know the difference.
public:
// Level 0 features ----------------------------------------------
virtual typename VatId::Reader getPeerVatId() = 0;
// Returns the connected vat's authenticated VatId. It is the VatNetwork's responsibility to
// authenticate this, so that the caller can be assured that they are really talking to the
// identified vat and not an imposter.
virtual kj::Own<OutgoingRpcMessage> newOutgoingMessage(uint firstSegmentWordSize) = 0;
// Allocate a new message to be sent on this connection.
//
// If `firstSegmentWordSize` is non-zero, it should be treated as a hint suggesting how large
// to make the first segment. This is entirely a hint and the connection may adjust it up or
// down. If it is zero, the connection should choose the size itself.
virtual kj::Promise<kj::Maybe<kj::Own<IncomingRpcMessage>>> receiveIncomingMessage() = 0;
// Wait for a message to be received and return it. If the read stream cleanly terminates,
// return null. If any other problem occurs, throw an exception.
virtual kj::Promise<void> shutdown() KJ_WARN_UNUSED_RESULT = 0;
// Waits until all outgoing messages have been sent, then shuts down the outgoing stream. The
// returned promise resolves after shutdown is complete.
private:
AnyStruct::Reader baseGetPeerVatId() override;
};
// Level 0 features ------------------------------------------------
virtual kj::Maybe<kj::Own<Connection>> connect(typename VatId::Reader hostId) = 0;
// Connect to a VatId. Note that this method immediately returns a `Connection`, even
// if the network connection has not yet been established. Messages can be queued to this
// connection and will be delivered once it is open. The caller must attempt to read from the
// connection to verify that it actually succeeded; the read will fail if the connection
// couldn't be opened. Some network implementations may actually start sending messages before
// hearing back from the server at all, to avoid a round trip.
//
// Returns nullptr if `hostId` refers to the local host.
virtual kj::Promise<kj::Own<Connection>> accept() = 0;
// Wait for the next incoming connection and return it.
// Level 4 features ------------------------------------------------
// TODO(someday)
private:
kj::Maybe<kj::Own<_::VatNetworkBase::Connection>>
baseConnect(AnyStruct::Reader hostId) override final;
kj::Promise<kj::Own<_::VatNetworkBase::Connection>> baseAccept() override final;
};
// =======================================================================================
// ***************************************************************************************
// Inline implementation details start here
// ***************************************************************************************
// =======================================================================================
template <typename VatId>
Capability::Client BootstrapFactory<VatId>::baseCreateFor(AnyStruct::Reader clientId) {
return createFor(clientId.as<VatId>());
}
template <typename SturdyRef, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
kj::Maybe<kj::Own<_::VatNetworkBase::Connection>>
VatNetwork<SturdyRef, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>::
baseConnect(AnyStruct::Reader ref) {
auto maybe = connect(ref.as<SturdyRef>());
return maybe.map([](kj::Own<Connection>& conn) -> kj::Own<_::VatNetworkBase::Connection> {
return kj::mv(conn);
});
}
template <typename SturdyRef, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
kj::Promise<kj::Own<_::VatNetworkBase::Connection>>
VatNetwork<SturdyRef, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>::baseAccept() {
return accept().then(
[](kj::Own<Connection>&& connection) -> kj::Own<_::VatNetworkBase::Connection> {
return kj::mv(connection);
});
}
template <typename SturdyRef, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
AnyStruct::Reader VatNetwork<
SturdyRef, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>::
Connection::baseGetPeerVatId() {
return getPeerVatId();
}
template <typename SturdyRef>
Capability::Client SturdyRefRestorer<SturdyRef>::baseRestore(AnyPointer::Reader ref) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
return restore(ref.getAs<SturdyRef>());
#pragma GCC diagnostic pop
}
template <typename VatId>
template <typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId>::RpcSystem(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
kj::Maybe<Capability::Client> bootstrap,
kj::Maybe<RealmGateway<>::Client> gateway)
: _::RpcSystemBase(network, kj::mv(bootstrap), kj::mv(gateway)) {}
template <typename VatId>
template <typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId>::RpcSystem(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
BootstrapFactory<VatId>& bootstrapFactory,
kj::Maybe<RealmGateway<>::Client> gateway)
: _::RpcSystemBase(network, bootstrapFactory, kj::mv(gateway)) {}
template <typename VatId>
template <typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult,
typename LocalSturdyRefObjectId>
RpcSystem<VatId>::RpcSystem(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
SturdyRefRestorer<LocalSturdyRefObjectId>& restorer)
: _::RpcSystemBase(network, restorer) {}
template <typename VatId>
Capability::Client RpcSystem<VatId>::bootstrap(typename VatId::Reader vatId) {
return baseBootstrap(_::PointerHelpers<VatId>::getInternalReader(vatId));
}
template <typename VatId>
Capability::Client RpcSystem<VatId>::restore(
typename VatId::Reader hostId, AnyPointer::Reader objectId) {
return baseRestore(_::PointerHelpers<VatId>::getInternalReader(hostId), objectId);
}
template <typename VatId>
inline void RpcSystem<VatId>::setFlowLimit(size_t words) {
baseSetFlowLimit(words);
}
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
Capability::Client bootstrapInterface) {
return RpcSystem<VatId>(network, kj::mv(bootstrapInterface));
}
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult,
typename RealmGatewayClient, typename InternalRef, typename ExternalRef>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
Capability::Client bootstrapInterface, RealmGatewayClient gateway) {
return RpcSystem<VatId>(network, kj::mv(bootstrapInterface),
gateway.template castAs<RealmGateway<>>());
}
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
BootstrapFactory<VatId>& bootstrapFactory) {
return RpcSystem<VatId>(network, bootstrapFactory);
}
template <typename VatId, typename ProvisionId, typename RecipientId,
typename ThirdPartyCapId, typename JoinResult,
typename RealmGatewayClient, typename InternalRef, typename ExternalRef>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
BootstrapFactory<VatId>& bootstrapFactory, RealmGatewayClient gateway) {
return RpcSystem<VatId>(network, bootstrapFactory, gateway.template castAs<RealmGateway<>>());
}
template <typename VatId, typename LocalSturdyRefObjectId,
typename ProvisionId, typename RecipientId, typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcServer(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
SturdyRefRestorer<LocalSturdyRefObjectId>& restorer) {
return RpcSystem<VatId>(network, restorer);
}
template <typename VatId, typename ProvisionId,
typename RecipientId, typename ThirdPartyCapId, typename JoinResult>
RpcSystem<VatId> makeRpcClient(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network) {
return RpcSystem<VatId>(network, nullptr);
}
template <typename VatId, typename ProvisionId,
typename RecipientId, typename ThirdPartyCapId, typename JoinResult,
typename RealmGatewayClient, typename InternalRef, typename ExternalRef>
RpcSystem<VatId> makeRpcClient(
VatNetwork<VatId, ProvisionId, RecipientId, ThirdPartyCapId, JoinResult>& network,
RealmGatewayClient gateway) {
return RpcSystem<VatId>(network, nullptr, gateway.template castAs<RealmGateway<>>());
}
} // namespace capnp
#endif // CAPNP_RPC_H_
| {
"content_hash": "ee35b2b097c8f6d8d24c0b524679405b",
"timestamp": "",
"source": "github",
"line_count": 506,
"max_line_length": 100,
"avg_line_length": 49.80632411067194,
"alnum_prop": 0.7345845567812078,
"repo_name": "hntrmrrs/capnproto",
"id": "6bc7e4581db9320f6141a1aa52f6ef5c6fcc5a6f",
"size": "26575",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "c++/src/capnp/rpc.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "4464080"
},
{
"name": "CMake",
"bytes": "19519"
},
{
"name": "Cap'n Proto",
"bytes": "165125"
},
{
"name": "Emacs Lisp",
"bytes": "2097"
},
{
"name": "M4",
"bytes": "24966"
},
{
"name": "Makefile",
"bytes": "22544"
},
{
"name": "Protocol Buffer",
"bytes": "5344"
},
{
"name": "Python",
"bytes": "3926"
},
{
"name": "Shell",
"bytes": "39844"
}
],
"symlink_target": ""
} |
class Short < Trade
private
def compute_cash_delta
if shares.nil? || price.nil?
self.cash_delta = nil
else
self.cash_delta = shares * price - commission
end
end
def compute_shares_delta
self.shares_delta = -shares
end
end | {
"content_hash": "ba4774937e9672e48136af5f25620a09",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 51,
"avg_line_length": 15.470588235294118,
"alnum_prop": 0.6387832699619772,
"repo_name": "sandiegoscott/portfolioz",
"id": "88067379c84feda6ecfdb6a6dd574a894857837a",
"size": "263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/transactions/trades/short.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2108"
},
{
"name": "HTML",
"bytes": "15415"
},
{
"name": "JavaScript",
"bytes": "696"
},
{
"name": "Ruby",
"bytes": "97179"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe "Mutations::BooleanFilter" do
it "allows booleans" do
f = Mutations::BooleanFilter.new
filtered, errors = f.filter(true)
assert_equal true, filtered
assert_equal nil, errors
filtered, errors = f.filter(false)
assert_equal false, filtered
assert_equal nil, errors
end
it "considers non-booleans to be invalid" do
f = Mutations::BooleanFilter.new
[[true], {:a => "1"}, Object.new].each do |thing|
_filtered, errors = f.filter(thing)
assert_equal :boolean, errors
end
end
it "considers nil to be invalid" do
f = Mutations::BooleanFilter.new(:nils => false)
filtered, errors = f.filter(nil)
assert_equal nil, filtered
assert_equal :nils, errors
end
it "considers nil to be valid" do
f = Mutations::BooleanFilter.new(:nils => true)
filtered, errors = f.filter(nil)
assert_equal nil, filtered
assert_equal nil, errors
end
it "considers certain strings to be valid booleans" do
f = Mutations::BooleanFilter.new
[["true", true], ["TRUE", true], ["TrUe", true], ["1", true], ["false", false], ["FALSE", false], ["FalSe", false], ["0", false], [0, false], [1, true]].each do |(str, v)|
filtered, errors = f.filter(str)
assert_equal v, filtered
assert_equal nil, errors
end
end
it "considers empty strings to be empty" do
f = Mutations::BooleanFilter.new
_filtered, errors = f.filter("")
assert_equal :empty, errors
end
it "considers other string to be invalid" do
f = Mutations::BooleanFilter.new
["truely", "2"].each do |str|
filtered, errors = f.filter(str)
assert_equal str, filtered
assert_equal :boolean, errors
end
end
end
| {
"content_hash": "64de8fbfb212cdbaad96a3892e08eb80",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 175,
"avg_line_length": 28.60655737704918,
"alnum_prop": 0.6446991404011462,
"repo_name": "cypriss/mutations",
"id": "0049e0dc3dcb4d0c439213f7927b4fcff293f943",
"size": "1745",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/boolean_filter_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "98784"
}
],
"symlink_target": ""
} |
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <openssl/ssl.h>
#include <assert.h>
#include "internal.h"
const char *SSL_state_string_long(const SSL *ssl) {
if (ssl->s3->hs == nullptr) {
return "SSL negotiation finished successfully";
}
return ssl->server ? ssl_server_handshake_state(ssl->s3->hs.get())
: ssl_client_handshake_state(ssl->s3->hs.get());
}
const char *SSL_state_string(const SSL *ssl) {
return "!!!!!!";
}
const char *SSL_alert_type_string_long(int value) {
value >>= 8;
if (value == SSL3_AL_WARNING) {
return "warning";
} else if (value == SSL3_AL_FATAL) {
return "fatal";
}
return "unknown";
}
const char *SSL_alert_type_string(int value) {
return "!";
}
const char *SSL_alert_desc_string(int value) {
return "!!";
}
const char *SSL_alert_desc_string_long(int value) {
switch (value & 0xff) {
case SSL3_AD_CLOSE_NOTIFY:
return "close notify";
case SSL3_AD_UNEXPECTED_MESSAGE:
return "unexpected_message";
case SSL3_AD_BAD_RECORD_MAC:
return "bad record mac";
case SSL3_AD_DECOMPRESSION_FAILURE:
return "decompression failure";
case SSL3_AD_HANDSHAKE_FAILURE:
return "handshake failure";
case SSL3_AD_NO_CERTIFICATE:
return "no certificate";
case SSL3_AD_BAD_CERTIFICATE:
return "bad certificate";
case SSL3_AD_UNSUPPORTED_CERTIFICATE:
return "unsupported certificate";
case SSL3_AD_CERTIFICATE_REVOKED:
return "certificate revoked";
case SSL3_AD_CERTIFICATE_EXPIRED:
return "certificate expired";
case SSL3_AD_CERTIFICATE_UNKNOWN:
return "certificate unknown";
case SSL3_AD_ILLEGAL_PARAMETER:
return "illegal parameter";
case TLS1_AD_DECRYPTION_FAILED:
return "decryption failed";
case TLS1_AD_RECORD_OVERFLOW:
return "record overflow";
case TLS1_AD_UNKNOWN_CA:
return "unknown CA";
case TLS1_AD_ACCESS_DENIED:
return "access denied";
case TLS1_AD_DECODE_ERROR:
return "decode error";
case TLS1_AD_DECRYPT_ERROR:
return "decrypt error";
case TLS1_AD_EXPORT_RESTRICTION:
return "export restriction";
case TLS1_AD_PROTOCOL_VERSION:
return "protocol version";
case TLS1_AD_INSUFFICIENT_SECURITY:
return "insufficient security";
case TLS1_AD_INTERNAL_ERROR:
return "internal error";
case SSL3_AD_INAPPROPRIATE_FALLBACK:
return "inappropriate fallback";
case TLS1_AD_USER_CANCELLED:
return "user canceled";
case TLS1_AD_NO_RENEGOTIATION:
return "no renegotiation";
case TLS1_AD_MISSING_EXTENSION:
return "missing extension";
case TLS1_AD_UNSUPPORTED_EXTENSION:
return "unsupported extension";
case TLS1_AD_CERTIFICATE_UNOBTAINABLE:
return "certificate unobtainable";
case TLS1_AD_UNRECOGNIZED_NAME:
return "unrecognized name";
case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return "bad certificate status response";
case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE:
return "bad certificate hash value";
case TLS1_AD_UNKNOWN_PSK_IDENTITY:
return "unknown PSK identity";
case TLS1_AD_CERTIFICATE_REQUIRED:
return "certificate required";
case TLS1_AD_NO_APPLICATION_PROTOCOL:
return "no application protocol";
default:
return "unknown";
}
}
| {
"content_hash": "a887af33613667a1bdd78eb82ab79cbd",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 73,
"avg_line_length": 26.16,
"alnum_prop": 0.6771515945827873,
"repo_name": "endlessm/chromium-browser",
"id": "5770aac7be7965553229d2776f977b16bbc2ad6b",
"size": "7740",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "third_party/boringssl/src/ssl/ssl_stat.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0-google-v5) on Thu Dec 19 17:42:43 EST 2013 -->
<title>UserDomainTargeting</title>
<meta name="date" content="2013-12-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="UserDomainTargeting";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainRateCardFeature.html" title="class in com.google.api.ads.dfp.v201308"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargetingError.html" title="class in com.google.api.ads.dfp.v201308"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/api/ads/dfp/v201308/UserDomainTargeting.html" target="_top">Frames</a></li>
<li><a href="UserDomainTargeting.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.google.api.ads.dfp.v201308</div>
<h2 title="Class UserDomainTargeting" class="title">Class UserDomainTargeting</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.google.api.ads.dfp.v201308.UserDomainTargeting</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable</dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">UserDomainTargeting</span>
extends java.lang.Object
implements java.io.Serializable</pre>
<div class="block">Provides line items the ability to target or exclude users visiting
their
websites from a list of domains or subdomains.</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../serialized-form.html#com.google.api.ads.dfp.v201308.UserDomainTargeting">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#UserDomainTargeting()">UserDomainTargeting</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#UserDomainTargeting(java.lang.String[], java.lang.Boolean)">UserDomainTargeting</a></strong>(java.lang.String[] domains,
java.lang.Boolean targeted)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object obj)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static org.apache.axis.encoding.Deserializer</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#getDeserializer(java.lang.String, java.lang.Class, javax.xml.namespace.QName)">getDeserializer</a></strong>(java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType)</code>
<div class="block">Get Custom Deserializer</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String[]</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#getDomains()">getDomains</a></strong>()</code>
<div class="block">Gets the domains value for this UserDomainTargeting.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#getDomains(int)">getDomains</a></strong>(int i)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static org.apache.axis.encoding.Serializer</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#getSerializer(java.lang.String, java.lang.Class, javax.xml.namespace.QName)">getSerializer</a></strong>(java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType)</code>
<div class="block">Get Custom Serializer</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.Boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#getTargeted()">getTargeted</a></strong>()</code>
<div class="block">Gets the targeted value for this UserDomainTargeting.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static org.apache.axis.description.TypeDesc</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#getTypeDesc()">getTypeDesc</a></strong>()</code>
<div class="block">Return type metadata object</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#hashCode()">hashCode</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#setDomains(int, java.lang.String)">setDomains</a></strong>(int i,
java.lang.String _value)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#setDomains(java.lang.String[])">setDomains</a></strong>(java.lang.String[] domains)</code>
<div class="block">Sets the domains value for this UserDomainTargeting.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargeting.html#setTargeted(java.lang.Boolean)">setTargeted</a></strong>(java.lang.Boolean targeted)</code>
<div class="block">Sets the targeted value for this UserDomainTargeting.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="UserDomainTargeting()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>UserDomainTargeting</h4>
<pre>public UserDomainTargeting()</pre>
</li>
</ul>
<a name="UserDomainTargeting(java.lang.String[], java.lang.Boolean)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>UserDomainTargeting</h4>
<pre>public UserDomainTargeting(java.lang.String[] domains,
java.lang.Boolean targeted)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getDomains()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDomains</h4>
<pre>public java.lang.String[] getDomains()</pre>
<div class="block">Gets the domains value for this UserDomainTargeting.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>domains * The domains or subdomains that are being targeted or excluded
by the
<a href="../../../../../../com/google/api/ads/dfp/v201308/LineItem.html" title="class in com.google.api.ads.dfp.v201308"><code>LineItem</code></a>. This attribute is required and the
maximum length of each
domain is 67 characters.</dd></dl>
</li>
</ul>
<a name="setDomains(java.lang.String[])">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDomains</h4>
<pre>public void setDomains(java.lang.String[] domains)</pre>
<div class="block">Sets the domains value for this UserDomainTargeting.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>domains</code> - * The domains or subdomains that are being targeted or excluded
by the
<a href="../../../../../../com/google/api/ads/dfp/v201308/LineItem.html" title="class in com.google.api.ads.dfp.v201308"><code>LineItem</code></a>. This attribute is required and the
maximum length of each
domain is 67 characters.</dd></dl>
</li>
</ul>
<a name="getDomains(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDomains</h4>
<pre>public java.lang.String getDomains(int i)</pre>
</li>
</ul>
<a name="setDomains(int, java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDomains</h4>
<pre>public void setDomains(int i,
java.lang.String _value)</pre>
</li>
</ul>
<a name="getTargeted()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTargeted</h4>
<pre>public java.lang.Boolean getTargeted()</pre>
<div class="block">Gets the targeted value for this UserDomainTargeting.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>targeted * Indicates whether domains should be targeted or excluded. This
attribute is
optional and defaults to <code>true</code>.</dd></dl>
</li>
</ul>
<a name="setTargeted(java.lang.Boolean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTargeted</h4>
<pre>public void setTargeted(java.lang.Boolean targeted)</pre>
<div class="block">Sets the targeted value for this UserDomainTargeting.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>targeted</code> - * Indicates whether domains should be targeted or excluded. This
attribute is
optional and defaults to <code>true</code>.</dd></dl>
</li>
</ul>
<a name="equals(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(java.lang.Object obj)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>equals</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="hashCode()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hashCode</h4>
<pre>public int hashCode()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>hashCode</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="getTypeDesc()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTypeDesc</h4>
<pre>public static org.apache.axis.description.TypeDesc getTypeDesc()</pre>
<div class="block">Return type metadata object</div>
</li>
</ul>
<a name="getSerializer(java.lang.String, java.lang.Class, javax.xml.namespace.QName)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getSerializer</h4>
<pre>public static org.apache.axis.encoding.Serializer getSerializer(java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType)</pre>
<div class="block">Get Custom Serializer</div>
</li>
</ul>
<a name="getDeserializer(java.lang.String, java.lang.Class, javax.xml.namespace.QName)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getDeserializer</h4>
<pre>public static org.apache.axis.encoding.Deserializer getDeserializer(java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType)</pre>
<div class="block">Get Custom Deserializer</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainRateCardFeature.html" title="class in com.google.api.ads.dfp.v201308"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/google/api/ads/dfp/v201308/UserDomainTargetingError.html" title="class in com.google.api.ads.dfp.v201308"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/api/ads/dfp/v201308/UserDomainTargeting.html" target="_top">Frames</a></li>
<li><a href="UserDomainTargeting.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "d3d5ec8663ec3840b0601814aede94e7",
"timestamp": "",
"source": "github",
"line_count": 462,
"max_line_length": 256,
"avg_line_length": 38.495670995671,
"alnum_prop": 0.6465560865898229,
"repo_name": "google-code-export/google-api-dfp-java",
"id": "cded4c973d64defbd081b9fdebd583cd56a837f1",
"size": "17785",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/com/google/api/ads/dfp/v201308/UserDomainTargeting.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "39950935"
}
],
"symlink_target": ""
} |
"""
Formatting and style flags for ecstasy.
"""
from enum import Enum, unique
import ecstasy.errors as errors
LIMIT = 0
class Hack(object):
"""
A hack namespace to make enumeration work continuously
across multiple flag enum-classes. 'last' will be
set to the last enumerated enum-class and
start to the value at which the flag values
of the enum-class currently being evaluated
in the Flags.__new__() method start (i.e. start
is the flag value of the previous enum-class left-
shifted by one bit).
"""
last = None
start = 1
class Flags(Enum):
"""
Base class for all flag enum-classes as well as the
individual flag objects/enum members inside the classes
(by virtue of the enum.Enum semantics).
The most important re-defined method is __new__ which initializes
a flag with a command-line format/style escape-code specific to
the flag, as well as with a numeric value (power of 2) that
depends on its position inside the enum-class and also on the
position of the enum-class itself inside the order of enum
classes (as the Hack mechanism will continuously increment
flag values over multiple Flags sub-enum-classes). This class
also defines various necessary operator and conversion overloads
that define the semantics/interaction of flags (such as that
you can bitwise-OR and bitwise-AND them).
"""
def __new__(cls, code):
"""
Constructs a new flag value.
Apart from constructing a flag via object.__new__,
this method also sets the flags 'code' attribute
and its value, which is automatically determined
by the position of the flag in all enum-classes.
"""
global LIMIT
if cls is not Hack.last:
if Hack.last:
# Last flag left shifted by 1 bit
Hack.start = list(Hack.last)[-1].value << 1
Hack.last = cls
obj = object.__new__(cls)
obj._value_ = Hack.start << len(cls) # noqa
obj.code = str(code)
LIMIT = obj._value_ << 1 # noqa
return obj
def __int__(self):
"""
Converts the flag to its value.
Returns:
The integer value stored inside the flag's 'value' attribute.
"""
return self.value
def __str__(self):
"""
Turns the flag into its style-code.
Returns:
The flag's style/formatting code.
"""
return self.code
def __or__(self, other):
"""
Bitwise-OR operator overload.
Arguments:
other (Flag or int): A flag or a flag-combination (i.e. an integer).
Returns:
The combination of the bitwise-OR-ed flags (int).
"""
return self.value | int(other)
def __ror__(self, other):
"""
Reverse Bitwise-OR operator overload.
Arguments:
other (int): An integer value, usually a flag combination.
Returns:
The combination of the passed integer and the flag (int).
"""
return self.value | other
def __and__(self, other):
"""
Bitwise-OR operator overload.
Arguments:
other (Flags): A flag.
Returns:
The combination of the bitwise-OR-ed flags (int).
"""
return self.value & other.value
def __rand__(self, other):
"""
Reverse Bitwise-AND operator overload.
Arguments:
other (int): An integer value, usually a flag combination.
Returns:
The result of AND-ing the passed integer and the flag (int).
"""
return other & self.value
@unique
class Style(Flags):
"""
Special formatting flags pertaining to any style
alterations that do not involve color (but other
factors of appearence).
"""
Reset = (0)
Bold = (1)
Dim = (2)
Underline = (4)
Blink = (5)
Invert = (7)
Hidden = (8)
@unique
class Color(Flags):
"""
Text color flags (not fill-color).
"""
Default = (39)
Black = (30)
DarkRed = (31)
DarkGreen = (32)
DarkYellow = (33)
DarkBlue = (34)
DarkMagenta = (35)
DarkCyan = (36)
Gray = (37)
DarkGray = (90)
Red = (91)
Green = (92)
Yellow = (93)
Blue = (94)
Magenta = (95)
Cyan = (96)
White = (97)
@unique
class Fill(Flags):
"""
Fill color flags (not text-color).
"""
Default = (49)
Black = (40)
DarkRed = (41)
DarkGreen = (42)
DarkYellow = (43)
DarkBlue = (44)
DarkMagenta = (45)
DarkCyan = (46)
Gray = (47)
DarkGray = (100)
Red = (101)
Green = (102)
Yellow = (103)
Blue = (104)
Magenta = (105)
Cyan = (106)
White = (107)
def codify(combination):
"""
Gets escape-codes for flag combinations.
Arguments:
combination (int): Either a single integer-convertible flag
or an OR'd flag-combination.
Returns:
A semi-colon-delimited string of appropriate escape sequences.
Raises:
errors.FlagError if the combination is out-of-range.
"""
if (isinstance(combination, int) and
(combination < 0 or combination >= LIMIT)):
raise errors.FlagError("Out-of-range flag-combination!")
codes = []
for enum in (Style, Color, Fill):
for flag in enum:
if combination & flag:
codes.append(str(flag))
return ";".join(codes)
| {
"content_hash": "a1e965662c0b4d1c8c5d53a97f635e1a",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 71,
"avg_line_length": 20.549356223175966,
"alnum_prop": 0.6741854636591479,
"repo_name": "goldsborough/ecstasy",
"id": "b797db7c168fd6ea70cedac286a6873958f2fd07",
"size": "4788",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ecstasy/flags.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "1496"
},
{
"name": "Python",
"bytes": "46132"
}
],
"symlink_target": ""
} |
<?php
namespace ZendTest\Mail\Header;
use Zend\Mail\Header\ContentType;
/**
* @group Zend_Mail
*/
class ContentTypeTest extends \PHPUnit_Framework_TestCase
{
public function testContentTypeFromStringCreatesValidContentTypeHeader()
{
$contentTypeHeader = ContentType::fromString('Content-Type: xxx/yyy');
$this->assertInstanceOf('Zend\Mail\Header\HeaderInterface', $contentTypeHeader);
$this->assertInstanceOf('Zend\Mail\Header\ContentType', $contentTypeHeader);
}
public function testContentTypeGetFieldNameReturnsHeaderName()
{
$contentTypeHeader = new ContentType();
$this->assertEquals('Content-Type', $contentTypeHeader->getFieldName());
}
public function testContentTypeGetFieldValueReturnsProperValue()
{
$contentTypeHeader = new ContentType();
$contentTypeHeader->setType('foo/bar');
$this->assertEquals('foo/bar', $contentTypeHeader->getFieldValue());
}
public function testContentTypeToStringReturnsHeaderFormattedString()
{
$contentTypeHeader = new ContentType();
$contentTypeHeader->setType('foo/bar');
$this->assertEquals("Content-Type: foo/bar", $contentTypeHeader->toString());
}
/**
* @group 6491
*/
public function testTrailingSemiColonFromString()
{
$contentTypeHeader = ContentType::fromString(
'Content-Type: multipart/alternative; boundary="Apple-Mail=_1B852F10-F9C6-463D-AADD-CD503A5428DD";'
);
$params = $contentTypeHeader->getParameters();
$this->assertEquals(array('boundary' => 'Apple-Mail=_1B852F10-F9C6-463D-AADD-CD503A5428DD'), $params);
}
public function testProvidingParametersIntroducesHeaderFolding()
{
$header = new ContentType();
$header->setType('application/x-unit-test');
$header->addParameter('charset', 'us-ascii');
$string = $header->toString();
$this->assertContains("Content-Type: application/x-unit-test;", $string);
$this->assertContains(";\r\n charset=\"us-ascii\"", $string);
}
public function testExtractsExtraInformationFromContentType()
{
$contentTypeHeader = ContentType::fromString(
'Content-Type: multipart/alternative; boundary="Apple-Mail=_1B852F10-F9C6-463D-AADD-CD503A5428DD"'
);
$params = $contentTypeHeader->getParameters();
$this->assertEquals($params, array('boundary' => 'Apple-Mail=_1B852F10-F9C6-463D-AADD-CD503A5428DD'));
}
public function testExtractsExtraInformationWithoutBeingConfusedByTrailingSemicolon()
{
$header = ContentType::fromString('Content-Type: application/pdf;name="foo.pdf";');
$this->assertEquals($header->getParameters(), array('name' => 'foo.pdf'));
}
/**
* @group #2728
*
* Tests setting different MIME types
*/
public function testSetContentType()
{
$header = new ContentType();
$header->setType('application/vnd.ms-excel');
$this->assertEquals('Content-Type: application/vnd.ms-excel', $header->toString());
$header->setType('application/rss+xml');
$this->assertEquals('Content-Type: application/rss+xml', $header->toString());
$header->setType('video/mp4');
$this->assertEquals('Content-Type: video/mp4', $header->toString());
$header->setType('message/rfc822');
$this->assertEquals('Content-Type: message/rfc822', $header->toString());
}
/**
* @group ZF2015-04
*/
public function testFromStringRaisesExceptionForInvalidName()
{
$this->setExpectedException('Zend\Mail\Header\Exception\InvalidArgumentException', 'header name');
$header = ContentType::fromString('Content-Type' . chr(32) . ': text/html');
}
public function headerLines()
{
return array(
'newline' => array("Content-Type: text/html;\nlevel=1"),
'cr-lf' => array("Content-Type: text/html\r\n;level=1",),
'multiline' => array("Content-Type: text/html;\r\nlevel=1\r\nq=0.1"),
);
}
/**
* @dataProvider headerLines
* @group ZF2015-04
*/
public function testFromStringRaisesExceptionForNonFoldingMultilineValues($headerLine)
{
$this->setExpectedException('Zend\Mail\Header\Exception\InvalidArgumentException', 'header value');
$header = ContentType::fromString($headerLine);
}
/**
* @group ZF2015-04
*/
public function testFromStringHandlesContinuations()
{
$header = ContentType::fromString("Content-Type: text/html;\r\n level=1");
$this->assertEquals('text/html', $header->getType());
$this->assertEquals(array('level' => '1'), $header->getParameters());
}
/**
* @group ZF2015-04
*/
public function testAddParameterRaisesInvalidArgumentExceptionForInvalidParameterName()
{
$header = new ContentType();
$header->setType('text/html');
$this->setExpectedException('Zend\Mail\Header\Exception\InvalidArgumentException', 'parameter name');
$header->addParameter("b\r\na\rr\n", "baz");
}
/**
* @group ZF2015-04
*/
public function testAddParameterRaisesInvalidArgumentExceptionForInvalidParameterValue()
{
$header = new ContentType();
$header->setType('text/html');
$this->setExpectedException('Zend\Mail\Header\Exception\InvalidArgumentException', 'parameter value');
$header->addParameter('foo', "\nbar\r\nbaz\r");
}
}
| {
"content_hash": "c30d7654fcaa70efe189775dd026c476",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 111,
"avg_line_length": 35.132075471698116,
"alnum_prop": 0.6478696741854637,
"repo_name": "stefanotorresi/zend-mail",
"id": "b9911863433bd06b3a506f2cbb04dc26e134d04a",
"size": "5888",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/Header/ContentTypeTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "617044"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "23695194a37542e68364821a06c2c2cc",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "47c794de07144bac69b171105884c61ebaa3168d",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Pavetta/Pavetta renidens/ Syn. Psychotria renidens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package se.l4.silo.engine.internal;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.LinkedList;
/**
* Helper to check against actual operations against a set of expected
* operations.
*
* @author Andreas Holstenson
*
*/
public class OpChecker
{
private final LinkedList<Object[]> queue;
public OpChecker()
{
queue = new LinkedList<>();
}
public void expect(Object... data)
{
queue.add(data);
}
public void check(Object... data)
{
if(queue.isEmpty())
{
throw new AssertionError("No more expected operations");
}
Object[] first = queue.poll();
if(first.length != data.length)
{
throw new AssertionError("Operation did not match, expected: "
+ Arrays.toString(first) + " but got " + Arrays.toString(data));
}
boolean matches = true;
for(int i=0, n=first.length; i<n; i++)
{
Object a = first[i];
Object b = data[i];
if(a == b) continue;
if(a == null || b == null)
{
matches = false;
}
else if(a instanceof InputStream)
{
try(InputStream in1 = (InputStream) a; InputStream in2 = (InputStream) b)
{
int r1;
int idx = 0;
while((r1 = in1.read()) != -1)
{
int r2 = in2.read();
if(r1 != r2)
{
throw new AssertionError("Operation did not match for argument "
+ i + ", of type bytes, mismatch on index " + idx);
}
idx++;
}
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
else if(! a.equals(b))
{
matches = false;
}
if(! matches)
{
throw new AssertionError("Operation did not match for argument "
+ i + ", expected: "
+ Arrays.toString(first) + " but got " + Arrays.toString(data));
}
}
}
public void checkEmpty()
{
if(! queue.isEmpty())
{
throw new AssertionError("Found trailing operations, not everything has been applied");
}
}
}
| {
"content_hash": "92b00573252ed5a9099b563aa3ce5799",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 90,
"avg_line_length": 19.27,
"alnum_prop": 0.6009340944473275,
"repo_name": "LevelFourAB/silo",
"id": "276d95a112688145f5f8a26ec68ae0ccb9d1198a",
"size": "1927",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "silo-engine/src/test/java/se/l4/silo/engine/internal/OpChecker.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "448446"
}
],
"symlink_target": ""
} |
package com.github.pabloo99.xmlsoccer.api.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* Created by pmazur on 2014-11-30.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GetPlayersResultDto {
private Integer id;
private String name;
private Double height;
private Double weight;
private String nationality;
private String position;
private Integer teamId;
private Integer playerNumber;
private Date dateOfBirth;
private Date dateOfSigning;
private String signing;
}
| {
"content_hash": "cfd030162c6afff7b6d5b862d17b66f9",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 46,
"avg_line_length": 20.82758620689655,
"alnum_prop": 0.7516556291390728,
"repo_name": "spauny/xmlsoccer",
"id": "ed5b31c5b933f166f62830b832450a1845f31abb",
"size": "604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/pabloo99/xmlsoccer/api/dto/GetPlayersResultDto.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "224386"
},
{
"name": "Java",
"bytes": "620604"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for End of Days (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0146675">End of Days (1999)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Donlee+Brussel">Donlee Brussel</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>End of Days (1999)</PRE>
<PRE>Cast: Arnold Schwarzenegger, Gabriel Byrne, Robin Tunney, Kevin Pollak,
Rod Steiger, Miriam Margolyes
Director: Peter Hyams
Screenplay: Andrew W. Marlowe
123 Minutes
Rated R</PRE>
<PRE>Review by Donlee Brussel</PRE>
<P>There are a lot of devil worshippers in New York. These Satan servants
are everywhere; I'm talking about the psychiatrists, cops, nurses and
hobos. They're all here to revere Gabriel Byrne in a role Al Pacino
was born to play. Welcome to Schwarzenegger's long anticipated return
to celluloid, "End of Days." It's also Arnold's first foray
into "drama" as he plays a suicidal alcoholic bodyguard who's here to
save us all from the devil himself.</P>
<P>In a nutshell, End of Days' plot is simply this: Satan needs to find
the girl he marked as his mate twenty years ago and impregnate her with
the Anti-Christ between 11:00 PM and 12:00 AM, Eastern Standard Time on
December 31, 1999 to initiate the "End of Days." Only Jericho Cane (Ah-
nuld) can save the world from Lucifer and his flammable urine. How
will he kill Mephistopheles when he has only ten seconds to nail Robin
Tunney? Only if you're willing to part with your hard-earned cash will
you find out and I seriously recommend that you don't.</P>
<P>Now some of you may be asking yourselves, "What the hell is Gabriel
doing back in another pisspoor religious movie?" You'd think after
Stigmata he'd learn to pick better scripts. Byrne just doesn't have
the intensity to pull this role off. Pacino had it and used it well in
the guilty pleasure "The Devil's Advocate." Playing a heavy like the
Prince of Darkness ain't easy, so why didn't casting director Jackie
Burch put as much time into "End of Days" as he did "Lost & Found," "I
Still Know..." and "Judge Dredd?"</P>
<P>Every action film these days requires a sidekick, so why should a
cliché-layered film like this be any different? They have Kevin
Pollack spewing cheesy one-liners from the "Die Hard" trilogy's cutting
room floor, and according to the audience I was with, they're
hilarious. I mean come on, lines like those are golden! In the stark
reality of the world Gabriel Byrne and Kevin Pollack haven't done
anything respectable besides "The Usual Suspects." That is the only
one good film they starred in, everything on their resumes preceding
and following it are comatose.</P>
<P>It's important to mention Arnold Schwarzenegger's big performance. Let
me tell you, this guy never has been able to act, he's not acting
in "End of Days" and I truly doubt he'll ever have any talent in
acting. Maybe, it's in the accent, you know, Arnold's voice just
doesn't seem capable of tugging at my emotions. He just doesn't have
the skill to do anything properly in a dramatic fashion. All he can do
is look the role, but looking it just isn't enough nowadays. There's a
scene in the film where Schwarzenegger's getting his ass whooped by
Miriam Margolyes in an inconceivably hilarious approach that makes me
question whether or not Arnold Schwarzenegger is getting a little weak
around the edges or he just thinks getting a beatdown from a 58 year
old is hilarious.</P>
<P>And of course, let's not forget Peter Hyams, the "acclaimed" director
of "Timecop," "Sudden Death" and "The Relic" doing a pretty sloppy job
of helming this film. If I were the exec at Universal, I would've
really pushed Sam Raimi to direct this. In a year of groundbreaking
special effects fests like "Star Wars" and "The Matrix, "Days" looks
incredibly lame. Those looking to see another Jar Jar Binks
or "bullet time" will be disappointed. The $100 million budget used
here was spent on the same old fireballs and explosions we've seen
several times before, directed by a hack with no sense of style or
artistic ability.</P>
<P>"End of Days" is nothing but another scab on everyone involved's
already wounded careers.</P>
<PRE>- © 1999 by Donlee Brussel</PRE>
<PRE>Sent via Deja.com <A HREF="http://www.deja.com/">http://www.deja.com/</A>
Before you buy.</PRE>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "4fd9b28e5f231ca9949722d1f9a782b5",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 201,
"avg_line_length": 59.93181818181818,
"alnum_prop": 0.7495259764884338,
"repo_name": "xianjunzhengbackup/code",
"id": "a5c7277c7a114243f3bf4f801385caaea7482003",
"size": "5274",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/21916.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
package com.fillodeos.sdr.webhook.domain;
import com.fillodeos.sdr.webhook.listener.jpa.WebhookEntityListener;
import javax.persistence.*;
import java.util.Set;
@Entity
@EntityListeners(WebhookEntityListener.class)
public class Webhook {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String url;
private String eventType;
private String entityName;
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> propertyList;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public Set<String> getPropertyList() {
return propertyList;
}
public void setPropertyList(Set<String> propertyList) {
this.propertyList = propertyList;
}
@Override
public String toString() {
return "Webhook{" +
"id=" + id +
", url='" + url + '\'' +
", entityName='" + entityName + '\'' +
", propertyList=" + propertyList +
'}';
}
}
| {
"content_hash": "ada03910143684421c027606ebef667a",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 68,
"avg_line_length": 21.439393939393938,
"alnum_prop": 0.607773851590106,
"repo_name": "jfillo/spring-data-rest-webhook",
"id": "e3d391a78842212fcf7ad12566c5b0dbfaa2bfe8",
"size": "1415",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/fillodeos/sdr/webhook/domain/Webhook.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "25284"
}
],
"symlink_target": ""
} |
namespace net {
enum {
// A private network error code used by the socket test utility classes.
// If the |result| member of a MockRead is
// ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, that MockRead is just a
// marker that indicates the peer will close the connection after the next
// MockRead. The other members of that MockRead are ignored.
ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ = -10000,
};
class AsyncSocket;
class ChannelIDService;
class MockClientSocket;
class SSLClientSocket;
class StreamSocket;
enum IoMode {
ASYNC,
SYNCHRONOUS
};
struct MockConnect {
// Asynchronous connection success.
// Creates a MockConnect with |mode| ASYC, |result| OK, and
// |peer_addr| 192.0.2.33.
MockConnect();
// Creates a MockConnect with the specified mode and result, with
// |peer_addr| 192.0.2.33.
MockConnect(IoMode io_mode, int r);
MockConnect(IoMode io_mode, int r, IPEndPoint addr);
~MockConnect();
IoMode mode;
int result;
IPEndPoint peer_addr;
};
// MockRead and MockWrite shares the same interface and members, but we'd like
// to have distinct types because we don't want to have them used
// interchangably. To do this, a struct template is defined, and MockRead and
// MockWrite are instantiated by using this template. Template parameter |type|
// is not used in the struct definition (it purely exists for creating a new
// type).
//
// |data| in MockRead and MockWrite has different meanings: |data| in MockRead
// is the data returned from the socket when MockTCPClientSocket::Read() is
// attempted, while |data| in MockWrite is the expected data that should be
// given in MockTCPClientSocket::Write().
enum MockReadWriteType {
MOCK_READ,
MOCK_WRITE
};
template <MockReadWriteType type>
struct MockReadWrite {
// Flag to indicate that the message loop should be terminated.
enum {
STOPLOOP = 1 << 31
};
// Default
MockReadWrite()
: mode(SYNCHRONOUS),
result(0),
data(NULL),
data_len(0),
sequence_number(0),
time_stamp(base::Time::Now()) {}
// Read/write failure (no data).
MockReadWrite(IoMode io_mode, int result)
: mode(io_mode),
result(result),
data(NULL),
data_len(0),
sequence_number(0),
time_stamp(base::Time::Now()) {}
// Read/write failure (no data), with sequence information.
MockReadWrite(IoMode io_mode, int result, int seq)
: mode(io_mode),
result(result),
data(NULL),
data_len(0),
sequence_number(seq),
time_stamp(base::Time::Now()) {}
// Asynchronous read/write success (inferred data length).
explicit MockReadWrite(const char* data)
: mode(ASYNC),
result(0),
data(data),
data_len(strlen(data)),
sequence_number(0),
time_stamp(base::Time::Now()) {}
// Read/write success (inferred data length).
MockReadWrite(IoMode io_mode, const char* data)
: mode(io_mode),
result(0),
data(data),
data_len(strlen(data)),
sequence_number(0),
time_stamp(base::Time::Now()) {}
// Read/write success.
MockReadWrite(IoMode io_mode, const char* data, int data_len)
: mode(io_mode),
result(0),
data(data),
data_len(data_len),
sequence_number(0),
time_stamp(base::Time::Now()) {}
// Read/write success (inferred data length) with sequence information.
MockReadWrite(IoMode io_mode, int seq, const char* data)
: mode(io_mode),
result(0),
data(data),
data_len(strlen(data)),
sequence_number(seq),
time_stamp(base::Time::Now()) {}
// Read/write success with sequence information.
MockReadWrite(IoMode io_mode, const char* data, int data_len, int seq)
: mode(io_mode),
result(0),
data(data),
data_len(data_len),
sequence_number(seq),
time_stamp(base::Time::Now()) {}
IoMode mode;
int result;
const char* data;
int data_len;
// For OrderedSocketData, which only allows reads to occur in a particular
// sequence. If a read occurs before the given |sequence_number| is reached,
// an ERR_IO_PENDING is returned.
int sequence_number; // The sequence number at which a read is allowed
// to occur.
base::Time time_stamp; // The time stamp at which the operation occurred.
};
typedef MockReadWrite<MOCK_READ> MockRead;
typedef MockReadWrite<MOCK_WRITE> MockWrite;
struct MockWriteResult {
MockWriteResult(IoMode io_mode, int result) : mode(io_mode), result(result) {}
IoMode mode;
int result;
};
// The SocketDataProvider is an interface used by the MockClientSocket
// for getting data about individual reads and writes on the socket.
class SocketDataProvider {
public:
SocketDataProvider() : socket_(NULL) {}
virtual ~SocketDataProvider() {}
// Returns the buffer and result code for the next simulated read.
// If the |MockRead.result| is ERR_IO_PENDING, it informs the caller
// that it will be called via the AsyncSocket::OnReadComplete()
// function at a later time.
virtual MockRead GetNextRead() = 0;
virtual MockWriteResult OnWrite(const std::string& data) = 0;
virtual void Reset() = 0;
// Accessor for the socket which is using the SocketDataProvider.
AsyncSocket* socket() { return socket_; }
void set_socket(AsyncSocket* socket) { socket_ = socket; }
MockConnect connect_data() const { return connect_; }
void set_connect_data(const MockConnect& connect) { connect_ = connect; }
private:
MockConnect connect_;
AsyncSocket* socket_;
DISALLOW_COPY_AND_ASSIGN(SocketDataProvider);
};
// The AsyncSocket is an interface used by the SocketDataProvider to
// complete the asynchronous read operation.
class AsyncSocket {
public:
// If an async IO is pending because the SocketDataProvider returned
// ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
// is called to complete the asynchronous read operation.
// data.async is ignored, and this read is completed synchronously as
// part of this call.
virtual void OnReadComplete(const MockRead& data) = 0;
virtual void OnConnectComplete(const MockConnect& data) = 0;
};
// SocketDataProvider which responds based on static tables of mock reads and
// writes.
class StaticSocketDataProvider : public SocketDataProvider {
public:
StaticSocketDataProvider();
StaticSocketDataProvider(MockRead* reads,
size_t reads_count,
MockWrite* writes,
size_t writes_count);
~StaticSocketDataProvider() override;
// These functions get access to the next available read and write data.
const MockRead& PeekRead() const;
const MockWrite& PeekWrite() const;
// These functions get random access to the read and write data, for timing.
const MockRead& PeekRead(size_t index) const;
const MockWrite& PeekWrite(size_t index) const;
size_t read_index() const { return read_index_; }
size_t write_index() const { return write_index_; }
size_t read_count() const { return read_count_; }
size_t write_count() const { return write_count_; }
bool at_read_eof() const { return read_index_ >= read_count_; }
bool at_write_eof() const { return write_index_ >= write_count_; }
virtual void CompleteRead() {}
// SocketDataProvider implementation.
MockRead GetNextRead() override;
MockWriteResult OnWrite(const std::string& data) override;
void Reset() override;
private:
MockRead* reads_;
size_t read_index_;
size_t read_count_;
MockWrite* writes_;
size_t write_index_;
size_t write_count_;
DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider);
};
// SocketDataProvider which can make decisions about next mock reads based on
// received writes. It can also be used to enforce order of operations, for
// example that tested code must send the "Hello!" message before receiving
// response. This is useful for testing conversation-like protocols like FTP.
class DynamicSocketDataProvider : public SocketDataProvider {
public:
DynamicSocketDataProvider();
~DynamicSocketDataProvider() override;
int short_read_limit() const { return short_read_limit_; }
void set_short_read_limit(int limit) { short_read_limit_ = limit; }
void allow_unconsumed_reads(bool allow) { allow_unconsumed_reads_ = allow; }
// SocketDataProvider implementation.
MockRead GetNextRead() override;
MockWriteResult OnWrite(const std::string& data) override = 0;
void Reset() override;
protected:
// The next time there is a read from this socket, it will return |data|.
// Before calling SimulateRead next time, the previous data must be consumed.
void SimulateRead(const char* data, size_t length);
void SimulateRead(const char* data) { SimulateRead(data, std::strlen(data)); }
private:
std::deque<MockRead> reads_;
// Max number of bytes we will read at a time. 0 means no limit.
int short_read_limit_;
// If true, we'll not require the client to consume all data before we
// mock the next read.
bool allow_unconsumed_reads_;
DISALLOW_COPY_AND_ASSIGN(DynamicSocketDataProvider);
};
// SSLSocketDataProviders only need to keep track of the return code from calls
// to Connect().
struct SSLSocketDataProvider {
SSLSocketDataProvider(IoMode mode, int result);
~SSLSocketDataProvider();
void SetNextProto(NextProto proto);
MockConnect connect;
SSLClientSocket::NextProtoStatus next_proto_status;
std::string next_proto;
bool was_npn_negotiated;
NextProto protocol_negotiated;
NextProtoVector next_protos_expected_in_ssl_config;
bool client_cert_sent;
SSLCertRequestInfo* cert_request_info;
scoped_refptr<X509Certificate> cert;
bool channel_id_sent;
ChannelIDService* channel_id_service;
int connection_status;
// Indicates that the socket should pause in the Connect method.
bool should_pause_on_connect;
// Whether or not the Socket should behave like there is a pre-existing
// session to resume. Whether or not such a session is reported as
// resumed is controlled by |connection_status|.
bool is_in_session_cache;
};
// A DataProvider where the client must write a request before the reads (e.g.
// the response) will complete.
class DelayedSocketData : public StaticSocketDataProvider {
public:
// |write_delay| the number of MockWrites to complete before allowing
// a MockRead to complete.
// |reads| the list of MockRead completions.
// |writes| the list of MockWrite completions.
// Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
// MockRead(true, 0, 0);
DelayedSocketData(int write_delay,
MockRead* reads,
size_t reads_count,
MockWrite* writes,
size_t writes_count);
// |connect| the result for the connect phase.
// |reads| the list of MockRead completions.
// |write_delay| the number of MockWrites to complete before allowing
// a MockRead to complete.
// |writes| the list of MockWrite completions.
// Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
// MockRead(true, 0, 0);
DelayedSocketData(const MockConnect& connect,
int write_delay,
MockRead* reads,
size_t reads_count,
MockWrite* writes,
size_t writes_count);
~DelayedSocketData() override;
void ForceNextRead();
// StaticSocketDataProvider:
MockRead GetNextRead() override;
MockWriteResult OnWrite(const std::string& data) override;
void Reset() override;
void CompleteRead() override;
private:
int write_delay_;
bool read_in_progress_;
base::WeakPtrFactory<DelayedSocketData> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(DelayedSocketData);
};
// A DataProvider where the reads are ordered.
// If a read is requested before its sequence number is reached, we return an
// ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to
// wait).
// The sequence number is incremented on every read and write operation.
// The message loop may be interrupted by setting the high bit of the sequence
// number in the MockRead's sequence number. When that MockRead is reached,
// we post a Quit message to the loop. This allows us to interrupt the reading
// of data before a complete message has arrived, and provides support for
// testing server push when the request is issued while the response is in the
// middle of being received.
class OrderedSocketData : public StaticSocketDataProvider {
public:
// |reads| the list of MockRead completions.
// |writes| the list of MockWrite completions.
// Note: All MockReads and MockWrites must be async.
// Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
// MockRead(true, 0, 0);
OrderedSocketData(MockRead* reads,
size_t reads_count,
MockWrite* writes,
size_t writes_count);
~OrderedSocketData() override;
// |connect| the result for the connect phase.
// |reads| the list of MockRead completions.
// |writes| the list of MockWrite completions.
// Note: All MockReads and MockWrites must be async.
// Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
// MockRead(true, 0, 0);
OrderedSocketData(const MockConnect& connect,
MockRead* reads,
size_t reads_count,
MockWrite* writes,
size_t writes_count);
// Posts a quit message to the current message loop, if one is running.
void EndLoop();
// StaticSocketDataProvider:
MockRead GetNextRead() override;
MockWriteResult OnWrite(const std::string& data) override;
void Reset() override;
void CompleteRead() override;
private:
int sequence_number_;
int loop_stop_stage_;
bool blocked_;
base::WeakPtrFactory<OrderedSocketData> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(OrderedSocketData);
};
class DeterministicMockTCPClientSocket;
// This class gives the user full control over the network activity,
// specifically the timing of the COMPLETION of I/O operations. Regardless of
// the order in which I/O operations are initiated, this class ensures that they
// complete in the correct order.
//
// Network activity is modeled as a sequence of numbered steps which is
// incremented whenever an I/O operation completes. This can happen under two
// different circumstances:
//
// 1) Performing a synchronous I/O operation. (Invoking Read() or Write()
// when the corresponding MockRead or MockWrite is marked !async).
// 2) Running the Run() method of this class. The run method will invoke
// the current MessageLoop, running all pending events, and will then
// invoke any pending IO callbacks.
//
// In addition, this class allows for I/O processing to "stop" at a specified
// step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation
// by calling Read() or Write() while stopped is permitted if the operation is
// asynchronous. It is an error to perform synchronous I/O while stopped.
//
// When creating the MockReads and MockWrites, note that the sequence number
// refers to the number of the step in which the I/O will complete. In the
// case of synchronous I/O, this will be the same step as the I/O is initiated.
// However, in the case of asynchronous I/O, this I/O may be initiated in
// a much earlier step. Furthermore, when the a Read() or Write() is separated
// from its completion by other Read() or Writes()'s, it can not be marked
// synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a
// synchronous Read() or Write() could not be completed synchronously because of
// the specific ordering constraints.
//
// Sequence numbers are preserved across both reads and writes. There should be
// no gaps in sequence numbers, and no repeated sequence numbers. i.e.
// MockRead reads[] = {
// MockRead(false, "first read", length, 0) // sync
// MockRead(true, "second read", length, 2) // async
// };
// MockWrite writes[] = {
// MockWrite(true, "first write", length, 1), // async
// MockWrite(false, "second write", length, 3), // sync
// };
//
// Example control flow:
// Read() is called. The current step is 0. The first available read is
// synchronous, so the call to Read() returns length. The current step is
// now 1. Next, Read() is called again. The next available read can
// not be completed until step 2, so Read() returns ERR_IO_PENDING. The current
// step is still 1. Write is called(). The first available write is able to
// complete in this step, but is marked asynchronous. Write() returns
// ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is
// called which will cause the write callback to be invoked, and will then
// stop. The current state is now 2. RunFor(1) is called again, which
// causes the read callback to be invoked, and will then stop. Then current
// step is 2. Write() is called again. Then next available write is
// synchronous so the call to Write() returns length.
//
// For examples of how to use this class, see:
// deterministic_socket_data_unittests.cc
class DeterministicSocketData : public StaticSocketDataProvider {
public:
// The Delegate is an abstract interface which handles the communication from
// the DeterministicSocketData to the Deterministic MockSocket. The
// MockSockets directly store a pointer to the DeterministicSocketData,
// whereas the DeterministicSocketData only stores a pointer to the
// abstract Delegate interface.
class Delegate {
public:
// Returns true if there is currently a write pending. That is to say, if
// an asynchronous write has been started but the callback has not been
// invoked.
virtual bool WritePending() const = 0;
// Returns true if there is currently a read pending. That is to say, if
// an asynchronous read has been started but the callback has not been
// invoked.
virtual bool ReadPending() const = 0;
// Called to complete an asynchronous write to execute the write callback.
virtual void CompleteWrite() = 0;
// Called to complete an asynchronous read to execute the read callback.
virtual int CompleteRead() = 0;
protected:
virtual ~Delegate() {}
};
// |reads| the list of MockRead completions.
// |writes| the list of MockWrite completions.
DeterministicSocketData(MockRead* reads,
size_t reads_count,
MockWrite* writes,
size_t writes_count);
~DeterministicSocketData() override;
// Consume all the data up to the give stop point (via SetStop()).
void Run();
// Set the stop point to be |steps| from now, and then invoke Run().
void RunFor(int steps);
// Stop at step |seq|, which must be in the future.
virtual void SetStop(int seq);
// Stop |seq| steps after the current step.
virtual void StopAfter(int seq);
bool stopped() const { return stopped_; }
void SetStopped(bool val) { stopped_ = val; }
MockRead& current_read() { return current_read_; }
MockWrite& current_write() { return current_write_; }
int sequence_number() const { return sequence_number_; }
void set_delegate(base::WeakPtr<Delegate> delegate) { delegate_ = delegate; }
// StaticSocketDataProvider:
// When the socket calls Read(), that calls GetNextRead(), and expects either
// ERR_IO_PENDING or data.
MockRead GetNextRead() override;
// When the socket calls Write(), it always completes synchronously. OnWrite()
// checks to make sure the written data matches the expected data. The
// callback will not be invoked until its sequence number is reached.
MockWriteResult OnWrite(const std::string& data) override;
void Reset() override;
void CompleteRead() override {}
private:
// Invoke the read and write callbacks, if the timing is appropriate.
void InvokeCallbacks();
void NextStep();
void VerifyCorrectSequenceNumbers(MockRead* reads,
size_t reads_count,
MockWrite* writes,
size_t writes_count);
int sequence_number_;
MockRead current_read_;
MockWrite current_write_;
int stopping_sequence_number_;
bool stopped_;
base::WeakPtr<Delegate> delegate_;
bool print_debug_;
bool is_running_;
};
// Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket
// objects get instantiated, they take their data from the i'th element of this
// array.
template <typename T>
class SocketDataProviderArray {
public:
SocketDataProviderArray() : next_index_(0) {}
T* GetNext() {
DCHECK_LT(next_index_, data_providers_.size());
return data_providers_[next_index_++];
}
void Add(T* data_provider) {
DCHECK(data_provider);
data_providers_.push_back(data_provider);
}
size_t next_index() { return next_index_; }
void ResetNextIndex() { next_index_ = 0; }
private:
// Index of the next |data_providers_| element to use. Not an iterator
// because those are invalidated on vector reallocation.
size_t next_index_;
// SocketDataProviders to be returned.
std::vector<T*> data_providers_;
};
class MockUDPClientSocket;
class MockTCPClientSocket;
class MockSSLClientSocket;
// ClientSocketFactory which contains arrays of sockets of each type.
// You should first fill the arrays using AddMock{SSL,}Socket. When the factory
// is asked to create a socket, it takes next entry from appropriate array.
// You can use ResetNextMockIndexes to reset that next entry index for all mock
// socket types.
class MockClientSocketFactory : public ClientSocketFactory {
public:
MockClientSocketFactory();
~MockClientSocketFactory() override;
void AddSocketDataProvider(SocketDataProvider* socket);
void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
void ResetNextMockIndexes();
SocketDataProviderArray<SocketDataProvider>& mock_data() {
return mock_data_;
}
// Note: this method is unsafe; the elements of the returned vector
// are not necessarily valid.
const std::vector<MockSSLClientSocket*>& ssl_client_sockets() const {
return ssl_client_sockets_;
}
// ClientSocketFactory
scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
const RandIntCallback& rand_int_cb,
NetLog* net_log,
const NetLog::Source& source) override;
scoped_ptr<StreamSocket> CreateTransportClientSocket(
const AddressList& addresses,
NetLog* net_log,
const NetLog::Source& source) override;
scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
scoped_ptr<ClientSocketHandle> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config,
const SSLClientSocketContext& context) override;
void ClearSSLSessionCache() override;
private:
SocketDataProviderArray<SocketDataProvider> mock_data_;
SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
std::vector<MockSSLClientSocket*> ssl_client_sockets_;
};
class MockClientSocket : public SSLClientSocket {
public:
// Value returned by GetTLSUniqueChannelBinding().
static const char kTlsUnique[];
// The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as
// unique socket IDs.
explicit MockClientSocket(const BoundNetLog& net_log);
// Socket implementation.
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override = 0;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override = 0;
int SetReceiveBufferSize(int32 size) override;
int SetSendBufferSize(int32 size) override;
// StreamSocket implementation.
int Connect(const CompletionCallback& callback) override = 0;
void Disconnect() override;
bool IsConnected() const override;
bool IsConnectedAndIdle() const override;
int GetPeerAddress(IPEndPoint* address) const override;
int GetLocalAddress(IPEndPoint* address) const override;
const BoundNetLog& NetLog() const override;
void SetSubresourceSpeculation() override {}
void SetOmniboxSpeculation() override {}
// SSLClientSocket implementation.
std::string GetSessionCacheKey() const override;
bool InSessionCache() const override;
void SetHandshakeCompletionCallback(const base::Closure& cb) override;
void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override;
int ExportKeyingMaterial(const base::StringPiece& label,
bool has_context,
const base::StringPiece& context,
unsigned char* out,
unsigned int outlen) override;
int GetTLSUniqueChannelBinding(std::string* out) override;
NextProtoStatus GetNextProto(std::string* proto) override;
ChannelIDService* GetChannelIDService() const override;
protected:
~MockClientSocket() override;
void RunCallbackAsync(const CompletionCallback& callback, int result);
void RunCallback(const CompletionCallback& callback, int result);
// SSLClientSocket implementation.
scoped_refptr<X509Certificate> GetUnverifiedServerCertificateChain()
const override;
// True if Connect completed successfully and Disconnect hasn't been called.
bool connected_;
// Address of the "remote" peer we're connected to.
IPEndPoint peer_addr_;
BoundNetLog net_log_;
private:
base::WeakPtrFactory<MockClientSocket> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(MockClientSocket);
};
class MockTCPClientSocket : public MockClientSocket, public AsyncSocket {
public:
MockTCPClientSocket(const AddressList& addresses,
net::NetLog* net_log,
SocketDataProvider* socket);
~MockTCPClientSocket() override;
const AddressList& addresses() const { return addresses_; }
// Socket implementation.
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
// StreamSocket implementation.
int Connect(const CompletionCallback& callback) override;
void Disconnect() override;
bool IsConnected() const override;
bool IsConnectedAndIdle() const override;
int GetPeerAddress(IPEndPoint* address) const override;
bool WasEverUsed() const override;
bool UsingTCPFastOpen() const override;
bool WasNpnNegotiated() const override;
bool GetSSLInfo(SSLInfo* ssl_info) override;
// AsyncSocket:
void OnReadComplete(const MockRead& data) override;
void OnConnectComplete(const MockConnect& data) override;
private:
int CompleteRead();
AddressList addresses_;
SocketDataProvider* data_;
int read_offset_;
MockRead read_data_;
bool need_read_data_;
// True if the peer has closed the connection. This allows us to simulate
// the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
// TCPClientSocket.
bool peer_closed_connection_;
// While an asynchronous IO is pending, we save our user-buffer state.
scoped_refptr<IOBuffer> pending_buf_;
int pending_buf_len_;
CompletionCallback pending_callback_;
bool was_used_to_convey_data_;
DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket);
};
// DeterministicSocketHelper is a helper class that can be used
// to simulate net::Socket::Read() and net::Socket::Write()
// using deterministic |data|.
// Note: This is provided as a common helper class because
// of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
// desire not to introduce an additional common base class.
class DeterministicSocketHelper {
public:
DeterministicSocketHelper(net::NetLog* net_log,
DeterministicSocketData* data);
virtual ~DeterministicSocketHelper();
bool write_pending() const { return write_pending_; }
bool read_pending() const { return read_pending_; }
void CompleteWrite();
int CompleteRead();
int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
const BoundNetLog& net_log() const { return net_log_; }
bool was_used_to_convey_data() const { return was_used_to_convey_data_; }
bool peer_closed_connection() const { return peer_closed_connection_; }
DeterministicSocketData* data() const { return data_; }
private:
bool write_pending_;
CompletionCallback write_callback_;
int write_result_;
MockRead read_data_;
IOBuffer* read_buf_;
int read_buf_len_;
bool read_pending_;
CompletionCallback read_callback_;
DeterministicSocketData* data_;
bool was_used_to_convey_data_;
bool peer_closed_connection_;
BoundNetLog net_log_;
};
// Mock UDP socket to be used in conjunction with DeterministicSocketData.
class DeterministicMockUDPClientSocket
: public DatagramClientSocket,
public AsyncSocket,
public DeterministicSocketData::Delegate,
public base::SupportsWeakPtr<DeterministicMockUDPClientSocket> {
public:
DeterministicMockUDPClientSocket(net::NetLog* net_log,
DeterministicSocketData* data);
~DeterministicMockUDPClientSocket() override;
// DeterministicSocketData::Delegate:
bool WritePending() const override;
bool ReadPending() const override;
void CompleteWrite() override;
int CompleteRead() override;
// Socket implementation.
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int SetReceiveBufferSize(int32 size) override;
int SetSendBufferSize(int32 size) override;
// DatagramSocket implementation.
void Close() override;
int GetPeerAddress(IPEndPoint* address) const override;
int GetLocalAddress(IPEndPoint* address) const override;
const BoundNetLog& NetLog() const override;
// DatagramClientSocket implementation.
int Connect(const IPEndPoint& address) override;
// AsyncSocket implementation.
void OnReadComplete(const MockRead& data) override;
void OnConnectComplete(const MockConnect& data) override;
void set_source_port(uint16 port) { source_port_ = port; }
private:
bool connected_;
IPEndPoint peer_address_;
DeterministicSocketHelper helper_;
uint16 source_port_; // Ephemeral source port.
DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket);
};
// Mock TCP socket to be used in conjunction with DeterministicSocketData.
class DeterministicMockTCPClientSocket
: public MockClientSocket,
public AsyncSocket,
public DeterministicSocketData::Delegate,
public base::SupportsWeakPtr<DeterministicMockTCPClientSocket> {
public:
DeterministicMockTCPClientSocket(net::NetLog* net_log,
DeterministicSocketData* data);
~DeterministicMockTCPClientSocket() override;
// DeterministicSocketData::Delegate:
bool WritePending() const override;
bool ReadPending() const override;
void CompleteWrite() override;
int CompleteRead() override;
// Socket:
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
// StreamSocket:
int Connect(const CompletionCallback& callback) override;
void Disconnect() override;
bool IsConnected() const override;
bool IsConnectedAndIdle() const override;
bool WasEverUsed() const override;
bool UsingTCPFastOpen() const override;
bool WasNpnNegotiated() const override;
bool GetSSLInfo(SSLInfo* ssl_info) override;
// AsyncSocket:
void OnReadComplete(const MockRead& data) override;
void OnConnectComplete(const MockConnect& data) override;
private:
DeterministicSocketHelper helper_;
DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket);
};
class MockSSLClientSocket : public MockClientSocket, public AsyncSocket {
public:
MockSSLClientSocket(scoped_ptr<ClientSocketHandle> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config,
SSLSocketDataProvider* socket);
~MockSSLClientSocket() override;
// Socket implementation.
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
// StreamSocket implementation.
int Connect(const CompletionCallback& callback) override;
void Disconnect() override;
bool IsConnected() const override;
bool WasEverUsed() const override;
bool UsingTCPFastOpen() const override;
int GetPeerAddress(IPEndPoint* address) const override;
bool WasNpnNegotiated() const override;
bool GetSSLInfo(SSLInfo* ssl_info) override;
// SSLClientSocket implementation.
std::string GetSessionCacheKey() const override;
bool InSessionCache() const override;
void SetHandshakeCompletionCallback(const base::Closure& cb) override;
void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override;
NextProtoStatus GetNextProto(std::string* proto) override;
bool set_was_npn_negotiated(bool negotiated) override;
void set_protocol_negotiated(NextProto protocol_negotiated) override;
NextProto GetNegotiatedProtocol() const override;
// This MockSocket does not implement the manual async IO feature.
void OnReadComplete(const MockRead& data) override;
void OnConnectComplete(const MockConnect& data) override;
bool WasChannelIDSent() const override;
void set_channel_id_sent(bool channel_id_sent) override;
ChannelIDService* GetChannelIDService() const override;
bool reached_connect() const { return reached_connect_; }
// Resumes the connection of a socket that was paused for testing.
// |connect_callback_| should be set before invoking this method.
void RestartPausedConnect();
private:
enum ConnectState {
STATE_NONE,
STATE_SSL_CONNECT,
STATE_SSL_CONNECT_COMPLETE,
};
void OnIOComplete(int result);
// Runs the state transistion loop.
int DoConnectLoop(int result);
int DoSSLConnect();
int DoSSLConnectComplete(int result);
scoped_ptr<ClientSocketHandle> transport_;
HostPortPair host_port_pair_;
SSLSocketDataProvider* data_;
bool is_npn_state_set_;
bool new_npn_value_;
bool is_protocol_negotiated_set_;
NextProto protocol_negotiated_;
CompletionCallback connect_callback_;
// Indicates what state of Connect the socket should enter.
ConnectState next_connect_state_;
// True if the Connect method has been called on the socket.
bool reached_connect_;
base::Closure handshake_completion_callback_;
base::WeakPtrFactory<MockSSLClientSocket> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
};
class MockUDPClientSocket : public DatagramClientSocket, public AsyncSocket {
public:
MockUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log);
~MockUDPClientSocket() override;
// Socket implementation.
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int SetReceiveBufferSize(int32 size) override;
int SetSendBufferSize(int32 size) override;
// DatagramSocket implementation.
void Close() override;
int GetPeerAddress(IPEndPoint* address) const override;
int GetLocalAddress(IPEndPoint* address) const override;
const BoundNetLog& NetLog() const override;
// DatagramClientSocket implementation.
int Connect(const IPEndPoint& address) override;
// AsyncSocket implementation.
void OnReadComplete(const MockRead& data) override;
void OnConnectComplete(const MockConnect& data) override;
void set_source_port(uint16 port) { source_port_ = port;}
private:
int CompleteRead();
void RunCallbackAsync(const CompletionCallback& callback, int result);
void RunCallback(const CompletionCallback& callback, int result);
bool connected_;
SocketDataProvider* data_;
int read_offset_;
MockRead read_data_;
bool need_read_data_;
uint16 source_port_; // Ephemeral source port.
// Address of the "remote" peer we're connected to.
IPEndPoint peer_addr_;
// While an asynchronous IO is pending, we save our user-buffer state.
scoped_refptr<IOBuffer> pending_buf_;
int pending_buf_len_;
CompletionCallback pending_callback_;
BoundNetLog net_log_;
base::WeakPtrFactory<MockUDPClientSocket> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket);
};
class TestSocketRequest : public TestCompletionCallbackBase {
public:
TestSocketRequest(std::vector<TestSocketRequest*>* request_order,
size_t* completion_count);
~TestSocketRequest() override;
ClientSocketHandle* handle() { return &handle_; }
const net::CompletionCallback& callback() const { return callback_; }
private:
void OnComplete(int result);
ClientSocketHandle handle_;
std::vector<TestSocketRequest*>* request_order_;
size_t* completion_count_;
CompletionCallback callback_;
DISALLOW_COPY_AND_ASSIGN(TestSocketRequest);
};
class ClientSocketPoolTest {
public:
enum KeepAlive {
KEEP_ALIVE,
// A socket will be disconnected in addition to handle being reset.
NO_KEEP_ALIVE,
};
static const int kIndexOutOfBounds;
static const int kRequestNotFound;
ClientSocketPoolTest();
~ClientSocketPoolTest();
template <typename PoolType>
int StartRequestUsingPool(
PoolType* socket_pool,
const std::string& group_name,
RequestPriority priority,
const scoped_refptr<typename PoolType::SocketParams>& socket_params) {
DCHECK(socket_pool);
TestSocketRequest* request =
new TestSocketRequest(&request_order_, &completion_count_);
requests_.push_back(request);
int rv = request->handle()->Init(group_name,
socket_params,
priority,
request->callback(),
socket_pool,
BoundNetLog());
if (rv != ERR_IO_PENDING)
request_order_.push_back(request);
return rv;
}
// Provided there were n requests started, takes |index| in range 1..n
// and returns order in which that request completed, in range 1..n,
// or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
// if that request did not complete (for example was canceled).
int GetOrderOfRequest(size_t index) const;
// Resets first initialized socket handle from |requests_|. If found such
// a handle, returns true.
bool ReleaseOneConnection(KeepAlive keep_alive);
// Releases connections until there is nothing to release.
void ReleaseAllConnections(KeepAlive keep_alive);
// Note that this uses 0-based indices, while GetOrderOfRequest takes and
// returns 0-based indices.
TestSocketRequest* request(int i) { return requests_[i]; }
size_t requests_size() const { return requests_.size(); }
ScopedVector<TestSocketRequest>* requests() { return &requests_; }
size_t completion_count() const { return completion_count_; }
private:
ScopedVector<TestSocketRequest> requests_;
std::vector<TestSocketRequest*> request_order_;
size_t completion_count_;
DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest);
};
class MockTransportSocketParams
: public base::RefCounted<MockTransportSocketParams> {
private:
friend class base::RefCounted<MockTransportSocketParams>;
~MockTransportSocketParams() {}
DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams);
};
class MockTransportClientSocketPool : public TransportClientSocketPool {
public:
typedef MockTransportSocketParams SocketParams;
class MockConnectJob {
public:
MockConnectJob(scoped_ptr<StreamSocket> socket,
ClientSocketHandle* handle,
const CompletionCallback& callback);
~MockConnectJob();
int Connect();
bool CancelHandle(const ClientSocketHandle* handle);
private:
void OnConnect(int rv);
scoped_ptr<StreamSocket> socket_;
ClientSocketHandle* handle_;
CompletionCallback user_callback_;
DISALLOW_COPY_AND_ASSIGN(MockConnectJob);
};
MockTransportClientSocketPool(int max_sockets,
int max_sockets_per_group,
ClientSocketPoolHistograms* histograms,
ClientSocketFactory* socket_factory);
~MockTransportClientSocketPool() override;
RequestPriority last_request_priority() const {
return last_request_priority_;
}
int release_count() const { return release_count_; }
int cancel_count() const { return cancel_count_; }
// TransportClientSocketPool implementation.
int RequestSocket(const std::string& group_name,
const void* socket_params,
RequestPriority priority,
ClientSocketHandle* handle,
const CompletionCallback& callback,
const BoundNetLog& net_log) override;
void CancelRequest(const std::string& group_name,
ClientSocketHandle* handle) override;
void ReleaseSocket(const std::string& group_name,
scoped_ptr<StreamSocket> socket,
int id) override;
private:
ClientSocketFactory* client_socket_factory_;
ScopedVector<MockConnectJob> job_list_;
RequestPriority last_request_priority_;
int release_count_;
int cancel_count_;
DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool);
};
class DeterministicMockClientSocketFactory : public ClientSocketFactory {
public:
DeterministicMockClientSocketFactory();
~DeterministicMockClientSocketFactory() override;
void AddSocketDataProvider(DeterministicSocketData* socket);
void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
void ResetNextMockIndexes();
// Return |index|-th MockSSLClientSocket (starting from 0) that the factory
// created.
MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const;
SocketDataProviderArray<DeterministicSocketData>& mock_data() {
return mock_data_;
}
std::vector<DeterministicMockTCPClientSocket*>& tcp_client_sockets() {
return tcp_client_sockets_;
}
std::vector<DeterministicMockUDPClientSocket*>& udp_client_sockets() {
return udp_client_sockets_;
}
// ClientSocketFactory
scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
const RandIntCallback& rand_int_cb,
NetLog* net_log,
const NetLog::Source& source) override;
scoped_ptr<StreamSocket> CreateTransportClientSocket(
const AddressList& addresses,
NetLog* net_log,
const NetLog::Source& source) override;
scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
scoped_ptr<ClientSocketHandle> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config,
const SSLClientSocketContext& context) override;
void ClearSSLSessionCache() override;
private:
SocketDataProviderArray<DeterministicSocketData> mock_data_;
SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
// Store pointers to handed out sockets in case the test wants to get them.
std::vector<DeterministicMockTCPClientSocket*> tcp_client_sockets_;
std::vector<DeterministicMockUDPClientSocket*> udp_client_sockets_;
std::vector<MockSSLClientSocket*> ssl_client_sockets_;
DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory);
};
class MockSOCKSClientSocketPool : public SOCKSClientSocketPool {
public:
MockSOCKSClientSocketPool(int max_sockets,
int max_sockets_per_group,
ClientSocketPoolHistograms* histograms,
TransportClientSocketPool* transport_pool);
~MockSOCKSClientSocketPool() override;
// SOCKSClientSocketPool implementation.
int RequestSocket(const std::string& group_name,
const void* socket_params,
RequestPriority priority,
ClientSocketHandle* handle,
const CompletionCallback& callback,
const BoundNetLog& net_log) override;
void CancelRequest(const std::string& group_name,
ClientSocketHandle* handle) override;
void ReleaseSocket(const std::string& group_name,
scoped_ptr<StreamSocket> socket,
int id) override;
private:
TransportClientSocketPool* const transport_pool_;
DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool);
};
// Convenience class to temporarily set the WebSocketEndpointLockManager unlock
// delay to zero for testing purposes. Automatically restores the original value
// when destroyed.
class ScopedWebSocketEndpointZeroUnlockDelay {
public:
ScopedWebSocketEndpointZeroUnlockDelay();
~ScopedWebSocketEndpointZeroUnlockDelay();
private:
base::TimeDelta old_delay_;
};
// Constants for a successful SOCKS v5 handshake.
extern const char kSOCKS5GreetRequest[];
extern const int kSOCKS5GreetRequestLength;
extern const char kSOCKS5GreetResponse[];
extern const int kSOCKS5GreetResponseLength;
extern const char kSOCKS5OkRequest[];
extern const int kSOCKS5OkRequestLength;
extern const char kSOCKS5OkResponse[];
extern const int kSOCKS5OkResponseLength;
} // namespace net
#endif // NET_SOCKET_SOCKET_TEST_UTIL_H_
| {
"content_hash": "7ae696baf6059304c3406303e2d50745",
"timestamp": "",
"source": "github",
"line_count": 1312,
"max_line_length": 80,
"avg_line_length": 35.051067073170735,
"alnum_prop": 0.7100484919651205,
"repo_name": "Jonekee/chromium.src",
"id": "d6c7abafd980ffe828ae75cc6009da2f2adf716d",
"size": "47286",
"binary": false,
"copies": "12",
"ref": "refs/heads/nw12",
"path": "net/socket/socket_test_util.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "34522"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9249764"
},
{
"name": "C++",
"bytes": "222763973"
},
{
"name": "CSS",
"bytes": "875874"
},
{
"name": "Dart",
"bytes": "74976"
},
{
"name": "Go",
"bytes": "18155"
},
{
"name": "HTML",
"bytes": "27190037"
},
{
"name": "Java",
"bytes": "7645280"
},
{
"name": "JavaScript",
"bytes": "18828195"
},
{
"name": "Makefile",
"bytes": "96270"
},
{
"name": "Objective-C",
"bytes": "1397246"
},
{
"name": "Objective-C++",
"bytes": "7575073"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "248854"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "418340"
},
{
"name": "Python",
"bytes": "8032766"
},
{
"name": "Shell",
"bytes": "464218"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18335"
}
],
"symlink_target": ""
} |
<?php
/**
* Google Maps Draw Module
* @package drawonmaps
*
* Class: Map
* File: map.php
* Description: Handler of map's objects
*/
class Map {
public $id = 0;
public $title = NULL;
public $description = NULL;
public $center_lat = 0;
public $center_lng = 0;
public $zoom = 0;
public $typeid = 0;
public $user_id = 0;
public function __construct($map_id=0) {
if (is_numeric($map_id) && $map_id > 0) {
$map = array();
$map = $this->loadMap($map_id);
if ($map) {
$this->id = $map[0]['id'];
$this->title = $map[0]['title'];
$this->description = $map[0]['description'];
$this->center_lat = $map[0]['center_lat'];
$this->center_lng = $map[0]['center_lng'];
$this->zoom = $map[0]['zoom'];
$this->typeid = $map[0]['typeid'];
$this->user_id = $map[0]['user_id'];
}
else {
throw new Exception('Map not found. Invalid map ID: '.$map_id);
}
}
else {
$this->title = 'Map Title';
$this->description = '';
$this->center_lat = SiteConf::$DEFAULT_CENTER_LAN;
$this->center_lng = SiteConf::$DEFAULT_CENTER_LNG;
$this->zoom = SiteConf::$DEFAULT_ZOOM;
$this->typeid = SiteConf::$DEFAULT_TYPEID;
$this->user_id = '';
}
}
// method for saving a map object on database
public function save() {
$db = DbConnect::getConnection();
if ($this->id) {
$sql = "update maps set "
. "title='".mysqli_real_escape_string($db,$this->title)."', "
. "description='".mysqli_real_escape_string($db,$this->description)."', "
. "center_lat=$this->center_lat, "
. "center_lng=$this->center_lng, "
. "zoom=$this->zoom, "
. "typeid='".mysqli_real_escape_string($db,$this->typeid)."' "
. "where id=".$this->id;
}
else
{
$sql = "insert into maps (title, description, center_lat, center_lng, zoom, typeid) values ("
. "'".mysqli_real_escape_string($db,$this->title)."', "
. "'".mysqli_real_escape_string($db,$this->description)."', "
. " ".$this->center_lat.", "
. " ".$this->center_lng.", "
. " ".$this->zoom.", "
. "'".mysqli_real_escape_string($db,$this->typeid)."')";
}
$rs = mysqli_query($db, $sql);
if ($rs === FALSE) {
throw new Exception('Error while saving the map: '. mysqli_error($db));
return false;
}
if (!$this->id) {
$this->id = $db->insert_id;
}
return $this->id;
}
// method for deleting a map and the map's objects
public function delete() {
$db = DbConnect::getConnection();
$sql = "delete from maps where id=$this->id";
$rs = mysqli_query($db, $sql);
if ($rs == FALSE) {
throw new Exception('The deletion of map failed: '. mysqli_error($db));
}
else {
$sql = "delete from map_objects where map_id=$this->id";
$rs = mysqli_query($db, $sql);
if ($rs == FALSE) {
throw new Exception('Error while deleting the map: '. mysqli_error($db));
}
}
return true;
}
// retrieve a map from database
public function loadMap($map_id) {
$db = DbConnect::getConnection();
$sql = "SELECT * FROM maps WHERE id=$map_id";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
// retrieve map's objects of map from database
public function getMapObjects() {
$db = DbConnect::getConnection();
$sql = "SELECT * FROM map_objects WHERE map_id=$this->id";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
// delete map's objects of map
public function deleteMapObjects() {
$db = DbConnect::getConnection();
$sql = "delete from map_objects where map_id=$this->id";
$rs = mysqli_query($db, $sql);
if ($rs == FALSE) {
throw new Exception('Error while deleting objects of map: '. mysqli_error($db));
}
return true;
}
// save map's objects on database
function updateMapObject($title, $coords, $object_id, $id=null, $marker_icon='') {
$id = intval($id);
$coords = trim($coords);
$object_id = intval($object_id);
$marker_icon = trim($marker_icon);
if ($object_id < 1) {
return array(false, 'Invalid map object on updateMapObject');
}
$db = DbConnect::getConnection();
if ($id>0) {
$sql = "update map_objects set title='".mysqli_real_escape_string($db,$title)."', coords='".mysqli_real_escape_string($db,$coords)."', object_id=".$object_id.", map_id=".$this->id.", marker_icon='".mysqli_real_escape_string($db,$marker_icon)."' where id=".$id;
}
else {
$sql = "insert into map_objects (title, coords, object_id, map_id, marker_icon) values ('".mysqli_real_escape_string($db,$title)."', '".mysqli_real_escape_string($db,$coords)."', ".$object_id.", ".$this->id.", '".mysqli_real_escape_string($db,$marker_icon)."')";
}
$rs = mysqli_query($db, $sql);
if ($rs === FALSE) {
return array(false, 'Error while saving objects of map: '. mysqli_error($db));
}
return array(true, $db->insert_id);
}
}
?>
| {
"content_hash": "9050a6f0863019faf75d6ec971de3ea0",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 266,
"avg_line_length": 30.212290502793294,
"alnum_prop": 0.5512204142011834,
"repo_name": "allyrogge/finalproject",
"id": "32942f305f12b0facf25444687038fb138ec517b",
"size": "5408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "drawonmaps/model/map.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "275570"
},
{
"name": "HTML",
"bytes": "61290"
},
{
"name": "JavaScript",
"bytes": "119424"
},
{
"name": "PHP",
"bytes": "54654"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.