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", "[email protected]")); //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 ]
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
9
Edit dataset card

Models trained or fine-tuned on NamCyan/tesoro-code

Collection including NamCyan/tesoro-code