id
int64 22
34.9k
| original_code
stringlengths 31
107k
| code_wo_comment
stringlengths 29
77.3k
| cleancode
stringlengths 25
62.1k
| repo
stringlengths 6
65
| label
sequencelengths 4
4
|
---|---|---|---|---|---|
24,576 | private void addEntriesToMainManifest(Manifest manifest) {
Attributes attrs = manifest.getMainAttributes();
// If a manifest doesn't have a version, the other attributes won't get written out. Lame.
attrs.put(Attributes.Name.MANIFEST_VERSION, new Date().toString());
for (Map.Entry<Attributes.Name, String> entry : this.manifestEntries.entrySet()) {
attrs.put(entry.getKey(), entry.getValue());
}
} | private void addEntriesToMainManifest(Manifest manifest) {
Attributes attrs = manifest.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, new Date().toString());
for (Map.Entry<Attributes.Name, String> entry : this.manifestEntries.entrySet()) {
attrs.put(entry.getKey(), entry.getValue());
}
} | private void addentriestomainmanifest(manifest manifest) { attributes attrs = manifest.getmainattributes(); attrs.put(attributes.name.manifest_version, new date().tostring()); for (map.entry<attributes.name, string> entry : this.manifestentries.entryset()) { attrs.put(entry.getkey(), entry.getvalue()); } } | DavidWhitlock/PortlandStateJava | [
0,
0,
1,
0
] |
32,849 | private boolean isTelLenthLegal(String tel) {
//TODO: Replace this with your own logic
return tel.length() == 11;
} | private boolean isTelLenthLegal(String tel) {
return tel.length() == 11;
} | private boolean istellenthlegal(string tel) { return tel.length() == 11; } | Asucanc/FishMail | [
0,
1,
0,
0
] |
32,850 | private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@")&&email.contains(".");
} | private boolean isEmailValid(String email) {
return email.contains("@")&&email.contains(".");
} | private boolean isemailvalid(string email) { return email.contains("@")&&email.contains("."); } | Asucanc/FishMail | [
0,
1,
0,
0
] |
85 | public HistoryItemActionModulesBuilder addModuleForVoiceCall() {
if (moduleInfo.getIsBlocked()) {
return this;
}
// TODO(zachh): Support post-dial digits; consider using DialerPhoneNumber.
// Do not set PhoneAccountHandle so that regular PreCall logic will be used. The account used to
// place or receive the call should be ignored for voice calls.
CallIntentBuilder callIntentBuilder =
new CallIntentBuilder(moduleInfo.getNormalizedNumber(), getCallInitiationType())
.setAllowAssistedDial(moduleInfo.getCanSupportAssistedDialing());
modules.add(IntentModule.newCallModule(context, callIntentBuilder));
return this;
} | public HistoryItemActionModulesBuilder addModuleForVoiceCall() {
if (moduleInfo.getIsBlocked()) {
return this;
}
CallIntentBuilder callIntentBuilder =
new CallIntentBuilder(moduleInfo.getNormalizedNumber(), getCallInitiationType())
.setAllowAssistedDial(moduleInfo.getCanSupportAssistedDialing());
modules.add(IntentModule.newCallModule(context, callIntentBuilder));
return this;
} | public historyitemactionmodulesbuilder addmoduleforvoicecall() { if (moduleinfo.getisblocked()) { return this; } callintentbuilder callintentbuilder = new callintentbuilder(moduleinfo.getnormalizednumber(), getcallinitiationtype()) .setallowassisteddial(moduleinfo.getcansupportassisteddialing()); modules.add(intentmodule.newcallmodule(context, callintentbuilder)); return this; } | DerpGang/packages_apps_Dialer | [
0,
1,
0,
0
] |
16,486 | public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
if(args.length != 4) {
System.out.print("args should be 2 : <inputpath> <outpath> <number of centroids> <dimensions> .") ;
System.exit(-1);
}
int k = Integer.valueOf(args[2]) ;
int dim = Integer.valueOf(args[3]) ;
Job init_job = Job.getInstance() ;
Configuration init_conf = init_job.getConfiguration();
init_conf.set("kmeans.k", args[2]);
init_conf.set("kmeans.dim", args[3]);
init_job.setJarByClass(KMean.class);
init_job.setJobName("clustered kmeans");
init_job.setMapperClass(KMeanInitMapper.class);
init_job.setReducerClass(KMeanInitReducer.class);
init_job.setOutputKeyClass(IntWritable.class);
init_job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(init_job, new Path(args[0]));
//TODO check rewrite in future
FileOutputFormat.setOutputPath(init_job, new Path(args[1] + "_m_" + Integer.toString(0)));
init_job.waitForCompletion(true);
double[][] old_centroids = new double[k][dim] ;
int fi = 1 ;
long t1 = System.currentTimeMillis() ;
while(true) {
System.out.print("start iteration") ;
Job kmean_cluster_jb = Job.getInstance() ;
Configuration conf = kmean_cluster_jb.getConfiguration() ;
conf.set("kmeans.k", args[2]);
conf.set("kmeans.dim", args[3]);
kmean_cluster_jb.setJarByClass(KMean.class);
kmean_cluster_jb.setJobName("clustered kmeans");
kmean_cluster_jb.setMapperClass(KMeanIterationMapper.class);
kmean_cluster_jb.setReducerClass(KMeanIterationReducer.class);
kmean_cluster_jb.setOutputKeyClass(IntWritable.class);
kmean_cluster_jb.setOutputValueClass(Text.class);
// TODO check rewrite in future
String uri = args[1] + "_m_" + Integer.toString(fi-1) + "/part-r-00000";
Configuration temp_conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), temp_conf);
Path input_path = new Path(uri);
FSDataInputStream input_stream = fs.open(input_path);
BufferedReader input_buffer = new BufferedReader(new InputStreamReader(input_stream));
double total_dis = 0 ;
double[][] new_centroids = new double[k][dim] ;
for(int i = 0 ; i < k ; i++) {
String line = input_buffer.readLine() ;
if(line == null) {
for(int j = 0 ; j < dim ; j++) {
new_centroids[i][j] = Double.valueOf(old_centroids[i][j]) ;
}
continue ;
}
int key = Integer.valueOf(line.split("\t")[0]) ;
String[] new_centroid = line.split("\t")[1].split(",") ;
for(int j = 0 ; j < dim ; j++) {
new_centroids[key][j] = Double.valueOf(new_centroid[j]) ;
total_dis += Math.pow(new_centroids[key][j] - old_centroids[key][j], 2) ;
}
conf.set("kmeans.centroid" + key, line.split("\t")[1]);
}
double threshold = Math.pow(0.001 ,2) * k * dim ;
if(total_dis < threshold)
break ;
FileInputFormat.addInputPath(kmean_cluster_jb, new Path(args[0]));
//TODO check rewrite in future
FileOutputFormat.setOutputPath(kmean_cluster_jb, new Path(args[1] + "_m_" + Integer.toString(fi)));
kmean_cluster_jb.waitForCompletion(true);
old_centroids = new_centroids;
fi++ ;
}
long t2 = System.currentTimeMillis() ;
System.out.println("\n Time token by un-parallel is : " + (t2-t1) + "ms");
} | public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
if(args.length != 4) {
System.out.print("args should be 2 : <inputpath> <outpath> <number of centroids> <dimensions> .") ;
System.exit(-1);
}
int k = Integer.valueOf(args[2]) ;
int dim = Integer.valueOf(args[3]) ;
Job init_job = Job.getInstance() ;
Configuration init_conf = init_job.getConfiguration();
init_conf.set("kmeans.k", args[2]);
init_conf.set("kmeans.dim", args[3]);
init_job.setJarByClass(KMean.class);
init_job.setJobName("clustered kmeans");
init_job.setMapperClass(KMeanInitMapper.class);
init_job.setReducerClass(KMeanInitReducer.class);
init_job.setOutputKeyClass(IntWritable.class);
init_job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(init_job, new Path(args[0]));
FileOutputFormat.setOutputPath(init_job, new Path(args[1] + "_m_" + Integer.toString(0)));
init_job.waitForCompletion(true);
double[][] old_centroids = new double[k][dim] ;
int fi = 1 ;
long t1 = System.currentTimeMillis() ;
while(true) {
System.out.print("start iteration") ;
Job kmean_cluster_jb = Job.getInstance() ;
Configuration conf = kmean_cluster_jb.getConfiguration() ;
conf.set("kmeans.k", args[2]);
conf.set("kmeans.dim", args[3]);
kmean_cluster_jb.setJarByClass(KMean.class);
kmean_cluster_jb.setJobName("clustered kmeans");
kmean_cluster_jb.setMapperClass(KMeanIterationMapper.class);
kmean_cluster_jb.setReducerClass(KMeanIterationReducer.class);
kmean_cluster_jb.setOutputKeyClass(IntWritable.class);
kmean_cluster_jb.setOutputValueClass(Text.class);
String uri = args[1] + "_m_" + Integer.toString(fi-1) + "/part-r-00000";
Configuration temp_conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), temp_conf);
Path input_path = new Path(uri);
FSDataInputStream input_stream = fs.open(input_path);
BufferedReader input_buffer = new BufferedReader(new InputStreamReader(input_stream));
double total_dis = 0 ;
double[][] new_centroids = new double[k][dim] ;
for(int i = 0 ; i < k ; i++) {
String line = input_buffer.readLine() ;
if(line == null) {
for(int j = 0 ; j < dim ; j++) {
new_centroids[i][j] = Double.valueOf(old_centroids[i][j]) ;
}
continue ;
}
int key = Integer.valueOf(line.split("\t")[0]) ;
String[] new_centroid = line.split("\t")[1].split(",") ;
for(int j = 0 ; j < dim ; j++) {
new_centroids[key][j] = Double.valueOf(new_centroid[j]) ;
total_dis += Math.pow(new_centroids[key][j] - old_centroids[key][j], 2) ;
}
conf.set("kmeans.centroid" + key, line.split("\t")[1]);
}
double threshold = Math.pow(0.001 ,2) * k * dim ;
if(total_dis < threshold)
break ;
FileInputFormat.addInputPath(kmean_cluster_jb, new Path(args[0]));
FileOutputFormat.setOutputPath(kmean_cluster_jb, new Path(args[1] + "_m_" + Integer.toString(fi)));
kmean_cluster_jb.waitForCompletion(true);
old_centroids = new_centroids;
fi++ ;
}
long t2 = System.currentTimeMillis() ;
System.out.println("\n Time token by un-parallel is : " + (t2-t1) + "ms");
} | public static void main(string[] args) throws ioexception, classnotfoundexception, interruptedexception { if(args.length != 4) { system.out.print("args should be 2 : <inputpath> <outpath> <number of centroids> <dimensions> .") ; system.exit(-1); } int k = integer.valueof(args[2]) ; int dim = integer.valueof(args[3]) ; job init_job = job.getinstance() ; configuration init_conf = init_job.getconfiguration(); init_conf.set("kmeans.k", args[2]); init_conf.set("kmeans.dim", args[3]); init_job.setjarbyclass(kmean.class); init_job.setjobname("clustered kmeans"); init_job.setmapperclass(kmeaninitmapper.class); init_job.setreducerclass(kmeaninitreducer.class); init_job.setoutputkeyclass(intwritable.class); init_job.setoutputvalueclass(text.class); fileinputformat.addinputpath(init_job, new path(args[0])); fileoutputformat.setoutputpath(init_job, new path(args[1] + "_m_" + integer.tostring(0))); init_job.waitforcompletion(true); double[][] old_centroids = new double[k][dim] ; int fi = 1 ; long t1 = system.currenttimemillis() ; while(true) { system.out.print("start iteration") ; job kmean_cluster_jb = job.getinstance() ; configuration conf = kmean_cluster_jb.getconfiguration() ; conf.set("kmeans.k", args[2]); conf.set("kmeans.dim", args[3]); kmean_cluster_jb.setjarbyclass(kmean.class); kmean_cluster_jb.setjobname("clustered kmeans"); kmean_cluster_jb.setmapperclass(kmeaniterationmapper.class); kmean_cluster_jb.setreducerclass(kmeaniterationreducer.class); kmean_cluster_jb.setoutputkeyclass(intwritable.class); kmean_cluster_jb.setoutputvalueclass(text.class); string uri = args[1] + "_m_" + integer.tostring(fi-1) + "/part-r-00000"; configuration temp_conf = new configuration(); filesystem fs = filesystem.get(uri.create(uri), temp_conf); path input_path = new path(uri); fsdatainputstream input_stream = fs.open(input_path); bufferedreader input_buffer = new bufferedreader(new inputstreamreader(input_stream)); double total_dis = 0 ; double[][] new_centroids = new double[k][dim] ; for(int i = 0 ; i < k ; i++) { string line = input_buffer.readline() ; if(line == null) { for(int j = 0 ; j < dim ; j++) { new_centroids[i][j] = double.valueof(old_centroids[i][j]) ; } continue ; } int key = integer.valueof(line.split("\t")[0]) ; string[] new_centroid = line.split("\t")[1].split(",") ; for(int j = 0 ; j < dim ; j++) { new_centroids[key][j] = double.valueof(new_centroid[j]) ; total_dis += math.pow(new_centroids[key][j] - old_centroids[key][j], 2) ; } conf.set("kmeans.centroid" + key, line.split("\t")[1]); } double threshold = math.pow(0.001 ,2) * k * dim ; if(total_dis < threshold) break ; fileinputformat.addinputpath(kmean_cluster_jb, new path(args[0])); fileoutputformat.setoutputpath(kmean_cluster_jb, new path(args[1] + "_m_" + integer.tostring(fi))); kmean_cluster_jb.waitforcompletion(true); old_centroids = new_centroids; fi++ ; } long t2 = system.currenttimemillis() ; system.out.println("\n time token by un-parallel is : " + (t2-t1) + "ms"); } | AmrHendy/K-Means | [
0,
1,
0,
0
] |
32,941 | protected long dynamicCountFromUserValue( XTCENamedObject item, String form ) {
// this can probably work on contentValues_
String paramFullPath = item.getFullPath();
for ( XTCEContainerContentEntry entry : contentList_ ) {
if ( ( entry.getEntryType() != FieldType.PARAMETER ) &&
( entry.getEntryType() != FieldType.ARGUMENT ) ) {
continue;
}
XTCEContainerEntryValue valueObj = entry.getValue();
if ( entry.getValue() == null ) {
continue;
}
if ( entry.getItemFullPath().equals( paramFullPath ) == true ) {
if ( valueObj.getOperator().equals( "==" ) == true ) { // NOI18N
try {
return Long.parseLong( valueObj.getCalibratedValue() );
} catch ( NumberFormatException ex ) {
warnings_.add(
XTCEFunctions.getText( "xml_dynamic_count_numeric_error" ) + // NOI18N
" " + // NOI18N
item.getName() +
" (" + // NOI18N
XTCEFunctions.getText( "general_value" ) + // NOI18N
" '" + // NOI18N
valueObj.getCalibratedValue() +
"')" ); // NOI18N
return 1;
}
}
warnings_.add(
XTCEFunctions.getText( "xml_dynamic_count_missing_error" ) + // NOI18N
" " + // NOI18N
item.getName() +
", " + // NOI18N
XTCEFunctions.getText( "xml_dynamic_count_assume1" ) ); // NOI18N
return 1;
}
}
return 1;
} | protected long dynamicCountFromUserValue( XTCENamedObject item, String form ) {
String paramFullPath = item.getFullPath();
for ( XTCEContainerContentEntry entry : contentList_ ) {
if ( ( entry.getEntryType() != FieldType.PARAMETER ) &&
( entry.getEntryType() != FieldType.ARGUMENT ) ) {
continue;
}
XTCEContainerEntryValue valueObj = entry.getValue();
if ( entry.getValue() == null ) {
continue;
}
if ( entry.getItemFullPath().equals( paramFullPath ) == true ) {
if ( valueObj.getOperator().equals( "==" ) == true ) {
try {
return Long.parseLong( valueObj.getCalibratedValue() );
} catch ( NumberFormatException ex ) {
warnings_.add(
XTCEFunctions.getText( "xml_dynamic_count_numeric_error" ) +
" " +
item.getName() +
" (" +
XTCEFunctions.getText( "general_value" ) +
" '" +
valueObj.getCalibratedValue() +
"')" );
return 1;
}
}
warnings_.add(
XTCEFunctions.getText( "xml_dynamic_count_missing_error" ) +
" " +
item.getName() +
", " +
XTCEFunctions.getText( "xml_dynamic_count_assume1" ) );
return 1;
}
}
return 1;
} | protected long dynamiccountfromuservalue( xtcenamedobject item, string form ) { string paramfullpath = item.getfullpath(); for ( xtcecontainercontententry entry : contentlist_ ) { if ( ( entry.getentrytype() != fieldtype.parameter ) && ( entry.getentrytype() != fieldtype.argument ) ) { continue; } xtcecontainerentryvalue valueobj = entry.getvalue(); if ( entry.getvalue() == null ) { continue; } if ( entry.getitemfullpath().equals( paramfullpath ) == true ) { if ( valueobj.getoperator().equals( "==" ) == true ) { try { return long.parselong( valueobj.getcalibratedvalue() ); } catch ( numberformatexception ex ) { warnings_.add( xtcefunctions.gettext( "xml_dynamic_count_numeric_error" ) + " " + item.getname() + " (" + xtcefunctions.gettext( "general_value" ) + " '" + valueobj.getcalibratedvalue() + "')" ); return 1; } } warnings_.add( xtcefunctions.gettext( "xml_dynamic_count_missing_error" ) + " " + item.getname() + ", " + xtcefunctions.gettext( "xml_dynamic_count_assume1" ) ); return 1; } } return 1; } | CesarCoelho/xtcetools | [
1,
0,
0,
0
] |
32,983 | private static void registerFluids(BlockRegistry blockRegistry) {
// TODO Adjust properties
Fluid steam = new Fluid("steam", new ResourceLocation(SteamAgeRevolution.MODID, "fluids/steam"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/steam_flow")).setGaseous(true)
.setTemperature(1000).setViscosity(200);
if(!(FluidRegistry.isFluidRegistered(steam))) { // Soft registration
FluidRegistry.registerFluid(steam);
FluidRegistry.addBucketForFluid(steam);
}
blockRegistry.register(new BlockSARFluid("steam", FluidRegistry.getFluid("steam"), Material.LAVA));
Fluid sulphur_dioxide = new Fluid("sulphur_dioxide",
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphur_dioxide"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphur_dioxide_flow")).setViscosity(250)
.setGaseous(true).setDensity(-100);
FluidRegistry.registerFluid(sulphur_dioxide);
FluidRegistry.addBucketForFluid(sulphur_dioxide);
blockRegistry.register(new BlockDamagingFluid("sulphur_dioxide", FluidRegistry.getFluid("sulphur_dioxide"),
Material.WATER, SARBlocks.damageSourceGas, 2));
Fluid sulphuric_acid = new Fluid("sulphuric_acid",
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphuric_acid"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphuric_acid_flow")).setViscosity(500);
FluidRegistry.registerFluid(sulphuric_acid);
FluidRegistry.addBucketForFluid(sulphuric_acid);
blockRegistry.register(new BlockAcidFluid("sulphuric_acid", FluidRegistry.getFluid("sulphuric_acid"),
Material.WATER, SARBlocks.damageSourceAcid, 4));
// TODO TE compat?
Fluid liquid_glowstone = new Fluid("liquid_glowstone",
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/liquid_glowstone"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/liquid_glowstone_flow")).setViscosity(2000)
.setGaseous(true);
FluidRegistry.registerFluid(liquid_glowstone);
FluidRegistry.addBucketForFluid(liquid_glowstone);
blockRegistry.register(new BlockLiquidGlowstone("liquid_glowstone", FluidRegistry.getFluid("liquid_glowstone"),
Material.LAVA));
Fluid potion = new Fluid("potion", new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution_flowing")) {
@SuppressWarnings("deprecation")
@Override
public String getLocalizedName(FluidStack stack) {
return I18n.translateToLocal(
PotionUtils.getPotionTypeFromNBT(stack.tag).getNamePrefixed("potion.effect."));
}
@Override
public int getColor(FluidStack stack) {
return PotionUtils.getPotionColorFromEffectList(PotionUtils.getEffectsFromTag(stack.tag));
}
};
FluidRegistry.registerFluid(potion);
FluidRegistry.addBucketForFluid(potion);
FluidRegistry
.registerFluid(new Fluid("slime", new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution")) {
@Override
public int getColor() {
return Color.GREEN.getRGB();
}
});
} | private static void registerFluids(BlockRegistry blockRegistry) {
Fluid steam = new Fluid("steam", new ResourceLocation(SteamAgeRevolution.MODID, "fluids/steam"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/steam_flow")).setGaseous(true)
.setTemperature(1000).setViscosity(200);
if(!(FluidRegistry.isFluidRegistered(steam))) {
FluidRegistry.registerFluid(steam);
FluidRegistry.addBucketForFluid(steam);
}
blockRegistry.register(new BlockSARFluid("steam", FluidRegistry.getFluid("steam"), Material.LAVA));
Fluid sulphur_dioxide = new Fluid("sulphur_dioxide",
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphur_dioxide"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphur_dioxide_flow")).setViscosity(250)
.setGaseous(true).setDensity(-100);
FluidRegistry.registerFluid(sulphur_dioxide);
FluidRegistry.addBucketForFluid(sulphur_dioxide);
blockRegistry.register(new BlockDamagingFluid("sulphur_dioxide", FluidRegistry.getFluid("sulphur_dioxide"),
Material.WATER, SARBlocks.damageSourceGas, 2));
Fluid sulphuric_acid = new Fluid("sulphuric_acid",
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphuric_acid"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/sulphuric_acid_flow")).setViscosity(500);
FluidRegistry.registerFluid(sulphuric_acid);
FluidRegistry.addBucketForFluid(sulphuric_acid);
blockRegistry.register(new BlockAcidFluid("sulphuric_acid", FluidRegistry.getFluid("sulphuric_acid"),
Material.WATER, SARBlocks.damageSourceAcid, 4));
Fluid liquid_glowstone = new Fluid("liquid_glowstone",
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/liquid_glowstone"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/liquid_glowstone_flow")).setViscosity(2000)
.setGaseous(true);
FluidRegistry.registerFluid(liquid_glowstone);
FluidRegistry.addBucketForFluid(liquid_glowstone);
blockRegistry.register(new BlockLiquidGlowstone("liquid_glowstone", FluidRegistry.getFluid("liquid_glowstone"),
Material.LAVA));
Fluid potion = new Fluid("potion", new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution_flowing")) {
@SuppressWarnings("deprecation")
@Override
public String getLocalizedName(FluidStack stack) {
return I18n.translateToLocal(
PotionUtils.getPotionTypeFromNBT(stack.tag).getNamePrefixed("potion.effect."));
}
@Override
public int getColor(FluidStack stack) {
return PotionUtils.getPotionColorFromEffectList(PotionUtils.getEffectsFromTag(stack.tag));
}
};
FluidRegistry.registerFluid(potion);
FluidRegistry.addBucketForFluid(potion);
FluidRegistry
.registerFluid(new Fluid("slime", new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution"),
new ResourceLocation(SteamAgeRevolution.MODID, "fluids/solution")) {
@Override
public int getColor() {
return Color.GREEN.getRGB();
}
});
} | private static void registerfluids(blockregistry blockregistry) { fluid steam = new fluid("steam", new resourcelocation(steamagerevolution.modid, "fluids/steam"), new resourcelocation(steamagerevolution.modid, "fluids/steam_flow")).setgaseous(true) .settemperature(1000).setviscosity(200); if(!(fluidregistry.isfluidregistered(steam))) { fluidregistry.registerfluid(steam); fluidregistry.addbucketforfluid(steam); } blockregistry.register(new blocksarfluid("steam", fluidregistry.getfluid("steam"), material.lava)); fluid sulphur_dioxide = new fluid("sulphur_dioxide", new resourcelocation(steamagerevolution.modid, "fluids/sulphur_dioxide"), new resourcelocation(steamagerevolution.modid, "fluids/sulphur_dioxide_flow")).setviscosity(250) .setgaseous(true).setdensity(-100); fluidregistry.registerfluid(sulphur_dioxide); fluidregistry.addbucketforfluid(sulphur_dioxide); blockregistry.register(new blockdamagingfluid("sulphur_dioxide", fluidregistry.getfluid("sulphur_dioxide"), material.water, sarblocks.damagesourcegas, 2)); fluid sulphuric_acid = new fluid("sulphuric_acid", new resourcelocation(steamagerevolution.modid, "fluids/sulphuric_acid"), new resourcelocation(steamagerevolution.modid, "fluids/sulphuric_acid_flow")).setviscosity(500); fluidregistry.registerfluid(sulphuric_acid); fluidregistry.addbucketforfluid(sulphuric_acid); blockregistry.register(new blockacidfluid("sulphuric_acid", fluidregistry.getfluid("sulphuric_acid"), material.water, sarblocks.damagesourceacid, 4)); fluid liquid_glowstone = new fluid("liquid_glowstone", new resourcelocation(steamagerevolution.modid, "fluids/liquid_glowstone"), new resourcelocation(steamagerevolution.modid, "fluids/liquid_glowstone_flow")).setviscosity(2000) .setgaseous(true); fluidregistry.registerfluid(liquid_glowstone); fluidregistry.addbucketforfluid(liquid_glowstone); blockregistry.register(new blockliquidglowstone("liquid_glowstone", fluidregistry.getfluid("liquid_glowstone"), material.lava)); fluid potion = new fluid("potion", new resourcelocation(steamagerevolution.modid, "fluids/solution"), new resourcelocation(steamagerevolution.modid, "fluids/solution_flowing")) { @suppresswarnings("deprecation") @override public string getlocalizedname(fluidstack stack) { return i18n.translatetolocal( potionutils.getpotiontypefromnbt(stack.tag).getnameprefixed("potion.effect.")); } @override public int getcolor(fluidstack stack) { return potionutils.getpotioncolorfromeffectlist(potionutils.geteffectsfromtag(stack.tag)); } }; fluidregistry.registerfluid(potion); fluidregistry.addbucketforfluid(potion); fluidregistry .registerfluid(new fluid("slime", new resourcelocation(steamagerevolution.modid, "fluids/solution"), new resourcelocation(steamagerevolution.modid, "fluids/solution")) { @override public int getcolor() { return color.green.getrgb(); } }); } | BrassGoggledCoders/SteamAgeRevolution | [
1,
1,
0,
0
] |
33,071 | @Test void testUnquotedBuiltInFunctionNames() {
// TODO: Once Oracle is an officially supported dialect, this test
// should be moved to OracleValidatorTest.java.
final Sql oracle = sql("?")
.withUnquotedCasing(Casing.TO_UPPER)
.withCaseSensitive(true);
// Built-in functions are always case-insensitive.
oracle.sql("select count(*), sum(deptno), floor(2.5) from dept").ok();
oracle.sql("select COUNT(*), FLOOR(2.5) from dept").ok();
oracle.sql("select cOuNt(*), FlOOr(2.5) from dept").ok();
oracle.sql("select cOuNt (*), FlOOr (2.5) from dept").ok();
oracle.sql("select current_time from dept").ok();
oracle.sql("select Current_Time from dept").ok();
oracle.sql("select CURRENT_TIME from dept").ok();
oracle.sql("select \"count\"(*) from dept").ok();
} | @Test void testUnquotedBuiltInFunctionNames() {
final Sql oracle = sql("?")
.withUnquotedCasing(Casing.TO_UPPER)
.withCaseSensitive(true);
oracle.sql("select count(*), sum(deptno), floor(2.5) from dept").ok();
oracle.sql("select COUNT(*), FLOOR(2.5) from dept").ok();
oracle.sql("select cOuNt(*), FlOOr(2.5) from dept").ok();
oracle.sql("select cOuNt (*), FlOOr (2.5) from dept").ok();
oracle.sql("select current_time from dept").ok();
oracle.sql("select Current_Time from dept").ok();
oracle.sql("select CURRENT_TIME from dept").ok();
oracle.sql("select \"count\"(*) from dept").ok();
} | @test void testunquotedbuiltinfunctionnames() { final sql oracle = sql("?") .withunquotedcasing(casing.to_upper) .withcasesensitive(true); oracle.sql("select count(*), sum(deptno), floor(2.5) from dept").ok(); oracle.sql("select count(*), floor(2.5) from dept").ok(); oracle.sql("select count(*), floor(2.5) from dept").ok(); oracle.sql("select count (*), floor (2.5) from dept").ok(); oracle.sql("select current_time from dept").ok(); oracle.sql("select current_time from dept").ok(); oracle.sql("select current_time from dept").ok(); oracle.sql("select \"count\"(*) from dept").ok(); } | AndrewPochapsky/calcite | [
0,
0,
0,
1
] |
8,635 | private void tryConnectToIPv6() throws Exception {
Collection<Inet6Address> possibleInetAddresses = AddressUtil
.getPossibleInetAddressesFor((Inet6Address) address.getInetAddress());
Level level = silent ? Level.FINEST : Level.INFO;
//TODO: collection.toString() will likely not produce any useful output!
if (logger.isLoggable(level)) {
logger.log(level, "Trying to connect possible IPv6 addresses: " + possibleInetAddresses);
}
boolean connected = false;
Exception error = null;
int configuredTimeoutMillis =
ioService.getSocketConnectTimeoutSeconds(endpointManager.getEndpointQualifier()) * MILLIS_PER_SECOND;
int timeoutMillis = configuredTimeoutMillis > 0 && configuredTimeoutMillis < Integer.MAX_VALUE
? configuredTimeoutMillis : DEFAULT_IPV6_SOCKET_CONNECT_TIMEOUT_SECONDS * MILLIS_PER_SECOND;
for (Inet6Address inetAddress : possibleInetAddresses) {
try {
tryToConnect(new InetSocketAddress(inetAddress, address.getPort()), timeoutMillis);
connected = true;
break;
} catch (Exception e) {
error = e;
}
}
if (!connected && error != null) {
// could not connect any of addresses
throw error;
}
} | private void tryConnectToIPv6() throws Exception {
Collection<Inet6Address> possibleInetAddresses = AddressUtil
.getPossibleInetAddressesFor((Inet6Address) address.getInetAddress());
Level level = silent ? Level.FINEST : Level.INFO;
if (logger.isLoggable(level)) {
logger.log(level, "Trying to connect possible IPv6 addresses: " + possibleInetAddresses);
}
boolean connected = false;
Exception error = null;
int configuredTimeoutMillis =
ioService.getSocketConnectTimeoutSeconds(endpointManager.getEndpointQualifier()) * MILLIS_PER_SECOND;
int timeoutMillis = configuredTimeoutMillis > 0 && configuredTimeoutMillis < Integer.MAX_VALUE
? configuredTimeoutMillis : DEFAULT_IPV6_SOCKET_CONNECT_TIMEOUT_SECONDS * MILLIS_PER_SECOND;
for (Inet6Address inetAddress : possibleInetAddresses) {
try {
tryToConnect(new InetSocketAddress(inetAddress, address.getPort()), timeoutMillis);
connected = true;
break;
} catch (Exception e) {
error = e;
}
}
if (!connected && error != null) {
throw error;
}
} | private void tryconnecttoipv6() throws exception { collection<inet6address> possibleinetaddresses = addressutil .getpossibleinetaddressesfor((inet6address) address.getinetaddress()); level level = silent ? level.finest : level.info; if (logger.isloggable(level)) { logger.log(level, "trying to connect possible ipv6 addresses: " + possibleinetaddresses); } boolean connected = false; exception error = null; int configuredtimeoutmillis = ioservice.getsocketconnecttimeoutseconds(endpointmanager.getendpointqualifier()) * millis_per_second; int timeoutmillis = configuredtimeoutmillis > 0 && configuredtimeoutmillis < integer.max_value ? configuredtimeoutmillis : default_ipv6_socket_connect_timeout_seconds * millis_per_second; for (inet6address inetaddress : possibleinetaddresses) { try { trytoconnect(new inetsocketaddress(inetaddress, address.getport()), timeoutmillis); connected = true; break; } catch (exception e) { error = e; } } if (!connected && error != null) { throw error; } } | HugeOrangeDev/hazelcast | [
0,
0,
1,
0
] |
33,242 | public @NotNull FramedPacket retrieve() {
if (!PacketUtils.CACHED_PACKET) {
// TODO: Using a local buffer may be possible
return PacketUtils.allocateTrimmedPacket(packet());
}
SoftReference<FramedPacket> ref;
FramedPacket cache;
if (updated == 0 ||
((ref = packet) == null ||
(cache = ref.get()) == null)) {
cache = PacketUtils.allocateTrimmedPacket(packet());
this.packet = new SoftReference<>(cache);
UPDATER.compareAndSet(this, 0, 1);
}
return cache;
} | public @NotNull FramedPacket retrieve() {
if (!PacketUtils.CACHED_PACKET) {
return PacketUtils.allocateTrimmedPacket(packet());
}
SoftReference<FramedPacket> ref;
FramedPacket cache;
if (updated == 0 ||
((ref = packet) == null ||
(cache = ref.get()) == null)) {
cache = PacketUtils.allocateTrimmedPacket(packet());
this.packet = new SoftReference<>(cache);
UPDATER.compareAndSet(this, 0, 1);
}
return cache;
} | public @notnull framedpacket retrieve() { if (!packetutils.cached_packet) { return packetutils.allocatetrimmedpacket(packet()); } softreference<framedpacket> ref; framedpacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = packetutils.allocatetrimmedpacket(packet()); this.packet = new softreference<>(cache); updater.compareandset(this, 0, 1); } return cache; } | Avinesia-Union/Minestom | [
1,
0,
0,
0
] |
25,149 | @Override
@JRubyMethod(name = "===")
public RubyBoolean op_eqq(ThreadContext context, IRubyObject obj) {
// maybe we could handle java.lang === java.lang.reflect as well ?
return context.runtime.newBoolean(obj == this || isInstance(obj));
} | @Override
@JRubyMethod(name = "===")
public RubyBoolean op_eqq(ThreadContext context, IRubyObject obj) {
return context.runtime.newBoolean(obj == this || isInstance(obj));
} | @override @jrubymethod(name = "===") public rubyboolean op_eqq(threadcontext context, irubyobject obj) { return context.runtime.newboolean(obj == this || isinstance(obj)); } | DJRickyB/jruby | [
1,
0,
0,
0
] |
25,166 | @Test
public void testCEV() {
int timeSteps = 200;// TODO why is this working with so few steps?
int priceSteps = 100;
double lowerMoneyness = 0.3; // Not working well for ITM calls
double upperMoneyness = 3.0;
double volTol = 5e-3;
boolean print = false; // set to false before pushing
TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print);
} | @Test
public void testCEV() {
int timeSteps = 200
int priceSteps = 100;
double lowerMoneyness = 0.3;
double upperMoneyness = 3.0;
double volTol = 5e-3;
boolean print = false;
TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print);
} | @test public void testcev() { int timesteps = 200 int pricesteps = 100; double lowermoneyness = 0.3; double uppermoneyness = 3.0; double voltol = 5e-3; boolean print = false; tester.testcev(solver, timesteps, pricesteps, lowermoneyness, uppermoneyness, voltol, print); } | Incapture/OG-Platform | [
1,
0,
1,
0
] |
8,849 | private static boolean performCalculationS2(int srcX, int srcY, RouteStrategy strategy) {
return performCalculationSX(srcX, srcY, 2, strategy); // TODO optimized algorhytm's.
} | private static boolean performCalculationS2(int srcX, int srcY, RouteStrategy strategy) {
return performCalculationSX(srcX, srcY, 2, strategy);
} | private static boolean performcalculations2(int srcx, int srcy, routestrategy strategy) { return performcalculationsx(srcx, srcy, 2, strategy); } | CSS-Lletya/open633 | [
1,
0,
0,
0
] |
25,271 | public void addQualifNoDip() throws IOException {
if (isValidIndCursus(QualifNonDiplomante.class, true)) {
// on transforme le commentaire pour corriger les caractères spéciaux
pojoQualif.getCursus().setComment(pojoQualif.getCursus().getComment());
//TODO: Fix this !!
// org.esupportail.commons.utils.strings.StringUtils
// .htmlToText(pojoQualif.getCursus().getComment()));
if (actionEnum.getWhatAction().equals(ActionEnum.UPDATE_ACTION)) {
//ajout en base
addOneCursus(getCurrentInd().getIndividu(), pojoQualif.getCursus());
//Ajout dans l'individu courant
getCurrentInd().getIndividu().getCursus().add(pojoQualif.getCursus());
}
pojoQualif.addCursus();
Collections.sort(pojoQualif.getCursusList(), new ComparatorString(IndCursus.class));
}
} | public void addQualifNoDip() throws IOException {
if (isValidIndCursus(QualifNonDiplomante.class, true)) {
pojoQualif.getCursus().setComment(pojoQualif.getCursus().getComment());
if (actionEnum.getWhatAction().equals(ActionEnum.UPDATE_ACTION)) {
addOneCursus(getCurrentInd().getIndividu(), pojoQualif.getCursus());
getCurrentInd().getIndividu().getCursus().add(pojoQualif.getCursus());
}
pojoQualif.addCursus();
Collections.sort(pojoQualif.getCursusList(), new ComparatorString(IndCursus.class));
}
} | public void addqualifnodip() throws ioexception { if (isvalidindcursus(qualifnondiplomante.class, true)) { pojoqualif.getcursus().setcomment(pojoqualif.getcursus().getcomment()); if (actionenum.getwhataction().equals(actionenum.update_action)) { addonecursus(getcurrentind().getindividu(), pojoqualif.getcursus()); getcurrentind().getindividu().getcursus().add(pojoqualif.getcursus()); } pojoqualif.addcursus(); collections.sort(pojoqualif.getcursuslist(), new comparatorstring(indcursus.class)); } } | EsupPortail/esup-opi | [
0,
0,
1,
0
] |
25,270 | public void addCursusPro() throws IOException {
if (isValidIndCursus(CursusPro.class, true)) {
// on transforme le commentaire pour corriger les caractères spéciaux
indCursusPojo.getCursus().setComment(indCursusPojo.getCursus().getComment());
//TODO: Fix this !!
// org.esupportail.commons.utils.strings.StringUtils
// .htmlToText(indCursusPojo.getCursus().getComment()));
if (actionEnum.getWhatAction().equals(ActionEnum.UPDATE_ACTION)) {
//ajout en base
addOneCursus(getCurrentInd().getIndividu(), indCursusPojo.getCursus());
//Ajout dans l'individu courant
getCurrentInd().getIndividu().getCursus().add(indCursusPojo.getCursus());
}
indCursusPojo.addCursus();
Collections.sort(indCursusPojo.getCursusList(), new ComparatorString(IndCursus.class));
}
} | public void addCursusPro() throws IOException {
if (isValidIndCursus(CursusPro.class, true)) {
indCursusPojo.getCursus().setComment(indCursusPojo.getCursus().getComment());
if (actionEnum.getWhatAction().equals(ActionEnum.UPDATE_ACTION)) {
addOneCursus(getCurrentInd().getIndividu(), indCursusPojo.getCursus());
getCurrentInd().getIndividu().getCursus().add(indCursusPojo.getCursus());
}
indCursusPojo.addCursus();
Collections.sort(indCursusPojo.getCursusList(), new ComparatorString(IndCursus.class));
}
} | public void addcursuspro() throws ioexception { if (isvalidindcursus(cursuspro.class, true)) { indcursuspojo.getcursus().setcomment(indcursuspojo.getcursus().getcomment()); if (actionenum.getwhataction().equals(actionenum.update_action)) { addonecursus(getcurrentind().getindividu(), indcursuspojo.getcursus()); getcurrentind().getindividu().getcursus().add(indcursuspojo.getcursus()); } indcursuspojo.addcursus(); collections.sort(indcursuspojo.getcursuslist(), new comparatorstring(indcursus.class)); } } | EsupPortail/esup-opi | [
0,
0,
1,
0
] |
17,130 | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true;
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | @override public void updatetask() { double distancefromtarget = this.host.getdistancesq(host.getattacktarget().posx, host.getattacktarget().boundingbox.miny, host.getattacktarget().posz); boolean canseetarget = true; if (canseetarget) { ++this.targettimelost; } else { this.targettimelost = 0; } if (distancefromtarget <= (double) this.followdistance && this.targettimelost >= 20) { this.host.getnavigator().clearpathentity(); } else { this.host.getnavigator().trymovetoentityliving(host.getattacktarget(), this.entitymovespeed); } this.host.getlookhelper().setlookpositionwithentity(host.getattacktarget(), 30.0f, 30.0f); float f; if (--this.rangedattacktime == 0) { if (distancefromtarget > (double) this.followdistance || !canseetarget) { return; } f = mathhelper.sqrt_double(distancefromtarget) / this.attackrange; this.rangedattacktime = mathhelper.floor_float(f * (float) (this.maxrangedattacktime - this.minrangedattacktime) + (float) this.minrangedattacktime); } else if (this.rangedattacktime < 0) { f = mathhelper.sqrt_double(distancefromtarget) / this.attackrange; this.rangedattacktime = mathhelper.floor_float(f * (float) (this.maxrangedattacktime - this.minrangedattacktime) + (float) this.minrangedattacktime); } } | DarkGuardsman/Artillects | [
1,
0,
0,
0
] |
17,208 | protected void runOperations(String directoryPath, UseCase useCase) throws IOException {
log.info(System.lineSeparator() +
"================================================" + System.lineSeparator() +
" ____ ____________________ ____" + System.lineSeparator() +
" / \\ / __|__ __| _ \\ / \\" + System.lineSeparator() +
" / /\\ \\ \\ \\ | | | |/ / / /\\ \\" + System.lineSeparator() +
" / /__\\ \\__\\ \\ | | | |\\ \\ / /__\\ \\" + System.lineSeparator() +
" /__/ \\__\\____/ |__| |__| \\__\\__/ \\__\\" + System.lineSeparator() +
"================================================");
log.info("Starting Astra run for directory: " + directoryPath);
AtomicLong currentFileIndex = new AtomicLong();
AtomicLong currentPercentage = new AtomicLong();
log.info("Counting files (this may take a few seconds)");
Instant startTime = Instant.now();
List<Path> javaFilesInDirectory;
try (Stream<Path> walk = Files.walk(Paths.get(directoryPath))) {
javaFilesInDirectory = walk
.filter(f -> f.toFile().isFile())
.filter(f -> f.getFileName().toString().endsWith("java"))
.collect(Collectors.toList());
}
log.info(javaFilesInDirectory.size() + " .java files in directory to review");
log.info("Applying prefilters to files in directory");
Predicate<String> prefilteringPredicate = useCase.getPrefilteringPredicate();
List<Path> filteredJavaFiles = javaFilesInDirectory.stream()
.filter(f -> prefilteringPredicate.test(f.toString()))
.collect(Collectors.toList());
log.info(filteredJavaFiles.size() + " files remain after prefiltering");
final Set<? extends ASTOperation> operations = useCase.getOperations();
final String[] sources = useCase.getSources();
final String[] classPath = useCase.getClassPath();
for (Path f : filteredJavaFiles) {
// TODO AstUtils.getClassFilesForSource(f.toString()); - attempt to get only relevant classpaths for a given source file?
// TODO Naively we can multi-thread here (i.e. per file) but simple testing indicated that this slowed us down.
applyOperationsAndSave(new File(f.toString()), operations, sources, classPath);
long newPercentage = currentFileIndex.incrementAndGet() * 100 / filteredJavaFiles.size();
if (newPercentage != currentPercentage.get()) {
currentPercentage.set(newPercentage);
logProgress(currentFileIndex.get(), currentPercentage.get(), startTime, filteredJavaFiles.size());
}
}
log.info(getPrintableDuration(Duration.between(startTime, Instant.now())));
} | protected void runOperations(String directoryPath, UseCase useCase) throws IOException {
log.info(System.lineSeparator() +
"================================================" + System.lineSeparator() +
" ____ ____________________ ____" + System.lineSeparator() +
" / \\ / __|__ __| _ \\ / \\" + System.lineSeparator() +
" / /\\ \\ \\ \\ | | | |/ / / /\\ \\" + System.lineSeparator() +
" / /__\\ \\__\\ \\ | | | |\\ \\ / /__\\ \\" + System.lineSeparator() +
" /__/ \\__\\____/ |__| |__| \\__\\__/ \\__\\" + System.lineSeparator() +
"================================================");
log.info("Starting Astra run for directory: " + directoryPath);
AtomicLong currentFileIndex = new AtomicLong();
AtomicLong currentPercentage = new AtomicLong();
log.info("Counting files (this may take a few seconds)");
Instant startTime = Instant.now();
List<Path> javaFilesInDirectory;
try (Stream<Path> walk = Files.walk(Paths.get(directoryPath))) {
javaFilesInDirectory = walk
.filter(f -> f.toFile().isFile())
.filter(f -> f.getFileName().toString().endsWith("java"))
.collect(Collectors.toList());
}
log.info(javaFilesInDirectory.size() + " .java files in directory to review");
log.info("Applying prefilters to files in directory");
Predicate<String> prefilteringPredicate = useCase.getPrefilteringPredicate();
List<Path> filteredJavaFiles = javaFilesInDirectory.stream()
.filter(f -> prefilteringPredicate.test(f.toString()))
.collect(Collectors.toList());
log.info(filteredJavaFiles.size() + " files remain after prefiltering");
final Set<? extends ASTOperation> operations = useCase.getOperations();
final String[] sources = useCase.getSources();
final String[] classPath = useCase.getClassPath();
for (Path f : filteredJavaFiles) {
applyOperationsAndSave(new File(f.toString()), operations, sources, classPath);
long newPercentage = currentFileIndex.incrementAndGet() * 100 / filteredJavaFiles.size();
if (newPercentage != currentPercentage.get()) {
currentPercentage.set(newPercentage);
logProgress(currentFileIndex.get(), currentPercentage.get(), startTime, filteredJavaFiles.size());
}
}
log.info(getPrintableDuration(Duration.between(startTime, Instant.now())));
} | protected void runoperations(string directorypath, usecase usecase) throws ioexception { log.info(system.lineseparator() + "================================================" + system.lineseparator() + " ____ ____________________ ____" + system.lineseparator() + " / \\ / __|__ __| _ \\ / \\" + system.lineseparator() + " / /\\ \\ \\ \\ | | | |/ / / /\\ \\" + system.lineseparator() + " / /__\\ \\__\\ \\ | | | |\\ \\ / /__\\ \\" + system.lineseparator() + " /__/ \\__\\____/ |__| |__| \\__\\__/ \\__\\" + system.lineseparator() + "================================================"); log.info("starting astra run for directory: " + directorypath); atomiclong currentfileindex = new atomiclong(); atomiclong currentpercentage = new atomiclong(); log.info("counting files (this may take a few seconds)"); instant starttime = instant.now(); list<path> javafilesindirectory; try (stream<path> walk = files.walk(paths.get(directorypath))) { javafilesindirectory = walk .filter(f -> f.tofile().isfile()) .filter(f -> f.getfilename().tostring().endswith("java")) .collect(collectors.tolist()); } log.info(javafilesindirectory.size() + " .java files in directory to review"); log.info("applying prefilters to files in directory"); predicate<string> prefilteringpredicate = usecase.getprefilteringpredicate(); list<path> filteredjavafiles = javafilesindirectory.stream() .filter(f -> prefilteringpredicate.test(f.tostring())) .collect(collectors.tolist()); log.info(filteredjavafiles.size() + " files remain after prefiltering"); final set<? extends astoperation> operations = usecase.getoperations(); final string[] sources = usecase.getsources(); final string[] classpath = usecase.getclasspath(); for (path f : filteredjavafiles) { applyoperationsandsave(new file(f.tostring()), operations, sources, classpath); long newpercentage = currentfileindex.incrementandget() * 100 / filteredjavafiles.size(); if (newpercentage != currentpercentage.get()) { currentpercentage.set(newpercentage); logprogress(currentfileindex.get(), currentpercentage.get(), starttime, filteredjavafiles.size()); } } log.info(getprintableduration(duration.between(starttime, instant.now()))); } | Arraying/astra | [
1,
0,
0,
0
] |
25,405 | public static FragmentHostManager get(View view) {
try {
return Dependency.get(FragmentService.class).getFragmentHostManager(view);
} catch (ClassCastException e) {
// TODO: Some auto handling here?
throw e;
}
} | public static FragmentHostManager get(View view) {
try {
return Dependency.get(FragmentService.class).getFragmentHostManager(view);
} catch (ClassCastException e) {
throw e;
}
} | public static fragmenthostmanager get(view view) { try { return dependency.get(fragmentservice.class).getfragmenthostmanager(view); } catch (classcastexception e) { throw e; } } | FrankKwok/Oreo | [
0,
1,
0,
0
] |
25,463 | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' ');
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} | public static void gettext(node node, stringbuilder sb) { nodelist children = node.getchildnodes(); for (int i = 0; i < children.getlength(); i++) { node child = children.item(i); if (child.getnodetype() == node.text_node) { sb.append(' '); sb.append(child.getnodevalue().trim()); } else if (child.getnodetype() == node.element_node) { gettext(child, sb); } } } | GoVivaceInc/SpeechPlugin | [
0,
0,
1,
0
] |
9,271 | private static String encodeComponent(String s, Charset charset) {
// TODO: Optimize me.
try {
return URLEncoder.encode(s, charset.name()).replace("+", "%20");
} catch (UnsupportedEncodingException ignored) {
throw new UnsupportedCharsetException(charset.name());
}
} | private static String encodeComponent(String s, Charset charset) {
try {
return URLEncoder.encode(s, charset.name()).replace("+", "%20");
} catch (UnsupportedEncodingException ignored) {
throw new UnsupportedCharsetException(charset.name());
}
} | private static string encodecomponent(string s, charset charset) { try { return urlencoder.encode(s, charset.name()).replace("+", "%20"); } catch (unsupportedencodingexception ignored) { throw new unsupportedcharsetexception(charset.name()); } } | AIPaaS/sky-walking | [
1,
0,
0,
0
] |
25,701 | @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.queue_list, container, false);
//Instantiate Firebase objects
mDatabase = FirebaseDatabase.getInstance(); //instance of Firebase object(i.e. database root object)
mDepositQueueReference = mDatabase.getReference("depositQueue"); //reference to depositQueue child object in root object
//Instantiate other variables
queueListView = rootView.findViewById(R.id.list);
loadingIndicator = rootView.findViewById(R.id.loading_indicator);
final List<Payment> paymentsList = new ArrayList<Payment>();
postAdapter = new QueueAdapter(getActivity(), R.layout.queue_view, paymentsList);
queueListView.setAdapter(postAdapter);
/**Delete this post adapter when you finish*/
// postAdapter.add(new Payment("James Blunt", "0149603509", "4500", "WAEC", "07033513241", "igwenus619@gmail.com"));
//Add ChildEventListener, so that changes made in the database are reflected
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
loadingIndicator.setVisibility(View.GONE);
Payment payment = dataSnapshot.getValue(Payment.class);
/**Uncomment this when you've finished*/
postAdapter.add(payment); //here, you could use queueListView.add() too
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "postComments:onCancelled", databaseError.toException());
}
};
mDepositQueueReference.addChildEventListener(mChildEventListener);
queueListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Payment payment = paymentsList.get(position);
Intent intent = new Intent(getActivity(), ConfirmDetailsActivity.class);
intent.putExtra("pushID", payment.getPushID());
intent.putExtra("accountName", payment.getAccountName());
intent.putExtra("accountNumber", payment.getAccountNumber());
intent.putExtra("depositAmount", payment.getDepositAmount());
intent.putExtra("depositorName", payment.getDepositorName());
intent.putExtra("depositorPhoneNumber", payment.getDepositorPhoneNumber());
intent.putExtra("depositorEmail", payment.getDepositorEmail());
Log.e(TAG, "Phone Number" + payment.depositorPhoneNumber);
startActivity(intent);
}
});
return rootView;
} | @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.queue_list, container, false);
mDatabase = FirebaseDatabase.getInstance();
mDepositQueueReference = mDatabase.getReference("depositQueue");
queueListView = rootView.findViewById(R.id.list);
loadingIndicator = rootView.findViewById(R.id.loading_indicator);
final List<Payment> paymentsList = new ArrayList<Payment>();
postAdapter = new QueueAdapter(getActivity(), R.layout.queue_view, paymentsList);
queueListView.setAdapter(postAdapter);
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
loadingIndicator.setVisibility(View.GONE);
Payment payment = dataSnapshot.getValue(Payment.class);
postAdapter.add(payment);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "postComments:onCancelled", databaseError.toException());
}
};
mDepositQueueReference.addChildEventListener(mChildEventListener);
queueListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Payment payment = paymentsList.get(position);
Intent intent = new Intent(getActivity(), ConfirmDetailsActivity.class);
intent.putExtra("pushID", payment.getPushID());
intent.putExtra("accountName", payment.getAccountName());
intent.putExtra("accountNumber", payment.getAccountNumber());
intent.putExtra("depositAmount", payment.getDepositAmount());
intent.putExtra("depositorName", payment.getDepositorName());
intent.putExtra("depositorPhoneNumber", payment.getDepositorPhoneNumber());
intent.putExtra("depositorEmail", payment.getDepositorEmail());
Log.e(TAG, "Phone Number" + payment.depositorPhoneNumber);
startActivity(intent);
}
});
return rootView;
} | @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.queue_list, container, false); mdatabase = firebasedatabase.getinstance(); mdepositqueuereference = mdatabase.getreference("depositqueue"); queuelistview = rootview.findviewbyid(r.id.list); loadingindicator = rootview.findviewbyid(r.id.loading_indicator); final list<payment> paymentslist = new arraylist<payment>(); postadapter = new queueadapter(getactivity(), r.layout.queue_view, paymentslist); queuelistview.setadapter(postadapter); mchildeventlistener = new childeventlistener() { @override public void onchildadded(datasnapshot datasnapshot, string s) { if (datasnapshot.exists()) { loadingindicator.setvisibility(view.gone); payment payment = datasnapshot.getvalue(payment.class); postadapter.add(payment); } } @override public void onchildchanged(datasnapshot datasnapshot, string s) { } @override public void onchildremoved(datasnapshot datasnapshot) { } @override public void onchildmoved(datasnapshot datasnapshot, string s) { } @override public void oncancelled(databaseerror databaseerror) { log.e(tag, "postcomments:oncancelled", databaseerror.toexception()); } }; mdepositqueuereference.addchildeventlistener(mchildeventlistener); queuelistview.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { payment payment = paymentslist.get(position); intent intent = new intent(getactivity(), confirmdetailsactivity.class); intent.putextra("pushid", payment.getpushid()); intent.putextra("accountname", payment.getaccountname()); intent.putextra("accountnumber", payment.getaccountnumber()); intent.putextra("depositamount", payment.getdepositamount()); intent.putextra("depositorname", payment.getdepositorname()); intent.putextra("depositorphonenumber", payment.getdepositorphonenumber()); intent.putextra("depositoremail", payment.getdepositoremail()); log.e(tag, "phone number" + payment.depositorphonenumber); startactivity(intent); } }); return rootview; } | HemlockBane/cashier-demo | [
0,
0,
0,
0
] |
25,731 | public static void symbols(PrintWriter out,
boolean emit_non_terms, boolean sym_interface)
{
terminal term;
non_terminal nt;
String class_or_interface = (sym_interface) ? "interface" : "class";
long start_time = System.currentTimeMillis();
/* top of file */
out.println();
out.println("//----------------------------------------------------");
out.println("// The following code was generated by " + version.title_str);
out.println("//----------------------------------------------------");
out.println();
emit_package(out);
/* class header */
out.println("/** CUP generated " + class_or_interface +
" containing symbol constants. */");
out.println("public " + class_or_interface + " " +
symbol_const_class_name + " {");
out.println(" /* terminals */");
/* walk over the terminals *//* later might sort these */
for (Enumeration e = terminal.all(); e.hasMoreElements();)
{
term = (terminal) e.nextElement();
/* output a constant decl for the terminal */
out.println(" public static final int " + term.name() + " = " +
term.index() + ";");
}
/* Emit names of terminals */
out.println(" public static final String[] terminalNames = new String[] {");
for (int i = 0; i < terminal.number(); i++) {
out.print(" \"");
out.print(terminal.find(i).name());
out.print("\"");
if (i < terminal.number() - 1) {
out.print(",");
}
out.println();
}
out.println(" };");
/* do the non terminals if they want them (parser doesn't need them) */
if (emit_non_terms)
{
out.println();
out.println(" /* non terminals */");
/* walk over the non terminals *//* later might sort these */
for (Enumeration e = non_terminal.all(); e.hasMoreElements();)
{
nt = (non_terminal) e.nextElement();
// ****
// TUM Comment: here we could add a typesafe enumeration
// ****
/* output a constant decl for the terminal */
out.println(" static final int " + nt.name() + " = " +
nt.index() + ";");
}
}
/* end of class */
out.println("}");
out.println();
symbols_time = System.currentTimeMillis() - start_time;
} | public static void symbols(PrintWriter out,
boolean emit_non_terms, boolean sym_interface)
{
terminal term;
non_terminal nt;
String class_or_interface = (sym_interface) ? "interface" : "class";
long start_time = System.currentTimeMillis();
out.println();
out.println("//----------------------------------------------------");
out.println("// The following code was generated by " + version.title_str);
out.println("//----------------------------------------------------");
out.println();
emit_package(out);
out.println("/** CUP generated " + class_or_interface +
" containing symbol constants. */");
out.println("public " + class_or_interface + " " +
symbol_const_class_name + " {");
out.println(" /* terminals */");
for (Enumeration e = terminal.all(); e.hasMoreElements();)
{
term = (terminal) e.nextElement();
out.println(" public static final int " + term.name() + " = " +
term.index() + ";");
}
out.println(" public static final String[] terminalNames = new String[] {");
for (int i = 0; i < terminal.number(); i++) {
out.print(" \"");
out.print(terminal.find(i).name());
out.print("\"");
if (i < terminal.number() - 1) {
out.print(",");
}
out.println();
}
out.println(" };");
if (emit_non_terms)
{
out.println();
out.println(" /* non terminals */");
for (Enumeration e = non_terminal.all(); e.hasMoreElements();)
{
nt = (non_terminal) e.nextElement();
out.println(" static final int " + nt.name() + " = " +
nt.index() + ";");
}
}
out.println("}");
out.println();
symbols_time = System.currentTimeMillis() - start_time;
} | public static void symbols(printwriter out, boolean emit_non_terms, boolean sym_interface) { terminal term; non_terminal nt; string class_or_interface = (sym_interface) ? "interface" : "class"; long start_time = system.currenttimemillis(); out.println(); out.println("//----------------------------------------------------"); out.println("// the following code was generated by " + version.title_str); out.println("//----------------------------------------------------"); out.println(); emit_package(out); out.println("/** cup generated " + class_or_interface + " containing symbol constants. */"); out.println("public " + class_or_interface + " " + symbol_const_class_name + " {"); out.println(" /* terminals */"); for (enumeration e = terminal.all(); e.hasmoreelements();) { term = (terminal) e.nextelement(); out.println(" public static final int " + term.name() + " = " + term.index() + ";"); } out.println(" public static final string[] terminalnames = new string[] {"); for (int i = 0; i < terminal.number(); i++) { out.print(" \""); out.print(terminal.find(i).name()); out.print("\""); if (i < terminal.number() - 1) { out.print(","); } out.println(); } out.println(" };"); if (emit_non_terms) { out.println(); out.println(" /* non terminals */"); for (enumeration e = non_terminal.all(); e.hasmoreelements();) { nt = (non_terminal) e.nextelement(); out.println(" static final int " + nt.name() + " = " + nt.index() + ";"); } } out.println("}"); out.println(); symbols_time = system.currenttimemillis() - start_time; } | AsaiKen/phpscan | [
0,
0,
0,
0
] |
9,378 | private void transferData(RawPacket[] pkts)
{
for (int i = 0; i < pkts.length; i++)
{
RawPacket pkt = pkts[i];
pkts[i] = null;
if (pkt != null)
{
if (pkt.isInvalid())
{
/*
* Return pkt to the pool because it is invalid and,
* consequently, will not be made available to reading.
*/
poolRawPacket(pkt);
}
else
{
RawPacket oldPkt;
synchronized (pktSyncRoot)
{
oldPkt = this.pkt;
this.pkt = pkt;
}
if (oldPkt != null)
{
/*
* Return oldPkt to the pool because it was made
* available to reading and it was not read.
*/
poolRawPacket(oldPkt);
}
if (transferHandler != null && !closed)
{
try
{
transferHandler.transferData(this);
}
catch (Throwable t)
{
// XXX We cannot allow transferHandler to kill us.
if (t instanceof InterruptedException)
{
Thread.currentThread().interrupt();
}
else if (t instanceof ThreadDeath)
{
throw (ThreadDeath) t;
}
else
{
logger.warn(
"An RTP packet may have not been fully"
+ " handled.",
t);
}
}
}
}
}
}
} | private void transferData(RawPacket[] pkts)
{
for (int i = 0; i < pkts.length; i++)
{
RawPacket pkt = pkts[i];
pkts[i] = null;
if (pkt != null)
{
if (pkt.isInvalid())
{
poolRawPacket(pkt);
}
else
{
RawPacket oldPkt;
synchronized (pktSyncRoot)
{
oldPkt = this.pkt;
this.pkt = pkt;
}
if (oldPkt != null)
{
poolRawPacket(oldPkt);
}
if (transferHandler != null && !closed)
{
try
{
transferHandler.transferData(this);
}
catch (Throwable t)
{
if (t instanceof InterruptedException)
{
Thread.currentThread().interrupt();
}
else if (t instanceof ThreadDeath)
{
throw (ThreadDeath) t;
}
else
{
logger.warn(
"An RTP packet may have not been fully"
+ " handled.",
t);
}
}
}
}
}
}
} | private void transferdata(rawpacket[] pkts) { for (int i = 0; i < pkts.length; i++) { rawpacket pkt = pkts[i]; pkts[i] = null; if (pkt != null) { if (pkt.isinvalid()) { poolrawpacket(pkt); } else { rawpacket oldpkt; synchronized (pktsyncroot) { oldpkt = this.pkt; this.pkt = pkt; } if (oldpkt != null) { poolrawpacket(oldpkt); } if (transferhandler != null && !closed) { try { transferhandler.transferdata(this); } catch (throwable t) { if (t instanceof interruptedexception) { thread.currentthread().interrupt(); } else if (t instanceof threaddeath) { throw (threaddeath) t; } else { logger.warn( "an rtp packet may have not been fully" + " handled.", t); } } } } } } } | GNUDimarik/libjitsi | [
1,
0,
0,
0
] |
34,098 | @Override
public void runOpMode() {
telemetry.addData("Status", "Initialized");
telemetry.update();
left_mtr = hardwareMap.dcMotor.get("left_mtr");
right_mtr = hardwareMap.dcMotor.get("right_mtr");
front_left_mtr = hardwareMap.dcMotor.get("front_left_mtr");
front_right_mtr = hardwareMap.dcMotor.get("front_right_mtr");
Shooter = hardwareMap.dcMotor.get("Shooter");
Conveyor = hardwareMap.dcMotor.get("Conveyor");
clow_moter = hardwareMap.dcMotor.get("clow moter");
Claw = hardwareMap.servo.get("Claw");
touchfront = hardwareMap.touchSensor.get("touchfront");
touch2 = hardwareMap.touchSensor.get("touch2");
// values is a reference to the hsvValues array.
float[] hsvValues = new float[3];
final float values[] = hsvValues;
// bPrevState and bCurrState keep track of the previous and current state of the button
boolean bPrevState = false;
boolean bCurrState = false;
String mode="";
Claw.setPosition(0);
right_mtr.setDirection(DcMotorSimple.Direction.REVERSE);
right_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
left_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
front_right_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
front_left_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
clow_moter.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
right_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
left_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
front_right_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
front_left_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
initVuforia();
initTfod();
/**
* Activate TensorFlow Object Detection before we wait for the start command.
* Do it here so that the Camera Stream window will have the TensorFlow annotations visible.
**/
if (tfod != null) {
tfod.activate();
// The TensorFlow software will scale the input images from the camera to a lower resolution.
// This can result in lower detection accuracy at longer distances (> 55cm or 22").
// If your target is at distance greater than 50 cm (20") you can adjust the magnification value
// to artificially zoom in to the center of image. For best results, the "aspectRatio" argument
// should be set to the value of the images used to create the TensorFlow Object Detection model
// (typically 1.78 or 16/9).
// Uncomment the following line if you want to adjust the magnification and/or the aspect ratio of the input images.
//tfod.setZoom(2.5, 1.78);
}
/** Wait for the game to begin */
telemetry.addData(">", "Press Play to start op mode");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
halt();
sleep(1000);
turnRight(0.5);
haltSequence(450);
goForward(.5);
haltSequence(150);
turnLeft(.5);
haltSequence(450);
goForward(0.4);
sleep(450);
halt();
sleep(1000);
telemetry.addData("Status", "Started");
telemetry.update();
if (tfod != null) {
// getUpdatedRecognitions() will return null if no new information is available since
// the last time that call was made.
List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions();
if (updatedRecognitions != null) {
telemetry.addData("# Object Detected", updatedRecognitions.size());
if (updatedRecognitions.size() == 0) {
mode = "A";
}
// step through the list of recognitions and display boundary info.
int i = 0;
for (Recognition recognition : updatedRecognitions) {
telemetry.addData(String.format("label (%d)", i), recognition.getLabel());
if (recognition.getLabel() =="Quad"){
mode = "C";
} else {
mode = "B";
}
telemetry.addData(String.format(" left,top (%d)", i), "%.03f , %.03f",
recognition.getLeft(), recognition.getTop());
telemetry.addData(String.format(" right,bottom (%d)", i), "%.03f , %.03f",
recognition.getRight(), recognition.getBottom());
}
//telemetry.addData(String.format("Mode (%s)", mode), "");
telemetry.update();
sleep(2000);
}
}
}
// go somewhere based on mode
if (mode == "A") {
doModeA();
} else if (mode == "B") {
doModeB();
} else if (mode == "C") {
doModeC();
} else {
// not sure what to do here
}
if (tfod != null) {
tfod.shutdown();
}
} | @Override
public void runOpMode() {
telemetry.addData("Status", "Initialized");
telemetry.update();
left_mtr = hardwareMap.dcMotor.get("left_mtr");
right_mtr = hardwareMap.dcMotor.get("right_mtr");
front_left_mtr = hardwareMap.dcMotor.get("front_left_mtr");
front_right_mtr = hardwareMap.dcMotor.get("front_right_mtr");
Shooter = hardwareMap.dcMotor.get("Shooter");
Conveyor = hardwareMap.dcMotor.get("Conveyor");
clow_moter = hardwareMap.dcMotor.get("clow moter");
Claw = hardwareMap.servo.get("Claw");
touchfront = hardwareMap.touchSensor.get("touchfront");
touch2 = hardwareMap.touchSensor.get("touch2");
float[] hsvValues = new float[3];
final float values[] = hsvValues;
boolean bPrevState = false;
boolean bCurrState = false;
String mode="";
Claw.setPosition(0);
right_mtr.setDirection(DcMotorSimple.Direction.REVERSE);
right_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
left_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
front_right_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
front_left_mtr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
clow_moter.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
right_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
left_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
front_right_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
front_left_mtr.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
initVuforia();
initTfod();
if (tfod != null) {
tfod.activate();
}
telemetry.addData(">", "Press Play to start op mode");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
halt();
sleep(1000);
turnRight(0.5);
haltSequence(450);
goForward(.5);
haltSequence(150);
turnLeft(.5);
haltSequence(450);
goForward(0.4);
sleep(450);
halt();
sleep(1000);
telemetry.addData("Status", "Started");
telemetry.update();
if (tfod != null) {
List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions();
if (updatedRecognitions != null) {
telemetry.addData("# Object Detected", updatedRecognitions.size());
if (updatedRecognitions.size() == 0) {
mode = "A";
}
int i = 0;
for (Recognition recognition : updatedRecognitions) {
telemetry.addData(String.format("label (%d)", i), recognition.getLabel());
if (recognition.getLabel() =="Quad"){
mode = "C";
} else {
mode = "B";
}
telemetry.addData(String.format(" left,top (%d)", i), "%.03f , %.03f",
recognition.getLeft(), recognition.getTop());
telemetry.addData(String.format(" right,bottom (%d)", i), "%.03f , %.03f",
recognition.getRight(), recognition.getBottom());
}
telemetry.update();
sleep(2000);
}
}
}
if (mode == "A") {
doModeA();
} else if (mode == "B") {
doModeB();
} else if (mode == "C") {
doModeC();
} else {
}
if (tfod != null) {
tfod.shutdown();
}
} | @override public void runopmode() { telemetry.adddata("status", "initialized"); telemetry.update(); left_mtr = hardwaremap.dcmotor.get("left_mtr"); right_mtr = hardwaremap.dcmotor.get("right_mtr"); front_left_mtr = hardwaremap.dcmotor.get("front_left_mtr"); front_right_mtr = hardwaremap.dcmotor.get("front_right_mtr"); shooter = hardwaremap.dcmotor.get("shooter"); conveyor = hardwaremap.dcmotor.get("conveyor"); clow_moter = hardwaremap.dcmotor.get("clow moter"); claw = hardwaremap.servo.get("claw"); touchfront = hardwaremap.touchsensor.get("touchfront"); touch2 = hardwaremap.touchsensor.get("touch2"); float[] hsvvalues = new float[3]; final float values[] = hsvvalues; boolean bprevstate = false; boolean bcurrstate = false; string mode=""; claw.setposition(0); right_mtr.setdirection(dcmotorsimple.direction.reverse); right_mtr.setzeropowerbehavior(dcmotor.zeropowerbehavior.brake); left_mtr.setzeropowerbehavior(dcmotor.zeropowerbehavior.brake); front_right_mtr.setzeropowerbehavior(dcmotor.zeropowerbehavior.brake); front_left_mtr.setzeropowerbehavior(dcmotor.zeropowerbehavior.brake); clow_moter.setzeropowerbehavior(dcmotor.zeropowerbehavior.brake); right_mtr.setmode(dcmotor.runmode.run_without_encoder); left_mtr.setmode(dcmotor.runmode.run_without_encoder); front_right_mtr.setmode(dcmotor.runmode.run_without_encoder); front_left_mtr.setmode(dcmotor.runmode.run_without_encoder); initvuforia(); inittfod(); if (tfod != null) { tfod.activate(); } telemetry.adddata(">", "press play to start op mode"); telemetry.update(); waitforstart(); if (opmodeisactive()) { halt(); sleep(1000); turnright(0.5); haltsequence(450); goforward(.5); haltsequence(150); turnleft(.5); haltsequence(450); goforward(0.4); sleep(450); halt(); sleep(1000); telemetry.adddata("status", "started"); telemetry.update(); if (tfod != null) { list<recognition> updatedrecognitions = tfod.getupdatedrecognitions(); if (updatedrecognitions != null) { telemetry.adddata("# object detected", updatedrecognitions.size()); if (updatedrecognitions.size() == 0) { mode = "a"; } int i = 0; for (recognition recognition : updatedrecognitions) { telemetry.adddata(string.format("label (%d)", i), recognition.getlabel()); if (recognition.getlabel() =="quad"){ mode = "c"; } else { mode = "b"; } telemetry.adddata(string.format(" left,top (%d)", i), "%.03f , %.03f", recognition.getleft(), recognition.gettop()); telemetry.adddata(string.format(" right,bottom (%d)", i), "%.03f , %.03f", recognition.getright(), recognition.getbottom()); } telemetry.update(); sleep(2000); } } } if (mode == "a") { domodea(); } else if (mode == "b") { domodeb(); } else if (mode == "c") { domodec(); } else { } if (tfod != null) { tfod.shutdown(); } } | FTC16694/FtcRobotController | [
1,
1,
0,
0
] |
9,539 | private void filter() {
String text = DrugMappingStringUtilities.safeToUpperCase(searchField.getText());
if (text.length() == 0) {
rowSorter.setRowFilter(null);
}
else {
//TODO escape special characters
rowSorter.setRowFilter(RowFilter.regexFilter(text));
}
if (rowSorter.getViewRowCount() == 0) {
ingredientMappingLogPanel.removeAll();
ingredientMappingResultPanel.removeAll();
mainFrame.getFrame().repaint();
}
if (ingredientsTable.getRowCount() > 0) {
ListSelectionModel selectionModel = ingredientsTable.getSelectionModel();
selectionModel.setSelectionInterval(0, 0);
}
} | private void filter() {
String text = DrugMappingStringUtilities.safeToUpperCase(searchField.getText());
if (text.length() == 0) {
rowSorter.setRowFilter(null);
}
else {
rowSorter.setRowFilter(RowFilter.regexFilter(text));
}
if (rowSorter.getViewRowCount() == 0) {
ingredientMappingLogPanel.removeAll();
ingredientMappingResultPanel.removeAll();
mainFrame.getFrame().repaint();
}
if (ingredientsTable.getRowCount() > 0) {
ListSelectionModel selectionModel = ingredientsTable.getSelectionModel();
selectionModel.setSelectionInterval(0, 0);
}
} | private void filter() { string text = drugmappingstringutilities.safetouppercase(searchfield.gettext()); if (text.length() == 0) { rowsorter.setrowfilter(null); } else { rowsorter.setrowfilter(rowfilter.regexfilter(text)); } if (rowsorter.getviewrowcount() == 0) { ingredientmappinglogpanel.removeall(); ingredientmappingresultpanel.removeall(); mainframe.getframe().repaint(); } if (ingredientstable.getrowcount() > 0) { listselectionmodel selectionmodel = ingredientstable.getselectionmodel(); selectionmodel.setselectioninterval(0, 0); } } | EHDEN/DrugMapping | [
0,
1,
0,
0
] |
9,553 | public void move(double inches, double power) {
robotInstance.drivetrain.povDrive(power, 0);
} | public void move(double inches, double power) {
robotInstance.drivetrain.povDrive(power, 0);
} | public void move(double inches, double power) { robotinstance.drivetrain.povdrive(power, 0); } | Centennial-FTC-Robotics/Omnitech2021-22 | [
0,
1,
0,
0
] |
17,777 | public static ButtonType showAlert(AlertType type, String title, String text, boolean onTop) {
// NOTE: alert must be (re-)created everytime, otherwise the following HACK doesn't work!
Alert alert = new Alert(AlertType.NONE);
alert.setAlertType(type);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(text);
// HACK: since it is not possible to set the owner of an javafx alert to
// a swing frame, we use the following approach to set the modality!
((Stage) alert.getDialogPane().getScene().getWindow()).setAlwaysOnTop(onTop);
// if no button was pressed, the dialog got canceled (ESC, close)
return alert.showAndWait().orElse(ButtonType.CANCEL);
} | public static ButtonType showAlert(AlertType type, String title, String text, boolean onTop) {
Alert alert = new Alert(AlertType.NONE);
alert.setAlertType(type);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(text);
((Stage) alert.getDialogPane().getScene().getWindow()).setAlwaysOnTop(onTop);
return alert.showAndWait().orElse(ButtonType.CANCEL);
} | public static buttontype showalert(alerttype type, string title, string text, boolean ontop) { alert alert = new alert(alerttype.none); alert.setalerttype(type); alert.settitle(title); alert.setheadertext(null); alert.setcontenttext(text); ((stage) alert.getdialogpane().getscene().getwindow()).setalwaysontop(ontop); return alert.showandwait().orelse(buttontype.cancel); } | BerlinUnited/NaoTH | [
1,
0,
0,
0
] |
25,987 | @Override
public QueryProfileVariant clone() {
if (frozen) return this;
try {
QueryProfileVariant clone = (QueryProfileVariant)super.clone();
if (this.inherited != null)
clone.inherited = new ArrayList<>(this.inherited); // TODO: Deep clone is more correct, but probably does not matter in practice
clone.values = CopyOnWriteContent.deepClone(this.values);
return clone;
}
catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
} | @Override
public QueryProfileVariant clone() {
if (frozen) return this;
try {
QueryProfileVariant clone = (QueryProfileVariant)super.clone();
if (this.inherited != null)
clone.inherited = new ArrayList<>(this.inherited);
clone.values = CopyOnWriteContent.deepClone(this.values);
return clone;
}
catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
} | @override public queryprofilevariant clone() { if (frozen) return this; try { queryprofilevariant clone = (queryprofilevariant)super.clone(); if (this.inherited != null) clone.inherited = new arraylist<>(this.inherited); clone.values = copyonwritecontent.deepclone(this.values); return clone; } catch (clonenotsupportedexception e) { throw new runtimeexception(e); } } | Anlon-Burke/vespa | [
1,
0,
0,
0
] |
9,614 | void loadUi(EmpSeries series) {
this.episodesCarouselAdapter = new EpisodesCarouselAdapter(this, series);
RecyclerView episodesCarousel = (RecyclerView) findViewById(R.id.carousel_series_items);
episodesCarousel.setAdapter(this.episodesCarouselAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
episodesCarousel.setLayoutManager(layoutManager);
if(series.episodes == null) {
// TODO: get programs for a specific series && seasonID
}
} | void loadUi(EmpSeries series) {
this.episodesCarouselAdapter = new EpisodesCarouselAdapter(this, series);
RecyclerView episodesCarousel = (RecyclerView) findViewById(R.id.carousel_series_items);
episodesCarousel.setAdapter(this.episodesCarouselAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
episodesCarousel.setLayoutManager(layoutManager);
if(series.episodes == null) {
}
} | void loadui(empseries series) { this.episodescarouseladapter = new episodescarouseladapter(this, series); recyclerview episodescarousel = (recyclerview) findviewbyid(r.id.carousel_series_items); episodescarousel.setadapter(this.episodescarouseladapter); linearlayoutmanager layoutmanager = new linearlayoutmanager(this, linearlayoutmanager.horizontal, false); episodescarousel.setlayoutmanager(layoutmanager); if(series.episodes == null) { } } | EricssonBroadcastServices/AndroidClientReferenceApp | [
0,
1,
0,
0
] |
17,865 | @Test(expected = AmazonClientException.class)
public void canBeConfiguredToOnlyRefreshCredentialsAfterFirstCallToGetCredentials() throws InterruptedException {
mockServer.setResponseFileName("sessionResponseExpired");
mockServer.setAvailableSecurityCredentials("test-credentials");
InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.createAsyncRefreshingProvider(false);
Thread.sleep(1000);
//Hacky assert but we know that this mockServer will create an exception that will be logged, if there's no log entry
//then there's no exception, which means that getCredentials didn't get called on the fetcher
assertThat(loggedEvents(), is(empty()));
credentialsProvider.getCredentials();
} | @Test(expected = AmazonClientException.class)
public void canBeConfiguredToOnlyRefreshCredentialsAfterFirstCallToGetCredentials() throws InterruptedException {
mockServer.setResponseFileName("sessionResponseExpired");
mockServer.setAvailableSecurityCredentials("test-credentials");
InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.createAsyncRefreshingProvider(false);
Thread.sleep(1000);
assertThat(loggedEvents(), is(empty()));
credentialsProvider.getCredentials();
} | @test(expected = amazonclientexception.class) public void canbeconfiguredtoonlyrefreshcredentialsafterfirstcalltogetcredentials() throws interruptedexception { mockserver.setresponsefilename("sessionresponseexpired"); mockserver.setavailablesecuritycredentials("test-credentials"); instanceprofilecredentialsprovider credentialsprovider = instanceprofilecredentialsprovider.createasyncrefreshingprovider(false); thread.sleep(1000); assertthat(loggedevents(), is(empty())); credentialsprovider.getcredentials(); } | IBM/ibm-cos-sdk-java | [
1,
0,
0,
0
] |
17,941 | @Override
public ExportResult<CalendarContainerResource> export(TokenAuthData authData) {
Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData);
List<CalendarModel> calendarModels = new ArrayList<>();
try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) {
ResponseBody body = graphResponse.body();
if (body == null) {
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null");
}
String graphBody = new String(body.bytes());
Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody);
// TODO String nextLink = (String) graphMap.get(ODATA_NEXT);
// TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink));
@SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value");
if (rawCalendars == null) {
return new ExportResult<>(ExportResult.ResultType.END);
}
for (Map<String, Object> rawCalendar : rawCalendars) {
TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar);
if (result.hasProblems()) {
// discard
// FIXME log problem
continue;
}
calendarModels.add(result.getTransformed());
}
} catch (IOException e) {
e.printStackTrace(); // FIXME log error
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage());
}
List<CalendarEventModel> calendarEventModels = new ArrayList<>();
for (CalendarModel calendarModel : calendarModels) {
String id = calendarModel.getId();
Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData);
try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) {
ResponseBody body = graphResponse.body();
if (body == null) {
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null");
}
String graphBody = new String(body.bytes());
Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody);
// TODO String nextLink = (String) graphMap.get(ODATA_NEXT);
// TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink));
@SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value");
if (rawEvents == null) {
return new ExportResult<>(ExportResult.ResultType.END);
}
for (Map<String, Object> rawEvent : rawEvents) {
Map<String, String> properties = new HashMap<>();
properties.put(CALENDAR_ID, id);
TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties);
if (result.hasProblems()) {
// discard
// FIXME log problem
continue;
}
calendarEventModels.add(result.getTransformed());
}
} catch (IOException e) {
e.printStackTrace(); // FIXME log error
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage());
}
}
CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels);
return new ExportResult<>(ExportResult.ResultType.END, resource, null);
} | @Override
public ExportResult<CalendarContainerResource> export(TokenAuthData authData) {
Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData);
List<CalendarModel> calendarModels = new ArrayList<>();
try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) {
ResponseBody body = graphResponse.body();
if (body == null) {
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null");
}
String graphBody = new String(body.bytes());
Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody);
@SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value");
if (rawCalendars == null) {
return new ExportResult<>(ExportResult.ResultType.END);
}
for (Map<String, Object> rawCalendar : rawCalendars) {
TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar);
if (result.hasProblems()) {
continue;
}
calendarModels.add(result.getTransformed());
}
} catch (IOException e) {
e.printStackTrace();
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage());
}
List<CalendarEventModel> calendarEventModels = new ArrayList<>();
for (CalendarModel calendarModel : calendarModels) {
String id = calendarModel.getId();
Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData);
try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) {
ResponseBody body = graphResponse.body();
if (body == null) {
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null");
}
String graphBody = new String(body.bytes());
Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody);
@SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value");
if (rawEvents == null) {
return new ExportResult<>(ExportResult.ResultType.END);
}
for (Map<String, Object> rawEvent : rawEvents) {
Map<String, String> properties = new HashMap<>();
properties.put(CALENDAR_ID, id);
TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties);
if (result.hasProblems()) {
continue;
}
calendarEventModels.add(result.getTransformed());
}
} catch (IOException e) {
e.printStackTrace();
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage());
}
}
CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels);
return new ExportResult<>(ExportResult.ResultType.END, resource, null);
} | @override public exportresult<calendarcontainerresource> export(tokenauthdata authdata) { request.builder calendarsbuilder = getbuilder(baseurl + calendars_url, authdata); list<calendarmodel> calendarmodels = new arraylist<>(); try (response graphresponse = client.newcall(calendarsbuilder.build()).execute()) { responsebody body = graphresponse.body(); if (body == null) { return new exportresult<>(exportresult.resulttype.error, "error retrieving contacts: response body was null"); } string graphbody = new string(body.bytes()); map graphmap = objectmapper.reader().fortype(map.class).readvalue(graphbody); @suppresswarnings("unchecked") list<map<string, object>> rawcalendars = (list<map<string, object>>) graphmap.get("value"); if (rawcalendars == null) { return new exportresult<>(exportresult.resulttype.end); } for (map<string, object> rawcalendar : rawcalendars) { transformresult<calendarmodel> result = transformerservice.transform(calendarmodel.class, rawcalendar); if (result.hasproblems()) { continue; } calendarmodels.add(result.gettransformed()); } } catch (ioexception e) { e.printstacktrace(); return new exportresult<>(exportresult.resulttype.error, "error retrieving calendar: " + e.getmessage()); } list<calendareventmodel> calendareventmodels = new arraylist<>(); for (calendarmodel calendarmodel : calendarmodels) { string id = calendarmodel.getid(); request.builder eventsbuilder = getbuilder(calculateeventsurl(id), authdata); try (response graphresponse = client.newcall(eventsbuilder.build()).execute()) { responsebody body = graphresponse.body(); if (body == null) { return new exportresult<>(exportresult.resulttype.error, "error retrieving calendar: response body was null"); } string graphbody = new string(body.bytes()); map graphmap = objectmapper.reader().fortype(map.class).readvalue(graphbody); @suppresswarnings("unchecked") list<map<string, object>> rawevents = (list<map<string, object>>) graphmap.get("value"); if (rawevents == null) { return new exportresult<>(exportresult.resulttype.end); } for (map<string, object> rawevent : rawevents) { map<string, string> properties = new hashmap<>(); properties.put(calendar_id, id); transformresult<calendareventmodel> result = transformerservice.transform(calendareventmodel.class, rawevent, properties); if (result.hasproblems()) { continue; } calendareventmodels.add(result.gettransformed()); } } catch (ioexception e) { e.printstacktrace(); return new exportresult<>(exportresult.resulttype.error, "error retrieving contacts: " + e.getmessage()); } } calendarcontainerresource resource = new calendarcontainerresource(calendarmodels, calendareventmodels); return new exportresult<>(exportresult.resulttype.end, resource, null); } | 29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/data-transfer-project | [
0,
0,
1,
0
] |
9,775 | public static void main(String[] args) {
File dir = new File(".");
Arrays.stream(dir.listFiles()).forEach(file -> {
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
// Ouch, my fingers hurt! All this typing!
});
// TODO use Unchecked.consumer from JOOL library
// SOLUTION(
Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> {
System.out.println(file.getCanonicalPath());
}));
// SOLUTION)
} | public static void main(String[] args) {
File dir = new File(".");
Arrays.stream(dir.listFiles()).forEach(file -> {
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
});
Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> {
System.out.println(file.getCanonicalPath());
}));
} | public static void main(string[] args) { file dir = new file("."); arrays.stream(dir.listfiles()).foreach(file -> { try { system.out.println(file.getcanonicalpath()); } catch (ioexception e) { throw new runtimeexception(e); } }); arrays.stream(dir.listfiles()).foreach(unchecked.consumer(file -> { system.out.println(file.getcanonicalpath()); })); } | AdrianaDinca/training | [
0,
0,
0,
0
] |
1,657 | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | public static string replaceallifnotinsidetag(string origstr, string findthis, string replacewith) { if (origstr == null) { return null; } if (findthis == null) { return origstr; } if (replacewith == null) { replacewith = ""; } stringbuilder result = new stringbuilder(); int index = origstr.indexof(findthis); while (index >= 0) { result.append(origstr.substring(0, index)); if ((index > 0) && origstr.charat(index - 1) == '>') { result.append(findthis); } else { result.append(replacewith); } origstr = origstr.substring(index + findthis.length()); index = origstr.indexof(findthis); } result.append(origstr); return result.tostring(); } | ASofterSpace/Toolbox-Java | [
1,
0,
0,
0
] |
1,659 | private static String addAfterLinesContainingEx(String origStr, String findThis, String addThat,
String eolMarker, boolean notInsideTag) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if ((addThat == null) || "".equals(addThat)) {
return origStr;
}
if ((eolMarker == null) || "".equals(eolMarker)) {
return origStr;
}
if ("".equals(findThis)) {
return replaceAll(origStr, "\n", "\n" + addThat) + "\n" + addThat;
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
if (notInsideTag) {
if ((index > 0) && origStr.charAt(index - 1) == '>') {
index = origStr.indexOf(findThis, index + 1);
continue;
}
}
int eol = origStr.indexOf(eolMarker, index);
if (eol < 0) {
result.append(origStr);
result.append(eolMarker);
origStr = "";
} else {
result.append(origStr.substring(0, eol + eolMarker.length()));
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(eol + eolMarker.length());
}
result.append(addThat);
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | private static String addAfterLinesContainingEx(String origStr, String findThis, String addThat,
String eolMarker, boolean notInsideTag) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if ((addThat == null) || "".equals(addThat)) {
return origStr;
}
if ((eolMarker == null) || "".equals(eolMarker)) {
return origStr;
}
if ("".equals(findThis)) {
return replaceAll(origStr, "\n", "\n" + addThat) + "\n" + addThat;
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
if (notInsideTag) {
if ((index > 0) && origStr.charAt(index - 1) == '>') {
index = origStr.indexOf(findThis, index + 1);
continue;
}
}
int eol = origStr.indexOf(eolMarker, index);
if (eol < 0) {
result.append(origStr);
result.append(eolMarker);
origStr = "";
} else {
result.append(origStr.substring(0, eol + eolMarker.length()));
origStr = origStr.substring(eol + eolMarker.length());
}
result.append(addThat);
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | private static string addafterlinescontainingex(string origstr, string findthis, string addthat, string eolmarker, boolean notinsidetag) { if (origstr == null) { return null; } if (findthis == null) { return origstr; } if ((addthat == null) || "".equals(addthat)) { return origstr; } if ((eolmarker == null) || "".equals(eolmarker)) { return origstr; } if ("".equals(findthis)) { return replaceall(origstr, "\n", "\n" + addthat) + "\n" + addthat; } stringbuilder result = new stringbuilder(); int index = origstr.indexof(findthis); while (index >= 0) { if (notinsidetag) { if ((index > 0) && origstr.charat(index - 1) == '>') { index = origstr.indexof(findthis, index + 1); continue; } } int eol = origstr.indexof(eolmarker, index); if (eol < 0) { result.append(origstr); result.append(eolmarker); origstr = ""; } else { result.append(origstr.substring(0, eol + eolmarker.length())); origstr = origstr.substring(eol + eolmarker.length()); } result.append(addthat); index = origstr.indexof(findthis); } result.append(origstr); return result.tostring(); } | ASofterSpace/Toolbox-Java | [
1,
0,
0,
0
] |
9,929 | @Nullable
public String getPartitionColumn() {
return _partitionColumn;
} | @Nullable
public String getPartitionColumn() {
return _partitionColumn;
} | @nullable public string getpartitioncolumn() { return _partitioncolumn; } | HoraceChoi95/incubator-pinot | [
0,
1,
0,
0
] |
10,010 | static GeoPolygon generateGeoPolygon(final PlanetModel planetModel,
final List<GeoPoint> filteredPointList,
final List<GeoPolygon> holes,
final GeoPoint testPoint,
final boolean testPointInside) {
// We will be trying twice to find the right GeoPolygon, using alternate siding choices for the first polygon
// side. While this looks like it might be 2x as expensive as it could be, there's really no other choice I can
// find.
final SidedPlane initialPlane = new SidedPlane(testPoint, filteredPointList.get(0), filteredPointList.get(1));
// We don't know if this is the correct siding choice. We will only know as we build the complex polygon.
// So we need to be prepared to try both possibilities.
GeoCompositePolygon rval = new GeoCompositePolygon(planetModel);
MutableBoolean seenConcave = new MutableBoolean();
if (buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, initialPlane, holes, testPoint) == false) {
// The testPoint was within the shape. Was that intended?
if (testPointInside) {
// Yes: build it for real
rval = new GeoCompositePolygon(planetModel);
seenConcave = new MutableBoolean();
buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, initialPlane, holes, null);
return rval;
}
// No: do the complement and return that.
rval = new GeoCompositePolygon(planetModel);
seenConcave = new MutableBoolean();
buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, new SidedPlane(initialPlane), holes, null);
return rval;
} else {
// The testPoint was outside the shape. Was that intended?
if (!testPointInside) {
// Yes: return what we just built
return rval;
}
// No: return the complement
rval = new GeoCompositePolygon(planetModel);
seenConcave = new MutableBoolean();
buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, new SidedPlane(initialPlane), holes, null);
return rval;
}
} | static GeoPolygon generateGeoPolygon(final PlanetModel planetModel,
final List<GeoPoint> filteredPointList,
final List<GeoPolygon> holes,
final GeoPoint testPoint,
final boolean testPointInside) {
final SidedPlane initialPlane = new SidedPlane(testPoint, filteredPointList.get(0), filteredPointList.get(1));
GeoCompositePolygon rval = new GeoCompositePolygon(planetModel);
MutableBoolean seenConcave = new MutableBoolean();
if (buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, initialPlane, holes, testPoint) == false) {
if (testPointInside) {
rval = new GeoCompositePolygon(planetModel);
seenConcave = new MutableBoolean();
buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, initialPlane, holes, null);
return rval;
}
rval = new GeoCompositePolygon(planetModel);
seenConcave = new MutableBoolean();
buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, new SidedPlane(initialPlane), holes, null);
return rval;
} else {
if (!testPointInside) {
return rval;
}
rval = new GeoCompositePolygon(planetModel);
seenConcave = new MutableBoolean();
buildPolygonShape(rval, seenConcave, planetModel, filteredPointList, new BitSet(), 0, 1, new SidedPlane(initialPlane), holes, null);
return rval;
}
} | static geopolygon generategeopolygon(final planetmodel planetmodel, final list<geopoint> filteredpointlist, final list<geopolygon> holes, final geopoint testpoint, final boolean testpointinside) { final sidedplane initialplane = new sidedplane(testpoint, filteredpointlist.get(0), filteredpointlist.get(1)); geocompositepolygon rval = new geocompositepolygon(planetmodel); mutableboolean seenconcave = new mutableboolean(); if (buildpolygonshape(rval, seenconcave, planetmodel, filteredpointlist, new bitset(), 0, 1, initialplane, holes, testpoint) == false) { if (testpointinside) { rval = new geocompositepolygon(planetmodel); seenconcave = new mutableboolean(); buildpolygonshape(rval, seenconcave, planetmodel, filteredpointlist, new bitset(), 0, 1, initialplane, holes, null); return rval; } rval = new geocompositepolygon(planetmodel); seenconcave = new mutableboolean(); buildpolygonshape(rval, seenconcave, planetmodel, filteredpointlist, new bitset(), 0, 1, new sidedplane(initialplane), holes, null); return rval; } else { if (!testpointinside) { return rval; } rval = new geocompositepolygon(planetmodel); seenconcave = new mutableboolean(); buildpolygonshape(rval, seenconcave, planetmodel, filteredpointlist, new bitset(), 0, 1, new sidedplane(initialplane), holes, null); return rval; } } | AliGhaff/testLucene | [
1,
0,
0,
0
] |
10,073 | public void setMessageContent(byte[] content, boolean strict, boolean computeContentLength, int givenLength)
throws ParseException {
// Note that that this could be a double byte character
// set - bug report by Masafumi Watanabe
computeContentLength(content);
if ((!computeContentLength)) {
if ((!strict && this.contentLengthHeader.getContentLength() != givenLength)
|| this.contentLengthHeader.getContentLength() < givenLength) {
throw new ParseException("Invalid content length "
+ this.contentLengthHeader.getContentLength() + " / " + givenLength, 0);
}
}
messageContent = null;
messageContentBytes = content;
messageContentObject = null;
} | public void setMessageContent(byte[] content, boolean strict, boolean computeContentLength, int givenLength)
throws ParseException {
computeContentLength(content);
if ((!computeContentLength)) {
if ((!strict && this.contentLengthHeader.getContentLength() != givenLength)
|| this.contentLengthHeader.getContentLength() < givenLength) {
throw new ParseException("Invalid content length "
+ this.contentLengthHeader.getContentLength() + " / " + givenLength, 0);
}
}
messageContent = null;
messageContentBytes = content;
messageContentObject = null;
} | public void setmessagecontent(byte[] content, boolean strict, boolean computecontentlength, int givenlength) throws parseexception { computecontentlength(content); if ((!computecontentlength)) { if ((!strict && this.contentlengthheader.getcontentlength() != givenlength) || this.contentlengthheader.getcontentlength() < givenlength) { throw new parseexception("invalid content length " + this.contentlengthheader.getcontentlength() + " / " + givenlength, 0); } } messagecontent = null; messagecontentbytes = content; messagecontentobject = null; } | E-C-Group/jsip | [
0,
0,
1,
0
] |
2,275 | void doJob() {
//mRenderThread = new RenderThread(getResources(), surface, v);
//init
final TextureView tv = (TextureView) findViewById(R.id.textureView1);
SurfaceTexture surface = tv.getSurfaceTexture();
TexSurfaceRenderTarget rt = new TexSurfaceRenderTarget();
View view = getWindow().getDecorView();
rt.init(surface);
rt.begin();
int[] buf = new int[1];
glGenTextures(1, buf, 0);
int texName = buf[0];
glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES , texName);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
FloatBuffer triangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length
* FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer();
triangleVertices.put(mTriangleVerticesData).position(0);
int program = buildProgram(sSimpleVS, sBasicFS /*sSimpleFS*/);
int attribPosition = glGetAttribLocation(program, "position");
checkGlError();
int attribTexCoords = glGetAttribLocation(program, "texCoords");
checkGlError();
int uniformTexture = glGetUniformLocation(program, "texture");
checkGlError();
int textureTranformHandle = glGetUniformLocation(program, "textureTransform");
checkGlError();
SurfaceTexture tex = new SurfaceTexture(texName);//TODO: wait for onFrameAvailable() ??
HwUiRender render = HwUiRender.create(this);
render.setSurface(tex);
//draw
for(int i=0;i<1;++i) {
long startTime = System.currentTimeMillis();
render.drawToSurface(view);
rt.begin();//TODO: replace on check & makecurrent
tex.updateTexImage();
float[] texTransform = new float[16];
tex.getTransformMatrix(texTransform);
glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES , texName);
checkGlError();
glUseProgram(program);
checkGlError();
glEnableVertexAttribArray(attribPosition);
checkGlError();
glEnableVertexAttribArray(attribTexCoords);
checkGlError();
glUniform1i(uniformTexture, 0);
glUniformMatrix4fv(textureTranformHandle, 1, false, texTransform, 0);
checkGlError();
triangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
glVertexAttribPointer(attribPosition, 3, GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);
checkGlError();
triangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
glVertexAttribPointer(attribTexCoords, 3, GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
rt.end();
mToggleButton.setText("" + (System.currentTimeMillis() - startTime));
}
render.setSurface(null);
//rt.cleanup();
} | void doJob() {
final TextureView tv = (TextureView) findViewById(R.id.textureView1);
SurfaceTexture surface = tv.getSurfaceTexture();
TexSurfaceRenderTarget rt = new TexSurfaceRenderTarget();
View view = getWindow().getDecorView();
rt.init(surface);
rt.begin();
int[] buf = new int[1];
glGenTextures(1, buf, 0);
int texName = buf[0];
glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES , texName);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
FloatBuffer triangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length
* FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer();
triangleVertices.put(mTriangleVerticesData).position(0);
int program = buildProgram(sSimpleVS, sBasicFS);
int attribPosition = glGetAttribLocation(program, "position");
checkGlError();
int attribTexCoords = glGetAttribLocation(program, "texCoords");
checkGlError();
int uniformTexture = glGetUniformLocation(program, "texture");
checkGlError();
int textureTranformHandle = glGetUniformLocation(program, "textureTransform");
checkGlError();
SurfaceTexture tex = new SurfaceTexture(texName)
HwUiRender render = HwUiRender.create(this);
render.setSurface(tex);
for(int i=0;i<1;++i) {
long startTime = System.currentTimeMillis();
render.drawToSurface(view);
rt.begin()
tex.updateTexImage();
float[] texTransform = new float[16];
tex.getTransformMatrix(texTransform);
glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES , texName);
checkGlError();
glUseProgram(program);
checkGlError();
glEnableVertexAttribArray(attribPosition);
checkGlError();
glEnableVertexAttribArray(attribTexCoords);
checkGlError();
glUniform1i(uniformTexture, 0);
glUniformMatrix4fv(textureTranformHandle, 1, false, texTransform, 0);
checkGlError();
triangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
glVertexAttribPointer(attribPosition, 3, GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);
checkGlError();
triangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
glVertexAttribPointer(attribTexCoords, 3, GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
rt.end();
mToggleButton.setText("" + (System.currentTimeMillis() - startTime));
}
render.setSurface(null);
} | void dojob() { final textureview tv = (textureview) findviewbyid(r.id.textureview1); surfacetexture surface = tv.getsurfacetexture(); texsurfacerendertarget rt = new texsurfacerendertarget(); view view = getwindow().getdecorview(); rt.init(surface); rt.begin(); int[] buf = new int[1]; glgentextures(1, buf, 0); int texname = buf[0]; glbindtexture(gles11ext.gl_texture_external_oes , texname); gltexparameterf(gl_texture_2d, gl_texture_min_filter, gl_nearest); gltexparameterf(gl_texture_2d, gl_texture_mag_filter, gl_linear); gltexparameteri(gl_texture_2d, gl_texture_wrap_s, gl_repeat); gltexparameteri(gl_texture_2d, gl_texture_wrap_t, gl_repeat); floatbuffer trianglevertices = bytebuffer.allocatedirect(mtriangleverticesdata.length * float_size_bytes).order(byteorder.nativeorder()).asfloatbuffer(); trianglevertices.put(mtriangleverticesdata).position(0); int program = buildprogram(ssimplevs, sbasicfs); int attribposition = glgetattriblocation(program, "position"); checkglerror(); int attribtexcoords = glgetattriblocation(program, "texcoords"); checkglerror(); int uniformtexture = glgetuniformlocation(program, "texture"); checkglerror(); int texturetranformhandle = glgetuniformlocation(program, "texturetransform"); checkglerror(); surfacetexture tex = new surfacetexture(texname) hwuirender render = hwuirender.create(this); render.setsurface(tex); for(int i=0;i<1;++i) { long starttime = system.currenttimemillis(); render.drawtosurface(view); rt.begin() tex.updateteximage(); float[] textransform = new float[16]; tex.gettransformmatrix(textransform); glbindtexture(gles11ext.gl_texture_external_oes , texname); checkglerror(); gluseprogram(program); checkglerror(); glenablevertexattribarray(attribposition); checkglerror(); glenablevertexattribarray(attribtexcoords); checkglerror(); gluniform1i(uniformtexture, 0); gluniformmatrix4fv(texturetranformhandle, 1, false, textransform, 0); checkglerror(); trianglevertices.position(triangle_vertices_data_pos_offset); glvertexattribpointer(attribposition, 3, gl_float, false, triangle_vertices_data_stride_bytes, trianglevertices); checkglerror(); trianglevertices.position(triangle_vertices_data_uv_offset); glvertexattribpointer(attribtexcoords, 3, gl_float, false, triangle_vertices_data_stride_bytes, trianglevertices); gldrawarrays(gl_triangle_strip, 0, 4); rt.end(); mtogglebutton.settext("" + (system.currenttimemillis() - starttime)); } render.setsurface(null); } | ChGen/AndroidGpuGraphicsTest | [
0,
1,
0,
0
] |
18,664 | @Test
public void shouldAddNullSubprojectIfProjectIsDefined() throws IOException {
Event event = EventBuilder.create(0, "11203800-63fd-11e8-83e2-3a587d902000").
tag("description", Variant.ofString("This is the annotation")).
tag("tags", Variant.ofVector(Vector.ofContainers(
Container.builder().tag("key", Variant.ofString("environment")).tag("value", Variant.ofString("staging")).build(),
Container.builder().tag("key", Variant.ofString("project")).tag("value", Variant.ofString("test")).build()))).
build();
Properties properties = new Properties();
properties.setProperty("file", "resource://annotation-event.mapping");
EventToJsonFormatter formatter = new EventToJsonFormatter(properties);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DocumentWriter.writeTo(stream, formatter.format(event));
assertEquals("{" +
"\"@timestamp\":\"1970-01-01T00:00:00.000000000Z\"," +
"\"environment\":\"staging\"," +
"\"project\":\"test\"," +
"\"tags\":\"environment=staging,project=test,subproject=null\"," +
"\"description\":\"This is the annotation\"" +
"}",
stream.toString(StandardCharsets.UTF_8.name())
);
} | @Test
public void shouldAddNullSubprojectIfProjectIsDefined() throws IOException {
Event event = EventBuilder.create(0, "11203800-63fd-11e8-83e2-3a587d902000").
tag("description", Variant.ofString("This is the annotation")).
tag("tags", Variant.ofVector(Vector.ofContainers(
Container.builder().tag("key", Variant.ofString("environment")).tag("value", Variant.ofString("staging")).build(),
Container.builder().tag("key", Variant.ofString("project")).tag("value", Variant.ofString("test")).build()))).
build();
Properties properties = new Properties();
properties.setProperty("file", "resource://annotation-event.mapping");
EventToJsonFormatter formatter = new EventToJsonFormatter(properties);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DocumentWriter.writeTo(stream, formatter.format(event));
assertEquals("{" +
"\"@timestamp\":\"1970-01-01T00:00:00.000000000Z\"," +
"\"environment\":\"staging\"," +
"\"project\":\"test\"," +
"\"tags\":\"environment=staging,project=test,subproject=null\"," +
"\"description\":\"This is the annotation\"" +
"}",
stream.toString(StandardCharsets.UTF_8.name())
);
} | @test public void shouldaddnullsubprojectifprojectisdefined() throws ioexception { event event = eventbuilder.create(0, "11203800-63fd-11e8-83e2-3a587d902000"). tag("description", variant.ofstring("this is the annotation")). tag("tags", variant.ofvector(vector.ofcontainers( container.builder().tag("key", variant.ofstring("environment")).tag("value", variant.ofstring("staging")).build(), container.builder().tag("key", variant.ofstring("project")).tag("value", variant.ofstring("test")).build()))). build(); properties properties = new properties(); properties.setproperty("file", "resource://annotation-event.mapping"); eventtojsonformatter formatter = new eventtojsonformatter(properties); bytearrayoutputstream stream = new bytearrayoutputstream(); documentwriter.writeto(stream, formatter.format(event)); assertequals("{" + "\"@timestamp\":\"1970-01-01t00:00:00.000000000z\"," + "\"environment\":\"staging\"," + "\"project\":\"test\"," + "\"tags\":\"environment=staging,project=test,subproject=null\"," + "\"description\":\"this is the annotation\"" + "}", stream.tostring(standardcharsets.utf_8.name()) ); } | InHavk/hercules | [
1,
0,
0,
0
] |
18,794 | @Test
public void test() {
ChatDirector chatDirector = new ChatDirector(new File(
this.getClass().getClassLoader().getResource("modules/common/config.yml").getFile()));
assertTrue(chatDirector.load());
// Checking Chain metrics
assertTrue(chatDirector.getChains().size() == 5);
assertTrue(chatDirector.getChains().containsKey("loading-test"));
assertTrue(chatDirector.getChains().containsKey("breaking-test"));
assertTrue(chatDirector.getChains().containsKey("echo-test"));
assertTrue(chatDirector.getChains().containsKey("halt-test"));
assertTrue(chatDirector.getChains().containsKey("reload-test"));
assertNotNull(chatDirector.getChains().get("loading-test"));
assertNotNull(chatDirector.getChains().get("breaking-test"));
assertNotNull(chatDirector.getChains().get("echo-test"));
assertNotNull(chatDirector.getChains().get("halt-test"));
assertNotNull(chatDirector.getChains().get("reload-test"));
// Checking Per Chain metrics
assertNotNull(chatDirector.getChains().get("loading-test").getItems());
assertNotNull(chatDirector.getChains().get("breaking-test").getItems());
assertNotNull(chatDirector.getChains().get("echo-test").getItems());
assertNotNull(chatDirector.getChains().get("halt-test").getItems());
assertNotNull(chatDirector.getChains().get("reload-test").getItems());
assertTrue(chatDirector.getChains().get("loading-test").getItems().size() == 9);
assertTrue(chatDirector.getChains().get("breaking-test").getItems().size() == 4);
assertTrue(chatDirector.getChains().get("echo-test").getItems().size() == 3);
assertTrue(chatDirector.getChains().get("halt-test").getItems().size() == 3);
assertTrue(chatDirector.getChains().get("reload-test").getItems().size() == 1);
assertTrue(chatDirector.getChains().get("loading-test").isValid());
assertTrue(chatDirector.getChains().get("breaking-test").isValid());
assertTrue(chatDirector.getChains().get("echo-test").isValid());
assertTrue(chatDirector.getChains().get("halt-test").isValid());
assertTrue(chatDirector.getChains().get("reload-test").isValid());
// Checking Each item in chain
IItem item = chatDirector.getChains().get("loading-test").getItems().get(0);
assertTrue(item instanceof BreakItem);
item = chatDirector.getChains().get("loading-test").getItems().get(1);
assertTrue(item instanceof BreakItem);
item = chatDirector.getChains().get("loading-test").getItems().get(2);
assertTrue(item instanceof HaltItem);
item = chatDirector.getChains().get("loading-test").getItems().get(3);
assertTrue(item instanceof HaltItem);
item = chatDirector.getChains().get("loading-test").getItems().get(4);
assertTrue(item instanceof EchoItem);
assertEquals("%CURRENT%", ((EchoItem) item).format);
item = chatDirector.getChains().get("loading-test").getItems().get(5);
assertTrue(item instanceof EchoItem);
assertEquals("raw string", ((EchoItem) item).format);
item = chatDirector.getChains().get("loading-test").getItems().get(6);
assertTrue(item instanceof EchoItem);
assertEquals("", ((EchoItem) item).format);
item = chatDirector.getChains().get("loading-test").getItems().get(7);
assertTrue(item instanceof ReloadItem);
item = chatDirector.getChains().get("loading-test").getItems().get(8);
assertTrue(item instanceof ReloadItem);
item = chatDirector.getChains().get("breaking-test").getItems().get(0);
assertTrue(item instanceof EchoItem);
assertEquals("This is the first value", ((EchoItem) item).format);
item = chatDirector.getChains().get("breaking-test").getItems().get(1);
assertTrue(item instanceof EchoItem);
assertEquals("This is the second value", ((EchoItem) item).format);
item = chatDirector.getChains().get("breaking-test").getItems().get(2);
assertTrue(item instanceof BreakItem);
item = chatDirector.getChains().get("breaking-test").getItems().get(3);
assertTrue(item instanceof EchoItem);
assertEquals("This is the third value", ((EchoItem) item).format);
item = chatDirector.getChains().get("echo-test").getItems().get(0);
assertTrue(item instanceof EchoItem);
assertEquals("hello!", ((EchoItem) item).format);
item = chatDirector.getChains().get("echo-test").getItems().get(1);
assertTrue(item instanceof EchoItem);
assertEquals("This was >%CURRENT%<", ((EchoItem) item).format);
item = chatDirector.getChains().get("echo-test").getItems().get(2);
assertTrue(item instanceof EchoItem);
assertEquals("This was >%CURRENT%<, but before that it was >%LAST%<", ((EchoItem) item).format);
item = chatDirector.getChains().get("halt-test").getItems().get(0);
assertTrue(item instanceof EchoItem);
assertEquals("This is the first value", ((EchoItem) item).format);
item = chatDirector.getChains().get("halt-test").getItems().get(1);
assertTrue(item instanceof HaltItem);
item = chatDirector.getChains().get("halt-test").getItems().get(2);
assertTrue(item instanceof EchoItem);
assertEquals("This is the second value", ((EchoItem) item).format);
item = chatDirector.getChains().get("reload-test").getItems().get(0);
assertTrue(item instanceof ReloadItem);
// TODO: Preform a check for reload?
} | @Test
public void test() {
ChatDirector chatDirector = new ChatDirector(new File(
this.getClass().getClassLoader().getResource("modules/common/config.yml").getFile()));
assertTrue(chatDirector.load());
assertTrue(chatDirector.getChains().size() == 5);
assertTrue(chatDirector.getChains().containsKey("loading-test"));
assertTrue(chatDirector.getChains().containsKey("breaking-test"));
assertTrue(chatDirector.getChains().containsKey("echo-test"));
assertTrue(chatDirector.getChains().containsKey("halt-test"));
assertTrue(chatDirector.getChains().containsKey("reload-test"));
assertNotNull(chatDirector.getChains().get("loading-test"));
assertNotNull(chatDirector.getChains().get("breaking-test"));
assertNotNull(chatDirector.getChains().get("echo-test"));
assertNotNull(chatDirector.getChains().get("halt-test"));
assertNotNull(chatDirector.getChains().get("reload-test"));
assertNotNull(chatDirector.getChains().get("loading-test").getItems());
assertNotNull(chatDirector.getChains().get("breaking-test").getItems());
assertNotNull(chatDirector.getChains().get("echo-test").getItems());
assertNotNull(chatDirector.getChains().get("halt-test").getItems());
assertNotNull(chatDirector.getChains().get("reload-test").getItems());
assertTrue(chatDirector.getChains().get("loading-test").getItems().size() == 9);
assertTrue(chatDirector.getChains().get("breaking-test").getItems().size() == 4);
assertTrue(chatDirector.getChains().get("echo-test").getItems().size() == 3);
assertTrue(chatDirector.getChains().get("halt-test").getItems().size() == 3);
assertTrue(chatDirector.getChains().get("reload-test").getItems().size() == 1);
assertTrue(chatDirector.getChains().get("loading-test").isValid());
assertTrue(chatDirector.getChains().get("breaking-test").isValid());
assertTrue(chatDirector.getChains().get("echo-test").isValid());
assertTrue(chatDirector.getChains().get("halt-test").isValid());
assertTrue(chatDirector.getChains().get("reload-test").isValid());
IItem item = chatDirector.getChains().get("loading-test").getItems().get(0);
assertTrue(item instanceof BreakItem);
item = chatDirector.getChains().get("loading-test").getItems().get(1);
assertTrue(item instanceof BreakItem);
item = chatDirector.getChains().get("loading-test").getItems().get(2);
assertTrue(item instanceof HaltItem);
item = chatDirector.getChains().get("loading-test").getItems().get(3);
assertTrue(item instanceof HaltItem);
item = chatDirector.getChains().get("loading-test").getItems().get(4);
assertTrue(item instanceof EchoItem);
assertEquals("%CURRENT%", ((EchoItem) item).format);
item = chatDirector.getChains().get("loading-test").getItems().get(5);
assertTrue(item instanceof EchoItem);
assertEquals("raw string", ((EchoItem) item).format);
item = chatDirector.getChains().get("loading-test").getItems().get(6);
assertTrue(item instanceof EchoItem);
assertEquals("", ((EchoItem) item).format);
item = chatDirector.getChains().get("loading-test").getItems().get(7);
assertTrue(item instanceof ReloadItem);
item = chatDirector.getChains().get("loading-test").getItems().get(8);
assertTrue(item instanceof ReloadItem);
item = chatDirector.getChains().get("breaking-test").getItems().get(0);
assertTrue(item instanceof EchoItem);
assertEquals("This is the first value", ((EchoItem) item).format);
item = chatDirector.getChains().get("breaking-test").getItems().get(1);
assertTrue(item instanceof EchoItem);
assertEquals("This is the second value", ((EchoItem) item).format);
item = chatDirector.getChains().get("breaking-test").getItems().get(2);
assertTrue(item instanceof BreakItem);
item = chatDirector.getChains().get("breaking-test").getItems().get(3);
assertTrue(item instanceof EchoItem);
assertEquals("This is the third value", ((EchoItem) item).format);
item = chatDirector.getChains().get("echo-test").getItems().get(0);
assertTrue(item instanceof EchoItem);
assertEquals("hello!", ((EchoItem) item).format);
item = chatDirector.getChains().get("echo-test").getItems().get(1);
assertTrue(item instanceof EchoItem);
assertEquals("This was >%CURRENT%<", ((EchoItem) item).format);
item = chatDirector.getChains().get("echo-test").getItems().get(2);
assertTrue(item instanceof EchoItem);
assertEquals("This was >%CURRENT%<, but before that it was >%LAST%<", ((EchoItem) item).format);
item = chatDirector.getChains().get("halt-test").getItems().get(0);
assertTrue(item instanceof EchoItem);
assertEquals("This is the first value", ((EchoItem) item).format);
item = chatDirector.getChains().get("halt-test").getItems().get(1);
assertTrue(item instanceof HaltItem);
item = chatDirector.getChains().get("halt-test").getItems().get(2);
assertTrue(item instanceof EchoItem);
assertEquals("This is the second value", ((EchoItem) item).format);
item = chatDirector.getChains().get("reload-test").getItems().get(0);
assertTrue(item instanceof ReloadItem);
} | @test public void test() { chatdirector chatdirector = new chatdirector(new file( this.getclass().getclassloader().getresource("modules/common/config.yml").getfile())); asserttrue(chatdirector.load()); asserttrue(chatdirector.getchains().size() == 5); asserttrue(chatdirector.getchains().containskey("loading-test")); asserttrue(chatdirector.getchains().containskey("breaking-test")); asserttrue(chatdirector.getchains().containskey("echo-test")); asserttrue(chatdirector.getchains().containskey("halt-test")); asserttrue(chatdirector.getchains().containskey("reload-test")); assertnotnull(chatdirector.getchains().get("loading-test")); assertnotnull(chatdirector.getchains().get("breaking-test")); assertnotnull(chatdirector.getchains().get("echo-test")); assertnotnull(chatdirector.getchains().get("halt-test")); assertnotnull(chatdirector.getchains().get("reload-test")); assertnotnull(chatdirector.getchains().get("loading-test").getitems()); assertnotnull(chatdirector.getchains().get("breaking-test").getitems()); assertnotnull(chatdirector.getchains().get("echo-test").getitems()); assertnotnull(chatdirector.getchains().get("halt-test").getitems()); assertnotnull(chatdirector.getchains().get("reload-test").getitems()); asserttrue(chatdirector.getchains().get("loading-test").getitems().size() == 9); asserttrue(chatdirector.getchains().get("breaking-test").getitems().size() == 4); asserttrue(chatdirector.getchains().get("echo-test").getitems().size() == 3); asserttrue(chatdirector.getchains().get("halt-test").getitems().size() == 3); asserttrue(chatdirector.getchains().get("reload-test").getitems().size() == 1); asserttrue(chatdirector.getchains().get("loading-test").isvalid()); asserttrue(chatdirector.getchains().get("breaking-test").isvalid()); asserttrue(chatdirector.getchains().get("echo-test").isvalid()); asserttrue(chatdirector.getchains().get("halt-test").isvalid()); asserttrue(chatdirector.getchains().get("reload-test").isvalid()); iitem item = chatdirector.getchains().get("loading-test").getitems().get(0); asserttrue(item instanceof breakitem); item = chatdirector.getchains().get("loading-test").getitems().get(1); asserttrue(item instanceof breakitem); item = chatdirector.getchains().get("loading-test").getitems().get(2); asserttrue(item instanceof haltitem); item = chatdirector.getchains().get("loading-test").getitems().get(3); asserttrue(item instanceof haltitem); item = chatdirector.getchains().get("loading-test").getitems().get(4); asserttrue(item instanceof echoitem); assertequals("%current%", ((echoitem) item).format); item = chatdirector.getchains().get("loading-test").getitems().get(5); asserttrue(item instanceof echoitem); assertequals("raw string", ((echoitem) item).format); item = chatdirector.getchains().get("loading-test").getitems().get(6); asserttrue(item instanceof echoitem); assertequals("", ((echoitem) item).format); item = chatdirector.getchains().get("loading-test").getitems().get(7); asserttrue(item instanceof reloaditem); item = chatdirector.getchains().get("loading-test").getitems().get(8); asserttrue(item instanceof reloaditem); item = chatdirector.getchains().get("breaking-test").getitems().get(0); asserttrue(item instanceof echoitem); assertequals("this is the first value", ((echoitem) item).format); item = chatdirector.getchains().get("breaking-test").getitems().get(1); asserttrue(item instanceof echoitem); assertequals("this is the second value", ((echoitem) item).format); item = chatdirector.getchains().get("breaking-test").getitems().get(2); asserttrue(item instanceof breakitem); item = chatdirector.getchains().get("breaking-test").getitems().get(3); asserttrue(item instanceof echoitem); assertequals("this is the third value", ((echoitem) item).format); item = chatdirector.getchains().get("echo-test").getitems().get(0); asserttrue(item instanceof echoitem); assertequals("hello!", ((echoitem) item).format); item = chatdirector.getchains().get("echo-test").getitems().get(1); asserttrue(item instanceof echoitem); assertequals("this was >%current%<", ((echoitem) item).format); item = chatdirector.getchains().get("echo-test").getitems().get(2); asserttrue(item instanceof echoitem); assertequals("this was >%current%<, but before that it was >%last%<", ((echoitem) item).format); item = chatdirector.getchains().get("halt-test").getitems().get(0); asserttrue(item instanceof echoitem); assertequals("this is the first value", ((echoitem) item).format); item = chatdirector.getchains().get("halt-test").getitems().get(1); asserttrue(item instanceof haltitem); item = chatdirector.getchains().get("halt-test").getitems().get(2); asserttrue(item instanceof echoitem); assertequals("this is the second value", ((echoitem) item).format); item = chatdirector.getchains().get("reload-test").getitems().get(0); asserttrue(item instanceof reloaditem); } | AtomicPulsee/ChatDirector | [
1,
0,
0,
0
] |
18,795 | @Override
public void initialize(URL location, ResourceBundle resources) {
// load the quiz
for (Question question : quiz.questions) {
questionsList.getItems().add(question.title);
}
populateView();
questionTextField.setOnKeyReleased(e -> {
questionsList.getItems().set(currentQuestionIndex, questionTextField.getText());
quiz.questions.get(currentQuestionIndex).title = questionTextField.getText();
saved = false;
});
newAnswerButton.setOnMouseClicked(e -> {
quiz.questions.get(currentQuestionIndex).options.add(new Option(""));
addAnswer(questionsTilePane.getChildren().size());
saved = false;
});
rightAnswerComboBox.setOnAction(e -> {
if (rightAnswerComboBox.getItems().size() > 0) {
currentQuestion.answer = rightAnswerComboBox.getSelectionModel().getSelectedIndex();
}
saved = false;
});
questionsList.setOnMouseClicked(e -> {
int selectedIndex = questionsList.getSelectionModel().getSelectedIndex();
if (selectedIndex < quiz.questions.size() && selectedIndex >= 0) {
currentQuestionIndex = selectedIndex;
currentQuestion = quiz.questions.get(selectedIndex);
}
populateView();
saved = false;
});
newQuestionButton.setOnAction(e -> {
newQuestion();
questionsList.getItems().add("");
currentQuestion = this.quiz.questions.get(currentQuestionIndex);
populateView();
saved = false;
});
deleteQuestionButton.setOnAction(e -> removeQuestion());
quizOptionsButton.setOnAction(e -> {
Stage stage = new Stage();
Window win = new Window(window.getApp(), stage, "Settings for '" + quiz.name + "'");
win.openView(new QuizSettingsPopupControl(quiz));
saved = false;
});
maxPointsTextInput.addEventFilter(KeyEvent.KEY_TYPED, e -> {
if (e.getCharacter().matches("[\\D]")) {
e.consume();
}
});
maxPointsTextInput.setOnKeyReleased(e -> {
if (!maxPointsTextInput.getText().isEmpty()) {
currentQuestion.maxReward = Integer.parseInt(maxPointsTextInput.getText());
} else {
currentQuestion.maxReward = 50; // TODO un hardcode this
}
saved = false;
});
FileMenu.getItems().get(2).setOnAction(e -> {
if (!saved) {
askForSave();
closeApp = false;
} else {
window.openView(new ChooseQuizScreenControl(true));
}
});
FileMenu.getItems().get(0).setOnAction(e -> InitSave());
FileMenu.getItems().get(1).setOnAction(e -> {
openSaveDialog();
});
window.getStage().setOnCloseRequest(e -> {
if (!saved) {
e.consume();
askForSave();
closeApp = true;
}
});
} | @Override
public void initialize(URL location, ResourceBundle resources) {
for (Question question : quiz.questions) {
questionsList.getItems().add(question.title);
}
populateView();
questionTextField.setOnKeyReleased(e -> {
questionsList.getItems().set(currentQuestionIndex, questionTextField.getText());
quiz.questions.get(currentQuestionIndex).title = questionTextField.getText();
saved = false;
});
newAnswerButton.setOnMouseClicked(e -> {
quiz.questions.get(currentQuestionIndex).options.add(new Option(""));
addAnswer(questionsTilePane.getChildren().size());
saved = false;
});
rightAnswerComboBox.setOnAction(e -> {
if (rightAnswerComboBox.getItems().size() > 0) {
currentQuestion.answer = rightAnswerComboBox.getSelectionModel().getSelectedIndex();
}
saved = false;
});
questionsList.setOnMouseClicked(e -> {
int selectedIndex = questionsList.getSelectionModel().getSelectedIndex();
if (selectedIndex < quiz.questions.size() && selectedIndex >= 0) {
currentQuestionIndex = selectedIndex;
currentQuestion = quiz.questions.get(selectedIndex);
}
populateView();
saved = false;
});
newQuestionButton.setOnAction(e -> {
newQuestion();
questionsList.getItems().add("");
currentQuestion = this.quiz.questions.get(currentQuestionIndex);
populateView();
saved = false;
});
deleteQuestionButton.setOnAction(e -> removeQuestion());
quizOptionsButton.setOnAction(e -> {
Stage stage = new Stage();
Window win = new Window(window.getApp(), stage, "Settings for '" + quiz.name + "'");
win.openView(new QuizSettingsPopupControl(quiz));
saved = false;
});
maxPointsTextInput.addEventFilter(KeyEvent.KEY_TYPED, e -> {
if (e.getCharacter().matches("[\\D]")) {
e.consume();
}
});
maxPointsTextInput.setOnKeyReleased(e -> {
if (!maxPointsTextInput.getText().isEmpty()) {
currentQuestion.maxReward = Integer.parseInt(maxPointsTextInput.getText());
} else {
currentQuestion.maxReward = 50;
}
saved = false;
});
FileMenu.getItems().get(2).setOnAction(e -> {
if (!saved) {
askForSave();
closeApp = false;
} else {
window.openView(new ChooseQuizScreenControl(true));
}
});
FileMenu.getItems().get(0).setOnAction(e -> InitSave());
FileMenu.getItems().get(1).setOnAction(e -> {
openSaveDialog();
});
window.getStage().setOnCloseRequest(e -> {
if (!saved) {
e.consume();
askForSave();
closeApp = true;
}
});
} | @override public void initialize(url location, resourcebundle resources) { for (question question : quiz.questions) { questionslist.getitems().add(question.title); } populateview(); questiontextfield.setonkeyreleased(e -> { questionslist.getitems().set(currentquestionindex, questiontextfield.gettext()); quiz.questions.get(currentquestionindex).title = questiontextfield.gettext(); saved = false; }); newanswerbutton.setonmouseclicked(e -> { quiz.questions.get(currentquestionindex).options.add(new option("")); addanswer(questionstilepane.getchildren().size()); saved = false; }); rightanswercombobox.setonaction(e -> { if (rightanswercombobox.getitems().size() > 0) { currentquestion.answer = rightanswercombobox.getselectionmodel().getselectedindex(); } saved = false; }); questionslist.setonmouseclicked(e -> { int selectedindex = questionslist.getselectionmodel().getselectedindex(); if (selectedindex < quiz.questions.size() && selectedindex >= 0) { currentquestionindex = selectedindex; currentquestion = quiz.questions.get(selectedindex); } populateview(); saved = false; }); newquestionbutton.setonaction(e -> { newquestion(); questionslist.getitems().add(""); currentquestion = this.quiz.questions.get(currentquestionindex); populateview(); saved = false; }); deletequestionbutton.setonaction(e -> removequestion()); quizoptionsbutton.setonaction(e -> { stage stage = new stage(); window win = new window(window.getapp(), stage, "settings for '" + quiz.name + "'"); win.openview(new quizsettingspopupcontrol(quiz)); saved = false; }); maxpointstextinput.addeventfilter(keyevent.key_typed, e -> { if (e.getcharacter().matches("[\\d]")) { e.consume(); } }); maxpointstextinput.setonkeyreleased(e -> { if (!maxpointstextinput.gettext().isempty()) { currentquestion.maxreward = integer.parseint(maxpointstextinput.gettext()); } else { currentquestion.maxreward = 50; } saved = false; }); filemenu.getitems().get(2).setonaction(e -> { if (!saved) { askforsave(); closeapp = false; } else { window.openview(new choosequizscreencontrol(true)); } }); filemenu.getitems().get(0).setonaction(e -> initsave()); filemenu.getitems().get(1).setonaction(e -> { opensavedialog(); }); window.getstage().setoncloserequest(e -> { if (!saved) { e.consume(); askforsave(); closeapp = true; } }); } | ExodiusStudios/quizzibles | [
1,
0,
0,
0
] |
10,647 | public void testBuildMalformedDocumentWithUnpairedSurrogate()
throws IOException {
String doc = "<doc>A\uD800A</doc>";
try {
builder.build(doc, "http://www.example.com");
fail("Allowed malformed doc");
}
catch (ParsingException success) {
assertNotNull(success.getMessage());
assertEquals("http://www.example.com/", success.getURI());
}
} | public void testBuildMalformedDocumentWithUnpairedSurrogate()
throws IOException {
String doc = "<doc>A\uD800A</doc>";
try {
builder.build(doc, "http://www.example.com");
fail("Allowed malformed doc");
}
catch (ParsingException success) {
assertNotNull(success.getMessage());
assertEquals("http://www.example.com/", success.getURI());
}
} | public void testbuildmalformeddocumentwithunpairedsurrogate() throws ioexception { string doc = "<doc>a\ud800a</doc>"; try { builder.build(doc, "http://www.example.com"); fail("allowed malformed doc"); } catch (parsingexception success) { assertnotnull(success.getmessage()); assertequals("http://www.example.com/", success.geturi()); } } | Evegen55/TIJ4_code | [
1,
0,
0,
0
] |
2,472 | @Override
protected Config getConfig() {
Config c = new Config();
c.caption = "custom tile listener";
c.serviceInterface = CustomTileListenerService.SERVICE_INTERFACE;
//TODO: Implement this in the future
//c.secureSettingName = Settings.Secure.ENABLED_CUSTOM_TILE_LISTENERS;
c.bindPermission =
cyanogenmod.platform.Manifest.permission.BIND_CUSTOM_TILE_LISTENER_SERVICE;
//TODO: Implement this in the future
//c.settingsAction = Settings.ACTION_CUSTOM_TILE_LISTENER_SETTINGS;
c.clientLabel = R.string.custom_tile_listener_binding_label;
return c;
} | @Override
protected Config getConfig() {
Config c = new Config();
c.caption = "custom tile listener";
c.serviceInterface = CustomTileListenerService.SERVICE_INTERFACE;
c.bindPermission =
cyanogenmod.platform.Manifest.permission.BIND_CUSTOM_TILE_LISTENER_SERVICE;
c.clientLabel = R.string.custom_tile_listener_binding_label;
return c;
} | @override protected config getconfig() { config c = new config(); c.caption = "custom tile listener"; c.serviceinterface = customtilelistenerservice.service_interface; c.bindpermission = cyanogenmod.platform.manifest.permission.bind_custom_tile_listener_service; c.clientlabel = r.string.custom_tile_listener_binding_label; return c; } | Ant-OS/android_vendor_cmsdk | [
0,
1,
0,
0
] |
18,884 | @Override
public void offer(HttpContent chunk) {
if (this.channel.isClosed())
return; // TODO somehow connect the cancel back to netsession
if (chunk.content().readableBytes() > this.max) {
this.channel.abort(); // TODO somehow connect the cancel back to netsession
return;
}
ByteBuf bb = chunk.content();
bb.retain(); // we will use it in upcoming send
System.out.println("ref count a: " + bb.refCnt());
StreamMessage b = new StreamMessage("Block", bb);
b.setField("Sequence", this.seq);
OperationResult or = this.channel.send(b);
// bb should now be back to 1
System.out.println("ref count b: " + bb.refCnt());
if (or.hasErrors()) {
this.channel.close();
return;
}
this.seq++;
// TODO track progress if possible
// final only if not canceled
if (chunk instanceof LastHttpContent)
this.channel.send(MessageUtil.streamFinal());
} | @Override
public void offer(HttpContent chunk) {
if (this.channel.isClosed())
return;
if (chunk.content().readableBytes() > this.max) {
this.channel.abort();
return;
}
ByteBuf bb = chunk.content();
bb.retain();
System.out.println("ref count a: " + bb.refCnt());
StreamMessage b = new StreamMessage("Block", bb);
b.setField("Sequence", this.seq);
OperationResult or = this.channel.send(b);
System.out.println("ref count b: " + bb.refCnt());
if (or.hasErrors()) {
this.channel.close();
return;
}
this.seq++;
if (chunk instanceof LastHttpContent)
this.channel.send(MessageUtil.streamFinal());
} | @override public void offer(httpcontent chunk) { if (this.channel.isclosed()) return; if (chunk.content().readablebytes() > this.max) { this.channel.abort(); return; } bytebuf bb = chunk.content(); bb.retain(); system.out.println("ref count a: " + bb.refcnt()); streammessage b = new streammessage("block", bb); b.setfield("sequence", this.seq); operationresult or = this.channel.send(b); system.out.println("ref count b: " + bb.refcnt()); if (or.haserrors()) { this.channel.close(); return; } this.seq++; if (chunk instanceof lasthttpcontent) this.channel.send(messageutil.streamfinal()); } | Gadreel/divconq | [
1,
1,
0,
0
] |
10,828 | private Printer escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
// TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
}
} | private Printer escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c);
}
} | private printer escapecharacter(char c) { if (c == '"') { return backslashchar(c); } switch (c) { case '\\': return backslashchar('\\'); case '\r': return backslashchar('r'); case '\n': return backslashchar('n'); case '\t': return backslashchar('t'); default: if (c < 32) { return this.append(string.format("\\x%02x", (int) c)); } return this.append(c); } } | AyuMol758/bazel | [
0,
1,
0,
0
] |
10,844 | @Override
public void meet(Projection node) throws RuntimeException {
super.meet(node);
ProjectionElemList list = node.getProjectionElemList();
String set = null;
StringBuilder projList = new StringBuilder();
boolean first = true;
//TODO: we do not support projections from multiple pig statements yet
for (String name : list.getTargetNames()) {
set = varToSet.get(name); //TODO: overwrite
if (set == null) {
throw new IllegalArgumentException("Have not found any pig logic for name[" + name + "]");
}
if (!first) {
projList.append(",");
}
first = false;
projList.append(name);
}
if (set == null)
throw new IllegalArgumentException(""); //TODO: Fill this
//SUBORG = FOREACH SUBORG_L GENERATE dept, univ;
pigScriptBuilder.append("PROJ = FOREACH ").append(set).append(" GENERATE ").append(projList.toString()).append(";\n");
} | @Override
public void meet(Projection node) throws RuntimeException {
super.meet(node);
ProjectionElemList list = node.getProjectionElemList();
String set = null;
StringBuilder projList = new StringBuilder();
boolean first = true;
for (String name : list.getTargetNames()) {
set = varToSet.get(name);
if (set == null) {
throw new IllegalArgumentException("Have not found any pig logic for name[" + name + "]");
}
if (!first) {
projList.append(",");
}
first = false;
projList.append(name);
}
if (set == null)
throw new IllegalArgumentException("");
pigScriptBuilder.append("PROJ = FOREACH ").append(set).append(" GENERATE ").append(projList.toString()).append(";\n");
} | @override public void meet(projection node) throws runtimeexception { super.meet(node); projectionelemlist list = node.getprojectionelemlist(); string set = null; stringbuilder projlist = new stringbuilder(); boolean first = true; for (string name : list.gettargetnames()) { set = vartoset.get(name); if (set == null) { throw new illegalargumentexception("have not found any pig logic for name[" + name + "]"); } if (!first) { projlist.append(","); } first = false; projlist.append(name); } if (set == null) throw new illegalargumentexception(""); pigscriptbuilder.append("proj = foreach ").append(set).append(" generate ").append(projlist.tostring()).append(";\n"); } | DLotts/incubator-rya | [
1,
1,
0,
0
] |
2,684 | public List<JsonMessage> processDatasets(List<String> datasetIncludeList,
List<String> datasetExcludeList,
List<String> tableExcludeList,
String dataRegionId) throws IOException, InterruptedException, NonRetryableApplicationException {
List<String> tablesIncludeList = new ArrayList<>();
for (String dataset : datasetIncludeList) {
try {
if (!datasetExcludeList.contains(dataset)) {
List<String> tokens = Utils.tokenize(dataset, ".", true);
String projectId = tokens.get(0);
String datasetId = tokens.get(1);
String datasetLocation = bqService.getDatasetLocation(projectId, datasetId);
/*
TODO: Support tagging in multiple locations
to support all locations:
1- Taxonomies/PolicyTags have to be created in each required location
2- Update the Tagger Cloud Function to read one mapping per location
For now, we don't submit tasks for tables in other locations than the PolicyTag location
*/
if (!datasetLocation.toLowerCase().equals(dataRegionId.toLowerCase())) {
logger.logWarnWithTracker(runId,
String.format(
"Ignoring dataset %s in location %s. Only location %s is configured",
dataset,
datasetLocation,
dataRegionId)
);
continue;
}
// get all tables that have DLP findings
List<String> datasetTables = scanner.listChildren(projectId, datasetId);
tablesIncludeList.addAll(datasetTables);
if (datasetTables.isEmpty()) {
String msg = String.format(
"No Tables found under dataset '%s'",
dataset);
logger.logWarnWithTracker(runId, msg);
} else {
logger.logInfoWithTracker(runId, String.format("Tables found in dataset %s : %s", dataset, datasetTables));
}
}
} catch (Exception exception) {
// log and continue
logger.logFailedDispatcherEntityId(runId, dataset, exception);
}
}
return processTables(tablesIncludeList, tableExcludeList);
} | public List<JsonMessage> processDatasets(List<String> datasetIncludeList,
List<String> datasetExcludeList,
List<String> tableExcludeList,
String dataRegionId) throws IOException, InterruptedException, NonRetryableApplicationException {
List<String> tablesIncludeList = new ArrayList<>();
for (String dataset : datasetIncludeList) {
try {
if (!datasetExcludeList.contains(dataset)) {
List<String> tokens = Utils.tokenize(dataset, ".", true);
String projectId = tokens.get(0);
String datasetId = tokens.get(1);
String datasetLocation = bqService.getDatasetLocation(projectId, datasetId);
if (!datasetLocation.toLowerCase().equals(dataRegionId.toLowerCase())) {
logger.logWarnWithTracker(runId,
String.format(
"Ignoring dataset %s in location %s. Only location %s is configured",
dataset,
datasetLocation,
dataRegionId)
);
continue;
}
List<String> datasetTables = scanner.listChildren(projectId, datasetId);
tablesIncludeList.addAll(datasetTables);
if (datasetTables.isEmpty()) {
String msg = String.format(
"No Tables found under dataset '%s'",
dataset);
logger.logWarnWithTracker(runId, msg);
} else {
logger.logInfoWithTracker(runId, String.format("Tables found in dataset %s : %s", dataset, datasetTables));
}
}
} catch (Exception exception) {
logger.logFailedDispatcherEntityId(runId, dataset, exception);
}
}
return processTables(tablesIncludeList, tableExcludeList);
} | public list<jsonmessage> processdatasets(list<string> datasetincludelist, list<string> datasetexcludelist, list<string> tableexcludelist, string dataregionid) throws ioexception, interruptedexception, nonretryableapplicationexception { list<string> tablesincludelist = new arraylist<>(); for (string dataset : datasetincludelist) { try { if (!datasetexcludelist.contains(dataset)) { list<string> tokens = utils.tokenize(dataset, ".", true); string projectid = tokens.get(0); string datasetid = tokens.get(1); string datasetlocation = bqservice.getdatasetlocation(projectid, datasetid); if (!datasetlocation.tolowercase().equals(dataregionid.tolowercase())) { logger.logwarnwithtracker(runid, string.format( "ignoring dataset %s in location %s. only location %s is configured", dataset, datasetlocation, dataregionid) ); continue; } list<string> datasettables = scanner.listchildren(projectid, datasetid); tablesincludelist.addall(datasettables); if (datasettables.isempty()) { string msg = string.format( "no tables found under dataset '%s'", dataset); logger.logwarnwithtracker(runid, msg); } else { logger.loginfowithtracker(runid, string.format("tables found in dataset %s : %s", dataset, datasettables)); } } } catch (exception exception) { logger.logfaileddispatcherentityid(runid, dataset, exception); } } return processtables(tablesincludelist, tableexcludelist); } | GoogleCloudPlatform/bq-pii-classifier | [
0,
1,
0,
0
] |
10,989 | @Override //using this override to place getAnnualReport and gameShouldEnd inside displayView while loop.
public void displayView() {
boolean keepGoing = true;
while (keepGoing == true) {
//check to see if the game should end and if so, display a message and return to Main Menu
//TODO Implement try catch.
//TODO when fully implemented, this will contain mortality rate variable from annual report
//TODO when fully implemented, this will contain currentYear variable from annual report.
//TODO create end of game report showing total game statistics. Use Annual Report format but bring in stats from every year.
//display the annual report above the GameMenuView
liveTheYear();
getAnnualReport();
if (GameControl.gameShouldEnd(0)) {
//TODO when fully implemented, this will contain mortality rate variable from annual report
this.console.println("More than 50% of your population died, therefore this game is over. Repent and try again.");
return;
} else if (GameControl.gameMatures(1)) {
//TODO when fully implemented, this will contain currentYear variable from annual report.
//TODO create end of game report showing total game statistics. Use Annual Report format but bring in stats from every year.
this.console.println("Ten glorious years have passed, therefore this game is over. Congratulations on a successful game!");
return;
}
// get message that should be displayed
// only print if it is non-null
String message = getMessage();
if (message != null) {
this.console.println(getMessage());
}
String[] inputs = getInputs();
keepGoing = doAction(inputs);
}
} | @Override public void displayView() {
boolean keepGoing = true;
while (keepGoing == true) {
liveTheYear();
getAnnualReport();
if (GameControl.gameShouldEnd(0)) {
this.console.println("More than 50% of your population died, therefore this game is over. Repent and try again.");
return;
} else if (GameControl.gameMatures(1)) {
this.console.println("Ten glorious years have passed, therefore this game is over. Congratulations on a successful game!");
return;
}
String message = getMessage();
if (message != null) {
this.console.println(getMessage());
}
String[] inputs = getInputs();
keepGoing = doAction(inputs);
}
} | @override public void displayview() { boolean keepgoing = true; while (keepgoing == true) { livetheyear(); getannualreport(); if (gamecontrol.gameshouldend(0)) { this.console.println("more than 50% of your population died, therefore this game is over. repent and try again."); return; } else if (gamecontrol.gamematures(1)) { this.console.println("ten glorious years have passed, therefore this game is over. congratulations on a successful game!"); return; } string message = getmessage(); if (message != null) { this.console.println(getmessage()); } string[] inputs = getinputs(); keepgoing = doaction(inputs); } } | Hsia-Esther/CityOfAaronGroup1 | [
0,
1,
0,
0
] |
2,869 | public void updatePosLog(double x, double y, double heading) { // Reference positions by doing point# * 3 + (0 for
// x, 1 for y, 2 for heading)
posLog.add(x);
posLog.add(y);
posLog.add(heading);
} | public void updatePosLog(double x, double y, double heading) {
posLog.add(x);
posLog.add(y);
posLog.add(heading);
} | public void updateposlog(double x, double y, double heading) { poslog.add(x); poslog.add(y); poslog.add(heading); } | AutonomousCarProject/Steering | [
1,
0,
0,
0
] |
11,109 | @Override
protected void configure() {
install(new DefaultModule.Builder().placeManager(PerunPlaceManager.class).build());
// make sure app is embedded in a correct DIV
bind(RootPresenter.class).to(PerunRootPresenter.class).asEagerSingleton();
// Main Application must bind generic Presenter and custom View !!
bindPresenter(PerunCabinetPresenter.class, PerunCabinetPresenter.MyView.class, PerunCabinetView.class, PerunCabinetPresenter.MyProxy.class);
// bind app-specific pages
// TODO - implement pages
bindPresenter(PublicationsPresenter.class, PublicationsPresenter.MyView.class, PublicationsView.class, PublicationsPresenter.MyProxy.class);
bindPresenter(NewPublicationPresenter.class, NewPublicationPresenter.MyView.class, NewPublicationView.class, NewPublicationPresenter.MyProxy.class);
// pre-defined places
bindConstant().annotatedWith(DefaultPlace.class).to(PerunCabinetPlaceTokens.PUBLICATIONS);
bindConstant().annotatedWith(ErrorPlace.class).to(PerunCabinetPlaceTokens.NOT_FOUND);
bindConstant().annotatedWith(UnauthorizedPlace.class).to(PerunCabinetPlaceTokens.UNAUTHORIZED);
// generic pages
bindPresenter(NotAuthorizedPresenter.class, NotAuthorizedPresenter.MyView.class, NotAuthorizedView.class, NotAuthorizedPresenter.MyProxy.class);
bindPresenter(NotFoundPresenter.class, NotFoundPresenter.MyView.class, NotFoundView.class, NotFoundPresenter.MyProxy.class);
bindPresenter(LogoutPresenter.class, LogoutPresenter.MyView.class, LogoutView.class, LogoutPresenter.MyProxy.class);
bindPresenter(NotUserPresenter.class, NotUserPresenter.MyView.class, NotUserView.class, NotUserPresenter.MyProxy.class);
} | @Override
protected void configure() {
install(new DefaultModule.Builder().placeManager(PerunPlaceManager.class).build());
bind(RootPresenter.class).to(PerunRootPresenter.class).asEagerSingleton();
bindPresenter(PerunCabinetPresenter.class, PerunCabinetPresenter.MyView.class, PerunCabinetView.class, PerunCabinetPresenter.MyProxy.class);
bindPresenter(PublicationsPresenter.class, PublicationsPresenter.MyView.class, PublicationsView.class, PublicationsPresenter.MyProxy.class);
bindPresenter(NewPublicationPresenter.class, NewPublicationPresenter.MyView.class, NewPublicationView.class, NewPublicationPresenter.MyProxy.class);
bindConstant().annotatedWith(DefaultPlace.class).to(PerunCabinetPlaceTokens.PUBLICATIONS);
bindConstant().annotatedWith(ErrorPlace.class).to(PerunCabinetPlaceTokens.NOT_FOUND);
bindConstant().annotatedWith(UnauthorizedPlace.class).to(PerunCabinetPlaceTokens.UNAUTHORIZED);
bindPresenter(NotAuthorizedPresenter.class, NotAuthorizedPresenter.MyView.class, NotAuthorizedView.class, NotAuthorizedPresenter.MyProxy.class);
bindPresenter(NotFoundPresenter.class, NotFoundPresenter.MyView.class, NotFoundView.class, NotFoundPresenter.MyProxy.class);
bindPresenter(LogoutPresenter.class, LogoutPresenter.MyView.class, LogoutView.class, LogoutPresenter.MyProxy.class);
bindPresenter(NotUserPresenter.class, NotUserPresenter.MyView.class, NotUserView.class, NotUserPresenter.MyProxy.class);
} | @override protected void configure() { install(new defaultmodule.builder().placemanager(perunplacemanager.class).build()); bind(rootpresenter.class).to(perunrootpresenter.class).aseagersingleton(); bindpresenter(peruncabinetpresenter.class, peruncabinetpresenter.myview.class, peruncabinetview.class, peruncabinetpresenter.myproxy.class); bindpresenter(publicationspresenter.class, publicationspresenter.myview.class, publicationsview.class, publicationspresenter.myproxy.class); bindpresenter(newpublicationpresenter.class, newpublicationpresenter.myview.class, newpublicationview.class, newpublicationpresenter.myproxy.class); bindconstant().annotatedwith(defaultplace.class).to(peruncabinetplacetokens.publications); bindconstant().annotatedwith(errorplace.class).to(peruncabinetplacetokens.not_found); bindconstant().annotatedwith(unauthorizedplace.class).to(peruncabinetplacetokens.unauthorized); bindpresenter(notauthorizedpresenter.class, notauthorizedpresenter.myview.class, notauthorizedview.class, notauthorizedpresenter.myproxy.class); bindpresenter(notfoundpresenter.class, notfoundpresenter.myview.class, notfoundview.class, notfoundpresenter.myproxy.class); bindpresenter(logoutpresenter.class, logoutpresenter.myview.class, logoutview.class, logoutpresenter.myproxy.class); bindpresenter(notuserpresenter.class, notuserpresenter.myview.class, notuserview.class, notuserpresenter.myproxy.class); } | Gaeldrin/perun-wui | [
0,
1,
0,
0
] |
3,131 | public CheckpointInfo restoreCheckpoint(ProcessKey processKey, UUID checkpointId) {
try (TemporaryPath checkpointArchive = IOUtils.tempFile("checkpoint", ".zip")) {
String checkpointName = export(processKey, checkpointId, checkpointArchive.path());
if (checkpointName == null) {
return null;
}
try (TemporaryPath extractedDir = IOUtils.tempDir("unzipped-checkpoint")) {
IOUtils.unzip(checkpointArchive.path(), extractedDir.path());
// TODO: only for v1 runtime
String eventName = readCheckpointEventName(extractedDir.path());
stateManager.tx(tx -> {
stateManager.deleteDirectory(tx, processKey, Constants.Files.CONCORD_SYSTEM_DIR_NAME);
stateManager.deleteDirectory(tx, processKey, Constants.Files.JOB_ATTACHMENTS_DIR_NAME);
stateManager.importPath(tx, processKey, null, extractedDir.path(), (p, attrs) -> true);
});
Map<String, Object> out = OutVariablesUtils.read(extractedDir.path().resolve(Constants.Files.JOB_ATTACHMENTS_DIR_NAME));
if (out.isEmpty()) {
queueDao.removeMeta(processKey, "out");
} else {
queueDao.updateMeta(processKey, Collections.singletonMap("out", out));
}
return CheckpointInfo.of(checkpointName, eventName);
}
} catch (Exception e) {
throw new RuntimeException("Restore checkpoint '" + checkpointId + "' error", e);
}
} | public CheckpointInfo restoreCheckpoint(ProcessKey processKey, UUID checkpointId) {
try (TemporaryPath checkpointArchive = IOUtils.tempFile("checkpoint", ".zip")) {
String checkpointName = export(processKey, checkpointId, checkpointArchive.path());
if (checkpointName == null) {
return null;
}
try (TemporaryPath extractedDir = IOUtils.tempDir("unzipped-checkpoint")) {
IOUtils.unzip(checkpointArchive.path(), extractedDir.path());
String eventName = readCheckpointEventName(extractedDir.path());
stateManager.tx(tx -> {
stateManager.deleteDirectory(tx, processKey, Constants.Files.CONCORD_SYSTEM_DIR_NAME);
stateManager.deleteDirectory(tx, processKey, Constants.Files.JOB_ATTACHMENTS_DIR_NAME);
stateManager.importPath(tx, processKey, null, extractedDir.path(), (p, attrs) -> true);
});
Map<String, Object> out = OutVariablesUtils.read(extractedDir.path().resolve(Constants.Files.JOB_ATTACHMENTS_DIR_NAME));
if (out.isEmpty()) {
queueDao.removeMeta(processKey, "out");
} else {
queueDao.updateMeta(processKey, Collections.singletonMap("out", out));
}
return CheckpointInfo.of(checkpointName, eventName);
}
} catch (Exception e) {
throw new RuntimeException("Restore checkpoint '" + checkpointId + "' error", e);
}
} | public checkpointinfo restorecheckpoint(processkey processkey, uuid checkpointid) { try (temporarypath checkpointarchive = ioutils.tempfile("checkpoint", ".zip")) { string checkpointname = export(processkey, checkpointid, checkpointarchive.path()); if (checkpointname == null) { return null; } try (temporarypath extracteddir = ioutils.tempdir("unzipped-checkpoint")) { ioutils.unzip(checkpointarchive.path(), extracteddir.path()); string eventname = readcheckpointeventname(extracteddir.path()); statemanager.tx(tx -> { statemanager.deletedirectory(tx, processkey, constants.files.concord_system_dir_name); statemanager.deletedirectory(tx, processkey, constants.files.job_attachments_dir_name); statemanager.importpath(tx, processkey, null, extracteddir.path(), (p, attrs) -> true); }); map<string, object> out = outvariablesutils.read(extracteddir.path().resolve(constants.files.job_attachments_dir_name)); if (out.isempty()) { queuedao.removemeta(processkey, "out"); } else { queuedao.updatemeta(processkey, collections.singletonmap("out", out)); } return checkpointinfo.of(checkpointname, eventname); } } catch (exception e) { throw new runtimeexception("restore checkpoint '" + checkpointid + "' error", e); } } | 700software/concord | [
1,
0,
0,
0
] |
19,591 | protected List createEmptyList() {
return new BackedList(this, contentList(), 0);
} | protected List createEmptyList() {
return new BackedList(this, contentList(), 0);
} | protected list createemptylist() { return new backedlist(this, contentlist(), 0); } | Gravitational-Field/Dive-In-Java | [
0,
0,
0,
0
] |
3,223 | protected void initFromRaFile() throws IOException {
// Central directory structure / central file header signature
int censig = raFile.readInt( fileOffset );
if( censig!=CENSIG ) {
throw new ZipException("expected CENSIC not found in central directory (at end of zip file)");
} else if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "found censigOffset=" + fileOffset );
}
short flag = raFile.readShort( fileOffset + 8 );
this.isEncrypted = (flag&1)>0;
this.fileNameLength = raFile.readShort( fileOffset + 28 );
byte[] fileNameBytes = raFile.readByteArray( fileOffset + 46, fileNameLength );
this.fileName = new String( fileNameBytes, AesZipFileDecrypter.charset );
if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "fileName = " + this.fileName );
}
this.extraFieldOffset = this.fileOffset + 46 + this.fileNameLength;
this.extraFieldLength = raFile.readShort( fileOffset + 30 );
this.localHeaderOffset = raFile.readInt( fileOffset + 28 + 14 );
if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "CDS - extraFieldOffset =" + Long.toHexString(this.extraFieldOffset) );
LOG.fine( "CDS - extraFieldLength =" + this.extraFieldLength );
LOG.fine( "CDS - localHeaderOffset=" + Long.toHexString(this.localHeaderOffset) );
}
// TODO - check, why we have to use the local header instead of the CDS sometimes...
if( this.isEncrypted ) {
byte[] efhid = raFile.readByteArray( this.extraFieldOffset, 2 );
if( efhid[0]!=0x01 || efhid[1]!=(byte)0x99 ) {
this.extraFieldOffset = localHeaderOffset+30+fileNameLength;
this.extraFieldLength = raFile.readShort( localHeaderOffset+28 );
if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "local header - extraFieldOffset=" + Long.toHexString(this.extraFieldOffset) );
LOG.fine( "local header - extraFieldLength=" + Long.toHexString(this.extraFieldLength) );
}
if( 0==extraFieldLength ) {
throw new ZipException("extra field is of length 0 - this is probably not a WinZip AES encrypted entry");
}
efhid = raFile.readByteArray( extraFieldOffset, 2);
if( efhid[0]==0x01 && efhid[1]==(byte)0x99 ) {
this.isAesEncrypted = true;
}
} else {
this.isAesEncrypted = true;
}
if( this.isAesEncrypted ) {
this.actualCompressionMethod = raFile.readShort( getExtraFieldOffset() + 9 );
this.localHeaderSize = 30 + getExtraFieldLength() + getFileNameLength();
}
}
this.compressedSize = raFile.readInt( fileOffset + 20 );
this.uncompressedSize = raFile.readInt( fileOffset + 24 );
} | protected void initFromRaFile() throws IOException {
int censig = raFile.readInt( fileOffset );
if( censig!=CENSIG ) {
throw new ZipException("expected CENSIC not found in central directory (at end of zip file)");
} else if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "found censigOffset=" + fileOffset );
}
short flag = raFile.readShort( fileOffset + 8 );
this.isEncrypted = (flag&1)>0;
this.fileNameLength = raFile.readShort( fileOffset + 28 );
byte[] fileNameBytes = raFile.readByteArray( fileOffset + 46, fileNameLength );
this.fileName = new String( fileNameBytes, AesZipFileDecrypter.charset );
if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "fileName = " + this.fileName );
}
this.extraFieldOffset = this.fileOffset + 46 + this.fileNameLength;
this.extraFieldLength = raFile.readShort( fileOffset + 30 );
this.localHeaderOffset = raFile.readInt( fileOffset + 28 + 14 );
if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "CDS - extraFieldOffset =" + Long.toHexString(this.extraFieldOffset) );
LOG.fine( "CDS - extraFieldLength =" + this.extraFieldLength );
LOG.fine( "CDS - localHeaderOffset=" + Long.toHexString(this.localHeaderOffset) );
}
if( this.isEncrypted ) {
byte[] efhid = raFile.readByteArray( this.extraFieldOffset, 2 );
if( efhid[0]!=0x01 || efhid[1]!=(byte)0x99 ) {
this.extraFieldOffset = localHeaderOffset+30+fileNameLength;
this.extraFieldLength = raFile.readShort( localHeaderOffset+28 );
if( LOG.isLoggable(Level.FINE) ) {
LOG.fine( "local header - extraFieldOffset=" + Long.toHexString(this.extraFieldOffset) );
LOG.fine( "local header - extraFieldLength=" + Long.toHexString(this.extraFieldLength) );
}
if( 0==extraFieldLength ) {
throw new ZipException("extra field is of length 0 - this is probably not a WinZip AES encrypted entry");
}
efhid = raFile.readByteArray( extraFieldOffset, 2);
if( efhid[0]==0x01 && efhid[1]==(byte)0x99 ) {
this.isAesEncrypted = true;
}
} else {
this.isAesEncrypted = true;
}
if( this.isAesEncrypted ) {
this.actualCompressionMethod = raFile.readShort( getExtraFieldOffset() + 9 );
this.localHeaderSize = 30 + getExtraFieldLength() + getFileNameLength();
}
}
this.compressedSize = raFile.readInt( fileOffset + 20 );
this.uncompressedSize = raFile.readInt( fileOffset + 24 );
} | protected void initfromrafile() throws ioexception { int censig = rafile.readint( fileoffset ); if( censig!=censig ) { throw new zipexception("expected censic not found in central directory (at end of zip file)"); } else if( log.isloggable(level.fine) ) { log.fine( "found censigoffset=" + fileoffset ); } short flag = rafile.readshort( fileoffset + 8 ); this.isencrypted = (flag&1)>0; this.filenamelength = rafile.readshort( fileoffset + 28 ); byte[] filenamebytes = rafile.readbytearray( fileoffset + 46, filenamelength ); this.filename = new string( filenamebytes, aeszipfiledecrypter.charset ); if( log.isloggable(level.fine) ) { log.fine( "filename = " + this.filename ); } this.extrafieldoffset = this.fileoffset + 46 + this.filenamelength; this.extrafieldlength = rafile.readshort( fileoffset + 30 ); this.localheaderoffset = rafile.readint( fileoffset + 28 + 14 ); if( log.isloggable(level.fine) ) { log.fine( "cds - extrafieldoffset =" + long.tohexstring(this.extrafieldoffset) ); log.fine( "cds - extrafieldlength =" + this.extrafieldlength ); log.fine( "cds - localheaderoffset=" + long.tohexstring(this.localheaderoffset) ); } if( this.isencrypted ) { byte[] efhid = rafile.readbytearray( this.extrafieldoffset, 2 ); if( efhid[0]!=0x01 || efhid[1]!=(byte)0x99 ) { this.extrafieldoffset = localheaderoffset+30+filenamelength; this.extrafieldlength = rafile.readshort( localheaderoffset+28 ); if( log.isloggable(level.fine) ) { log.fine( "local header - extrafieldoffset=" + long.tohexstring(this.extrafieldoffset) ); log.fine( "local header - extrafieldlength=" + long.tohexstring(this.extrafieldlength) ); } if( 0==extrafieldlength ) { throw new zipexception("extra field is of length 0 - this is probably not a winzip aes encrypted entry"); } efhid = rafile.readbytearray( extrafieldoffset, 2); if( efhid[0]==0x01 && efhid[1]==(byte)0x99 ) { this.isaesencrypted = true; } } else { this.isaesencrypted = true; } if( this.isaesencrypted ) { this.actualcompressionmethod = rafile.readshort( getextrafieldoffset() + 9 ); this.localheadersize = 30 + getextrafieldlength() + getfilenamelength(); } } this.compressedsize = rafile.readint( fileoffset + 20 ); this.uncompressedsize = rafile.readint( fileoffset + 24 ); } | CATION-M/X-moe | [
1,
0,
0,
0
] |
3,224 | public short getCryptoHeaderLength() {
// TODO support 128+192 byte keys reduces the salt byte size to 8+2 or 12+2
return 18;
} | public short getCryptoHeaderLength() {
return 18;
} | public short getcryptoheaderlength() { return 18; } | CATION-M/X-moe | [
0,
1,
0,
0
] |
11,510 | @Override
public Set< Justification > computeJustifications() {
Set< Set< OWLAxiom > > justifications = null;
try {
justifications = explainAxiom( axiom_ );
}
catch ( OWLException e ) {
throw new RuntimeException( e );
}
// We represent justifications as instances of a custom class outside of this function, which requires transitioning
// This is done in order to hide usage of the OWLAPI in code that does not need to rely directly on it.
Set< Justification > return_justifications = new TreeSet< Justification > (); // order is important for hitting set computation -> use TreeSet!
/* //TODO Use this if printing is not desired
for ( Set< OWLAxiom > justification : justifications ) {
// JAVA 8:
// justification.removeIf( ( OWLAxiom a ) -> { return a.isOfType( AxiomType.TBoxAndRBoxAxiomTypes ) } );
//
// JAVA < 8 (there is probably a better way even then):
for ( Iterator< OWLAxiom > it = justification.iterator(); it.hasNext(); ) {
OWLAxiom a = it.next();
if ( a.isOfType( AxiomType.TBoxAndRBoxAxiomTypes ) ) {
it.remove();
}
}
return_justifications.add( new Justification( justification ) );
}
*/
for ( Set< OWLAxiom > justification : justifications ) {
return_justifications.add( new Justification( justification ) );
}
//if ( SparqlUpdater.verbose_level > 0 ) {
//Justification.print( return_justifications, axiom_ );
//}
// We only consider ABox axioms for deletion. Therefore, we remove TBox and RBox assertions.
// TODO if printing is not desired, this loop can be combined with the one above and the method used here can be removed within the Justification class.
for ( Justification justification : return_justifications ) {
justification.removeTBoxAndRBoxAxioms();
}
return return_justifications;
} | @Override
public Set< Justification > computeJustifications() {
Set< Set< OWLAxiom > > justifications = null;
try {
justifications = explainAxiom( axiom_ );
}
catch ( OWLException e ) {
throw new RuntimeException( e );
}
Set< Justification > return_justifications = new TreeSet< Justification > ();
for ( Set< OWLAxiom > justification : justifications ) {
return_justifications.add( new Justification( justification ) );
}
for ( Justification justification : return_justifications ) {
justification.removeTBoxAndRBoxAxioms();
}
return return_justifications;
} | @override public set< justification > computejustifications() { set< set< owlaxiom > > justifications = null; try { justifications = explainaxiom( axiom_ ); } catch ( owlexception e ) { throw new runtimeexception( e ); } set< justification > return_justifications = new treeset< justification > (); for ( set< owlaxiom > justification : justifications ) { return_justifications.add( new justification( justification ) ); } for ( justification justification : return_justifications ) { justification.removetboxandrboxaxioms(); } return return_justifications; } | Institute-Web-Science-and-Technologies/SparqlUpdater | [
1,
0,
0,
0
] |
19,708 | public boolean canKick(String name) {
if (isFounder(name)) {
return true;
}
if (getRank(name) >= whoCanKick) {
return true;
}
return false;
} | public boolean canKick(String name) {
if (isFounder(name)) {
return true;
}
if (getRank(name) >= whoCanKick) {
return true;
}
return false;
} | public boolean cankick(string name) { if (isfounder(name)) { return true; } if (getrank(name) >= whocankick) { return true; } return false; } | CoderMMK/RSPS | [
0,
0,
0,
1
] |
19,709 | public boolean canBan(String name) {
if (isFounder(name)) {
return true;
}
if (getRank(name) >= whoCanBan) {
return true;
}
return false;
} | public boolean canBan(String name) {
if (isFounder(name)) {
return true;
}
if (getRank(name) >= whoCanBan) {
return true;
}
return false;
} | public boolean canban(string name) { if (isfounder(name)) { return true; } if (getrank(name) >= whocanban) { return true; } return false; } | CoderMMK/RSPS | [
0,
0,
0,
1
] |
3,404 | public void GetLiveTvProgramsAsync(ProgramQuery query, final Response<ItemsResult> response)
{
if (query == null)
{
throw new IllegalArgumentException("query");
}
QueryStringDictionary dict = new QueryStringDictionary ();
String isoDateFormat = "o";
if (query.getMaxEndDate() != null)
{
dict.Add("MaxEndDate", getIsoString(query.getMaxEndDate()));
}
if (query.getMaxStartDate() != null)
{
dict.Add("MaxStartDate", getIsoString(query.getMaxStartDate()));
}
if (query.getMinEndDate() != null)
{
dict.Add("MinEndDate", getIsoString(query.getMinEndDate()));
}
if (query.getMinStartDate() != null)
{
dict.Add("MinStartDate", getIsoString(query.getMinStartDate()));
}
if (!query.getEnableTotalRecordCount())
{
dict.Add("EnableTotalRecordCount", "false");
}
dict.AddIfNotNull("EnableImages", query.getEnableImages());
dict.AddIfNotNull("ImageTypeLimit", query.getImageTypeLimit());
dict.AddIfNotNull("EnableImageTypes", query.getEnableImageTypes());
dict.AddIfNotNull("Fields", query.getFields());
dict.AddIfNotNull("SortBy", query.getSortBy());
dict.AddIfNotNullOrEmpty("UserId", query.getUserId());
if (query.getChannelIds() != null)
{
dict.Add("ChannelIds", tangible.DotNetToJavaStringHelper.join(",", query.getChannelIds()));
}
// TODO: This endpoint supports POST if the query String is too long
String url = GetApiUrl("LiveTv/Programs", dict);
url = AddDataFormat(url);
Send(url, "GET", new SerializedResponse<>(response, jsonSerializer, ItemsResult.class));
} | public void GetLiveTvProgramsAsync(ProgramQuery query, final Response<ItemsResult> response)
{
if (query == null)
{
throw new IllegalArgumentException("query");
}
QueryStringDictionary dict = new QueryStringDictionary ();
String isoDateFormat = "o";
if (query.getMaxEndDate() != null)
{
dict.Add("MaxEndDate", getIsoString(query.getMaxEndDate()));
}
if (query.getMaxStartDate() != null)
{
dict.Add("MaxStartDate", getIsoString(query.getMaxStartDate()));
}
if (query.getMinEndDate() != null)
{
dict.Add("MinEndDate", getIsoString(query.getMinEndDate()));
}
if (query.getMinStartDate() != null)
{
dict.Add("MinStartDate", getIsoString(query.getMinStartDate()));
}
if (!query.getEnableTotalRecordCount())
{
dict.Add("EnableTotalRecordCount", "false");
}
dict.AddIfNotNull("EnableImages", query.getEnableImages());
dict.AddIfNotNull("ImageTypeLimit", query.getImageTypeLimit());
dict.AddIfNotNull("EnableImageTypes", query.getEnableImageTypes());
dict.AddIfNotNull("Fields", query.getFields());
dict.AddIfNotNull("SortBy", query.getSortBy());
dict.AddIfNotNullOrEmpty("UserId", query.getUserId());
if (query.getChannelIds() != null)
{
dict.Add("ChannelIds", tangible.DotNetToJavaStringHelper.join(",", query.getChannelIds()));
}
String url = GetApiUrl("LiveTv/Programs", dict);
url = AddDataFormat(url);
Send(url, "GET", new SerializedResponse<>(response, jsonSerializer, ItemsResult.class));
} | public void getlivetvprogramsasync(programquery query, final response<itemsresult> response) { if (query == null) { throw new illegalargumentexception("query"); } querystringdictionary dict = new querystringdictionary (); string isodateformat = "o"; if (query.getmaxenddate() != null) { dict.add("maxenddate", getisostring(query.getmaxenddate())); } if (query.getmaxstartdate() != null) { dict.add("maxstartdate", getisostring(query.getmaxstartdate())); } if (query.getminenddate() != null) { dict.add("minenddate", getisostring(query.getminenddate())); } if (query.getminstartdate() != null) { dict.add("minstartdate", getisostring(query.getminstartdate())); } if (!query.getenabletotalrecordcount()) { dict.add("enabletotalrecordcount", "false"); } dict.addifnotnull("enableimages", query.getenableimages()); dict.addifnotnull("imagetypelimit", query.getimagetypelimit()); dict.addifnotnull("enableimagetypes", query.getenableimagetypes()); dict.addifnotnull("fields", query.getfields()); dict.addifnotnull("sortby", query.getsortby()); dict.addifnotnullorempty("userid", query.getuserid()); if (query.getchannelids() != null) { dict.add("channelids", tangible.dotnettojavastringhelper.join(",", query.getchannelids())); } string url = getapiurl("livetv/programs", dict); url = adddataformat(url); send(url, "get", new serializedresponse<>(response, jsonserializer, itemsresult.class)); } | AndreasGB/jellyfin-apiclient-java | [
0,
1,
0,
0
] |
19,828 | @Test
public void testPositionConstructor() {
position = new Position(rowInRange, cellInRange);
// I know tests need to be independent but not sure how else to do this
assertEquals(rowInRange, position.getRow());
assertEquals(cellInRange, position.getCell());
} | @Test
public void testPositionConstructor() {
position = new Position(rowInRange, cellInRange);
assertEquals(rowInRange, position.getRow());
assertEquals(cellInRange, position.getCell());
} | @test public void testpositionconstructor() { position = new position(rowinrange, cellinrange); assertequals(rowinrange, position.getrow()); assertequals(cellinrange, position.getcell()); } | DaniloSosa98/SE-WebCheckers | [
1,
0,
0,
0
] |
11,711 | @GET
@Path("{connectorId}/contents")
public Response getTypedContent(@PathParam("connectorId") long connectorId, @QueryParam("nodeId") String nodeId, @QueryParam("type") ConnectorNodeType type) {
Connector connector = getConnector(connectorId);
InputStream content = connector.getContent(new ConnectorNode(nodeId, null, type));
if (content == null) {
return JaxRsUtil.createResponse().status(Response.Status.NOT_FOUND).build();
}
// nre: TODO: Why not guess by extension?
try {
return JaxRsUtil.createResponse().status(Status.OK).entity(IoUtil.readInputStream(content, connectorId + "-" + nodeId + "-content-stream"))
.header("Content-Type", type.getMimeType())
.build();
} finally {
IoUtil.closeSilently(content);
}
} | @GET
@Path("{connectorId}/contents")
public Response getTypedContent(@PathParam("connectorId") long connectorId, @QueryParam("nodeId") String nodeId, @QueryParam("type") ConnectorNodeType type) {
Connector connector = getConnector(connectorId);
InputStream content = connector.getContent(new ConnectorNode(nodeId, null, type));
if (content == null) {
return JaxRsUtil.createResponse().status(Response.Status.NOT_FOUND).build();
}
try {
return JaxRsUtil.createResponse().status(Status.OK).entity(IoUtil.readInputStream(content, connectorId + "-" + nodeId + "-content-stream"))
.header("Content-Type", type.getMimeType())
.build();
} finally {
IoUtil.closeSilently(content);
}
} | @get @path("{connectorid}/contents") public response gettypedcontent(@pathparam("connectorid") long connectorid, @queryparam("nodeid") string nodeid, @queryparam("type") connectornodetype type) { connector connector = getconnector(connectorid); inputstream content = connector.getcontent(new connectornode(nodeid, null, type)); if (content == null) { return jaxrsutil.createresponse().status(response.status.not_found).build(); } try { return jaxrsutil.createresponse().status(status.ok).entity(ioutil.readinputstream(content, connectorid + "-" + nodeid + "-content-stream")) .header("content-type", type.getmimetype()) .build(); } finally { ioutil.closesilently(content); } } | 1and1/camunda-bpm-platform | [
1,
0,
0,
0
] |
3,528 | private Complex getFeederLoadVA(String sourceBusId) {
Bus3Phase sourceBus = (Bus3Phase) this.net.getBus(sourceBusId);
Complex3x1 vabc_1 = sourceBus.get3PhaseVotlages();
Complex3x1 currInj3Phase = new Complex3x1();
for(Branch bra: sourceBus.getConnectedPhysicalBranchList()){
if(bra.isActive()){
Branch3Phase acLine = (Branch3Phase) bra;
Complex3x1 Isource = null;
if(bra.getFromBus().getId().equals(sourceBus.getId())){
Bus3Phase toBus = (Bus3Phase) bra.getToBus();
Complex3x1 vabc_2 = toBus.get3PhaseVotlages();
Complex3x3 Yft = acLine.getYftabc();
Complex3x3 Yff = acLine.getYffabc();
Isource = Yff.multiply(vabc_1).add(Yft.multiply(vabc_2));
currInj3Phase = currInj3Phase.subtract(Isource );
}
else{
Bus3Phase fromBus = (Bus3Phase) bra.getFromBus();
Complex3x1 vabc_2 = fromBus.get3PhaseVotlages();
Complex3x3 Ytf = acLine.getYtfabc();
Complex3x3 Ytt = acLine.getYttabc();
Isource = Ytt.multiply(vabc_1).add(Ytf.multiply(vabc_2));
currInj3Phase = currInj3Phase.subtract(Isource);
}
}
}
//TODO this needs to be updated if actual values are used in the distribution system
double distVABase = this.net.getBaseMva()*1.0E6;
Bus3Phase sourceBus3Ph = (Bus3Phase) sourceBus;
// from distribution to transmission
Complex totalPower = sourceBus3Ph.get3PhaseVotlages().dotProduct(currInj3Phase.conjugate()).divide(3.0).multiply(distVABase);
return totalPower.multiply(-1.0);
} | private Complex getFeederLoadVA(String sourceBusId) {
Bus3Phase sourceBus = (Bus3Phase) this.net.getBus(sourceBusId);
Complex3x1 vabc_1 = sourceBus.get3PhaseVotlages();
Complex3x1 currInj3Phase = new Complex3x1();
for(Branch bra: sourceBus.getConnectedPhysicalBranchList()){
if(bra.isActive()){
Branch3Phase acLine = (Branch3Phase) bra;
Complex3x1 Isource = null;
if(bra.getFromBus().getId().equals(sourceBus.getId())){
Bus3Phase toBus = (Bus3Phase) bra.getToBus();
Complex3x1 vabc_2 = toBus.get3PhaseVotlages();
Complex3x3 Yft = acLine.getYftabc();
Complex3x3 Yff = acLine.getYffabc();
Isource = Yff.multiply(vabc_1).add(Yft.multiply(vabc_2));
currInj3Phase = currInj3Phase.subtract(Isource );
}
else{
Bus3Phase fromBus = (Bus3Phase) bra.getFromBus();
Complex3x1 vabc_2 = fromBus.get3PhaseVotlages();
Complex3x3 Ytf = acLine.getYtfabc();
Complex3x3 Ytt = acLine.getYttabc();
Isource = Ytt.multiply(vabc_1).add(Ytf.multiply(vabc_2));
currInj3Phase = currInj3Phase.subtract(Isource);
}
}
}
double distVABase = this.net.getBaseMva()*1.0E6;
Bus3Phase sourceBus3Ph = (Bus3Phase) sourceBus;
Complex totalPower = sourceBus3Ph.get3PhaseVotlages().dotProduct(currInj3Phase.conjugate()).divide(3.0).multiply(distVABase);
return totalPower.multiply(-1.0);
} | private complex getfeederloadva(string sourcebusid) { bus3phase sourcebus = (bus3phase) this.net.getbus(sourcebusid); complex3x1 vabc_1 = sourcebus.get3phasevotlages(); complex3x1 currinj3phase = new complex3x1(); for(branch bra: sourcebus.getconnectedphysicalbranchlist()){ if(bra.isactive()){ branch3phase acline = (branch3phase) bra; complex3x1 isource = null; if(bra.getfrombus().getid().equals(sourcebus.getid())){ bus3phase tobus = (bus3phase) bra.gettobus(); complex3x1 vabc_2 = tobus.get3phasevotlages(); complex3x3 yft = acline.getyftabc(); complex3x3 yff = acline.getyffabc(); isource = yff.multiply(vabc_1).add(yft.multiply(vabc_2)); currinj3phase = currinj3phase.subtract(isource ); } else{ bus3phase frombus = (bus3phase) bra.getfrombus(); complex3x1 vabc_2 = frombus.get3phasevotlages(); complex3x3 ytf = acline.getytfabc(); complex3x3 ytt = acline.getyttabc(); isource = ytt.multiply(vabc_1).add(ytf.multiply(vabc_2)); currinj3phase = currinj3phase.subtract(isource); } } } double distvabase = this.net.getbasemva()*1.0e6; bus3phase sourcebus3ph = (bus3phase) sourcebus; complex totalpower = sourcebus3ph.get3phasevotlages().dotproduct(currinj3phase.conjugate()).divide(3.0).multiply(distvabase); return totalpower.multiply(-1.0); } | GMLC-TDC/Use-Cases | [
1,
0,
0,
0
] |
11,856 | @Override
public <K> void executeTask(
final AdvancedCacheLoader.KeyFilter<K> filter,
final ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry> action
) throws InterruptedException{
if (filter == null)
throw new IllegalArgumentException("No filter specified");
if (action == null)
throw new IllegalArgumentException("No action specified");
ParallelIterableMap<Object, InternalCacheEntry> map =
(ParallelIterableMap<Object, InternalCacheEntry>) entries;
map.forEach(512, new ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry>() {
@Override
public void apply(Object o, InternalCacheEntry internalCacheEntry) {
}
// @Override
// public void apply(Object key, OffHeapInternalCacheEntry value) {
// if (filter.shouldLoadKey((K)key)) {
// action.apply((K)key, value);
// }
// }
});
//TODO figure out the way how to do interruption better (during iteration)
if(Thread.currentThread().isInterrupted()){
throw new InterruptedException();
}
} | @Override
public <K> void executeTask(
final AdvancedCacheLoader.KeyFilter<K> filter,
final ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry> action
) throws InterruptedException{
if (filter == null)
throw new IllegalArgumentException("No filter specified");
if (action == null)
throw new IllegalArgumentException("No action specified");
ParallelIterableMap<Object, InternalCacheEntry> map =
(ParallelIterableMap<Object, InternalCacheEntry>) entries;
map.forEach(512, new ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry>() {
@Override
public void apply(Object o, InternalCacheEntry internalCacheEntry) {
}
});
if(Thread.currentThread().isInterrupted()){
throw new InterruptedException();
}
} | @override public <k> void executetask( final advancedcacheloader.keyfilter<k> filter, final paralleliterablemap.keyvalueaction<object, internalcacheentry> action ) throws interruptedexception{ if (filter == null) throw new illegalargumentexception("no filter specified"); if (action == null) throw new illegalargumentexception("no action specified"); paralleliterablemap<object, internalcacheentry> map = (paralleliterablemap<object, internalcacheentry>) entries; map.foreach(512, new paralleliterablemap.keyvalueaction<object, internalcacheentry>() { @override public void apply(object o, internalcacheentry internalcacheentry) { } }); if(thread.currentthread().isinterrupted()){ throw new interruptedexception(); } } | Cotton-Ben/infinispan | [
1,
0,
0,
0
] |
11,891 | @Override
public final V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
Iterator<Integer> indexItr = order.iterator();
V result = initResult();
for (Future<K> future : futures) {
// TODO: the max time this can take is actually N * timeout. Consider fixing this.
result = aggregate(future.get(timeout, unit), indexItr, result);
}
return result;
} | @Override
public final V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
Iterator<Integer> indexItr = order.iterator();
V result = initResult();
for (Future<K> future : futures) {
result = aggregate(future.get(timeout, unit), indexItr, result);
}
return result;
} | @override public final v get(long timeout, timeunit unit) throws interruptedexception, executionexception, timeoutexception { iterator<integer> indexitr = order.iterator(); v result = initresult(); for (future<k> future : futures) { result = aggregate(future.get(timeout, unit), indexitr, result); } return result; } | CyberFlameGO/appengine-java-standard | [
1,
0,
0,
0
] |
11,905 | private void processCommands(GuildMessageReceivedEvent event, GuildData guildData, String trigger, String[] args, boolean isMention) {
ICommandMain cmd = CascadeBot.INS.getCommandManager().getCommand(trigger, event.getAuthor(), guildData);
if (cmd != null) {
if (cmd.getModule().isPublicModule() &&
!guildData.isModuleEnabled(cmd.getModule())) {
if (guildData.getSettings().willDisplayModuleErrors() || Environment.isDevelopment()) {
EmbedBuilder builder = MessagingObjects.getClearThreadLocalEmbedBuilder();
builder.setDescription(String.format("The module `%s` for command `%s` is disabled!", cmd.getModule().toString(), trigger));
builder.setTimestamp(Instant.now());
builder.setFooter("Requested by " + event.getAuthor().getAsTag(), event.getAuthor().getEffectiveAvatarUrl());
Messaging.sendDangerMessage(event.getChannel(), builder, guildData.getSettings().useEmbedForMessages());
}
// TODO: Modlog?
return;
}
CommandContext context = new CommandContext(
event.getJDA(),
event.getChannel(),
event.getMessage(),
event.getGuild(),
guildData,
args,
event.getMember(),
trigger,
isMention
);
if (args.length >= 1) {
if (processSubCommands(cmd, args, context)) {
return;
}
}
dispatchCommand(cmd, context);
}
} | private void processCommands(GuildMessageReceivedEvent event, GuildData guildData, String trigger, String[] args, boolean isMention) {
ICommandMain cmd = CascadeBot.INS.getCommandManager().getCommand(trigger, event.getAuthor(), guildData);
if (cmd != null) {
if (cmd.getModule().isPublicModule() &&
!guildData.isModuleEnabled(cmd.getModule())) {
if (guildData.getSettings().willDisplayModuleErrors() || Environment.isDevelopment()) {
EmbedBuilder builder = MessagingObjects.getClearThreadLocalEmbedBuilder();
builder.setDescription(String.format("The module `%s` for command `%s` is disabled!", cmd.getModule().toString(), trigger));
builder.setTimestamp(Instant.now());
builder.setFooter("Requested by " + event.getAuthor().getAsTag(), event.getAuthor().getEffectiveAvatarUrl());
Messaging.sendDangerMessage(event.getChannel(), builder, guildData.getSettings().useEmbedForMessages());
}
return;
}
CommandContext context = new CommandContext(
event.getJDA(),
event.getChannel(),
event.getMessage(),
event.getGuild(),
guildData,
args,
event.getMember(),
trigger,
isMention
);
if (args.length >= 1) {
if (processSubCommands(cmd, args, context)) {
return;
}
}
dispatchCommand(cmd, context);
}
} | private void processcommands(guildmessagereceivedevent event, guilddata guilddata, string trigger, string[] args, boolean ismention) { icommandmain cmd = cascadebot.ins.getcommandmanager().getcommand(trigger, event.getauthor(), guilddata); if (cmd != null) { if (cmd.getmodule().ispublicmodule() && !guilddata.ismoduleenabled(cmd.getmodule())) { if (guilddata.getsettings().willdisplaymoduleerrors() || environment.isdevelopment()) { embedbuilder builder = messagingobjects.getclearthreadlocalembedbuilder(); builder.setdescription(string.format("the module `%s` for command `%s` is disabled!", cmd.getmodule().tostring(), trigger)); builder.settimestamp(instant.now()); builder.setfooter("requested by " + event.getauthor().getastag(), event.getauthor().geteffectiveavatarurl()); messaging.senddangermessage(event.getchannel(), builder, guilddata.getsettings().useembedformessages()); } return; } commandcontext context = new commandcontext( event.getjda(), event.getchannel(), event.getmessage(), event.getguild(), guilddata, args, event.getmember(), trigger, ismention ); if (args.length >= 1) { if (processsubcommands(cmd, args, context)) { return; } } dispatchcommand(cmd, context); } } | Ikinon/CascadeBot | [
0,
1,
0,
0
] |
3,730 | @Override
public MutableList<T> clone()
{
return new FastList<T>(this);
} | @Override
public MutableList<T> clone()
{
return new FastList<T>(this);
} | @override public mutablelist<t> clone() { return new fastlist<t>(this); } | DiegoEliasCosta/gs-collections | [
1,
0,
0,
0
] |
3,764 | @PostMapping("{id}/bloqueio")
public ResponseEntity<?> bloquear(HttpServletRequest request, @PathVariable String id){
String ip = request.getRemoteAddr();
String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
Optional<Proposta> possivelProposta = propostaRepository.findByNumeroCartao(id);
if(possivelProposta.isEmpty()){
logger.info("Tentativa de bloqueio, cartao: {} não encontrado", id);
return ResponseEntity.notFound().build();
}
Proposta proposta = possivelProposta.get();
if(proposta.estaBloqueado()){
logger.info("Tentativa de bloqueio, cartao: {} já bloqueado", id);
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
if(!notificarLegado(id)){
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("message", "Não foi possivel concluir a ação, tente mais tarde"));
}
proposta.bloquear(ip, userAgent);
propostaRepository.save(proposta);
logger.info("Cartão: {} bloqueado com sucesso", id);
return ResponseEntity.ok().build();
} | @PostMapping("{id}/bloqueio")
public ResponseEntity<?> bloquear(HttpServletRequest request, @PathVariable String id){
String ip = request.getRemoteAddr();
String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
Optional<Proposta> possivelProposta = propostaRepository.findByNumeroCartao(id);
if(possivelProposta.isEmpty()){
logger.info("Tentativa de bloqueio, cartao: {} não encontrado", id);
return ResponseEntity.notFound().build();
}
Proposta proposta = possivelProposta.get();
if(proposta.estaBloqueado()){
logger.info("Tentativa de bloqueio, cartao: {} já bloqueado", id);
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
if(!notificarLegado(id)){
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("message", "Não foi possivel concluir a ação, tente mais tarde"));
}
proposta.bloquear(ip, userAgent);
propostaRepository.save(proposta);
logger.info("Cartão: {} bloqueado com sucesso", id);
return ResponseEntity.ok().build();
} | @postmapping("{id}/bloqueio") public responseentity<?> bloquear(httpservletrequest request, @pathvariable string id){ string ip = request.getremoteaddr(); string useragent = request.getheader(httpheaders.user_agent); optional<proposta> possivelproposta = propostarepository.findbynumerocartao(id); if(possivelproposta.isempty()){ logger.info("tentativa de bloqueio, cartao: {} não encontrado", id); return responseentity.notfound().build(); } proposta proposta = possivelproposta.get(); if(proposta.establoqueado()){ logger.info("tentativa de bloqueio, cartao: {} já bloqueado", id); return responseentity.status(httpstatus.unprocessable_entity).build(); } if(!notificarlegado(id)){ return responseentity.status(httpstatus.bad_gateway) .body(map.of("message", "não foi possivel concluir a ação, tente mais tarde")); } proposta.bloquear(ip, useragent); propostarepository.save(proposta); logger.info("cartão: {} bloqueado com sucesso", id); return responseentity.ok().build(); } | EDUMATT3/orange-talents-06-template-proposta | [
1,
0,
0,
0
] |
20,267 | @Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_to_this_address_action: {
if (onSendToAddressClickListener != null) {
onSendToAddressClickListener.onClick(view);
}
break;
}
case R.id.add_custom_token_action: {
if (onAddCustonTokenClickListener != null) {
onAddCustonTokenClickListener.onClick(view);
}
break;
}
case R.id.watch_account_action: {
if (onWatchWalletClickListener != null) {
onWatchWalletClickListener.onClick(view);
}
break;
}
case R.id.open_in_etherscan_action: {
if (onOpenInEtherscanClickListener != null) {
onOpenInEtherscanClickListener.onClick(view);
}
break;
}
case R.id.close_action: {
if (onCloseActionListener != null) {
onCloseActionListener.onClick(view);
}
break;
}
}
} | @Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_to_this_address_action: {
if (onSendToAddressClickListener != null) {
onSendToAddressClickListener.onClick(view);
}
break;
}
case R.id.add_custom_token_action: {
if (onAddCustonTokenClickListener != null) {
onAddCustonTokenClickListener.onClick(view);
}
break;
}
case R.id.watch_account_action: {
if (onWatchWalletClickListener != null) {
onWatchWalletClickListener.onClick(view);
}
break;
}
case R.id.open_in_etherscan_action: {
if (onOpenInEtherscanClickListener != null) {
onOpenInEtherscanClickListener.onClick(view);
}
break;
}
case R.id.close_action: {
if (onCloseActionListener != null) {
onCloseActionListener.onClick(view);
}
break;
}
}
} | @override public void onclick(view view) { switch (view.getid()) { case r.id.send_to_this_address_action: { if (onsendtoaddressclicklistener != null) { onsendtoaddressclicklistener.onclick(view); } break; } case r.id.add_custom_token_action: { if (onaddcustontokenclicklistener != null) { onaddcustontokenclicklistener.onclick(view); } break; } case r.id.watch_account_action: { if (onwatchwalletclicklistener != null) { onwatchwalletclicklistener.onclick(view); } break; } case r.id.open_in_etherscan_action: { if (onopeninetherscanclicklistener != null) { onopeninetherscanclicklistener.onclick(view); } break; } case r.id.close_action: { if (oncloseactionlistener != null) { oncloseactionlistener.onclick(view); } break; } } } | HTSUPK/alpha-wallet-android | [
1,
0,
0,
0
] |
20,270 | private void processRequest(@NotNull HttpServletRequest req) throws BadRequestException {
if (!EXPECTED_CONTENT_TYPE.isSameMimeType(ContentType.parse(req.getContentType()))) {
throw new BadRequestException("Content type must be '%s'.".formatted(EXPECTED_CONTENT_TYPE.getMimeType()));
}
URI source = extractParameterAsUri(req, "source");
URI target = extractParameterAsUri(req, "target");
// Spec: 'The receiver MUST reject the request if the source URL is the same as the target URL.'
if (source.equals(target)) {
throw new BadRequestException("Source and target URL must not be identical.");
}
// TODO: allow configuration of allowed target URI hosts.
LOGGER.debug("Received webmention submission request with source='{}' and target='{}'.", source, target);
// TODO: perform check async
/*
* Spec:
* 'If the receiver is going to use the Webmention in some way, (displaying it as a comment on a post,
* incrementing a "like" counter, notifying the author of a post), then it MUST perform an HTTP GET request
* on source [...] to confirm that it actually mentions the target.
*/
try {
if (verificationService.isSubmissionValid(httpClient, source, target)) {
LOGGER.debug("Webmention submission request with source='{}' and target='{}' passed verification.",
source,
target);
} else {
throw new BadRequestException("Source does not contain link to target URL.");
}
} catch (IOException e) {
// In theory I/O failures cold also be issues on our side (e.g. trusted CAs being wrong), but
// differentiating between those and issues on the source URIs side (e.g. 404s) seems hard.
throw new BadRequestException("Verification of source URL could not be performed.", e);
} catch (VerificationService.UnsupportedContentTypeException e) {
throw new BadRequestException(
"Verification of source URL failed due to no supported content type being served.",
e);
}
handleSubmission(source, target);
} | private void processRequest(@NotNull HttpServletRequest req) throws BadRequestException {
if (!EXPECTED_CONTENT_TYPE.isSameMimeType(ContentType.parse(req.getContentType()))) {
throw new BadRequestException("Content type must be '%s'.".formatted(EXPECTED_CONTENT_TYPE.getMimeType()));
}
URI source = extractParameterAsUri(req, "source");
URI target = extractParameterAsUri(req, "target");
if (source.equals(target)) {
throw new BadRequestException("Source and target URL must not be identical.");
}
LOGGER.debug("Received webmention submission request with source='{}' and target='{}'.", source, target);
try {
if (verificationService.isSubmissionValid(httpClient, source, target)) {
LOGGER.debug("Webmention submission request with source='{}' and target='{}' passed verification.",
source,
target);
} else {
throw new BadRequestException("Source does not contain link to target URL.");
}
} catch (IOException e) {
throw new BadRequestException("Verification of source URL could not be performed.", e);
} catch (VerificationService.UnsupportedContentTypeException e) {
throw new BadRequestException(
"Verification of source URL failed due to no supported content type being served.",
e);
}
handleSubmission(source, target);
} | private void processrequest(@notnull httpservletrequest req) throws badrequestexception { if (!expected_content_type.issamemimetype(contenttype.parse(req.getcontenttype()))) { throw new badrequestexception("content type must be '%s'.".formatted(expected_content_type.getmimetype())); } uri source = extractparameterasuri(req, "source"); uri target = extractparameterasuri(req, "target"); if (source.equals(target)) { throw new badrequestexception("source and target url must not be identical."); } logger.debug("received webmention submission request with source='{}' and target='{}'.", source, target); try { if (verificationservice.issubmissionvalid(httpclient, source, target)) { logger.debug("webmention submission request with source='{}' and target='{}' passed verification.", source, target); } else { throw new badrequestexception("source does not contain link to target url."); } } catch (ioexception e) { throw new badrequestexception("verification of source url could not be performed.", e); } catch (verificationservice.unsupportedcontenttypeexception e) { throw new badrequestexception( "verification of source url failed due to no supported content type being served.", e); } handlesubmission(source, target); } | FelixRilling/webmention4j | [
1,
1,
0,
0
] |
20,319 | @BeforeEach
public void setUp() throws Exception {
// Hack our RouteBuilder into the context. Bean definition / ComponentScan doesn't work for RouteBuilders.
if (camelContext.getRoute(CamelCustomerRatingServiceAdapter.URI) == null) {
camelContext.addRoutes(ccrsAdapter);
}
if (camelContext.getRoute(CamelCustomerRatingServiceClient.URI) == null) {
camelContext.addRoutes(ccrsClient);
}
} | @BeforeEach
public void setUp() throws Exception {
if (camelContext.getRoute(CamelCustomerRatingServiceAdapter.URI) == null) {
camelContext.addRoutes(ccrsAdapter);
}
if (camelContext.getRoute(CamelCustomerRatingServiceClient.URI) == null) {
camelContext.addRoutes(ccrsClient);
}
} | @beforeeach public void setup() throws exception { if (camelcontext.getroute(camelcustomerratingserviceadapter.uri) == null) { camelcontext.addroutes(ccrsadapter); } if (camelcontext.getroute(camelcustomerratingserviceclient.uri) == null) { camelcontext.addroutes(ccrsclient); } } | BertKoor/camelCase | [
0,
0,
1,
0
] |
20,732 | public static void exportTaskgraph() {
final TFileChooser fc = new TFileChooser(EXPORT_TASKGRAPH_DIR);
final FileImportExportDecorator chooser = new FileImportExportDecorator(fc);
int result = chooser.showExportDialog(GUIEnv.getApplicationFrame());
if (result == TFileChooser.APPROVE_OPTION) {
Thread thread = new Thread() {
public void run() {
TrianaProgressBar pb = null;
String filename = "";
try {
// Bug fix for not picking up file name text.
if (fc.getUI() instanceof BasicFileChooserUI) {
filename = ((BasicFileChooserUI) fc.getUI()).getFileName();
}
pb = new TrianaProgressBar("exporting: " + filename, false);
chooser.exportWorkflow(GUIEnv.getApplicationFrame().getSelectedTaskGraphPanel().getTaskGraph());
} catch (IOException e) {
ErrorDialog.show("Error Exporting TaskGraph", e.getMessage());
e.printStackTrace();
} catch (TaskGraphException e) {
ErrorDialog.show("Error Exporting TaskGraph", e.getMessage());
e.printStackTrace();
} finally {
if (pb != null) {
pb.disposeProgressBar();
}
}
}
};
thread.setName("Export Task Graph");
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
} | public static void exportTaskgraph() {
final TFileChooser fc = new TFileChooser(EXPORT_TASKGRAPH_DIR);
final FileImportExportDecorator chooser = new FileImportExportDecorator(fc);
int result = chooser.showExportDialog(GUIEnv.getApplicationFrame());
if (result == TFileChooser.APPROVE_OPTION) {
Thread thread = new Thread() {
public void run() {
TrianaProgressBar pb = null;
String filename = "";
try {
if (fc.getUI() instanceof BasicFileChooserUI) {
filename = ((BasicFileChooserUI) fc.getUI()).getFileName();
}
pb = new TrianaProgressBar("exporting: " + filename, false);
chooser.exportWorkflow(GUIEnv.getApplicationFrame().getSelectedTaskGraphPanel().getTaskGraph());
} catch (IOException e) {
ErrorDialog.show("Error Exporting TaskGraph", e.getMessage());
e.printStackTrace();
} catch (TaskGraphException e) {
ErrorDialog.show("Error Exporting TaskGraph", e.getMessage());
e.printStackTrace();
} finally {
if (pb != null) {
pb.disposeProgressBar();
}
}
}
};
thread.setName("Export Task Graph");
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
} | public static void exporttaskgraph() { final tfilechooser fc = new tfilechooser(export_taskgraph_dir); final fileimportexportdecorator chooser = new fileimportexportdecorator(fc); int result = chooser.showexportdialog(guienv.getapplicationframe()); if (result == tfilechooser.approve_option) { thread thread = new thread() { public void run() { trianaprogressbar pb = null; string filename = ""; try { if (fc.getui() instanceof basicfilechooserui) { filename = ((basicfilechooserui) fc.getui()).getfilename(); } pb = new trianaprogressbar("exporting: " + filename, false); chooser.exportworkflow(guienv.getapplicationframe().getselectedtaskgraphpanel().gettaskgraph()); } catch (ioexception e) { errordialog.show("error exporting taskgraph", e.getmessage()); e.printstacktrace(); } catch (taskgraphexception e) { errordialog.show("error exporting taskgraph", e.getmessage()); e.printstacktrace(); } finally { if (pb != null) { pb.disposeprogressbar(); } } } }; thread.setname("export task graph"); thread.setpriority(thread.norm_priority); thread.start(); } } | CSCSI/Triana | [
0,
0,
1,
0
] |
20,999 | @Override
public KVMessage putKV(final int clientPort, final String key, final String value)
throws InvalidMessageException {
logger.info(clientPort + "> PUT for key=" + key + " value=" + value);
KVMessage res;
StatusType putStat;
// TODO: Cleanup the clientRequests after the requests are completed
clientRequests.putIfAbsent(key, new ConcurrentNode(MAX_READS));
NodeOperation op = value.equals("null") ? NodeOperation.DELETE : NodeOperation.WRITE;
// add thread to back of list for this key - add is thread safe
int[] node = { clientPort, op.getVal() };
clientRequests.get(key).addToQueue(node);
if (test) {
logger.info(clientPort + "> !!!!===wait===!!!!");
while (wait)
;
logger.info(clientPort + "> !!!!===DONE WAITING===!!!!");
}
// wait (spin) until threads turn and no one is reading
// TODO: If a key gets deleted, I think clientRequests.get(key) would no longer
// work
while (clientRequests.get(key).peek()[0] != clientPort)
;
// while (clientRequests.get(key).peek()[0] != clientPort ||
// clientRequests.get(key).availablePermits() != MAX_READS);
logger.info(clientPort + "> !!!!===Finished spinning===!!!!");
if (value.equals("null")) {
// Delete the key
logger.info(clientPort + "> Trying to delete record ...");
putStat = StatusType.DELETE_SUCCESS;
try {
// TODO: Mark it as deleted then loop to see if anybody is reading/writing to it
// If a write is after, keep the row by unmarking it as deleted (since the
// operation cancels)
// If a read is after, check the deleted flag, if its deleted, make sure to
// return key DNE
// Otherwise, return the key
// If at any point the queue is empty, and the row is marked as deleted, THEN
// remove it from the clientRequests
// Delete it from the cache as well!
// remove the top item from the list for this key
if (!inStorage(key)) {
logger.info(clientPort + "> Not in storage ...");
putStat = StatusType.DELETE_ERROR;
} else if (!clientRequests.get(key).isDeleted()) {
logger.info(clientPort + "> Marked for deletion");
clientRequests.get(key).setDeleted(true);
Runnable pruneDelete = new Runnable() {
@Override
public void run() {
logger.info(clientPort + "> Starting pruning thread");
do {
// logger.debug("Prune waiting");
} while (!clientRequests.get(key).isEmpty());
clientRequests.remove(key);
if (cache != null) {
cache.remove(key);
}
File file = new File(storageDirectory + key);
file.delete();
logger.info(clientPort + "> " + key + " successfully pruned");
}
};
clientRequests.get(key).startPruning(pruneDelete);
} else {
logger.info(clientPort + "> Key does not exist - marked for deletion!");
putStat = StatusType.DELETE_ERROR;
}
} catch (Exception e) {
logger.info(clientPort + "> Deletion exception ...");
logger.error(e);
exceptionLogger(e);
putStat = StatusType.DELETE_ERROR;
}
} else {
// Insert/update the key
logger.info(clientPort + "> Trying to insert/update record");
try {
if (!inStorage(key)) {
// Inserting a new key
logger.info(clientPort + "> Going to insert record");
putStat = StatusType.PUT_SUCCESS;
} else {
// Updating a key
logger.info(clientPort + "> Going to update record");
putStat = StatusType.PUT_UPDATE;
if (clientRequests.get(key).isDeleted()) {
// Stop the deletion
clientRequests.get(key).stopPruning();
clientRequests.get(key).setDeleted(false);
}
}
insertCache(key, value);
FileWriter myWriter = new FileWriter(storageDirectory + key);
myWriter.write(value);
myWriter.close();
// Sleep for a bit to let data take effect
// Thread.sleep(1000);
} catch (Exception e) {
logger.error(e);
exceptionLogger(e);
putStat = StatusType.PUT_ERROR;
}
}
// remove the top item from the list for this key
removeTopQueue(key);
logger.info(clientPort + "> !!!!===Removing from queue===!!!!");
try {
res = new KVMessage(key, value, putStat);
} catch (InvalidMessageException ime) {
throw ime;
}
return res;
} | @Override
public KVMessage putKV(final int clientPort, final String key, final String value)
throws InvalidMessageException {
logger.info(clientPort + "> PUT for key=" + key + " value=" + value);
KVMessage res;
StatusType putStat;
clientRequests.putIfAbsent(key, new ConcurrentNode(MAX_READS));
NodeOperation op = value.equals("null") ? NodeOperation.DELETE : NodeOperation.WRITE;
int[] node = { clientPort, op.getVal() };
clientRequests.get(key).addToQueue(node);
if (test) {
logger.info(clientPort + "> !!!!===wait===!!!!");
while (wait)
;
logger.info(clientPort + "> !!!!===DONE WAITING===!!!!");
}
while (clientRequests.get(key).peek()[0] != clientPort)
;
logger.info(clientPort + "> !!!!===Finished spinning===!!!!");
if (value.equals("null")) {
logger.info(clientPort + "> Trying to delete record ...");
putStat = StatusType.DELETE_SUCCESS;
try {
if (!inStorage(key)) {
logger.info(clientPort + "> Not in storage ...");
putStat = StatusType.DELETE_ERROR;
} else if (!clientRequests.get(key).isDeleted()) {
logger.info(clientPort + "> Marked for deletion");
clientRequests.get(key).setDeleted(true);
Runnable pruneDelete = new Runnable() {
@Override
public void run() {
logger.info(clientPort + "> Starting pruning thread");
do {
} while (!clientRequests.get(key).isEmpty());
clientRequests.remove(key);
if (cache != null) {
cache.remove(key);
}
File file = new File(storageDirectory + key);
file.delete();
logger.info(clientPort + "> " + key + " successfully pruned");
}
};
clientRequests.get(key).startPruning(pruneDelete);
} else {
logger.info(clientPort + "> Key does not exist - marked for deletion!");
putStat = StatusType.DELETE_ERROR;
}
} catch (Exception e) {
logger.info(clientPort + "> Deletion exception ...");
logger.error(e);
exceptionLogger(e);
putStat = StatusType.DELETE_ERROR;
}
} else {
logger.info(clientPort + "> Trying to insert/update record");
try {
if (!inStorage(key)) {
logger.info(clientPort + "> Going to insert record");
putStat = StatusType.PUT_SUCCESS;
} else {
logger.info(clientPort + "> Going to update record");
putStat = StatusType.PUT_UPDATE;
if (clientRequests.get(key).isDeleted()) {
clientRequests.get(key).stopPruning();
clientRequests.get(key).setDeleted(false);
}
}
insertCache(key, value);
FileWriter myWriter = new FileWriter(storageDirectory + key);
myWriter.write(value);
myWriter.close();
} catch (Exception e) {
logger.error(e);
exceptionLogger(e);
putStat = StatusType.PUT_ERROR;
}
}
removeTopQueue(key);
logger.info(clientPort + "> !!!!===Removing from queue===!!!!");
try {
res = new KVMessage(key, value, putStat);
} catch (InvalidMessageException ime) {
throw ime;
}
return res;
} | @override public kvmessage putkv(final int clientport, final string key, final string value) throws invalidmessageexception { logger.info(clientport + "> put for key=" + key + " value=" + value); kvmessage res; statustype putstat; clientrequests.putifabsent(key, new concurrentnode(max_reads)); nodeoperation op = value.equals("null") ? nodeoperation.delete : nodeoperation.write; int[] node = { clientport, op.getval() }; clientrequests.get(key).addtoqueue(node); if (test) { logger.info(clientport + "> !!!!===wait===!!!!"); while (wait) ; logger.info(clientport + "> !!!!===done waiting===!!!!"); } while (clientrequests.get(key).peek()[0] != clientport) ; logger.info(clientport + "> !!!!===finished spinning===!!!!"); if (value.equals("null")) { logger.info(clientport + "> trying to delete record ..."); putstat = statustype.delete_success; try { if (!instorage(key)) { logger.info(clientport + "> not in storage ..."); putstat = statustype.delete_error; } else if (!clientrequests.get(key).isdeleted()) { logger.info(clientport + "> marked for deletion"); clientrequests.get(key).setdeleted(true); runnable prunedelete = new runnable() { @override public void run() { logger.info(clientport + "> starting pruning thread"); do { } while (!clientrequests.get(key).isempty()); clientrequests.remove(key); if (cache != null) { cache.remove(key); } file file = new file(storagedirectory + key); file.delete(); logger.info(clientport + "> " + key + " successfully pruned"); } }; clientrequests.get(key).startpruning(prunedelete); } else { logger.info(clientport + "> key does not exist - marked for deletion!"); putstat = statustype.delete_error; } } catch (exception e) { logger.info(clientport + "> deletion exception ..."); logger.error(e); exceptionlogger(e); putstat = statustype.delete_error; } } else { logger.info(clientport + "> trying to insert/update record"); try { if (!instorage(key)) { logger.info(clientport + "> going to insert record"); putstat = statustype.put_success; } else { logger.info(clientport + "> going to update record"); putstat = statustype.put_update; if (clientrequests.get(key).isdeleted()) { clientrequests.get(key).stoppruning(); clientrequests.get(key).setdeleted(false); } } insertcache(key, value); filewriter mywriter = new filewriter(storagedirectory + key); mywriter.write(value); mywriter.close(); } catch (exception e) { logger.error(e); exceptionlogger(e); putstat = statustype.put_error; } } removetopqueue(key); logger.info(clientport + "> !!!!===removing from queue===!!!!"); try { res = new kvmessage(key, value, putstat); } catch (invalidmessageexception ime) { throw ime; } return res; } | CAPIndustries/capDB | [
1,
1,
0,
0
] |
21,001 | public static void main(String[] args) {
try {
if (args.length != 6) {
logger.error("Error! Invalid number of arguments!");
logger.error("Usage: Server <name> <port> <ZooKeeper Port> <ECS IP> <isLoadReplica> <parentName>!");
System.exit(1);
} else {
String name = args[0];
int port = Integer.parseInt(args[1]);
int zkPort = Integer.parseInt(args[2]);
String ECSIP = args[3];
boolean isLoadReplica = Boolean.parseBoolean(args[4]);
String parentName = args[5];
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
new LogSetup("logs/" + name + "_" + fmt.format(new Date()) + ".log", Level.ALL, true);
// No need to use the run method here since the contructor is supposed to
// start the server on its own
// TODO: Allow passing additional arguments from the command line:
new KVServer(START_CACHE_SIZE, START_CACHE_STRATEGY, name, port, zkPort, ECSIP, isLoadReplica, parentName);
}
} catch (IOException e) {
System.out.println("Error! Unable to initialize logger!");
e.printStackTrace();
System.exit(1);
} catch (NumberFormatException nfe) {
System.out.println("Error! Invalid argument <port>! Not a number!");
System.out.println("Usage: Server <port>!");
System.exit(1);
}
} | public static void main(String[] args) {
try {
if (args.length != 6) {
logger.error("Error! Invalid number of arguments!");
logger.error("Usage: Server <name> <port> <ZooKeeper Port> <ECS IP> <isLoadReplica> <parentName>!");
System.exit(1);
} else {
String name = args[0];
int port = Integer.parseInt(args[1]);
int zkPort = Integer.parseInt(args[2]);
String ECSIP = args[3];
boolean isLoadReplica = Boolean.parseBoolean(args[4]);
String parentName = args[5];
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
new LogSetup("logs/" + name + "_" + fmt.format(new Date()) + ".log", Level.ALL, true);
new KVServer(START_CACHE_SIZE, START_CACHE_STRATEGY, name, port, zkPort, ECSIP, isLoadReplica, parentName);
}
} catch (IOException e) {
System.out.println("Error! Unable to initialize logger!");
e.printStackTrace();
System.exit(1);
} catch (NumberFormatException nfe) {
System.out.println("Error! Invalid argument <port>! Not a number!");
System.out.println("Usage: Server <port>!");
System.exit(1);
}
} | public static void main(string[] args) { try { if (args.length != 6) { logger.error("error! invalid number of arguments!"); logger.error("usage: server <name> <port> <zookeeper port> <ecs ip> <isloadreplica> <parentname>!"); system.exit(1); } else { string name = args[0]; int port = integer.parseint(args[1]); int zkport = integer.parseint(args[2]); string ecsip = args[3]; boolean isloadreplica = boolean.parseboolean(args[4]); string parentname = args[5]; simpledateformat fmt = new simpledateformat("yyyy-mm-dd-hh-mm-ss"); new logsetup("logs/" + name + "_" + fmt.format(new date()) + ".log", level.all, true); new kvserver(start_cache_size, start_cache_strategy, name, port, zkport, ecsip, isloadreplica, parentname); } } catch (ioexception e) { system.out.println("error! unable to initialize logger!"); e.printstacktrace(); system.exit(1); } catch (numberformatexception nfe) { system.out.println("error! invalid argument <port>! not a number!"); system.out.println("usage: server <port>!"); system.exit(1); } } | CAPIndustries/capDB | [
1,
0,
0,
0
] |
21,046 | @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
llView = (LinearLayout)inflater.inflate(R.layout.fragment_layers, container, false);
llView.findViewById(R.id.btnAddStrokeLayer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Layer newLayer = new StrokePL();
createLayer(((IDd<ID>)mTree).getId(), newLayer);
}
});
llView.findViewById(R.id.btnAddGroupLayer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Layer newLayer = new GroupLayer();
createLayer(((IDd<ID>)mTree).getId(), newLayer);
}
});
llView.findViewById(R.id.btnAddOtherLayer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO This will need to change, for settings, etc.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
List<Class> classes = new ArrayList<Class>();
try {
classes = ClassScanner.getConcreteDescendants(getContext(), Layer.class, null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
classes.remove(UACanvas.class);
ArrayList<String> classNames = new ArrayList<String>();
for (Class<?> clazz : classes) {
classNames.add(clazz.getName());
}
String[] layerTypes = new String[]{};
layerTypes = classNames.toArray(layerTypes);
final List<Class> fClasses = classes;
builder.setTitle("Pick a layer type")
.setItems(layerTypes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
Layer newLayer = (Layer)fClasses.get(which).newInstance();
createLayer(((IDd<ID>)mTree).getId(), newLayer);
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
showToast("Error creating layer:\n" + e.getMessage());
} catch (IllegalAccessException e) {
e.printStackTrace();
showToast("Error creating layer:\n" + e.getMessage());
}
}
});
builder.show();
}
});
updateView();
return llView;
} | @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
llView = (LinearLayout)inflater.inflate(R.layout.fragment_layers, container, false);
llView.findViewById(R.id.btnAddStrokeLayer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Layer newLayer = new StrokePL();
createLayer(((IDd<ID>)mTree).getId(), newLayer);
}
});
llView.findViewById(R.id.btnAddGroupLayer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Layer newLayer = new GroupLayer();
createLayer(((IDd<ID>)mTree).getId(), newLayer);
}
});
llView.findViewById(R.id.btnAddOtherLayer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
List<Class> classes = new ArrayList<Class>();
try {
classes = ClassScanner.getConcreteDescendants(getContext(), Layer.class, null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
classes.remove(UACanvas.class);
ArrayList<String> classNames = new ArrayList<String>();
for (Class<?> clazz : classes) {
classNames.add(clazz.getName());
}
String[] layerTypes = new String[]{};
layerTypes = classNames.toArray(layerTypes);
final List<Class> fClasses = classes;
builder.setTitle("Pick a layer type")
.setItems(layerTypes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
Layer newLayer = (Layer)fClasses.get(which).newInstance();
createLayer(((IDd<ID>)mTree).getId(), newLayer);
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
showToast("Error creating layer:\n" + e.getMessage());
} catch (IllegalAccessException e) {
e.printStackTrace();
showToast("Error creating layer:\n" + e.getMessage());
}
}
});
builder.show();
}
});
updateView();
return llView;
} | @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { llview = (linearlayout)inflater.inflate(r.layout.fragment_layers, container, false); llview.findviewbyid(r.id.btnaddstrokelayer).setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { layer newlayer = new strokepl(); createlayer(((idd<id>)mtree).getid(), newlayer); } }); llview.findviewbyid(r.id.btnaddgrouplayer).setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { layer newlayer = new grouplayer(); createlayer(((idd<id>)mtree).getid(), newlayer); } }); llview.findviewbyid(r.id.btnaddotherlayer).setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { alertdialog.builder builder = new alertdialog.builder(getactivity()); list<class> classes = new arraylist<class>(); try { classes = classscanner.getconcretedescendants(getcontext(), layer.class, null); } catch (nosuchmethodexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (classnotfoundexception e) { e.printstacktrace(); } classes.remove(uacanvas.class); arraylist<string> classnames = new arraylist<string>(); for (class<?> clazz : classes) { classnames.add(clazz.getname()); } string[] layertypes = new string[]{}; layertypes = classnames.toarray(layertypes); final list<class> fclasses = classes; builder.settitle("pick a layer type") .setitems(layertypes, new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int which) { try { layer newlayer = (layer)fclasses.get(which).newinstance(); createlayer(((idd<id>)mtree).getid(), newlayer); } catch (java.lang.instantiationexception e) { e.printstacktrace(); showtoast("error creating layer:\n" + e.getmessage()); } catch (illegalaccessexception e) { e.printstacktrace(); showtoast("error creating layer:\n" + e.getmessage()); } } }); builder.show(); } }); updateview(); return llview; } | Erhannis/UnstableArt | [
1,
0,
0,
0
] |
21,397 | private mxGraphComponent createGraphComponent(mxGraph graph) {
mxGraphComponent component = new mxGraphComponent(graph);
component.setAutoExtend(true);
component.setAntiAlias(true);
component.setTextAntiAlias(true);
component.setToolTips(true);
// component.setImportEnabled(false);
component.setFoldingEnabled(true);
component.setConnectable(false);
component.setDragEnabled(false);
// component.setKeepSelectionVisibleOnZoom(true);
// component.getViewport().setBackground(Color.white);
//TODO setup
return component;
} | private mxGraphComponent createGraphComponent(mxGraph graph) {
mxGraphComponent component = new mxGraphComponent(graph);
component.setAutoExtend(true);
component.setAntiAlias(true);
component.setTextAntiAlias(true);
component.setToolTips(true);
component.setFoldingEnabled(true);
component.setConnectable(false);
component.setDragEnabled(false);
return component;
} | private mxgraphcomponent creategraphcomponent(mxgraph graph) { mxgraphcomponent component = new mxgraphcomponent(graph); component.setautoextend(true); component.setantialias(true); component.settextantialias(true); component.settooltips(true); component.setfoldingenabled(true); component.setconnectable(false); component.setdragenabled(false); return component; } | ICARUS-tooling/icarus2-modeling-framework | [
0,
1,
0,
0
] |
13,266 | public int getAge() {
// TODO: put safe grabbing of age here
return 0;
} | public int getAge() {
return 0;
} | public int getage() { return 0; } | 210118-java-enterprise/demos | [
0,
1,
0,
0
] |
13,267 | @InstanceName
public String getCaption() {
// todo rework when new instance name is ready
String pattern =/* AppContext.getProperty("cuba.user.namePattern");
if (StringUtils.isBlank(pattern)) {
pattern =*/ "{1} [{0}]";
/*}*/
MessageFormat fmt = new MessageFormat(pattern);
return StringUtils.trimToEmpty(fmt.format(new Object[]{
StringUtils.trimToEmpty(username),
StringUtils.trimToEmpty(name)
}));
} | @InstanceName
public String getCaption() {
String pattern "{1} [{0}]";
MessageFormat fmt = new MessageFormat(pattern);
return StringUtils.trimToEmpty(fmt.format(new Object[]{
StringUtils.trimToEmpty(username),
StringUtils.trimToEmpty(name)
}));
} | @instancename public string getcaption() { string pattern "{1} [{0}]"; messageformat fmt = new messageformat(pattern); return stringutils.trimtoempty(fmt.format(new object[]{ stringutils.trimtoempty(username), stringutils.trimtoempty(name) })); } | Haulmont/jmix-old | [
1,
0,
0,
0
] |
13,309 | private SolrQuery createQuery(String queryString, int startPage, int pageSize, boolean useDismax) {
SolrQuery query = new SolrQuery(queryString);
query.setTimeAllowed(queryTimeout);
query.setIncludeScore(true); // The relevance (of each results element) to the search terms.
query.setHighlight(false);
if (useDismax) {
query.set("defType", "dismax");
}
//TODO: Put The "options" from the "queryField" picklist into a config file.
//This list matches the "options" from the "queryField" picklist on unformattedSearch.ftl,
//without the "date" fields.
query.setStart(startPage * pageSize); // Which results element to return first in this batch.
query.setRows(pageSize); // The number of results elements to return.
// request only fields that we need to display
query.setFields("id", "score", "title_display", "publication_date", "eissn", "journal", "article_type",
"author_display", "abstract", "abstract_primary_display", "striking_image", "figure_table_caption",
"subject", "expression_of_concern", "retraction");
query.addFacetField("subject_facet");
query.addFacetField("author_facet");
query.addFacetField("editor_facet");
query.addFacetField("article_type_facet");
query.addFacetField("affiliate_facet");
query.set("facet.method", "fc");
query.setFacetLimit(MAX_FACET_SIZE);
query.setFacetMinCount(MIN_FACET_COUNT);
// Add a filter to ensure that Solr never returns partial documents
query.addFilterQuery(createFilterFullDocuments());
return query;
} | private SolrQuery createQuery(String queryString, int startPage, int pageSize, boolean useDismax) {
SolrQuery query = new SolrQuery(queryString);
query.setTimeAllowed(queryTimeout);
query.setIncludeScore(true);
query.setHighlight(false);
if (useDismax) {
query.set("defType", "dismax");
}
query.setStart(startPage * pageSize);
query.setRows(pageSize);
query.setFields("id", "score", "title_display", "publication_date", "eissn", "journal", "article_type",
"author_display", "abstract", "abstract_primary_display", "striking_image", "figure_table_caption",
"subject", "expression_of_concern", "retraction");
query.addFacetField("subject_facet");
query.addFacetField("author_facet");
query.addFacetField("editor_facet");
query.addFacetField("article_type_facet");
query.addFacetField("affiliate_facet");
query.set("facet.method", "fc");
query.setFacetLimit(MAX_FACET_SIZE);
query.setFacetMinCount(MIN_FACET_COUNT);
query.addFilterQuery(createFilterFullDocuments());
return query;
} | private solrquery createquery(string querystring, int startpage, int pagesize, boolean usedismax) { solrquery query = new solrquery(querystring); query.settimeallowed(querytimeout); query.setincludescore(true); query.sethighlight(false); if (usedismax) { query.set("deftype", "dismax"); } query.setstart(startpage * pagesize); query.setrows(pagesize); query.setfields("id", "score", "title_display", "publication_date", "eissn", "journal", "article_type", "author_display", "abstract", "abstract_primary_display", "striking_image", "figure_table_caption", "subject", "expression_of_concern", "retraction"); query.addfacetfield("subject_facet"); query.addfacetfield("author_facet"); query.addfacetfield("editor_facet"); query.addfacetfield("article_type_facet"); query.addfacetfield("affiliate_facet"); query.set("facet.method", "fc"); query.setfacetlimit(max_facet_size); query.setfacetmincount(min_facet_count); query.addfilterquery(createfilterfulldocuments()); return query; } | AndrewGuthua/JournalSystem | [
1,
0,
0,
0
] |
13,361 | private String getTypeString(String _sTypeName, TypeClass _aTypeClass, boolean _bAsHeaderSourceCode){
String sTypeString = "";
switch (_aTypeClass.getValue()){
case TypeClass.BOOLEAN_value:
sTypeString = m_xLanguageSourceCodeGenerator.getbooleanTypeDescription();
break;
case TypeClass.BYTE_value:
sTypeString = m_xLanguageSourceCodeGenerator.getbyteTypeDescription();
break;
case TypeClass.CHAR_value:
sTypeString = m_xLanguageSourceCodeGenerator.getcharTypeDescription();
break;
case TypeClass.DOUBLE_value:
sTypeString = m_xLanguageSourceCodeGenerator.getdoubleTypeDescription();
break;
case TypeClass.FLOAT_value:
sTypeString = m_xLanguageSourceCodeGenerator.getfloatTypeDescription();
break;
case TypeClass.HYPER_value:
sTypeString = m_xLanguageSourceCodeGenerator.gethyperTypeDescription();
break;
case TypeClass.LONG_value:
sTypeString = m_xLanguageSourceCodeGenerator.getlongTypeDescription();
break;
case TypeClass.SHORT_value:
sTypeString = m_xLanguageSourceCodeGenerator.getshortTypeDescription();
break;
case TypeClass.STRING_value:
sTypeString = m_xLanguageSourceCodeGenerator.getstringTypeDescription(_bAsHeaderSourceCode);
break;
case TypeClass.UNSIGNED_HYPER_value:
sTypeString = m_xLanguageSourceCodeGenerator.getunsignedhyperTypeDescription();
break;
case TypeClass.UNSIGNED_LONG_value:
sTypeString = m_xLanguageSourceCodeGenerator.getunsignedlongTypeDescription();
break;
case TypeClass.UNSIGNED_SHORT_value:
sTypeString = m_xLanguageSourceCodeGenerator.getdoubleTypeDescription();
break;
case TypeClass.SEQUENCE_value:
//TODO consider mulitdimensional Arrays
XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(_sTypeName);
if (xTypeDescription != null){
sTypeString = getTypeString(xTypeDescription.getName(), xTypeDescription.getTypeClass(), _bAsHeaderSourceCode);
}
break;
case TypeClass.ANY_value:
sTypeString = m_xLanguageSourceCodeGenerator.getanyTypeDescription(_bAsHeaderSourceCode);
break;
case TypeClass.TYPE_value:
sTypeString = m_xLanguageSourceCodeGenerator.getObjectTypeDescription("com.sun.star.uno.Type", _bAsHeaderSourceCode);
break;
case TypeClass.ENUM_value:
case TypeClass.STRUCT_value:
case TypeClass.INTERFACE_ATTRIBUTE_value:
case TypeClass.INTERFACE_METHOD_value:
case TypeClass.INTERFACE_value:
case TypeClass.PROPERTY_value:
sTypeString = m_xLanguageSourceCodeGenerator.getObjectTypeDescription(_sTypeName, _bAsHeaderSourceCode);
break;
default:
}
return sTypeString;
} | private String getTypeString(String _sTypeName, TypeClass _aTypeClass, boolean _bAsHeaderSourceCode){
String sTypeString = "";
switch (_aTypeClass.getValue()){
case TypeClass.BOOLEAN_value:
sTypeString = m_xLanguageSourceCodeGenerator.getbooleanTypeDescription();
break;
case TypeClass.BYTE_value:
sTypeString = m_xLanguageSourceCodeGenerator.getbyteTypeDescription();
break;
case TypeClass.CHAR_value:
sTypeString = m_xLanguageSourceCodeGenerator.getcharTypeDescription();
break;
case TypeClass.DOUBLE_value:
sTypeString = m_xLanguageSourceCodeGenerator.getdoubleTypeDescription();
break;
case TypeClass.FLOAT_value:
sTypeString = m_xLanguageSourceCodeGenerator.getfloatTypeDescription();
break;
case TypeClass.HYPER_value:
sTypeString = m_xLanguageSourceCodeGenerator.gethyperTypeDescription();
break;
case TypeClass.LONG_value:
sTypeString = m_xLanguageSourceCodeGenerator.getlongTypeDescription();
break;
case TypeClass.SHORT_value:
sTypeString = m_xLanguageSourceCodeGenerator.getshortTypeDescription();
break;
case TypeClass.STRING_value:
sTypeString = m_xLanguageSourceCodeGenerator.getstringTypeDescription(_bAsHeaderSourceCode);
break;
case TypeClass.UNSIGNED_HYPER_value:
sTypeString = m_xLanguageSourceCodeGenerator.getunsignedhyperTypeDescription();
break;
case TypeClass.UNSIGNED_LONG_value:
sTypeString = m_xLanguageSourceCodeGenerator.getunsignedlongTypeDescription();
break;
case TypeClass.UNSIGNED_SHORT_value:
sTypeString = m_xLanguageSourceCodeGenerator.getdoubleTypeDescription();
break;
case TypeClass.SEQUENCE_value:
XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(_sTypeName);
if (xTypeDescription != null){
sTypeString = getTypeString(xTypeDescription.getName(), xTypeDescription.getTypeClass(), _bAsHeaderSourceCode);
}
break;
case TypeClass.ANY_value:
sTypeString = m_xLanguageSourceCodeGenerator.getanyTypeDescription(_bAsHeaderSourceCode);
break;
case TypeClass.TYPE_value:
sTypeString = m_xLanguageSourceCodeGenerator.getObjectTypeDescription("com.sun.star.uno.Type", _bAsHeaderSourceCode);
break;
case TypeClass.ENUM_value:
case TypeClass.STRUCT_value:
case TypeClass.INTERFACE_ATTRIBUTE_value:
case TypeClass.INTERFACE_METHOD_value:
case TypeClass.INTERFACE_value:
case TypeClass.PROPERTY_value:
sTypeString = m_xLanguageSourceCodeGenerator.getObjectTypeDescription(_sTypeName, _bAsHeaderSourceCode);
break;
default:
}
return sTypeString;
} | private string gettypestring(string _stypename, typeclass _atypeclass, boolean _basheadersourcecode){ string stypestring = ""; switch (_atypeclass.getvalue()){ case typeclass.boolean_value: stypestring = m_xlanguagesourcecodegenerator.getbooleantypedescription(); break; case typeclass.byte_value: stypestring = m_xlanguagesourcecodegenerator.getbytetypedescription(); break; case typeclass.char_value: stypestring = m_xlanguagesourcecodegenerator.getchartypedescription(); break; case typeclass.double_value: stypestring = m_xlanguagesourcecodegenerator.getdoubletypedescription(); break; case typeclass.float_value: stypestring = m_xlanguagesourcecodegenerator.getfloattypedescription(); break; case typeclass.hyper_value: stypestring = m_xlanguagesourcecodegenerator.gethypertypedescription(); break; case typeclass.long_value: stypestring = m_xlanguagesourcecodegenerator.getlongtypedescription(); break; case typeclass.short_value: stypestring = m_xlanguagesourcecodegenerator.getshorttypedescription(); break; case typeclass.string_value: stypestring = m_xlanguagesourcecodegenerator.getstringtypedescription(_basheadersourcecode); break; case typeclass.unsigned_hyper_value: stypestring = m_xlanguagesourcecodegenerator.getunsignedhypertypedescription(); break; case typeclass.unsigned_long_value: stypestring = m_xlanguagesourcecodegenerator.getunsignedlongtypedescription(); break; case typeclass.unsigned_short_value: stypestring = m_xlanguagesourcecodegenerator.getdoubletypedescription(); break; case typeclass.sequence_value: xtypedescription xtypedescription = introspector.getintrospector().getreferencedtype(_stypename); if (xtypedescription != null){ stypestring = gettypestring(xtypedescription.getname(), xtypedescription.gettypeclass(), _basheadersourcecode); } break; case typeclass.any_value: stypestring = m_xlanguagesourcecodegenerator.getanytypedescription(_basheadersourcecode); break; case typeclass.type_value: stypestring = m_xlanguagesourcecodegenerator.getobjecttypedescription("com.sun.star.uno.type", _basheadersourcecode); break; case typeclass.enum_value: case typeclass.struct_value: case typeclass.interface_attribute_value: case typeclass.interface_method_value: case typeclass.interface_value: case typeclass.property_value: stypestring = m_xlanguagesourcecodegenerator.getobjecttypedescription(_stypename, _basheadersourcecode); break; default: } return stypestring; } | Grosskopf/openoffice | [
1,
0,
0,
0
] |
13,362 | private String getCentralVariableStemName(TypeClass _aTypeClass){
String sCentralVariableStemName = "";
int nTypeClass = _aTypeClass.getValue();
switch(nTypeClass){
case TypeClass.SEQUENCE_value:
//TODO consider mulitdimensional Arrays
XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(getTypeName());
if (xTypeDescription != null){
sCentralVariableStemName = getCentralVariableStemName(xTypeDescription.getTypeClass());
}
break;
case TypeClass.TYPE_value:
sCentralVariableStemName = SVARIABLENAME;
break;
case TypeClass.STRUCT_value:
sCentralVariableStemName = Introspector.getShortClassName(getTypeName());
break;
case TypeClass.INTERFACE_ATTRIBUTE_value:
case TypeClass.INTERFACE_METHOD_value:
case TypeClass.INTERFACE_value:
case TypeClass.PROPERTY_value:
String sShortClassName = m_oIntrospector.getShortClassName(getTypeName());
sCentralVariableStemName = getVariableNameforUnoObject(sShortClassName);
default:
sCentralVariableStemName = SVARIABLENAME;
}
return sCentralVariableStemName;
} | private String getCentralVariableStemName(TypeClass _aTypeClass){
String sCentralVariableStemName = "";
int nTypeClass = _aTypeClass.getValue();
switch(nTypeClass){
case TypeClass.SEQUENCE_value:
XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(getTypeName());
if (xTypeDescription != null){
sCentralVariableStemName = getCentralVariableStemName(xTypeDescription.getTypeClass());
}
break;
case TypeClass.TYPE_value:
sCentralVariableStemName = SVARIABLENAME;
break;
case TypeClass.STRUCT_value:
sCentralVariableStemName = Introspector.getShortClassName(getTypeName());
break;
case TypeClass.INTERFACE_ATTRIBUTE_value:
case TypeClass.INTERFACE_METHOD_value:
case TypeClass.INTERFACE_value:
case TypeClass.PROPERTY_value:
String sShortClassName = m_oIntrospector.getShortClassName(getTypeName());
sCentralVariableStemName = getVariableNameforUnoObject(sShortClassName);
default:
sCentralVariableStemName = SVARIABLENAME;
}
return sCentralVariableStemName;
} | private string getcentralvariablestemname(typeclass _atypeclass){ string scentralvariablestemname = ""; int ntypeclass = _atypeclass.getvalue(); switch(ntypeclass){ case typeclass.sequence_value: xtypedescription xtypedescription = introspector.getintrospector().getreferencedtype(gettypename()); if (xtypedescription != null){ scentralvariablestemname = getcentralvariablestemname(xtypedescription.gettypeclass()); } break; case typeclass.type_value: scentralvariablestemname = svariablename; break; case typeclass.struct_value: scentralvariablestemname = introspector.getshortclassname(gettypename()); break; case typeclass.interface_attribute_value: case typeclass.interface_method_value: case typeclass.interface_value: case typeclass.property_value: string sshortclassname = m_ointrospector.getshortclassname(gettypename()); scentralvariablestemname = getvariablenameforunoobject(sshortclassname); default: scentralvariablestemname = svariablename; } return scentralvariablestemname; } | Grosskopf/openoffice | [
1,
0,
0,
0
] |
13,363 | public String getVariableStemName(TypeClass _aTypeClass){
int nTypeClass = _aTypeClass.getValue();
switch(nTypeClass){
case TypeClass.BOOLEAN_value:
sVariableStemName = "b" + m_sCentralVariableStemName;
break;
case TypeClass.DOUBLE_value:
case TypeClass.FLOAT_value:
sVariableStemName = "f" + m_sCentralVariableStemName;
break;
case TypeClass.BYTE_value:
case TypeClass.HYPER_value:
case TypeClass.LONG_value:
case TypeClass.UNSIGNED_HYPER_value:
case TypeClass.UNSIGNED_LONG_value:
case TypeClass.UNSIGNED_SHORT_value:
case TypeClass.SHORT_value:
sVariableStemName = "n" + m_sCentralVariableStemName;
break;
case TypeClass.CHAR_value:
case TypeClass.STRING_value:
sVariableStemName = "s" + m_sCentralVariableStemName;
break;
case TypeClass.SEQUENCE_value:
//TODO consider mulitdimensional Arrays
XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(getTypeName());
if (xTypeDescription != null){
sVariableStemName = getVariableStemName(xTypeDescription.getTypeClass());
}
break;
case TypeClass.TYPE_value:
sVariableStemName = "a" + m_sCentralVariableStemName;
break;
case TypeClass.ANY_value:
sVariableStemName = "o" + m_sCentralVariableStemName;
break;
case TypeClass.STRUCT_value:
case TypeClass.ENUM_value:
sVariableStemName = "a" + m_sCentralVariableStemName;
break;
case TypeClass.INTERFACE_ATTRIBUTE_value:
case TypeClass.INTERFACE_METHOD_value:
case TypeClass.INTERFACE_value:
case TypeClass.PROPERTY_value:
String sShortClassName = m_oIntrospector.getShortClassName(getTypeName());
sVariableStemName = getVariableNameforUnoObject(sShortClassName);
default:
}
return sVariableStemName;
} | public String getVariableStemName(TypeClass _aTypeClass){
int nTypeClass = _aTypeClass.getValue();
switch(nTypeClass){
case TypeClass.BOOLEAN_value:
sVariableStemName = "b" + m_sCentralVariableStemName;
break;
case TypeClass.DOUBLE_value:
case TypeClass.FLOAT_value:
sVariableStemName = "f" + m_sCentralVariableStemName;
break;
case TypeClass.BYTE_value:
case TypeClass.HYPER_value:
case TypeClass.LONG_value:
case TypeClass.UNSIGNED_HYPER_value:
case TypeClass.UNSIGNED_LONG_value:
case TypeClass.UNSIGNED_SHORT_value:
case TypeClass.SHORT_value:
sVariableStemName = "n" + m_sCentralVariableStemName;
break;
case TypeClass.CHAR_value:
case TypeClass.STRING_value:
sVariableStemName = "s" + m_sCentralVariableStemName;
break;
case TypeClass.SEQUENCE_value:
XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(getTypeName());
if (xTypeDescription != null){
sVariableStemName = getVariableStemName(xTypeDescription.getTypeClass());
}
break;
case TypeClass.TYPE_value:
sVariableStemName = "a" + m_sCentralVariableStemName;
break;
case TypeClass.ANY_value:
sVariableStemName = "o" + m_sCentralVariableStemName;
break;
case TypeClass.STRUCT_value:
case TypeClass.ENUM_value:
sVariableStemName = "a" + m_sCentralVariableStemName;
break;
case TypeClass.INTERFACE_ATTRIBUTE_value:
case TypeClass.INTERFACE_METHOD_value:
case TypeClass.INTERFACE_value:
case TypeClass.PROPERTY_value:
String sShortClassName = m_oIntrospector.getShortClassName(getTypeName());
sVariableStemName = getVariableNameforUnoObject(sShortClassName);
default:
}
return sVariableStemName;
} | public string getvariablestemname(typeclass _atypeclass){ int ntypeclass = _atypeclass.getvalue(); switch(ntypeclass){ case typeclass.boolean_value: svariablestemname = "b" + m_scentralvariablestemname; break; case typeclass.double_value: case typeclass.float_value: svariablestemname = "f" + m_scentralvariablestemname; break; case typeclass.byte_value: case typeclass.hyper_value: case typeclass.long_value: case typeclass.unsigned_hyper_value: case typeclass.unsigned_long_value: case typeclass.unsigned_short_value: case typeclass.short_value: svariablestemname = "n" + m_scentralvariablestemname; break; case typeclass.char_value: case typeclass.string_value: svariablestemname = "s" + m_scentralvariablestemname; break; case typeclass.sequence_value: xtypedescription xtypedescription = introspector.getintrospector().getreferencedtype(gettypename()); if (xtypedescription != null){ svariablestemname = getvariablestemname(xtypedescription.gettypeclass()); } break; case typeclass.type_value: svariablestemname = "a" + m_scentralvariablestemname; break; case typeclass.any_value: svariablestemname = "o" + m_scentralvariablestemname; break; case typeclass.struct_value: case typeclass.enum_value: svariablestemname = "a" + m_scentralvariablestemname; break; case typeclass.interface_attribute_value: case typeclass.interface_method_value: case typeclass.interface_value: case typeclass.property_value: string sshortclassname = m_ointrospector.getshortclassname(gettypename()); svariablestemname = getvariablenameforunoobject(sshortclassname); default: } return svariablestemname; } | Grosskopf/openoffice | [
1,
0,
0,
0
] |
29,971 | public int getRuleStatusVec(int[] fillInArray) {
if (fillInArray != null && fillInArray.length>=1) {
fillInArray[0] = 0;
}
return 1;
} | public int getRuleStatusVec(int[] fillInArray) {
if (fillInArray != null && fillInArray.length>=1) {
fillInArray[0] = 0;
}
return 1;
} | public int getrulestatusvec(int[] fillinarray) { if (fillinarray != null && fillinarray.length>=1) { fillinarray[0] = 0; } return 1; } | HughP/quickdic-dictionary | [
1,
0,
0,
0
] |
30,000 | public void go() throws Exception {
BufferedReader br = new BufferedReader(new FileReader("verilog\\out.log"));
String line;
Pattern p = Pattern.compile(".+JAG RD REF=. OB=1 BLT=. GPU=. \\$(......).*");
long lineNo = 0;
int Xmin[] = new int[3];
int Xmax[] = new int[3];
int Ymin[] = new int[3];
int Ymax[] = new int[3];
long slino[] = new long[3];
long elino[] = new long[3];
for(int k = 0; k < 3; k++) {
Xmin[k] = Ymin[k] = Integer.MAX_VALUE;
Xmax[k] = Ymax[k] = Integer.MIN_VALUE;
}
while( (line = br.readLine()) != null) {
lineNo++;
if (lineNo >= 10L * 1000L * 1000L)
break;
Matcher m = p.matcher(line);
if (m.matches()) {
// System.out.println(line);
int addr = Integer.parseInt(m.group(1), 16);
int index = -1;
boolean wtf = false;
if (addr == 0xeb40) {
// OLP
// System.out.print(".");
for(int k = 0; k < 3; k++) {
if (slino[k] != 0) {
//wtf = (Ymin[k] != Ymax[k]);
System.out.format("%-9d %-9d S%d (%d,%d) -> (%d,%d) %s ", slino[k], elino[k], (k+1), Xmin[k], Ymin[k], Xmax[k], Ymax[k],
(wtf ? "WTF" : ""));
}
Xmin[k] = Ymin[k] = Integer.MAX_VALUE;
Xmax[k] = Ymax[k] = Integer.MIN_VALUE;
slino[k] = 0;
elino[k] = 0;
}
System.out.println();
}
/*if (wtf)
break;*/
if (addr >= SCREEN1 && addr < SCREEN1 + SCREENSIZE) {
index = 0;
addr -= SCREEN1;
}
else if (addr >= SCREEN2 && addr < SCREEN2 + SCREENSIZE) {
index = 1;
addr -= SCREEN2;
}
else if (addr >= SCREEN3 && addr < SCREEN3 + SCREENSIZE) {
index = 2;
addr -= SCREEN3;
}
if (index < 0)
continue;
// System.out.format("%06x %04x\n", addr, val);
int y = (addr >> 1) / WIDTH;
int x = (addr >> 1) % WIDTH;
// System.out.format("%d (%d,%d)\n", index, x, y);
if (slino[index] == 0)
slino[index] = lineNo;
elino[index] = lineNo;
if (Xmin[index] > x)
Xmin[index] = x;
if (Xmax[index] < x)
Xmax[index] = x;
if (Ymin[index] > y)
Ymin[index] = y;
if (Ymax[index] < y)
Ymax[index] = y;
}
}
br.close();
} | public void go() throws Exception {
BufferedReader br = new BufferedReader(new FileReader("verilog\\out.log"));
String line;
Pattern p = Pattern.compile(".+JAG RD REF=. OB=1 BLT=. GPU=. \\$(......).*");
long lineNo = 0;
int Xmin[] = new int[3];
int Xmax[] = new int[3];
int Ymin[] = new int[3];
int Ymax[] = new int[3];
long slino[] = new long[3];
long elino[] = new long[3];
for(int k = 0; k < 3; k++) {
Xmin[k] = Ymin[k] = Integer.MAX_VALUE;
Xmax[k] = Ymax[k] = Integer.MIN_VALUE;
}
while( (line = br.readLine()) != null) {
lineNo++;
if (lineNo >= 10L * 1000L * 1000L)
break;
Matcher m = p.matcher(line);
if (m.matches()) {
int addr = Integer.parseInt(m.group(1), 16);
int index = -1;
boolean wtf = false;
if (addr == 0xeb40) {
for(int k = 0; k < 3; k++) {
if (slino[k] != 0) {
System.out.format("%-9d %-9d S%d (%d,%d) -> (%d,%d) %s ", slino[k], elino[k], (k+1), Xmin[k], Ymin[k], Xmax[k], Ymax[k],
(wtf ? "WTF" : ""));
}
Xmin[k] = Ymin[k] = Integer.MAX_VALUE;
Xmax[k] = Ymax[k] = Integer.MIN_VALUE;
slino[k] = 0;
elino[k] = 0;
}
System.out.println();
}
if (addr >= SCREEN1 && addr < SCREEN1 + SCREENSIZE) {
index = 0;
addr -= SCREEN1;
}
else if (addr >= SCREEN2 && addr < SCREEN2 + SCREENSIZE) {
index = 1;
addr -= SCREEN2;
}
else if (addr >= SCREEN3 && addr < SCREEN3 + SCREENSIZE) {
index = 2;
addr -= SCREEN3;
}
if (index < 0)
continue;
int y = (addr >> 1) / WIDTH;
int x = (addr >> 1) % WIDTH;
if (slino[index] == 0)
slino[index] = lineNo;
elino[index] = lineNo;
if (Xmin[index] > x)
Xmin[index] = x;
if (Xmax[index] < x)
Xmax[index] = x;
if (Ymin[index] > y)
Ymin[index] = y;
if (Ymax[index] < y)
Ymax[index] = y;
}
}
br.close();
} | public void go() throws exception { bufferedreader br = new bufferedreader(new filereader("verilog\\out.log")); string line; pattern p = pattern.compile(".+jag rd ref=. ob=1 blt=. gpu=. \\$(......).*"); long lineno = 0; int xmin[] = new int[3]; int xmax[] = new int[3]; int ymin[] = new int[3]; int ymax[] = new int[3]; long slino[] = new long[3]; long elino[] = new long[3]; for(int k = 0; k < 3; k++) { xmin[k] = ymin[k] = integer.max_value; xmax[k] = ymax[k] = integer.min_value; } while( (line = br.readline()) != null) { lineno++; if (lineno >= 10l * 1000l * 1000l) break; matcher m = p.matcher(line); if (m.matches()) { int addr = integer.parseint(m.group(1), 16); int index = -1; boolean wtf = false; if (addr == 0xeb40) { for(int k = 0; k < 3; k++) { if (slino[k] != 0) { system.out.format("%-9d %-9d s%d (%d,%d) -> (%d,%d) %s ", slino[k], elino[k], (k+1), xmin[k], ymin[k], xmax[k], ymax[k], (wtf ? "wtf" : "")); } xmin[k] = ymin[k] = integer.max_value; xmax[k] = ymax[k] = integer.min_value; slino[k] = 0; elino[k] = 0; } system.out.println(); } if (addr >= screen1 && addr < screen1 + screensize) { index = 0; addr -= screen1; } else if (addr >= screen2 && addr < screen2 + screensize) { index = 1; addr -= screen2; } else if (addr >= screen3 && addr < screen3 + screensize) { index = 2; addr -= screen3; } if (index < 0) continue; int y = (addr >> 1) / width; int x = (addr >> 1) % width; if (slino[index] == 0) slino[index] = lineno; elino[index] = lineno; if (xmin[index] > x) xmin[index] = x; if (xmax[index] < x) xmax[index] = x; if (ymin[index] > y) ymin[index] = y; if (ymax[index] < y) ymax[index] = y; } } br.close(); } | ElectronAsh/jag_sim | [
0,
0,
0,
0
] |
21,824 | private void downloadMedia(MediaFileInfo fileInfo) {
if (fileInfo == null) {
return;
}
int mediaId = fileInfo.getId();
getDelegate(fileInfo.getType()).onDownloadMedia(fileInfo)
.thenAcceptAsync((result) -> {
// @todo: replace with StringBuilder
if (result != null && result.isSuccessful()) {
logger.info("downloading of media id=" + mediaId + " succeeded.");
AsyncTask.execute(() -> {
// result contains the local file URI if successful
mediaFileDao.setLocalUri(mediaId, result.unwrap());
});
} else {
logger.warn("downloading of media id=" + mediaId + " failed.");
if (result.getErrorType() == ActionResult.NETWORK_ERROR) {
logger.warn("due to network error.");
} else {
logger.warn("due to unknown error.");
}
}
}).exceptionally((e) -> {
logger.error("downloading of media id=" + mediaId + " failed spectacularly:");
e.printStackTrace();
return null;
});
} | private void downloadMedia(MediaFileInfo fileInfo) {
if (fileInfo == null) {
return;
}
int mediaId = fileInfo.getId();
getDelegate(fileInfo.getType()).onDownloadMedia(fileInfo)
.thenAcceptAsync((result) -> {
if (result != null && result.isSuccessful()) {
logger.info("downloading of media id=" + mediaId + " succeeded.");
AsyncTask.execute(() -> {
mediaFileDao.setLocalUri(mediaId, result.unwrap());
});
} else {
logger.warn("downloading of media id=" + mediaId + " failed.");
if (result.getErrorType() == ActionResult.NETWORK_ERROR) {
logger.warn("due to network error.");
} else {
logger.warn("due to unknown error.");
}
}
}).exceptionally((e) -> {
logger.error("downloading of media id=" + mediaId + " failed spectacularly:");
e.printStackTrace();
return null;
});
} | private void downloadmedia(mediafileinfo fileinfo) { if (fileinfo == null) { return; } int mediaid = fileinfo.getid(); getdelegate(fileinfo.gettype()).ondownloadmedia(fileinfo) .thenacceptasync((result) -> { if (result != null && result.issuccessful()) { logger.info("downloading of media id=" + mediaid + " succeeded."); asynctask.execute(() -> { mediafiledao.setlocaluri(mediaid, result.unwrap()); }); } else { logger.warn("downloading of media id=" + mediaid + " failed."); if (result.geterrortype() == actionresult.network_error) { logger.warn("due to network error."); } else { logger.warn("due to unknown error."); } } }).exceptionally((e) -> { logger.error("downloading of media id=" + mediaid + " failed spectacularly:"); e.printstacktrace(); return null; }); } | COMP30022-Russia/Russia_Client | [
1,
0,
0,
0
] |
21,825 | private CompletableFuture<Void> uploadMedia(MediaFileInfo fileInfo) {
if (fileInfo == null) {
return CompletableFuture.completedFuture(null);
}
int mediaId = fileInfo.getId();
return getDelegate(fileInfo.getType()).onUploadMedia(fileInfo)
.thenAcceptAsync((result) -> {
// @todo: replace with StringBuilder
if (result != null && result.isSuccessful()) {
logger.info("uploading of media id=" + mediaId + " succeeded.");
AsyncTask.execute(() -> {
mediaFileDao.insertOrUpdate(fileInfo);
mediaFileDao.setRemoteAvailable(mediaId);
});
} else {
logger.warn("uploading of media id=" + mediaId + " failed.");
if (result.getErrorType() == ActionResult.NETWORK_ERROR) {
logger.warn("due to network error.");
} else {
logger.warn("due to unknown error.");
}
}
}).exceptionally((e) -> {
logger.error("uploading of media id=" + mediaId + " failed spectacularly:");
e.printStackTrace();
return null;
});
} | private CompletableFuture<Void> uploadMedia(MediaFileInfo fileInfo) {
if (fileInfo == null) {
return CompletableFuture.completedFuture(null);
}
int mediaId = fileInfo.getId();
return getDelegate(fileInfo.getType()).onUploadMedia(fileInfo)
.thenAcceptAsync((result) -> {
if (result != null && result.isSuccessful()) {
logger.info("uploading of media id=" + mediaId + " succeeded.");
AsyncTask.execute(() -> {
mediaFileDao.insertOrUpdate(fileInfo);
mediaFileDao.setRemoteAvailable(mediaId);
});
} else {
logger.warn("uploading of media id=" + mediaId + " failed.");
if (result.getErrorType() == ActionResult.NETWORK_ERROR) {
logger.warn("due to network error.");
} else {
logger.warn("due to unknown error.");
}
}
}).exceptionally((e) -> {
logger.error("uploading of media id=" + mediaId + " failed spectacularly:");
e.printStackTrace();
return null;
});
} | private completablefuture<void> uploadmedia(mediafileinfo fileinfo) { if (fileinfo == null) { return completablefuture.completedfuture(null); } int mediaid = fileinfo.getid(); return getdelegate(fileinfo.gettype()).onuploadmedia(fileinfo) .thenacceptasync((result) -> { if (result != null && result.issuccessful()) { logger.info("uploading of media id=" + mediaid + " succeeded."); asynctask.execute(() -> { mediafiledao.insertorupdate(fileinfo); mediafiledao.setremoteavailable(mediaid); }); } else { logger.warn("uploading of media id=" + mediaid + " failed."); if (result.geterrortype() == actionresult.network_error) { logger.warn("due to network error."); } else { logger.warn("due to unknown error."); } } }).exceptionally((e) -> { logger.error("uploading of media id=" + mediaid + " failed spectacularly:"); e.printstacktrace(); return null; }); } | COMP30022-Russia/Russia_Client | [
1,
0,
0,
0
] |
13,695 | public static Command getMecControllerCommand(PathPlannerTrajectory ppTrajectory, MecDriveTrain mecDriveTrain) {
// Create config for trajectory
/*TrajectoryConfig config =
new TrajectoryConfig(Constants.maxMecSpeed,Constants.maxMecAcceleration)
// Add kinematics to ensure max speed is actually obeyed
.setKinematics(mecDriveTrain.getMecKinetimatics());
// An example trajectory to follow. All units in meters.
Trajectory exampleTrajectory =
TrajectoryGenerator.generateTrajectory(
// Start at the origin facing the +X direction
new Pose2d(0, 0, new Rotation2d(0)),
// Pass through these two interior waypoints, making an 's' curve path
List.of(new Translation2d(1, 1), new Translation2d(2, -1)),
// End 3 meters straight ahead of where we started, facing forward
new Pose2d(3, 0, new Rotation2d(0)),
config);*/
ProfiledPIDController thetaController = new ProfiledPIDController(Constants.kpMecThetaController, 0., 0.,
new Constraints(Constants.maxMecRotationVelocity, Constants.maxMecRotationAccel));
thetaController.enableContinuousInput(-Math.PI, Math.PI);
thetaController.reset(RobotState.getPoseEstimate().getRotation().getRadians());
//mecDriveTrain.setPose(ppTrajectory.getInitialPose());
PPMecanumControllerCommand mecanumControllerCommand = new PPMecanumControllerCommand(
ppTrajectory,
RobotState::getPoseEstimate,
//TODO go to WPILIB source code for mecControlCommand and see how they use this feedforward
//and then use that in the mecDriveTrain.setSpeeds() method
//mecDriveTrain.getMecFeedforward(),
RobotState.getMecKinematics(),
// Position contollers
new PIDController(Constants.kpMecPosXController, 0, 0),
new PIDController(Constants.kpMecPosYController, 0, 0),
thetaController,
// Needed for normalizing wheel speeds
//Constants.maxMecSpeed,
// Velocity PID's
/*new PIDController(Constants.kpMecL1Velocity, 0, 0),
new PIDController(Constants.kpMecL2Velocity, 0, 0),
new PIDController(Constants.kpMecR1Velocity, 0, 0),
new PIDController(Constants.kpMecR2Velocity, 0, 0),*/
//mecDriveTrain::getCurrentWheelSpeeds,
mecDriveTrain::setSpeeds, // Consumer for the output motor voltages
mecDriveTrain
);
//PathPlannerState initialState = ppTrajectory.getInitialState();
/*return new InstantCommand(() ->
mecDriveTrain.setPose(new Pose2d(initialState.poseMeters.getTranslation(), initialState.holonomicRotation)))
.andThen(mecanumControllerCommand);
//.andThen(mecDriveTrain::stopDrive);*/
return mecanumControllerCommand;
} | public static Command getMecControllerCommand(PathPlannerTrajectory ppTrajectory, MecDriveTrain mecDriveTrain) {
ProfiledPIDController thetaController = new ProfiledPIDController(Constants.kpMecThetaController, 0., 0.,
new Constraints(Constants.maxMecRotationVelocity, Constants.maxMecRotationAccel));
thetaController.enableContinuousInput(-Math.PI, Math.PI);
thetaController.reset(RobotState.getPoseEstimate().getRotation().getRadians());
PPMecanumControllerCommand mecanumControllerCommand = new PPMecanumControllerCommand(
ppTrajectory,
RobotState::getPoseEstimate,
RobotState.getMecKinematics(),
new PIDController(Constants.kpMecPosXController, 0, 0),
new PIDController(Constants.kpMecPosYController, 0, 0),
thetaController,
mecDriveTrain::setSpeeds,
mecDriveTrain
);
return mecanumControllerCommand;
} | public static command getmeccontrollercommand(pathplannertrajectory pptrajectory, mecdrivetrain mecdrivetrain) { profiledpidcontroller thetacontroller = new profiledpidcontroller(constants.kpmecthetacontroller, 0., 0., new constraints(constants.maxmecrotationvelocity, constants.maxmecrotationaccel)); thetacontroller.enablecontinuousinput(-math.pi, math.pi); thetacontroller.reset(robotstate.getposeestimate().getrotation().getradians()); ppmecanumcontrollercommand mecanumcontrollercommand = new ppmecanumcontrollercommand( pptrajectory, robotstate::getposeestimate, robotstate.getmeckinematics(), new pidcontroller(constants.kpmecposxcontroller, 0, 0), new pidcontroller(constants.kpmecposycontroller, 0, 0), thetacontroller, mecdrivetrain::setspeeds, mecdrivetrain ); return mecanumcontrollercommand; } | FRC6302/2022Bot1 | [
1,
0,
0,
0
] |
14,329 | public void importAlliancesScoring(HashMap<MatchGeneral, MatchDetailRelicJSON> scores){
File allianceFile = new File(Config.SCORING_DIR + File.separator + "alliances.txt");
if (allianceFile.exists()) {
try {
BufferedReader reader = new BufferedReader(new FileReader(allianceFile));
String line;
alliances = new Alliance[4];
while ((line = reader.readLine()) != null) {
/* Alliance info */
String[] allianceInfo = line.split("\\|");
int division = Integer.parseInt(allianceInfo[0]);
int allianceNumber = Integer.parseInt(allianceInfo[1]);
int[] allianceNumbers = {Integer.parseInt(allianceInfo[3]), Integer.parseInt(allianceInfo[4]), Integer.parseInt(allianceInfo[5])};
alliances[allianceNumber-1] = new Alliance(division, allianceNumber, allianceNumbers);
}
reader.close();
/* TODO - Make Upload Alliances so we can uncomment this
controller.btnUploadAlliances.setDisable(false);*/
updateAllianceLabels(scores);
TOALogger.log(Level.INFO, "Alliance import successful.");
} catch (Exception e) {
e.printStackTrace();
controller.sendError("Could not open file. " + e.getLocalizedMessage());
}
} else {
controller.sendError("Could not locate alliances.txt from the Scoring System. Did you generate an elimination bracket?");
}
} | public void importAlliancesScoring(HashMap<MatchGeneral, MatchDetailRelicJSON> scores){
File allianceFile = new File(Config.SCORING_DIR + File.separator + "alliances.txt");
if (allianceFile.exists()) {
try {
BufferedReader reader = new BufferedReader(new FileReader(allianceFile));
String line;
alliances = new Alliance[4];
while ((line = reader.readLine()) != null) {
String[] allianceInfo = line.split("\\|");
int division = Integer.parseInt(allianceInfo[0]);
int allianceNumber = Integer.parseInt(allianceInfo[1]);
int[] allianceNumbers = {Integer.parseInt(allianceInfo[3]), Integer.parseInt(allianceInfo[4]), Integer.parseInt(allianceInfo[5])};
alliances[allianceNumber-1] = new Alliance(division, allianceNumber, allianceNumbers);
}
reader.close();
updateAllianceLabels(scores);
TOALogger.log(Level.INFO, "Alliance import successful.");
} catch (Exception e) {
e.printStackTrace();
controller.sendError("Could not open file. " + e.getLocalizedMessage());
}
} else {
controller.sendError("Could not locate alliances.txt from the Scoring System. Did you generate an elimination bracket?");
}
} | public void importalliancesscoring(hashmap<matchgeneral, matchdetailrelicjson> scores){ file alliancefile = new file(config.scoring_dir + file.separator + "alliances.txt"); if (alliancefile.exists()) { try { bufferedreader reader = new bufferedreader(new filereader(alliancefile)); string line; alliances = new alliance[4]; while ((line = reader.readline()) != null) { string[] allianceinfo = line.split("\\|"); int division = integer.parseint(allianceinfo[0]); int alliancenumber = integer.parseint(allianceinfo[1]); int[] alliancenumbers = {integer.parseint(allianceinfo[3]), integer.parseint(allianceinfo[4]), integer.parseint(allianceinfo[5])}; alliances[alliancenumber-1] = new alliance(division, alliancenumber, alliancenumbers); } reader.close(); updatealliancelabels(scores); toalogger.log(level.info, "alliance import successful."); } catch (exception e) { e.printstacktrace(); controller.senderror("could not open file. " + e.getlocalizedmessage()); } } else { controller.senderror("could not locate alliances.txt from the scoring system. did you generate an elimination bracket?"); } } | Agardner329/TOA-DataSync | [
0,
1,
0,
0
] |
14,380 | public void testEmit() throws Exception {
eh.on("ok", new EventEmitter.Listener() {
@Override
public void onEvent(Object data) {
String ss = (String) data;
if (ss == "ok")
Log.d(TAG, "pass@" + ss);
else
Log.d(TAG, "fail@" + ss);
}
});
eh.on("no", new EventEmitter.Listener() {
@Override
public void onEvent(Object data) {
String ss = (String) data;
if (ss == "no")
Log.d(TAG, "pass@" + ss);
else
Log.d(TAG, "fail@" + ss);
}
});
eh.emit("ok");
eh.emit("ok", "ok");
eh.emit("ok", "no");
eh.emit("no");
eh.emit("no", "no");
eh.emit("no", "ok");
eh.emit("unknown");
eh.emit("unknown", "ok");
eh.emit("unknown", "no");
fail(); // FIXME these tests are not correct
} | public void testEmit() throws Exception {
eh.on("ok", new EventEmitter.Listener() {
@Override
public void onEvent(Object data) {
String ss = (String) data;
if (ss == "ok")
Log.d(TAG, "pass@" + ss);
else
Log.d(TAG, "fail@" + ss);
}
});
eh.on("no", new EventEmitter.Listener() {
@Override
public void onEvent(Object data) {
String ss = (String) data;
if (ss == "no")
Log.d(TAG, "pass@" + ss);
else
Log.d(TAG, "fail@" + ss);
}
});
eh.emit("ok");
eh.emit("ok", "ok");
eh.emit("ok", "no");
eh.emit("no");
eh.emit("no", "no");
eh.emit("no", "ok");
eh.emit("unknown");
eh.emit("unknown", "ok");
eh.emit("unknown", "no");
fail();
} | public void testemit() throws exception { eh.on("ok", new eventemitter.listener() { @override public void onevent(object data) { string ss = (string) data; if (ss == "ok") log.d(tag, "pass@" + ss); else log.d(tag, "fail@" + ss); } }); eh.on("no", new eventemitter.listener() { @override public void onevent(object data) { string ss = (string) data; if (ss == "no") log.d(tag, "pass@" + ss); else log.d(tag, "fail@" + ss); } }); eh.emit("ok"); eh.emit("ok", "ok"); eh.emit("ok", "no"); eh.emit("no"); eh.emit("no", "no"); eh.emit("no", "ok"); eh.emit("unknown"); eh.emit("unknown", "ok"); eh.emit("unknown", "no"); fail(); } | InstantWebP2P/node-android | [
0,
0,
0,
1
] |
14,566 | private void resolveDetail(CompletionItem item, CompletionData data, Tree tree) {
if (tree instanceof MethodTree) {
var method = (MethodTree) tree;
var parameters = new StringJoiner(", ");
for (var p : method.getParameters()) {
parameters.add(p.getType() + " " + p.getName());
}
item.detail = method.getReturnType() + " " + method.getName() + "(" + parameters + ")";
if (!method.getThrows().isEmpty()) {
var exceptions = new StringJoiner(", ");
for (var e : method.getThrows()) {
exceptions.add(e.toString());
}
item.detail += " throws " + exceptions;
}
if (data.plusOverloads != 0) {
item.detail += " (+" + data.plusOverloads + " overloads)";
}
}
} | private void resolveDetail(CompletionItem item, CompletionData data, Tree tree) {
if (tree instanceof MethodTree) {
var method = (MethodTree) tree;
var parameters = new StringJoiner(", ");
for (var p : method.getParameters()) {
parameters.add(p.getType() + " " + p.getName());
}
item.detail = method.getReturnType() + " " + method.getName() + "(" + parameters + ")";
if (!method.getThrows().isEmpty()) {
var exceptions = new StringJoiner(", ");
for (var e : method.getThrows()) {
exceptions.add(e.toString());
}
item.detail += " throws " + exceptions;
}
if (data.plusOverloads != 0) {
item.detail += " (+" + data.plusOverloads + " overloads)";
}
}
} | private void resolvedetail(completionitem item, completiondata data, tree tree) { if (tree instanceof methodtree) { var method = (methodtree) tree; var parameters = new stringjoiner(", "); for (var p : method.getparameters()) { parameters.add(p.gettype() + " " + p.getname()); } item.detail = method.getreturntype() + " " + method.getname() + "(" + parameters + ")"; if (!method.getthrows().isempty()) { var exceptions = new stringjoiner(", "); for (var e : method.getthrows()) { exceptions.add(e.tostring()); } item.detail += " throws " + exceptions; } if (data.plusoverloads != 0) { item.detail += " (+" + data.plusoverloads + " overloads)"; } } } | 80952556400/java-language-server | [
1,
0,
0,
0
] |
30,960 | public void validateFloweringTime(String scientificName, String eventDate, String reproductiveState, String country, String kingdom, String latitude, String longitude) {
HashMap<String, String> initialValues = new HashMap<String, String>();
initialValues.put("eventDate", eventDate);
initialValues.put("scientificName", scientificName);
initialValues.put("reproductive", reproductiveState);
initialValues.put("country", country);
initialValues.put("kingdom", kingdom);
initialValues.put("latitude", latitude);
initialValues.put("longitude", longitude);
initDate(new CurationStep("Validate Collecting Event Date: check dwc:eventDate against reproductive state. ", initialValues));
// TODO: fix to compare provided eventDate and reproductiveState with data from FNA
Vector<String> months = new Vector<String>();
Vector<String> foundFloweringTime = null;
if(authoritativeFloweringTimeMap != null && authoritativeFloweringTimeMap.containsKey(scientificName.toLowerCase())){
foundFloweringTime = authoritativeFloweringTimeMap.get(scientificName.toLowerCase());
}
if(foundFloweringTime == null){
setCurationStatus(CurationComment.UNABLE_DETERMINE_VALIDITY);
addToComment("Can't find the flowering time of the "+scientificName+" in the current available phenology data from FNA.");
correctedFloweringTime = null;
}else{
if(months==null || !months.containsAll(foundFloweringTime) || !foundFloweringTime.containsAll(months) ){
setCurationStatus(CurationComment.UNABLE_CURATED);
addToComment("Provided event date and flowering state is inconsistent with known flowering times for species according to FNA.");
}else{
setCurationStatus(CurationComment.CORRECT);
addToComment("The event date and flowering state is consistent with authoritative data from FNA");
correctedFloweringTime = months;
}
}
} | public void validateFloweringTime(String scientificName, String eventDate, String reproductiveState, String country, String kingdom, String latitude, String longitude) {
HashMap<String, String> initialValues = new HashMap<String, String>();
initialValues.put("eventDate", eventDate);
initialValues.put("scientificName", scientificName);
initialValues.put("reproductive", reproductiveState);
initialValues.put("country", country);
initialValues.put("kingdom", kingdom);
initialValues.put("latitude", latitude);
initialValues.put("longitude", longitude);
initDate(new CurationStep("Validate Collecting Event Date: check dwc:eventDate against reproductive state. ", initialValues));
Vector<String> months = new Vector<String>();
Vector<String> foundFloweringTime = null;
if(authoritativeFloweringTimeMap != null && authoritativeFloweringTimeMap.containsKey(scientificName.toLowerCase())){
foundFloweringTime = authoritativeFloweringTimeMap.get(scientificName.toLowerCase());
}
if(foundFloweringTime == null){
setCurationStatus(CurationComment.UNABLE_DETERMINE_VALIDITY);
addToComment("Can't find the flowering time of the "+scientificName+" in the current available phenology data from FNA.");
correctedFloweringTime = null;
}else{
if(months==null || !months.containsAll(foundFloweringTime) || !foundFloweringTime.containsAll(months) ){
setCurationStatus(CurationComment.UNABLE_CURATED);
addToComment("Provided event date and flowering state is inconsistent with known flowering times for species according to FNA.");
}else{
setCurationStatus(CurationComment.CORRECT);
addToComment("The event date and flowering state is consistent with authoritative data from FNA");
correctedFloweringTime = months;
}
}
} | public void validatefloweringtime(string scientificname, string eventdate, string reproductivestate, string country, string kingdom, string latitude, string longitude) { hashmap<string, string> initialvalues = new hashmap<string, string>(); initialvalues.put("eventdate", eventdate); initialvalues.put("scientificname", scientificname); initialvalues.put("reproductive", reproductivestate); initialvalues.put("country", country); initialvalues.put("kingdom", kingdom); initialvalues.put("latitude", latitude); initialvalues.put("longitude", longitude); initdate(new curationstep("validate collecting event date: check dwc:eventdate against reproductive state. ", initialvalues)); vector<string> months = new vector<string>(); vector<string> foundfloweringtime = null; if(authoritativefloweringtimemap != null && authoritativefloweringtimemap.containskey(scientificname.tolowercase())){ foundfloweringtime = authoritativefloweringtimemap.get(scientificname.tolowercase()); } if(foundfloweringtime == null){ setcurationstatus(curationcomment.unable_determine_validity); addtocomment("can't find the flowering time of the "+scientificname+" in the current available phenology data from fna."); correctedfloweringtime = null; }else{ if(months==null || !months.containsall(foundfloweringtime) || !foundfloweringtime.containsall(months) ){ setcurationstatus(curationcomment.unable_curated); addtocomment("provided event date and flowering state is inconsistent with known flowering times for species according to fna."); }else{ setcurationstatus(curationcomment.correct); addtocomment("the event date and flowering state is consistent with authoritative data from fna"); correctedfloweringtime = months; } } } | FilteredPush/FP-KurationServices | [
1,
0,
0,
0
] |
22,911 | private void pickRawContactDelta() {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "parse: " + mRawContactDeltas.size() + " rawContactDelta(s)");
}
for (int j = 0; j < mRawContactDeltas.size(); j++) {
final RawContactDelta rawContactDelta = mRawContactDeltas.get(j);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "parse: " + j + " rawContactDelta" + rawContactDelta);
}
if (rawContactDelta == null || !rawContactDelta.isVisible()) continue;
final AccountType accountType = rawContactDelta.getAccountType(mAccountTypeManager);
if (accountType == null) continue;
if (mRawContactIdToDisplayAlone > 0) {
// Look for the raw contact if specified.
if (rawContactDelta.getRawContactId().equals(mRawContactIdToDisplayAlone)) {
mCurrentRawContactDelta = rawContactDelta;
return;
}
} else if (mPrimaryAccount != null
&& mPrimaryAccount.equals(rawContactDelta.getAccountWithDataSet())) {
// Otherwise try to find the one that matches the default.
mCurrentRawContactDelta = rawContactDelta;
return;
} else if (accountType.areContactsWritable()){
// TODO: Find better raw contact delta
// Just select an arbitrary writable contact.
mCurrentRawContactDelta = rawContactDelta;
}
}
} | private void pickRawContactDelta() {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "parse: " + mRawContactDeltas.size() + " rawContactDelta(s)");
}
for (int j = 0; j < mRawContactDeltas.size(); j++) {
final RawContactDelta rawContactDelta = mRawContactDeltas.get(j);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "parse: " + j + " rawContactDelta" + rawContactDelta);
}
if (rawContactDelta == null || !rawContactDelta.isVisible()) continue;
final AccountType accountType = rawContactDelta.getAccountType(mAccountTypeManager);
if (accountType == null) continue;
if (mRawContactIdToDisplayAlone > 0) {
if (rawContactDelta.getRawContactId().equals(mRawContactIdToDisplayAlone)) {
mCurrentRawContactDelta = rawContactDelta;
return;
}
} else if (mPrimaryAccount != null
&& mPrimaryAccount.equals(rawContactDelta.getAccountWithDataSet())) {
mCurrentRawContactDelta = rawContactDelta;
return;
} else if (accountType.areContactsWritable()){
mCurrentRawContactDelta = rawContactDelta;
}
}
} | private void pickrawcontactdelta() { if (log.isloggable(tag, log.verbose)) { log.v(tag, "parse: " + mrawcontactdeltas.size() + " rawcontactdelta(s)"); } for (int j = 0; j < mrawcontactdeltas.size(); j++) { final rawcontactdelta rawcontactdelta = mrawcontactdeltas.get(j); if (log.isloggable(tag, log.verbose)) { log.v(tag, "parse: " + j + " rawcontactdelta" + rawcontactdelta); } if (rawcontactdelta == null || !rawcontactdelta.isvisible()) continue; final accounttype accounttype = rawcontactdelta.getaccounttype(maccounttypemanager); if (accounttype == null) continue; if (mrawcontactidtodisplayalone > 0) { if (rawcontactdelta.getrawcontactid().equals(mrawcontactidtodisplayalone)) { mcurrentrawcontactdelta = rawcontactdelta; return; } } else if (mprimaryaccount != null && mprimaryaccount.equals(rawcontactdelta.getaccountwithdataset())) { mcurrentrawcontactdelta = rawcontactdelta; return; } else if (accounttype.arecontactswritable()){ mcurrentrawcontactdelta = rawcontactdelta; } } } | BrahmaOS/brahmaos-packages-apps-Contacts | [
1,
0,
0,
0
] |
22,966 | @Override
public void interruptionOccurred(int currentIteration, int numIterations) {
// FIXME: maybe skip writing the SOM at 0 iterations (0 mod x == 0 ...)
String filename = fileProperties.namePrefix(false) + "_" + currentIteration;
try {
SOMLibMapOutputter.writeWeightVectorFile(GrowingSOM.this, fileProperties.outputDirectory(), filename,
true, "$CURRENT_ITERATION=" + currentIteration, "$NUM_ITERATIONS=" + numIterations);
} catch (IOException e) {
Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(
"Could not open or write to output file " + filename + ": " + e.getMessage());
}
} | @Override
public void interruptionOccurred(int currentIteration, int numIterations) {
String filename = fileProperties.namePrefix(false) + "_" + currentIteration;
try {
SOMLibMapOutputter.writeWeightVectorFile(GrowingSOM.this, fileProperties.outputDirectory(), filename,
true, "$CURRENT_ITERATION=" + currentIteration, "$NUM_ITERATIONS=" + numIterations);
} catch (IOException e) {
Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(
"Could not open or write to output file " + filename + ": " + e.getMessage());
}
} | @override public void interruptionoccurred(int currentiteration, int numiterations) { string filename = fileproperties.nameprefix(false) + "_" + currentiteration; try { somlibmapoutputter.writeweightvectorfile(growingsom.this, fileproperties.outputdirectory(), filename, true, "$current_iteration=" + currentiteration, "$num_iterations=" + numiterations); } catch (ioexception e) { logger.getlogger("at.tuwien.ifs.somtoolbox").severe( "could not open or write to output file " + filename + ": " + e.getmessage()); } } | ChrisPrein/TUW_SelfOrganizingSystems_WS2021 | [
0,
0,
1,
0
] |
23,001 | public void generate(ICubicWorld world, ICubePrimer cube, CubePos cubePos) {
//TODO: maybe skip some of this stuff if the cube is empty? (would need to use hints)
int radius = this.range;
this.world = world;
this.rand.setSeed(world.getSeed());
//used to randomize contribution of each coordinate to the cube seed
//without these swapping x/y/z coordinates would result in the same seed
//so structures would generate symmetrically
long randX = this.rand.nextLong();
long randY = this.rand.nextLong();
long randZ = this.rand.nextLong();
int cubeX = cubePos.getX();
int cubeY = cubePos.getY();
int cubeZ = cubePos.getZ();
//x/y/zOrigin is location of the structure "center", and cubeX/Y/Z is the currently generated cube
for (int xOrigin = cubeX - radius; xOrigin <= cubeX + radius; ++xOrigin) {
for (int yOrigin = cubeY - radius; yOrigin <= cubeY + radius; ++yOrigin) {
for (int zOrigin = cubeZ - radius; zOrigin <= cubeZ + radius; ++zOrigin) {
long randX_mul = xOrigin*randX;
long randY_mul = yOrigin*randY;
long randZ_mul = zOrigin*randZ;
this.rand.setSeed(randX_mul ^ randY_mul ^ randZ_mul ^ world.getSeed());
this.generate(world, cube, xOrigin, yOrigin, zOrigin, cubePos);
}
}
}
} | public void generate(ICubicWorld world, ICubePrimer cube, CubePos cubePos) {
int radius = this.range;
this.world = world;
this.rand.setSeed(world.getSeed());
long randX = this.rand.nextLong();
long randY = this.rand.nextLong();
long randZ = this.rand.nextLong();
int cubeX = cubePos.getX();
int cubeY = cubePos.getY();
int cubeZ = cubePos.getZ();
for (int xOrigin = cubeX - radius; xOrigin <= cubeX + radius; ++xOrigin) {
for (int yOrigin = cubeY - radius; yOrigin <= cubeY + radius; ++yOrigin) {
for (int zOrigin = cubeZ - radius; zOrigin <= cubeZ + radius; ++zOrigin) {
long randX_mul = xOrigin*randX;
long randY_mul = yOrigin*randY;
long randZ_mul = zOrigin*randZ;
this.rand.setSeed(randX_mul ^ randY_mul ^ randZ_mul ^ world.getSeed());
this.generate(world, cube, xOrigin, yOrigin, zOrigin, cubePos);
}
}
}
} | public void generate(icubicworld world, icubeprimer cube, cubepos cubepos) { int radius = this.range; this.world = world; this.rand.setseed(world.getseed()); long randx = this.rand.nextlong(); long randy = this.rand.nextlong(); long randz = this.rand.nextlong(); int cubex = cubepos.getx(); int cubey = cubepos.gety(); int cubez = cubepos.getz(); for (int xorigin = cubex - radius; xorigin <= cubex + radius; ++xorigin) { for (int yorigin = cubey - radius; yorigin <= cubey + radius; ++yorigin) { for (int zorigin = cubez - radius; zorigin <= cubez + radius; ++zorigin) { long randx_mul = xorigin*randx; long randy_mul = yorigin*randy; long randz_mul = zorigin*randz; this.rand.setseed(randx_mul ^ randy_mul ^ randz_mul ^ world.getseed()); this.generate(world, cube, xorigin, yorigin, zorigin, cubepos); } } } } | Cyclonit/CubicChunks | [
0,
1,
0,
0
] |
31,498 | public void testGetEnteredDate() {
System.out.println("testGetEnteredDate");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testGetEnteredDate() {
System.out.println("testGetEnteredDate");
fail("The test case is empty.");
} | public void testgetentereddate() { system.out.println("testgetentereddate"); fail("the test case is empty."); } | CBIIT/camod | [
0,
0,
0,
1
] |
31,499 | public void testSetEnteredDate() {
System.out.println("testSetEnteredDate");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testSetEnteredDate() {
System.out.println("testSetEnteredDate");
fail("The test case is empty.");
} | public void testsetentereddate() { system.out.println("testsetentereddate"); fail("the test case is empty."); } | CBIIT/camod | [
0,
0,
0,
1
] |
31,500 | public void testGetModifiedDate() {
System.out.println("testGetModifiedDate");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testGetModifiedDate() {
System.out.println("testGetModifiedDate");
fail("The test case is empty.");
} | public void testgetmodifieddate() { system.out.println("testgetmodifieddate"); fail("the test case is empty."); } | CBIIT/camod | [
0,
0,
0,
1
] |
31,501 | public void testSetModifiedDate() {
System.out.println("testSetModifiedDate");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testSetModifiedDate() {
System.out.println("testSetModifiedDate");
fail("The test case is empty.");
} | public void testsetmodifieddate() { system.out.println("testsetmodifieddate"); fail("the test case is empty."); } | CBIIT/camod | [
0,
1,
0,
0
] |
31,502 | public void testGetReleaseDate() {
System.out.println("testGetReleaseDate");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testGetReleaseDate() {
System.out.println("testGetReleaseDate");
fail("The test case is empty.");
} | public void testgetreleasedate() { system.out.println("testgetreleasedate"); fail("the test case is empty."); } | CBIIT/camod | [
0,
0,
0,
1
] |
31,503 | public void testSetReleaseDate() {
System.out.println("testSetReleaseDate");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testSetReleaseDate() {
System.out.println("testSetReleaseDate");
fail("The test case is empty.");
} | public void testsetreleasedate() { system.out.println("testsetreleasedate"); fail("the test case is empty."); } | CBIIT/camod | [
0,
0,
0,
1
] |
31,504 | public void testGetVisibleTo() {
System.out.println("testGetVisibleTo");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testGetVisibleTo() {
System.out.println("testGetVisibleTo");
fail("The test case is empty.");
} | public void testgetvisibleto() { system.out.println("testgetvisibleto"); fail("the test case is empty."); } | CBIIT/camod | [
0,
0,
0,
1
] |
31,505 | public void testSetVisibleTo() {
System.out.println("testSetVisibleTo");
// TODO add your test code below by replacing the default call to fail.
fail("The test case is empty.");
} | public void testSetVisibleTo() {
System.out.println("testSetVisibleTo");
fail("The test case is empty.");
} | public void testsetvisibleto() { system.out.println("testsetvisibleto"); fail("the test case is empty."); } | CBIIT/camod | [
0,
0,
0,
1
] |