lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | Lets say we have some types defined as so : And we construct two lists of the sub class type like thisIs there a way we can implement a function that can can filter both subClassAList and subClassBList on the Value property ? I know this can be achieved through casting the results of a function like so : But then we ne... | public class BaseClass { public int Value { get ; set ; } } public class SubClassA : BaseClass { public bool SomeBoolValue { get ; set ; } } public class SubClassB : BaseClass { public decimal SomeDecimalValue { get ; set ; } } List < SubClassA > subClassAList = new List < SubClassA > { new SubClassA { SomeBoolValue = ... | Writing a function to filter a list of a items by a property on it 's base type in c # |
C# | I have written some unit tests yesterday that pass in .NET 4.6.1 but fail in .NET core 3.0 because the number of array instances that is generated during that test is different in both environments . After some investigation it turned out that the count of empty arrays created with LINQ is different . I was finally abl... | [ Test ] public void ArrayTest ( ) { var numbers = Enumerable.Range ( 1 , 5 ) ; int [ ] items1 = numbers.Where ( i = > i > 5 ) .ToArray ( ) ; int [ ] items2 = numbers.Where ( i = > i > 5 ) .ToArray ( ) ; Assert.IsFalse ( items1 == items2 ) ; // fails in .NET core 3 but passes in .NET 461 Assert.IsFalse ( items1.Equals ... | Definition of `` Equals '' for empty arrays and difference between .NET and .NET core |
C# | Hi guys , I came across this line . Can anyone decipher this line/group them into parenthesis for me ? Appreciate any help given . Thanks in advance : D | bool isGeneric = variableA ! = null ? variableB ! = null ? false : true : true ; | c # - conditional operator expression ( a few in a row ) |
C# | Regarding Razor expression usage ( ASP.Net ) cases , there are two cases commonly met : andAs they both seem to work the same on Razor 2.0 , I would like to know if there are any differences , especially in corner cases ( null/malfored values etc ) .Eventually I would also like to know which is best as a practice to fo... | < div title= '' @ MyClass.Test '' > < /div > < div title= @ MyClass.Test > < /div > | Usage of Razor expressions with or without string quotes |
C# | I was looking at the Dictionary < TKey , TValue > code in .NET Core and I 've notice a kind of coding pattern also used in some builtin datastructures like Queue < T > or Stack < T > and List < T > .For example about the : https : //github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Collecti... | Entry [ ] entries = _entries ; IEqualityComparer < TKey > comparer = _comparer ; | What the interest of copying the reference of a field in a method body to read it while the field is never reassigned ? |
C# | I have this query that counts the total number of +1 's a user has made on our website : Data originates from this table : A simple count of distinct URLs where IsOn = true will show the count of pages they have +1 'd . However , the table also stores when they un-plus1 something , by storing the value in IsOn as false... | return db.tblGPlusOneClicks .Where ( c = > c.UserID == UserID & & c.IsOn ) .Select ( c= > c.URLID ) .Distinct ( ) .Count ( ) ; | Linq to return records that do n't have a follow up record |
C# | I have used grid extra to design individual responsive components in my WPF application . I have a View like following : Next what I require was to bring a disable panel to flood over this user control disabling all the controls and graying out the UI like : As you can see next I wrap both in a container Panel and will... | < UserControl x : Class= '' ... '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '... | GridExtra Child Element Z-index |
C# | I am writing a small email templating engine using Razor syntax to fill in the tokens . I have a few email types : These types have corresponding templates and models , so for example Welcome email has a template : and a corresponding model : Now I wanted to create a method that will force a correct model for given enu... | public enum EmailType { Welcome , Reminder } < p > Welcome , @ Model.Name < /p > public class WelcomeModel { public string Name { get ; set ; } } public ITemplate < T > GenerateTemplate ( EmailType emailType ) { switch ( emailType ) { case EmailType.Welcome : return new EmailTemplate < WelcomeModel > ( ) ; case EmailTy... | Is it possible to return generic class based on enum input ? |
C# | How do I connect a button to a function in C # , ASP ? Maybe something like : C # Class : | < TemplateField > < ItemTemplate > < asp : Button ID= '' btnFunction1 '' runat= '' server CommandName= '' Function1 '' / > < /ItemTemplate > < /TemplateField > protected void Function1 ( ) { } | Gridview Button Functionality |
C# | I have the codewhy does the first one run and the second throw a exception ? Why selects int [ ] the Format ( String , Object ) overloadstring [ ] the Format ( String , Object [ ] ) overload | //this runs string [ ] s_items = { `` 0 '' , '' 0 '' } ; string s_output = string.Format ( `` { 0 } { 1 } '' , s_items ) ; //this one throws a exceptionint [ ] i_items = { 0,0 } ; string i_output = string.Format ( `` { 0 } { 1 } '' , i_items ) ; | Correct overload selection |
C# | First post on here and quite a simple one.I 've been looking into simplifying some complex queries in an application I 'm developing and I 'm scratching my head a bit on the below.So say I have these two classes : A domain entity `` EmailRecipient '' ( used with EF code-first so expect a SQL table to be generated with ... | public class EmailRecipient { public Guid Id { get ; set ; } public string FriendlyName { get ; set ; } public string ExchangeName { get ; set ; } public string Surname { get ; set ; } public string Forename { get ; set ; } public string EmailAddress { get ; set ; } public string JobTitle { get ; set ; } public virtual... | Entity Framework projection behaviour |
C# | I have one big difficulty . I got the question to answer : What features should MyClass have in order to be correct ? I have tried to find the answer since friday but I have no results yet . Have you got any ideas about it ? | var myVariable = new MyClass { 25 } ; | Anonymous types ( classes features ) |
C# | Here I 'm new to AsyncController please help me why I 'm not able to fetch data from db by using async : If I change above code as : Its working.Please guide me where exactly i 'm doing wrong | public async Task < ActionResult > Index ( ) { Task < IEnumerable < Country > > objctry = Task.Factory.StartNew < IEnumerable < Country > > ( objrepo.GetCountry ) ; await Task.WhenAll ( objctry ) ; return View ( objctry ) ; } public ActionResult Index ( ) { var x = objrepo.GetCountry ( ) ; return View ( x ) ; } | Why asyncController failed to fetching data |
C# | I 'm not that savvy in regex , so I 'm not sure how to achieve the following thing : I 'd like to capture any arbitary string from an input that may or may not be surrounded by the ' $ ' character . If a ' $ ' character is present at the beginning of the string , the ' $ ' character at the end must be present.Currently... | ^\w+ ( [ _.- ] \w+ ) * $ testtest-5test.1.3test-alpha.2 $ test $ $ test ( or test $ ) | capture optional surrounding characters |
C# | I have two rectangles in my WPF application . I want to play an animation when I click on an element . The animation should be applied to only the clicked rectangle . With the code below , when I click on a rectangle , all the shapes get animated . What should I do ? ? and the c # | Window.Resources > < ResourceDictionary > < LinearGradientBrush x : Key= '' ExecutionInitialization '' EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' # FFC0FBBA '' / > < GradientStop Color= '' # FF0FA000 '' Offset= '' 1 '' / > < GradientStop Color= '' # FF0FA000 '' / > < /LinearGradientBrush >... | Storyboard is applied to many elements |
C# | I would like to search the data from database from two tables with multiple optional values.First I am creating AsQueryable object for querying.Then I 'm applying conditions to this AsQueryable object one by one.Then finally I 'm trying to get the data from searchQuery object into some other object by selecting columns... | [ HttpPost ] public ActionResult GetAll ( Details objDetail ) { var searchQuery = ( from acc in AppDB.tblAccount join user in AppDB.tblUser on acc.uID equals user.uID select new { acc , user } ) .AsQueryable ( ) ; if ( objDetail.Type ! = null ) searchQuery = searchQuery.Where ( x = > x.acc.Type == objDetail.Type ) ; if... | How to get data by mutiple values on one column with different values on other columns from database in Entity Framework ? |
C# | I 'm having an issue when iterating through one dimension of a two dimensional array , in a C # console application . It 's part of a game that comes up with witty responses for each time you miss a shot , or you shot successfully . Let me start off with a two-dimensional boolean that I 've made : There are two rows in... | public static bool [ , ] hasResponseBeenUsedBefore = new bool [ 2 , 11 ] ; int usedManyTimes = 0 ; for ( int i = 0 ; i < hasResponseBeenUsedBefore.GetLength ( 1 ) ; i++ ) { MessageBox.Show ( i.ToString ( ) ) ; if ( hasResponseBeenUsedBefore [ 2 , i ] == true ) // 2 is the dimension for unsuccessful responses { usedMany... | Iterating through other part of dimension in a for loop throws an IndexOutOfRangeException ( C # ) |
Java | I 'm working with JMS and queues ( Azure queues ) for the first time . I 'm required to make a queue where Rubi server would write some data and Java would read it from queue and will do further executions . This process is working fine locally on my machine . I 've created a REST endpoint which is writing data in the ... | Setup of JMS message listener invoker failed for destination 'queue ' - trying to recover . Cause : Identifier contains invalid JMS identifier character '- ' : ' x-request-id ' [ 36mc.m.s.l.NextGenRequestLoggingFilter [ 0 ; 39m [ 2m : [ 0 ; 39m Before request [ uri=/services/deal-service/api/v2/deals/ack ; headers= [ x... | JMS message listener invoker failed , Cause : Identifier contains invalid JMS identifier character '- ' : ' x-request-id ' |
Java | Good day ! I have a regex pattern : It should tell me if java / android package name is legal or not.It works fine on desktop java , but it failures on android devicesLets say I have some package names : Test should show that the only valid package is `` com.mxtech.ffmpeg.v7_neon '' , but is also shows that test string... | Pattern p = Pattern.compile ( `` ^ [ a-zA-Z_\\ $ ] [ \\w\\ $ ] * ( ? : \\ . [ a-zA-Z_\\ $ ] [ \\w\\ $ ] * ) * $ '' ) ; `` . . `` , `` ПАвыапЫВАПыва '' , `` com.mxtech.ffmpeg.v7_neon '' , ... `` _ПАвыапЫВАПыва\_ `` | Java and Android regex difference |
Java | I was thinking about how to solve race condition between two threads which tries to write to the same variable using immutable objects and without helping any keywords such as synchronize ( lock ) /volatile in java.But I could n't figure it out , is it possible to solve this problem with such solution at all ? If you r... | public class Test { private static IAmSoImmutable iAmSoImmutable ; private static final Runnable increment1000Times = ( ) - > { for ( int i = 0 ; i < 1000 ; i++ ) { iAmSoImmutable.increment ( ) ; } } ; public static void main ( String ... args ) throws Exception { for ( int i = 0 ; i < 10 ; i++ ) { iAmSoImmutable = new... | How to solve race condition of two writers using immutable objects |
Java | I am trying to playaround with Java 8 Stream API and wanted to convert the following method using Java 8 stream filter map reduce.I have a list of Movies and every Movie object has a list of Actors along with other fields.I want to find all the movies where the actor with a specific first and last name has worked in it... | public List < Movie > getMoviesForActor ( String firstName , String lastName ) { final List < Movie > allMovies = movieRepository.getAllMovies ( ) ; final Predicate < Actor > firstNamePredicate = actor - > actor.getFirstName ( ) .equalsIgnoreCase ( firstName ) ; final Predicate < Actor > lastNamePredicate = actor - > a... | Find Movies where an actor with first and last name has worked using Java 8 Streams , map , filter , reduce |
Java | I want to just know about why Object , String etc . have static { } block at the end.what is the use of static block in Object Class.Open the cmd prompt and type | javap java.lang.Object | Why Object class have static block ? |
Java | I ’ m learning Java 8 streams . Tell me pls , how can I write a sortArray method more compactly ? | import org.junit.Test ; import java.util.ArrayList ; import java.util.Arrays ; import java.util.HashMap ; import java.util.Map ; import static org.junit.Assert.assertArrayEquals ; public class TestStream { /* * Sort numbers in an array without changing even numbers position */ @ Test public void test_1 ( ) { int [ ] no... | Sort numbers in an array without changing even numbers position using Java-8 |
Java | I am creating a video calling app and have the following code which is called when the application receives a push notification - it unlocks the screen and presents an 'incoming call ' user interface : This works fine when a call is incoming - the user can interact with the app using the UI presented . However , the pr... | public class MainActivity extends ReactActivity { @ Override protected String getMainComponentName ( ) { return `` x '' ; } @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.O_MR1 ) { setShowWhenLocked ( true ) ;... | How to lock Android device after unlocking with setShowWhenLocked ( true ) ; |
Java | I have a JPanel that contains bunch of context.I would like to be able to add the said JPanel to two JFrames . Any tips ? This is example of what I would likeI want both JFrames to show hello world , rather than one showing it and the other being empty . And if data in JPanel updates I want both JFrames to show it.Than... | public class Test { public static void main ( String [ ] args ) { JPanel panel = new JPanel ( ) ; panel.add ( new JLabel ( `` Hello world '' ) ) ; panel.validate ( ) ; JFrame frame1 , frame2 ; frame1 = new JFrame ( `` One '' ) ; frame2 = new JFrame ( `` Two '' ) ; frame1.add ( panel ) ; frame2.add ( panel ) ; frame1.va... | Add JPanel to multiple JFrames |
Java | Looking at Java 's String class we can see that hash code is cached after first evaluation.Where hash is an instance variable . I have a question , why do we need that h extra variable ? | public int hashCode ( ) { int h = hash ; if ( h == 0 & & value.length > 0 ) { char val [ ] = value ; for ( int i = 0 ; i < value.length ; i++ ) { h = 31 * h + val [ i ] ; } hash = h ; } return h ; } | java String hashcode caching mechanism |
Java | I am bit confused with the behaviour of thread.isInterrupted in the program below.When executing the above program as such , it prints , But when I uncomment the System.out statement to print the interrupt status , it runs into an infinite loop printing `` Current thread not interrupted '' I am not able to figure out e... | public class ThreadPractice { public static void main ( String args [ ] ) throws InterruptedException { Thread t = new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { System.out.println ( `` Starting thread ... '' + Thread.currentThread ( ) .getName ( ) ) ; Thread.sleep ( 10000 ) ; System.out.println... | Different behaviour when calling thread.isInterrupted and printing the result |
Java | SummaryWhen a user clicks on the RecyclerView item , I would like to add tags to that image from the information that has been stored in a BaaS [ Sashido ] ( X Co-ordinates , Y Co-ordinates and Tag name ) . But , the problem I 'm having is n't getting the position per-say . I create a toast when the image has been clic... | @ Overridepublic void onBindViewHolder ( RecyclerViewHolderPreviousPosts holder , int position ) { holder.bind ( previousPostsList.get ( position ) , listener ) ; } void bind ( final PreviousPostsDataModel model , final OnItemClickListener listener ) { ... uploadedImage.setOnClickListener ( new View.OnClickListener ( )... | Android - Adding Views to Images does n't update - onClick |
Java | I 'm trying to filter a resource and exclude some elements based on a field . To exclude I have a set ( that contains a id that needs to be excluded ) and a list ( it contains multiple range of ids that needs to be excluded ) . I wrote the below logic and I 'm not satisfied with the 2nd filter logic . Is there any bett... | Set < String > extensionsToExclude = new HashSet < > ( Arrays.asList ( `` 20 '' , '' 25 '' , '' 60 '' , '' 900 '' ) ) ; List < String > rangesToExclude = new ArrayList < > ( Arrays.asList ( `` 1-10 '' , '' 20-25 '' , '' 50-70 '' , '' 1000-1000000 '' ) ) ; return directoryRecords.stream ( ) .filter ( ( directoryRecord )... | Java Stream : Filter with multiple ranges |
Java | I recently ran into something like this ... Is there any way to do what I 'm trying to while keeping this as an anonymous class ? Or do we have to use an inner class or something else ? | public final class Foo < T > implements Iterable < T > { // ... public void remove ( T t ) { /* banana banana banana */ } // ... public Iterator < T > Iterator { return new Iterator < T > ( ) { // ... @ Override public void remove ( T t ) { // here , 'this ' references our anonymous class ... // 'remove ' references th... | Resolving Ambiguity when Accessing Parent Class from Anonymous Class |
Java | Is there in java a way to write generic interface what points out to the implementor of such interface in more convenient way ? For example I 've write interface : I want to point out that only instance of implementor can be passed in updateData ( T t ) method.So , i have to write something like this : But seems it is ... | public interface Updatable < T > { void updateData ( T t ) ; } public class Office implements Updatable < Office > { @ Override public void updateData ( Office office ) { //To change body of implemented methods use File | Settings | File Templates . } ... ... ... } | Convenient way to write generic interface that points out to its implementor |
Java | Why does the following Java code produces : The code in question is : There is no instance of SuperClass ever created , is n't there ? Not only that Java starts looking for the method to invoke from the SuperClass , it even somehow knows that a = 10 ! Let 's consider a similar Python code : It works as I expect : The o... | 10superclass class SuperClass { int a ; public SuperClass ( ) { this.a = 10 ; } private void another_print ( ) { System.out.println ( `` superclass '' ) ; } public void print ( ) { System.out.println ( this.a ) ; this.another_print ( ) ; } } class SubClass extends SuperClass { int a ; public SubClass ( ) { this.a = 20 ... | What does Java ` this ` actually refer to in an inheritance situation ? |
Java | According to the Java documentation for String.length : public int length ( ) Returns the length of this string . The length is equal to the number of Unicode code units in the string . Specified by : length in interface CharSequence Returns : the length of the sequence of characters represented by this object.But then... | public class HelloWorld { public static void main ( String [ ] args ) { String myString = `` I have a in my string '' ; System.out.println ( `` String : `` + myString ) ; System.out.println ( `` Bytes : `` + bytesToHex ( myString.getBytes ( ) ) ) ; System.out.println ( `` String Length : `` + myString.length ( ) ) ; Sy... | Why is Java String.length inconsistent across platforms with unicode characters ? |
Java | I am novice to java 8.I am trying below scenario.output : : Map I want to use java 8 stream api.I am trying like this but it gives me error , So my question , Can i invoke below method from Collectors.toMap ( ) | class Numbers { private Long userId ; private Long number1 ; private Long number2 ; } List < Numbers > list = new ArrayList ( ) ; Input == { `` userId '' :1 , `` number1 '' :10 , `` number2 '' :20 } { `` userId '' :1 , `` number1 '' :20 , `` number2 '' :40 } { `` userId '' :1 , `` sum '' :90 // addition of all numbers ... | Invoke method from stream api in java |
Java | I am trying to get a blackberry message by subject and open it in the default email app . I have this so far : But how would I open the message once I have a handle on it ? | Store store = Session.waitForDefaultSession ( ) .getStore ( ) ; Folder folder = store.getFolder ( `` Inbox '' ) ; Message [ ] msgs = folder.getMessages ( ) ; Message msg = msgs [ 0 ] ; | Open a specific email in the blackberry email app |
Java | Why does java.text.DecimalFormat evaluate the following results : I would have expected the result to be 23 in both cases , because special character # omits zeros . How does the leading special character 0 affect the fraction part ? ( Tried to match/understand it with the BNF given in javadoc , but failed to do so . ) | new DecimalFormat ( `` 0. # '' ) .format ( 23.0 ) // result : `` 23 '' new DecimalFormat ( `` . # '' ) .format ( 23.0 ) // result : `` 23.0 '' | Why does DecimalFormat `` . # '' and `` 0. # '' have different results on 23.0 ? |
Java | I have this homework in Java where I have to convert an infix string without parenthesis to a postfix string . I 've been tinkering with the code from two days but I have n't been able to catch the bug . Here 's my code.Here , the variables are as follows : st is a character stackch is the current characterpre is the t... | public class itp { String exp , post ; double res ; int l ; stack st ; public itp ( String s ) { exp = s ; post = `` '' ; l = exp.length ( ) ; st = new stack ( l ) ; conv ( ) ; calc ( ) ; System.out.println ( `` The postfix notation of `` +exp+ '' is `` +post ) ; System.out.println ( `` The result of `` +exp+ '' is `` ... | Infix to postfix not working as expected |
Java | This is a question I read on some lectures about dynamic programming I randomly found on the internet . ( I am graduated and I know the basic of dynamic programming already ) In the section of explaining why memoization is needed , i.e.If memoization is not used , then many subproblems will be re-calculated many time t... | // psuedo code int F [ 100000 ] = { 0 } ; int fibonacci ( int x ) { if ( x < = 1 ) return x ; if ( F [ x ] > 0 ) return F [ x ] ; return F [ x ] = fibonacci ( x-1 ) + fibonacci ( x-2 ) ; } ( defun F ( n ) ( if ( < = n 1 ) n ( + ( F ( - n 1 ) ) ( F ( - n 2 ) ) ) ) ) static int F ( int n ) { if ( n < = 1 ) return n ; els... | Why functional programming language support automated memoization but not imperative languages ? |
Java | Hey I have a question I have been trying to figure out for a couple hours now , I need to use nested loops to print the followingThis is what I have so far . This is what it prints | -- -- -1 -- -- - -- -- 333 -- -- -- -55555 -- - -- 7777777 -- -999999999- public static void Problem6 ( ) { System.out.println ( `` Problem 6 : '' ) ; for ( int i = 1 ; i < = 5 ; i++ ) { for ( int j = 5 ; j > = i ; j -- ) { System.out.print ( `` - '' ) ; } for ( int j = 1 ; j < = 9 ; j += 2 ) { System.out.print ( j ) ;... | Nest Loops , Can not figure out how to code this |
Java | How can I achieve the same what is described in the following Stack Overflow question ? How can I find all unused methods of my project in the Android Studio IDEA ? Using the command line only ? | ./gradlew lint ... | Lint check for unused methods ( command line ) |
Java | I 'm trying to create a clob from a string of > 4000 chars ( supplied in the file_data bind variable ) to be used in a Oracle SELECT predicate below : If I add TO_CLOB ( ) round file_data it fails the infamous Oracle 4k limit for a varchar ( it 's fine for < 4k strings ) . The error ( in SQL Developer ) is : FYI The fl... | myQuery=select *from dcr_molsWHERE flexmatch ( ctab , :file_data , 'MATCH=ALL ' ) =1 ; ORA-01460 : unimplemented or unreasonable conversion requested01460 . 00000 - `` unimplemented or unreasonable conversion requested '' MapSqlParameterSource parameters = new MapSqlParameterSource ( ) ; parameters.addValue ( `` file_d... | Use an Oracle clob in a predicate created from a String > 4k |
Java | I have a huge problem to understand why wrapper class in Java does n't behave like a reference type.Example : The output will be:2010I thought that two will be 20 like in this example where I create my own class : So the question , is Integer wrapper class special ? Why does it behave as I have shown in my examples ? | Integer one = 10 ; Integer two = one ; one = 20 ; System.out.println ( one ) ; System.out.println ( two ) ; class OwnInteger { private int integer ; public OwnInteger ( int integer ) { this.integer = integer ; } public int getInteger ( ) { return integer ; } public void setInteger ( int integer ) { this.integer = integ... | Why wrapper class in Java does n't behave like a reference type ? |
Java | Below code snippet is from Effective Java 2nd Edition Double Checked Locking// Double-check idiom for lazy initialization of instance fields From what i know the main Problem with Double Checked Locking is the reordering inside second check locking so that the other thread might see the values of field/result as set wh... | private volatile FieldType field ; FieldType getField ( ) { FieldType result = field ; if ( result == null ) { // First check ( no locking ) synchronized ( this ) { result = field ; if ( result == null ) // Second check ( with locking ) field = result = computeFieldValue ( ) ; } } return result ; } private FieldType fi... | Is this a better version of Double Check Locking without volatile and synchronization overhead |
Java | Two projects : the product ( project-A ) and the auto benchmark project for A ( project-B ) .In B 's build file , we need to call A 's build file to run the build and bundle-with-app-server process like this : And , in project B , we have a lot of Ant tasks that output messages using java.util.logging ( The JDK Logging... | < ant antfile= '' $ { build-file-A } '' inheritall= '' false '' target= '' all '' / > | The build file called using < ant > task resets the logging configs of the caller |
Java | I 've got two similar implementations ( java and c++ ) for a trivial algorithm like the selection sort.and the c one : Now , I tried testing them on a large array ( 100000 random int ) .The results at first werejava : ~17 sec ( compiled and executed with oracle jdk/jvm ) c : ~22 sec ( compiled with gcc v4.8 without any... | public interface SortingAlgorithm { public void sort ( int [ ] a ) ; } public class SelectionSort implements SortingAlgorithm { @ Override public void sort ( int [ ] a ) { for ( int i = 0 ; i < a.length ; i++ ) { int lowerElementIndex = i ; for ( int j = i + 1 ; j < a.length ; j++ ) { if ( a [ j ] < a [ lowerElementInd... | C performance and compiling options |
Java | I 'm using parseq framework for asynchronous computation . Consider the following code . It first queries the content of google.com and then map the content to it 's length . Finally , the length is printed.The problem is that only the first task is ran . Why ? | public class Main { public static void main ( String [ ] args ) throws Exception { OkHttpClient okHttpClient = new OkHttpClient ( ) ; final int numCores = Runtime.getRuntime ( ) .availableProcessors ( ) ; final ExecutorService taskScheduler = Executors.newFixedThreadPool ( numCores + 1 ) ; final ScheduledExecutorServic... | Linkedin parseq . How to run task after task ? |
Java | I have a string eg : this needs to be Sorted as which is based upon the string inside the square bracket.how can i do this in java ? | [ 01:07 ] bbbbbbb [ 00:48 ] aaaaaa [ 01:36 ] ccccccccc [ 03:45 ] gggggggg [ 03:31 ] fffffff [ 01:54 ] ddddddddd [ 02:09 ] eeeeeee [ 03:59 ] hhhhhhhh [ 00:48 ] aaaaaa [ 01:07 ] bbbbbbb [ 01:36 ] ccccccccc [ 01:54 ] ddddddddd [ 02:09 ] eeeeeee [ 03:31 ] fffffff [ 03:45 ] gggggggg [ 03:59 ] hhhhhhhh | Sorting a string based upon value in square bracket |
Java | I 'm as upgrading from Spring Boot 1.5.21 to 2.2.5.I need to use MonetaryModule to deserialize rest calls , and depending on Spring 's ObjectMapper.I have defined such a bean for this module in a some @ Configuration class ( MonetaryModule is extending Module ) : I can see in /beans endpoint it was created . However , ... | @ Beanpublic MonetaryModule monetaryModule ( ) { return new MonetaryModule ( ) ; } private void configureModules ( Jackson2ObjectMapperBuilder builder ) { Collection < Module > moduleBeans = getBeans ( this.applicationContext , Module.class ) ; builder.modulesToInstall ( moduleBeans.toArray ( new Module [ 0 ] ) ) ; } =... | Jackson module not registered after update to Spring Boot 2 |
Java | I have read through inner class tutorial and do n't understand one thing . It is being said that inner class holds hidden reference to outer class , so I come up with several questions via this plain class : So we have one local inner class which resides inside method doSomething ( ) and I have some questions involved.... | public class OuterClass { public void doSomething ( ) { JButton button = new JButton ( ) ; button.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { } } ) ; } } | Local inner class |
Java | I 'm pretty sure this is not possible in one line , but I just wanted to check : Basically I 'm collecting all widget items into a map where the key is the availableStock quantity and the value is a list of all widgets that have that quantity ( since multiple widgets might have the same value ) . Once I have that map ,... | List < WidgetItem > selectedItems = null ; Map < Integer , List < WidgetItem > > itemsByStockAvailable = WidgetItems.stream ( ) .collect ( Collectors.groupingBy ( WidgetItem : :getAvailableStock ) ) ; selectedItems = itemsByStockAvailable.get ( itemsByStockAvailable.keySet ( ) .stream ( ) .sorted ( ) .findFirst ( ) .ge... | Java Streams : Organize a collection into a map and select smallest key |
Java | Hello I 'm working on a project on Java Card which implies a lot of modulo-multiplication . I managed to implement an modulo-multiplication on this platform using RSA cryptosystem but it seems to work for certain numbers.The code works well for little number but fails on bigger one | public byte [ ] modMultiply ( byte [ ] x , short xOffset , short xLength , byte [ ] y , short yOffset , short yLength , short tempOutoffset ) { //copy x value to temporary rambuffer Util.arrayCopy ( x , xOffset , tempBuffer , tempOutoffset , xLength ) ; // copy the y value to match th size of rsa_object Util.arrayFillN... | Using RSA for modulo-multiplication leads to error on Java Card |
Java | Java 's LocalDate API seems to be giving the incorrect answer when calling plus ( ... ) with a long Period , where I 'm getting an off by one error . Am I doing something wrong here ? | import java.time.LocalDate ; import java.time.Month ; import java.time.Period ; import java.time.temporal.ChronoUnit ; public class Main { public static void main ( String [ ] args ) { // Long Period LocalDate birthA = LocalDate.of ( 1965 , Month.SEPTEMBER , 27 ) ; LocalDate eventA = LocalDate.of ( 1992 , Month.MAY , 9... | LocalDate.plus Incorrect Answer |
Java | In Java , I 've to set a POJO class with values . However to decide which setter function to be used , I 've to depend on if condition . My current code looks as follow : This is just an example but I 've 70+ such properties to be set . My code is working but I wonder if it is right way of doing things ? AFAIK , such c... | // Code written in a function which is called within a loop , while parsing xml file.if ( name.equals ( `` dim1 '' ) ) { line.setDim1Code ( Integer.parseInt ( value ) ) ; } else if ( name.equals ( `` dim2 '' ) ) { line.setDim2Code ( Integer.parseInt ( value ) ) ; } else if ( name.equals ( `` debitcredit '' ) ) { line.s... | Getting rid of if/else |
Java | Problem Statement : -I was ask this interview question recently.. I was able to come up with the below code only which runs in O ( k log n ) - Given k < = n sorted arrays each of size n , there exists a data structure requiring O ( kn ) preprocessing time and memory that answers iterated search queries in O ( k + log n... | private List < List < Integer > > dataInput ; public SearchItem ( final List < List < Integer > > inputs ) { dataInput = new ArrayList < List < Integer > > ( ) ; for ( List < Integer > input : inputs ) { dataInput.add ( new ArrayList < Integer > ( input ) ) ; } } public List < Integer > getItem ( final Integer x ) { Li... | Efficiently find an element in multiple sorted lists ? |
Java | I 'm working on a reader/writer for DNG/TIFF files . As there are several options to work with files in general ( FileInputStream , FileChannel , RandomAccessFile ) , I 'm wondering which strategy would fit my needs.A DNG/TIFF file is a composition of : some ( 5-20 ) small blocks ( several tens to hundred bytes ) very ... | short readShort ( long offset ) throws IOException , InterruptedException { return read ( offset , Short.BYTES ) .getShort ( ) ; } ByteBuffer read ( long offset , long byteCount ) throws IOException , InterruptedException { ByteBuffer buffer = ByteBuffer.allocate ( Math.toIntExact ( byteCount ) ) ; buffer.order ( Gener... | Read scattered data from multiple files in java |
Java | I am createing a game where a landscape is generated all of the generations work perfectly , a week ago i have created a basic 'forest ' generation system wich just is a for loop that takes a chunk , and places random amounts of trees in random locations . But that does not give the result i would like to a achieve . C... | for ( int t = 0 ; t < = randomForTrees.nextInt ( maxTreesPerChunk ) ; t++ ) { // generates random locations for the X , Z positions\\ // the Y position is the height on the terrain gain with the X , Z coordinates \\ float TreeX = random.nextInt ( ( int ) ( Settings.TERRAIN_VERTEX_COUNT + Settings.TERRAIN_SIZE ) ) + ter... | How to generate forests in java |
Java | PlayFramework application , the footer.html file : Here I have right path , so the footer.html is exist.But the lm is 0 i.e . it is 1970 year.. but now is 2011.The question : why ? Can it be related somehow to security-manager or something related to security ? | % { file = new File ( `` footer.html '' ) ; path = file.getCanonicalPath ( ) ; lm = file.lastModified ( ) ; // date = new Date ( lm ) ; } % < span > Last update : $ { lm } < /span > | play-framework getting the last-modification date for file |
Java | I have a question related to lambda expressions in Java 8.Consider the following Message class : which implements the MessageBase interface . I store objects of the Message class in a TreeMap - Map < Long , Message > messages . The key is a timestamp and the value is a Message object . I have to find all TreeMap entrie... | public class Message implements MessageBase { private String id ; private String message ; private String author ; private Long timestamp ; public Message ( ) { this.id=null ; this.message=null ; this.author=null ; this.timestamp= null ; } public Message ( String id , String message , String author , Long timestamp ) {... | Searching a TreeMap by a member of the value class using lambda expressions |
Java | Possible Duplicate : Returning false from Equals methods without Overriding One of my colleague asked me a question today as mentioned below Write TestEquals class ( custom or user defined class ) so that the below s.o.p in the code prints false.Note : You can not override equals method.I thought a lot but could n't fi... | public class Puzzle3 { public static void main ( String [ ] args ) { TestEquals testEquals = new TestEquals ( ) ; System.out.println ( testEquals.equals ( testEquals ) ) ; } } | equals to return false |
Java | Am confused about how finally keyword actually works ... Before the try block runs to completion it returns to wherever the method was invoked . But , before it returns to the invoking method , the code in the finally block is still executed . So , remember that the code in the finally block willstill be executed even ... | public class Main { static int count = 0 ; Long x ; static Dog d = new Dog ( 5 ) ; public static void main ( String [ ] args ) throws Exception { System.out.println ( xDog ( d ) .getId ( ) ) ; } public static Dog xDog ( Dog d ) { try { return d ; } catch ( Exception e ) { } finally { d = new Dog ( 10 ) ; } return d ; }... | finally not working as expected |
Java | When I use a JComboBox on Windows 7 , the four corners each have a pixel that does n't match the background colour of the parent component . In Windows 8 this problem does n't happen ( although that could be because in Windows 8 , the JComboBox is rendered as a perfect rectangle ) . Nor does it happen on OS X.What can ... | import com.sun.java.swing.plaf.windows.WindowsLookAndFeel ; import javax.swing . * ; import java.awt . * ; public class Main { public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { try { UIManager.setLookAndFeel ( new WindowsLookAndFeel ( ) ) ; } catch ( Exc... | JComboBox on Windows 7 has rendering artifacts |
Java | I 'm making a code editor and I 'm working on the autocomplete . I want to programmatically get a list of all the classes that come with the JDK.Examples include : I 've found ways to get classes for a specific package . For instance , I can get all classes that start with com.mypackage.foo . The problem is that I 'm t... | java.io.Filejava.util.ArrayListjavax.swing.Action | Iterating through all JDK classes |
Java | I was just trying to create somewhat similar to Collectors.toList ( ) of my own but it does n't seem to work } My question is if ArrayList : :new does n't work here , what will work . I tried different variation but none seems to work | import java.util.ArrayList ; public class ShipmentTracingDTO { boolean destination = false ; public ShipmentTracingDTO ( Boolean destination ) { this.destination = destination ; } public ShipmentTracingDTO ( ) { } public static void main ( String [ ] args ) { ArrayList < ShipmentTracingDTO > tracings = new ArrayList < ... | Valid Supplier for collect method of stream |
Java | I came across this question in an SCJP book . The code prints out 1 instead of an NPE as would be expected . Could somebody please explain the reason for the same ? | public class Main { public static void main ( String [ ] ar ) { A m = new A ( ) ; System.out.println ( m.getNull ( ) .getValue ( ) ) ; } } class A { A getNull ( ) { return null ; } static int getValue ( ) { return 1 ; } } | Why this code DOES NOT return a NullPointerException ? |
Java | I need to use onApplicationEnd ( ) as part of Application.cfc to execute a call on a 3rd party Java object to close a connection to another device on the network . The code I have worked perfectly if I call it as a normal request , but when I place it in the onApplicationEnd ( ) method I 'm running into some errors . T... | < cffunction name= '' onApplicationEnd '' returnType= '' void '' > < cfargument name= '' appScope '' required= '' true '' / > < cfset var logLocation = `` test '' / > < cflog file= '' # logLocation # '' text= '' *** [ Application.cfc ] - **** START RUN **** '' / > < cflog file= '' # logLocation # '' text= '' *** [ Appl... | onApplicationEnd - Is CF actually shutting down ? |
Java | What is the difference between the C main function and the Java main function ? vsHow do these main functions relate to each languages creation and what are the benefits or outcomes of each ? | int main ( int argc , const char* argv [ ] ) public static void main ( String [ ] args ) | C main vs Java main |
Java | I am a beginner in java.I have been working on an maze problem trying it solve it by recursion.I have written the code which seems to work on few inputs and not others . The input is a maze consisting of 0 's and 1 's . # is the start and @ is the exit.0 is wall and 1 's are open.The output will be the hops from # to @... | import java.util.Scanner ; class practisenumwords { public static void main ( String [ ] args ) { Scanner in=new Scanner ( System.in ) ; int r=in.nextInt ( ) ; int c=in.nextInt ( ) ; maze maz=new maze ( r , c ) ; /*input in string copied to array*/ char [ ] ch ; ch = `` 00000000111111101111011001101 @ # 11100 '' .toCha... | Maze recursion - going wrong for few inputs ( likely error in the logic ) |
Java | In Java I have a class that implements an interface : If some variables are declared inside of the interface I could access them : But in Scala the above line does not compile . Seems like it is hidden . Is there any way to access these variables in Scala without creating a new object or doing anything else hacky ? | AlertDialog implements DialogInterface AlertDialog.BUTTON_POSITIVE | Why ca n't I access a variable declared in a class , which implements a Java interface , from Scala ? |
Java | This method returns 'true ' . Why ? | public static boolean f ( ) { double val = Double.MAX_VALUE/10 ; double save = val ; for ( int i = 1 ; i < 1000 ; i++ ) { val -= i ; } return ( val == save ) ; } | Java 's '== ' operator on doubles |
Java | Few separate questions on QuartzIf i want event to be executed once , is it sufficient to Considering this snippet . Event runs , when scheduled time is `` before now '' and fails to be executed when scheduled time is in the futureUsing the code above , i observe the followingThe difference between now and the time it ... | trigger.setRepeatCount ( 0 ) ; JobDetail job = new JobDetail ( ) ; job.setName ( eventType.toString ( ) + `` event '' ) ; job.setJobClass ( Action.class ) ; SimpleTrigger trigger = new SimpleTrigger ( ) ; trigger.setStartTime ( new Date ( momentInTime.inMillis ( ) ) ) ; trigger.setName ( `` trigger '' ) ; trigger.setRe... | On quartz scheduler , clarification needed |
Java | I have 3 API GET calls . The problem I 'm facing with my approach is , the app is able to fetch the data successfully from two APIs and I 'm able to display it on UI as well . But , for the third API call , due to the below error , the data that is being shown previously disappears which is bad.How do I make concurrent... | D/Volley : [ 380 ] BasicNetwork.logSlowRequests : HTTP response for request= < [ ] http : //example.com/api/search/getTwitterData ? limit=10 & tag=JavaScript 0x865f5dc2 NORMAL 3 > [ lifetime=6683 ] , [ size=10543 ] , [ rc=200 ] , [ retryCount=0 ] public class StaggeredSearchActivity extends AppCompatActivity { ... @ Ov... | How to make concurrent GET calls using Volley ? |
Java | In Food Tab , I want to achieve thisBut I only able to get thisHow can I increase the width of the JTextField which are in Food Tab ? Below is my code | public class FoodOrdering { static private JFrame frame ; static private JTextField textField ; static private GridBagConstraints gbc ; static private JLabel [ ] foodLabel ; static private JLabel [ ] labels ; static private JTextField [ ] qtyField ; static private JLabel [ ] foodImage ; static private File [ ] file ; p... | How to increase the width of JTextField in Tab ? |
Java | I have this tableAnd I am using the following code to retrieve data from my tablethat returns all the English words that its Kurdish word contains بةرزSo it works fine , it prints all the English words that I want.My problem is that when I get the corresponded Kurdish word it does n't print the complete cell . It just ... | targetText= '' بةرز '' ; try ( PreparedStatement ps = conn.prepareStatement ( `` SELECT English , Kurdish FROM Info `` + '' WHERE Kurdish = ? `` + '' OR REGEXP_MATCHES ( Kurdish , ? ) `` + '' OR REGEXP_MATCHES ( Kurdish , ? ) `` + '' OR REGEXP_MATCHES ( Kurdish , ? ) `` ) ) { ps.setString ( 1 , targetText ) ; ps.setStr... | Using java for searching for data by using part of the row in microsoft access database |
Java | I am trying to insert records into postgres DB , and its taking about 3 hours while it takes 40seconds using python psycopg2 and cursor.copy_from methodWhat is wrong with my code , using clojure.java.jdbc/db-do-prepared also takes about 3 hours too.Please help ! File size is 175M and it has 409,854 records | ( defn- str < - > int [ str ] ( let [ n ( read-string str ) ] ( if ( integer ? n ) n ) ) ) ( with-open [ file ( reader `` /path/to/foo.txt '' ) ] ( try ( doseq [ v ( clojure-csv.core/parse-csv file ) ] ( clojure.java.jdbc/insert ! db : records nil [ ( v 0 ) ( v 1 ) ( v 2 ) ( str < - > int ( v 3 ) ) ] ) ) ( println `` R... | Insert file records into postgres db using clojure jdbc is taking long time compared to python psycopg2 |
Java | Java 9 provides as a way to create Empty immutable List , set and Map.But I am not able understand what is the actual use case of creating an empty immutable list / set / map.Please help me to understand the actual use case of an empty immutable list / set / map . | List list = List.of ( ) ; Set set = Set.of ( ) ; Map map = Map.of ( ) ; | Is there any practical application/use case when we create empty immutable list / set / map |
Java | I am very confused by Scala Constructors . For example , I have the following classes that represent a tree with operators such as Add and leaf nodes on the tree that are numbers.I read in one site that what goes in a Scala constructor is automatically immutable ( val ) , but this guy on Stack Overflow said `` The inpu... | abstract class Node ( symbol : String ) { } abstract class Operator ( symbol : String , binaryOp : ( Double , Double ) = > Double ) extends Node ( symbol ) { } class Add ( a : Number , b : Number ) extends Operator ( `` + '' , ( a : Double , b : Double ) = > a+b ) { } class Number ( symbol : String ) extends Node ( sym... | Scala Constructor Confusion - please clarify |
Java | I recently read some code that uses a special syntax regarding { } , I 've asked a more experienced Java developer , but he also ca n't answer.Why does the code author put these lines inside { } ? I guess that the variables declared within the { } will be released right after execution exits { } , right , because I ca ... | public void doSomething ( ) { someWorks ( ) ; { someVariables ; someMoreWorks ( ) ; } someEvenWorks ( ) ; { ... } } | What is alone { code } in Java for ? |
Java | I am creating a simple IDE using JTextPane and detecting keywords and coloring them.Currently , I am able to detect : CommentsString LiteralsIntegers & FloatsKeywordsThe way I detect these types are through regular expressions.Now , I am trying to detect variables like [ int x = 10 ; ] and coloring them a different col... | Pattern words = Pattern.compile ( \\bint\\b|\\bfloat\\b\\bchar\\b ) ; Matcher matcherWords = words.matcher ( code ) ; while ( matcherWords.find ( ) ) { System.out.print ( code.substring ( matcherWords.start ( ) , matcherWords.end ( ) ) ; // How to get next word that is a variable ? } | Detecting variables through a string |
Java | My question : What is the advantage of using the Eclipse ConsoleManager class in opposite of putting my console in a view . I have created my own console ( a REPL ) in java and would like to integrate it with Eclipse . I know of two ways to do so : Create a plug-in view and just display my own textpane in it . Example ... | PlatformUI.getWorkbench ( ) .getActiveWorkbenchWindow ( ) .getActivePage ( ) . showView ( REPL_PLUGIN_ID , project.getName ( ) , IWorkbenchPage.VIEW_ACTIVATE ) ; ConsolePlugin.getDefault ( ) .getConsoleManager ( ) .addConsoles ( myConsoles ) | Eclipse plug-in IConsole vs View |
Java | I 'm currently working with the API Apache POI and I 'm trying to edit a Word document with it ( *.docx ) . A document is composed by paragraphs ( in XWPFParagraph objects ) and a paragraph contains text embedded in 'runs ' ( XWPFRun ) . A paragraph can have many runs ( depending on the text properties , but it 's some... | XWPFParagraph paragraph = ... // Get a paragraph from the documentSystem.out.println ( paragraph.getText ( ) ) ; // Prints : Some text with a tag < # SOMETAG # > System.out.println ( `` Number of runs : `` + paragraph.getRuns ( ) .size ( ) ) ; for ( XWPFRun run : paragraph.getRuns ( ) ) { System.out.println ( run.text ... | Get the list of object containing text matching a pattern |
Java | I was asked the following question during phone interview I had : Given the following class definition : and its child class that initializes a super class using a random integer generator.you need to intercept the value of x ( the random int produced by someRandomIntegerValGenerator ) and store it in ClassB member . C... | public class ClassA { public ClassA ( int x ) { // do some calculationand initialize the state } } public class ClassB extends ClassA { public ClassB ( ) { super ( StaticUtilityClass.someRandomIntegerValGenerator ( ) ) } } | How to intercept super class constructor argument ? |
Java | Recently I 've run into an issue regarding String concatenation . This benchmark summarizes it : On JDK 1.8.0_222 ( OpenJDK 64-Bit Server VM , 25.222-b10 ) I 've got the following results : This looks like an issue similar to JDK-8043677 , where an expression having side effectbreaks optimization of new StringBuilder.a... | @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) public class BrokenConcatenationBenchmark { @ Benchmark public String slow ( Data data ) { final Class < ? extends Data > clazz = data.clazz ; return `` class `` + clazz.getName ( ) ; } @ Benchmark public String fast ( Data data ) { final Class < ? extends Data > clazz = data.c... | Java 8 : Class.getName ( ) slows down String concatenation chain |
Java | Compilingusing Oracle JDK gives : which makes no sense as a class should be able to access its parent 's protected methods . This expression works fine in Eclipse 's compiler.Also , ( ) - > super.clone ( ) compiles fine ... .Is this a bug ? | import java.util.concurrent.Callable ; class Ideone { Callable < ? > x = super : :clone ; } Main.java:6 : error : incompatible types : invalid method reference Callable < ? > x = super : :clone ; ^ clone ( ) has protected access in Object | Functional reference to Object.clone ( ) does n't compile |
Java | I look through java source code try to learn the implementation of collection.Found a interesting thing in the ArrayDeque class.What does the following 2 lines mean ? Is it a bitwise operation ? Why they use it and what 's the purpose here ? I know one scenario to use the bitwise is to pack 2 values in 1 variable . But... | public E pollFirst ( ) { int h = head ; @ SuppressWarnings ( `` unchecked '' ) E result = ( E ) elements [ h ] ; // Element is null if deque empty if ( result == null ) return null ; elements [ h ] = null ; // Must null out slot head = ( h + 1 ) & ( elements.length - 1 ) ; return result ; } public E pollLast ( ) { int ... | Why the ArrayDeque class use bitwise operation in the pollFirst method ? |
Java | Based on some conditions I want to perform some operation on a specific element of a list only.I have a list of integers like this : and I want to subtract 1 from each element EXCEPT 0.I have tried some approaches like by applying the filter of Java 8 but it removed the zero values from the list.I tried to apply other ... | List < Integer > list = new ArrayList ( Arrays.asList ( 30,33,29,0,34,0,45 ) ) ; List < Integer > list2 = list.stream ( ) .filter ( x - > x > 0 ) .map ( x - > x - 1 ) .collect ( Collectors.toList ( ) ) ; //list.stream ( ) .findFirst ( ) .ifPresent ( x - > x - 1 ) .collect ( Collectors.toList ( ) ) ; //This is giving er... | How to perform some mathematical operation on some specific elements of a list using java 8 ? |
Java | I have noticed that Java heap allocation is in the multiples of 2 MB . For example I started the JVM with -Xmx values as 1021m , 1022m both JVMs started with the heap size of 1022m . Similarly heap sizes 1023m,1024m started with 1024m.The output is below : In both the cases it shows the MaxHeapSize as 1071644672 bytes ... | C : \Users\myuser > java -Xmx1021m -XX : +PrintFlagsFinal -version | findstr `` MaxHeapSize '' uintx MaxHeapSize : = 1071644672 { product } java version `` 1.8.0_121 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_121-b13 ) Java HotSpot ( TM ) Client VM ( build 25.121-b13 , mixed mode ) C : \Users\myuser > java -Xm... | Java Heap Allocation is in multiples of 2MB |
Java | Have been using JAudioTagger library for 2 years now , i ca n't figure out how to disable the Logger of it.Also asked the owner of the project : https : //bitbucket.org/ijabz/jaudiotagger/issues/257/how-to-disable-jaudio-tagger-logger What i have tried ? ( No luck ) For now i just have disabled the Logger generally fro... | Logger.getLogger ( `` org.jaudiotagger '' ) .setLevel ( Level.OFF ) ; Logger.getLogger ( `` org.jaudiotagger.tag '' ) .setLevel ( Level.OFF ) ; Logger.getLogger ( `` org.jaudiotagger.audio.mp3.MP3File '' ) .setLevel ( Level.OFF ) ; Logger.getLogger ( `` org.jaudiotagger.tag.id3.ID3v23Tag '' ) .setLevel ( Level.OFF ) ; ... | How to disable JAudioTagger Logger completely |
Java | I 've stuck by a few lines in my java program , which take too much time ( about 20s ) , and it seems weird to me.Here are the linesWhich res defined as following : In my program , res.size ( ) ~= 1500Do you have any idea of where my problem could come from ? Thanks ! | Map < URL , Integer > res2 = new HashMap < > ( ) ; for ( URL url : res ) { res2.put ( url , null ) ; } List < URL > res = new ArrayList < > ( ) ; | Add to hashmap takes a long time |
Java | I work on a web application that calls multiple web service clients from within its code.Each web service has some common namespaces , however I am currently mapping these namespaces to different packages when I generate each cliente.g.Web Service 1 's namespace1 - > com.company.webservice.client1.serviceWeb Service 2 ... | // Web Service Client 1 's namespace parameter -- namespace2package http : //www.multispeak.org/Version_3.0=com.company.webservice.client1.service// Web Service Client 2 's namespace parameter -- namespace2package http : //www.multispeak.org/Version_3.0=com.company.webservice.client2.service | Axis2 Namespace/Classpath Issue |
Java | Let say I use JPA by using @ transactions annotations.So to have any method run under a transaction I add a @ transaction annotations and BINGO my method run under a transaction.To achieve the above we need have a interface for the class and the instance is managed by some container.Also I should always call the method... | class Bar { @ Inject private FooI foo ; ... void doWork ( ) { foo.methodThatRunUnderTx ( ) ; } } class FooImpl implements FooI { @ Override @ Transaction public void methodThatRunUnderTx ( ) { // code run with jpa context and transaction open } } interface FooI { void methodThatRunUnderTx ( ) ; } class Bar { @ Inject p... | Java design issue where behavior is attached to annotations |
Java | I have mainly CPU intensive operation which is running on a thread pool . Operation however has certain amount of waiting foe external events which does n't happen uniformly in time.Since in Java , as far as I know , there is not a thread pool implementation which automatically sizes its number of threads based on obse... | pool.increase ( ) ; waitForSpecialKeyPress ( ) ; pool.decrease ( ) ; | Java threadpool oversubscription |
Java | I am trying to figure out how to set a blob column under where clause . any idea ? For example if I put the following query in cqlsh it works//id is a blob column in cassandraI tried the followingThis gave me a type converter exceptionand I tried this This gave me no error however it returned no results . The query in ... | select * from hello where id=0xc1c1795a0b ; JavaRDD < CassandraRow > cassandraRowsRDD = javaFunctions ( sc ) .cassandraTable ( `` test '' , `` hello '' ) .select ( `` range '' ) .where ( `` id= ? `` , `` 0xc1c1795a0b '' ) ; JavaRDD < CassandraRow > cassandraRowsRDD = javaFunctions ( sc ) .cassandraTable ( `` test '' , ... | How to set a blob column in the where clause using spark-connector-api ? |
Java | Would you please give me reference why there is significant difference in the execution time between the following 2 factorial implementations using the Java Stream API : Serial implementationParallel implementation ( using Stream.parallel ( ) ) executed in a custom fork join pool with parallelism set to 1My expectatio... | public class FastFactorialSupplier implements FactorialSupplier { private final ExecutorService executorService ; public FastFactorialSupplier ( ExecutorService executorService ) { this.executorService = executorService ; } @ Override public BigInteger get ( long k ) { try { return executorService .submit ( ( ) - > Lon... | Difference between serial and parallel execution with parallelism=1 |
Java | To avoid calling get ( ) which can throw an exception : I can replace this expression with : But what if I need to perform a larger expression like : Is it possible to still use a lambda form for this that mitigates a call to get ( ) ? My use-case is to avoid get ( ) entirely where possible to prevent a possible unchec... | if ( a.isPresent ( ) ) list.add ( a.get ( ) ) ; a.ifPresent ( list : :add ) ; if ( a.isPresent ( ) & & b & & c ) list.add ( a.get ( ) ) ; | Can Optional ifPresent ( ) be used in a larger expression to mitigate a call to get ( ) ? |
Java | I have got lot of crash report in my android app from users as I see in the developer console . The stack trace that I see is : There is no reference to my app 's package name . I am using Eclipse for my development . Is it something related to multidex . Do I need to switch to Android Studio to solve this . I am unabl... | java.lang.RuntimeException : at android.app.ActivityThread.handleReceiver ( ActivityThread.java:2884 ) at android.app.ActivityThread.-wrap14 ( ActivityThread.java ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1565 ) at android.os.Handler.dispatchMessage ( Handler.java:111 ) at android.os.Loope... | Unable to identify source of java.lang.ClassNotFoundException BaseDexClassLoader |
Java | Many languages have a facility to check to see if an Object is of a certain type ( including parent subclasses ) , implemented with 'is ' and used like this : Or slightly more tediously you can in other languages check by using the 'as ' keyword to do a soft typecast and seeing if the result null . I have n't used Java... | if ( obj is MyType ) | What is the easiest way to do 'is ' in Java ? |
Java | I want to write a method for a Java class . The method accepts as input a string of XML data as given below.The XML string contains a lot of substring starting and ending with < > . The substring may contain XML entities such as > , < , & , ' and `` . The method need to replace them with & gt ; , & lt ; , & amp ; . & a... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < library > < book > < name > < > Programming in ANSI C < > < /name > < author > < > Balaguruswamy < > < /author > < comment > < > This comment may contain xml entities such as & , < and > . < > < /comment > < /book > < book > < name > < > A Mathematical Theory of Co... | String replace in substring |
Java | Suppose I have a class which wraps a HashMap as follows : This class is initialized via `` Thread1 '' .However , the put , get , printMap and other operations are only ever called by `` Thread2 '' .Am I correct in understanding that this class is thread safe as : Since the reference to the map is declared final , all o... | public final class MyClass { private final Map < String , String > map ; //Called by Thread1 public MyClass ( int size ) { this.map = new HashMap < String , String > ( size ) ; } //Only ever called by Thread2 public final String put ( String key , String val ) { return map.put ( key , value ) ; } //Only ever called by ... | Java Happens-Before and Thread Safety |
Java | I am a dotnet guy and am trying to create a java applet for my application . I have been able to successfully create the applet and its also working fine in my application after I signed it.The only issue that I have is that when I embed it into an HTML file ( in my case the .cshtml file ) , I see a white border around... | < applet width= '' 55 '' height= '' 40 '' border= '' 0 '' codebase= '' ~/Content/My/applet '' id= '' DxApplet '' name= '' DxApplet '' code= '' DxApplet.class '' archive= '' DxButtonApplet.jar '' > < param name= '' boxborder '' value= '' false '' > @ Html.Raw ( ViewBag.AppletParameters ) < /applet > applet : focus { out... | Remove outer white border in a java applet when embedded inside an HTML page |
Java | Currently we are using To format the time range to an external vendor for a range of data , for India , that formatter will give time like this:2018-04-26T00:00:00.000+0530However , my vendor say they can not accept this format and it have to look like 2018-04-26T00:00:00.000+05:30However , look like in DateTimeFormatt... | DateTimeFormatter.ofPattern ( `` yyyy-MM-dd'T'HH : mm : ss.SSSX '' ) | Can I have more control on zone offset formatting at DateTimeFormatter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.