incrementing the counter of a for-loop

Question: I came by an exercise in a Hakerrank challenge where I used a basic for loop to iterate over an array, then I thought about incrementing the loop counter based on a condition. Here is my solution :
<code>public static int sockMerchant(int n, int[] ar) {
    int pairs = 0;
    Arrays.sort(ar);
    if (n % 2 != 0) n = n - 1;
    for (int i = 0; i < n - 1; i++) {
        if (ar[i] == ar[i + 1]) {
            ++pairs;
            // incrementing the loop counter
            i++;
        }
    }
    return pairs;
}
</code>
I'm wondering if there is any incidence or issues when incrementing the for-loop counter. Any ideas guys of things to be careful about with the written code?
Comment: Some people downvote faster than their own shadow ;-) You algo (n--) would miss, for instance, `[ 1, 2, 2 ]`... Besides, there is no much gain by reducing the number of loops by 1, here.
Answer: Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.
But, Java allows the modification of a loop's index.
Take a look at the detailed answer by Greg Hewgill.
https://stackoverflow.com/a/9012318/13651978

incrementing the counter of a for-loop


If a moderator comments on a post, does that mean the moderator is going to do anything about the post, and the community doesn't need to do anything?

Question: I have seen a comment left from a moderator about a question being asked; I agree with what the moderator said about the question being off-topic. Do I need to do anything, or will the moderator take care of the question?
Answer: Sometimes moderators leave comments saying what it is wrong with a question in its actual form; not all the times a moderator then takes action about that post.
As a matter of questions to close, moderators close questions that are blatantly duplicates, off-topic, not real questions, or not constructive questions. If you happen to agree, you can vote to close the question too, or flag it choosing "it doesn't belong here." If the question is not so very obviously a not desired question because it's a borderline question, moderators will probably not take any action, and it will be the community that needs to close the question.
This is also true for comments left from moderators about answers: If a moderator leave a comment on an answer, it doesn't necessarily mean the answer will be deleted. If you think the answer is a really bad one, which is not useful at all, you can down-vote it.


Where do people get web design patterns/inspiration from?

Question: I like to think I come up with original concepts as and when I can but I do find it really gives me a kick start when I can see examples of what other people have been doing to inspire my own design process. I thought it might be good to post a question providing links to some of the best design pattern/inspiration web sites I have come across in the past.
Here are some that I use quite frequently, probably in order of most used:
http://www.smashingmagazine.com/
http://patterntap.com/
http://patternry.com/?page=1
http://konigi.com/
http://www.designfridge.co.uk/
Does anyone have any others to add to this list?
Answer: Here's a great collection of pattern resources by smashing magazin:
http://www.smashingmagazine.com/2009/06/15/40-helpful-resources-on-user-interface-design-patterns/
And one by Yahoo:
http://developer.yahoo.com/ypatterns/
Comment: THX :) an upvote and that's all :)
Answer: I have a collection of this kind of patterns/inspiration sites at
http://profs.info.uaic.ro/~evalica/patterns/
Hope to be useful
Comment: Thanks, never come across this before....this is really handy, lots to get through here.
Answer: Anders Toxboe has put together a pretty good site for UI-Patterns - http://ui-patterns.com/.
Answer: James Melzer also put together a bundle of links:
http://jamesmelzer.com/interaction-design/patterns-resources
Comment: Interesting, this is pretty similar to what I've been tasked with...makes for an interesting read! Thanks
Comment: Link now shows just a 500 Internal Server Error.
Answer: UX Pond provides a search facility that looks at all these UI pattern sites at once.
Comment: This is cool, I've used the logo version of this hadn't seen this one before though.


What is considered an incredible feat the for the "Jack of All Trades" commendations

Question: For the Halo:Reach multiplayer commendation, "Jack of All Trades," what is considered an incredible feat?
Answer: "Perform an incredible feat in Multiplayer Matchmaking." Incredible feats in matchmaking are akin to earning medals that are not categorized under any other commendation. These medals include (but not limited to?):

Protector (Save a teammate by killing his foe)
Avenger (Avenge a teammate's dath)
Revenge (Kill the opponent responsible for your death)
Show Stopper (Kill an opponent while they are performing an assassination)
Yoink (Kill an enemy player while they are being assassinated)
Close Call (Kill an opponent while you are weakened and without a shield. Survive)
Rejection (Active Armor Lock and survive massive damage)
Extermination ( Killing the last alive player on the opposing team with at least an Overkill that results in the entire team being dead at once)

Source


equivalence classes and partitions exercises

Question: let A= {1,2,3,4,5}x{1,2,3,4,5} and consider the equivalence relation R over A defined as:(x_1,y_1)=(x_2,y_2) if and only if x_1 + y_1= x_2 + y_2; show all the equivalence classes of R and the partition induced by R
the problem I have is that my teacher said that there are 9 equivalence classes in this relation, and I only have one; please I would appreciate your help :)
Comment: I think i see my mistake because i need to consider the ordered pairs instead of the numbers alone, is as you say :D
Comment: There is certainly more than one equivalence class. For example, (1,2) is not equivalent to (3,3) because 1+2 is not equal to 3+3. On the other hand, the 25 elements of A are not in separate equivalence classes, because, for example, (3,4), (2,5), and (5,2) are all equivalent (and in the same equivalence class. Can you take things from there?
Comment: I´ve got 5 equivalence classes but all of them are the same because  the equivalence class of 1(which is {1,2,3,4,5}), is the same as the equivalence class of 2, and is equal to the equivalence classes of 3, 4 and 5, but I think that there is no more equivalence classes but the problem here is that my teacher said that there are 9 equivalence classes so I dont know if I am wrong or my teacher is wrong , what do you think?
Comment: What do you mean by "the equivalence class of 1"?  The elements of $A$ are _pairs_ of numbers.  It doesn't mean anything for a single number to be $R$-related to anything here.
Comment: I have the definition her it says that the equivalence class of [a]={x elements of X: a is related to x} (in this case X={1,2,3,4,5}) so the equivalence class of [1]={1,2,3,4,5} because 1 is related to all this numbers: (1,1), (1,2),(1,3),(1,4),(1,5) are all in the equivalence relation R
Comment: Why would 1 be related to, say, 2?  The definition of $R$ doesn't say that.  I think you may be confused because formally speaking a relation is a set of ordered pairs of elements from its domain, and here the domain $A$ is also itself a set of ordered pairs, so that $R$ is a set of ordered pairs of ordered pairs.  _E.g._ $((2,5),(4,3)) \in R$.  (If this is not what is confusing you, then you can ignore what I just said.)
Answer: Hint:  Let $f$ be the function on the Cartesian product $\{1,2,3,4,5\} \times \{1,2,3,4,5\}$ defined by $f(x,y) = x+y$.  By the definition of the relation $R$, two pairs $(x,y)$ and $(x',y')$ are in the same $R$-equivalence class if and only if $f(x,y) = f(x',y')$; for example, $(2,5)$ and $(4,3)$ are in the same $R$-equivalence class because $f(2,5) = 7 = f(4,3)$.  The number of $R$-equivalence classes is the same as the number of possible values that the function $f$ can take.
Comment: So what my teacher said is correct there are 9 equivalence classes because there are 9 different values that the function can take but i only have 5 can you give me another hint for the other 4 classes i would really appreciate it
Comment: Yes, your teacher was correct.  My next hint is that the thing you think is an equivalence class is not an equivalence class.  It is not even a subset of the domain $\{1,2,3,4,5\} \times \{1,2,3,4,5\}$ of the equivalence relation!
Comment: yep is becuase i was considering just one element I think I can handle the exercise from here and again thanks for the help :D
Comment: I'm glad to hear it, and you're welcome.
Comment: And just one last question is ((1,1),(1,1)), ((2,2),(2,2)),((3,3),(3,3)), ((4,4),(4,4)) , ((5,5),(5,5)) are elements of the relation?
Comment: Yes, those are in $R$ by definition of $R$. This is a good thing because "everything in the domain is related to itself" is one of the conditions (called reflexivity) that a relation must satisfy in order to be called an equivalence relation.
Comment: so ((1,2),(1,2)) , ((1,2),(2,1)), ((2,1),(2,1)) and ((2,1),(1,2)) are elements of R, arent they?
Comment: Yep, those are in $R$ also.


What is the difference between Zepto and jQuery 2?

Question: There are those two similar projects:
Zepto.js

Zepto is a minimalist JavaScript library for modern browsers with a
  largely jQuery-compatible API.

jQuery 2.0

jQuery 2.0 beta: Here is your taste of the future, a jQuery that can be faster and smaller without the need to support IE 6, 7, or 8. It's a great choice for platform-specific HTML applications.

Is this only about performance or do they follow different approaches?
Comment: This is a useful, interesting, relevant question about a specific programming problem. Why was it closed? It's not "which is better", but "what are the caveats of using"
Comment: In case you ever try to switch from jQuery to Zepto: http://blog.pamelafox.org/2011/11/porting-from-jquery-to-zepto.html
Comment: @BenjaminGruenbaum: Why was it closed?  Well, despite SO describing itself as a Q&A site, many people understand it as a problem/solution site.  The 2 are not the same.  If you don't have a _specific_ problem, many people will close your question.  I think that's dumb, but that's how many people behave.
Comment: @iconoclast you realize that comment is 10yo?
Comment: @BenjaminGruenbaum: what difference does that make?  We still have plenty of people who close questions with very poor rationale.
Comment: @iconoclast it shows comments about it don't help :]
Comment: I don't share your assessment of the situation.  The lack of immediate success doesn't invalidate all effort.
Answer: The primary difference between Zepto.js and jQuery are their respective file sizes of Zepto.js's ~20kb (minified, not gzipped) instead of jQuery's ~80kb,And Zepto.js's ~10kb (minified, Gzipped) instead of jQuery's ~30kb. Furthermore, Zepto's support for browsers such as IE<10 is either lacking or not guaranteed, its target platforms are:

Safari 5+ (desktop)
Chrome 5+ (desktop)
Mozilla Firefox 4+
iOS 4+ Safari
Android 2.2+ Browser
Other WebKit-based browsers/runtimes
webOS 1.4.5+ Browser
BlackBerry Tablet OS 1.0.7+ Browser
Amazon Silk 1.0+
Opera 10+
Internet Explorer 10+
Comment: jquery 2 is ~30kb and zepto is ~10kb when both are gzipped and minified. Non gzipped, jquery 2 is still ~80kb and zepto is ~30kb.
Comment: Both Zepto & jQuery support custom builds so kitchen sink size of either may not be so important. The difference is jQuery has better support and performance, is updated more frequently, and has a more active community. The appeal of Zepto is largely diminished with jQuery 2.0 covering the gaps Zepto once filled.
Comment: -1. As asparagino points out, MHD's numbers are incorrect. His answer is valid.
Answer: jquery 2 is ~30kb and zepto is ~10kb when both are gzipped and minified. Non gzipped but minified, jquery 2 is ~80kb and zepto is ~30kb.
Use an analytics program to check the audience for your site. If a significant chunk of your users use IE9, you need jquery and zepto won't fly. If over a few percent use IE8 and lower and you can't face leaving them stranded without your site, you will need to use jquery 1. If you're targetting that last one, I'm sorry - a lot of new shiny toys won't work for you.
If you're building an html5 app for android/ios/phonegap etc then you're primarily targeting webkit, so zepto does give you big size saving. The primary insight and reason for zepto to exist is that when running on webkit only platforms a lot of jquery's cross platform workarounds are simply unnecessary.
Zepto does also add a couple of touch event handlers to assist with mobile dev, but it's mainly the page weight vs platform support you need to think about.
Comment: Presumably if you pick any one platform then cross-platform workarounds are unnecessary :)
Comment: Zepto is closer to ~25kb ;). And they have build instructions to repackage the library for the minimum size that you need.
Comment: I assume you're talking about the non-gzipped but minified build, which hasn't really fluctuated more than a couple of kb in the eight months since I wrote this. So... 25kb is ~30kb :P
Answer: This is a somewhat old question, but I would like to add performance.  From what I'd heard, Zepto performed better than jQuery.
This jsPerf shows different results.  I can use jQuery's class selection (of a single element) 137% as often, compared to Zepto's.  For ID selection, I can use jQuery's 285% as often.
That's a huge deal considering on most applications, DOM interactions are the only performance statistic that matters (other than network requests).
Also looking at that perf, I can see that I could do document.getElementsByClassNAme 8326% as often as jQuery, so we should all ditch all of these if possible :-)
Comment: That's not what the guys at Zurb say. One of the reasons they dropped Zepto from their CSS framework was because jQuery outperformed Zepto even if Zepto's file was smaller. Other reasons were because many plugins were written for jQuery. Check out their blog post: http://zurb.com/article/1293/why-we-dropped-zepto
Comment: @ricardozea, this answer and that article say the same thing: jQuery is faster with selectors.  To be clear, though, you'd need about 100 jsperfs to fully test the libraries, and then hire a statistician to determine which is faster on average for the average site and average user.
Comment: heh Nope :-)  That's just what I've been told; my findings were that jQuery was faster (with selectors at least).
Comment: You're saying: "*...Zepto performed better than jQuery.*". Yes, we're agreeing that jQuery is faster.
Answer: Zepto lacks the deferred/promise API that jQuery features. There is an add-on, Simply Deferred, which remedies this: https://github.com/sudhirj/simply-deferred .
Comment: Consider reading that about jQuery promises: http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
Answer: I think never used zepto for fast wroking transition into web take a look Deep inside his icy cave, the wise and powerful Yeti heard people asking, "Where did Zepto go?" Back when Foundation 4 was being conceived we switched to Zepto (with a jQuery option) for its smaller file size and faster load time.
But over time we found that lighter file size did not translate into better performance overall. Sure, Zepto downloaded quickly. But once loaded, it wasn't quite as fast as jQuery. It didn't help that many third-party plugins required jQuery, not Zepto — in fact, we found that some third party JavaScripts conflicted outright with Zepto.
Maintaining different code bases wasn't easy for us, either. For example, Zepto lacks a proper height calculation function, making certain grid calculations difficult.
To solve all this, the answer was clear as a spring Himalayan sky: Foundation 5 uses jQuery 2. In addition to better speed and industry acceptance, jQuery 2 benefits from better documentation and support as well. jQuery is API compatible.
**

But we assumed Zepto would be faster than jQuery. We didn't want to
  make the same assumption twice, so we tested Zepto vs. jQuery 2. The
  result: jQuery 2 has more operations per second. That gives Foundation
  5 better performance, which translates to better experience for all
  users.

**
In the end, we want to help people design great products faster — and this time, that means giving the most responsive front-end framework in the world itself a speed boost.
Comment: If you are so concerned about performance, why are you using jQuery at all? Sure jQuery has better performance than Zepto, but jQuery's performance sucks compared to VanillaJS. Basically, VanillaJS is a better and superior version of jQuery. Imagine vast libraries of high-performance optimized functions packed together into a featherlight package. That's the power of VanillaJS. I highly reccomend trying it.
Answer: From what I've read, people seem to lean heavily towards Zepto. The most-common reasoning behind that is file-size, but jQuery 2 is actually faster than Zepto after it is loaded. Also, you won't find much support for Zepto since most people develop around jQuery. I'm not suggesting you shouldn't use Zepto, but you should look into why you want to use it and if other JavaScript libraries you are using support/conflict with it.
I would say it depends on your project. For personal or limited use, Zepto may be the better option. However, jQuery is much more supported by other libraries and if the file size is the only thing determining your reason then it is flawed. JavaScript should be loaded after the page is loaded, therefore it wouldn't hinder your page load time in either case.
Here is performance test including jQuery 1.7.2, Zepto 1.0rc1, and also jQMobi 1.03.


Load the valude in dropdown list from mysql database

Question: I am trying to load the value from the mysql database on drop list in jsp . When run the I got some exception. can anyone help me please to fix this issue. I Have use Department bean and adddepartment.jsp file as presentatio layer.
<form action="LoginServlet" method="POST" id="theform" name="theform">

                            Department Id:
                            <input type="text" name="departmentId" id="userName"/>

                            Department Name:
                            <input type="password" name="departmentName" id="password"/>

                            Department Name:
                            <input type="password" name="departmentName" id="password"/>

                            Department Head ID:
                            <select name="departmentHeadId" style="width: 158px"> <option value="0">Select Department Head</option>
                                    <%
                            //if(request.getParameter("btnvew")!=null)

                         {
                           String val="";
                            Department dp=new Department();
                            ResultSet rs=dp.addHeadId();
                            while(rs.next())
                                {
                                 val=rs.getString(1);
                                %>

                                  <option value="<%= val%>"><%= val%></option>
                                  <%
                                }
                            }
                           %>

                        </select>

                            Appointed Date:
                            <input id="example6" type="text">

                            <input type="submit" value="Login"/>

org.apache.jasper.JasperException: An exception occurred processing JSP page /AddDepartment.jsp at line 52

49:                        String val="";
50:                         Department dp=new Department();
51:                         ResultSet rs=dp.addHeadId();
52:                         while(rs.next())
53:                             {
54:                              val=rs.getString(1);
55:
Stacktrace:] with root cause
java.lang.NullPointerException
    at org.apache.jsp.AddDepartment_jsp._jspService(AddDepartment_jsp.java:170)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

public class Department {

    private Connection con;

    public ResultSet addHeadId() throws SQLException {

        ResultSet rs;
        String query = "select * from department_heads";
        Statement stmt = con.createStatement();
        rs = stmt.executeQuery(query);

        return rs;

    }
}

Answer: Your Department#addHeadId() seems to return 'null' as result, as the line on which the NullPointerException happens is
while(rs.next())

Please try debugging the addHeadId()-method. Acutally Statement#executeQuery(String) is explicitly specified to never return 'null', so the error seems weird.
Comment: the connection instance isn't initialized
Comment: well ... the code snipet does not initialize the connection, but I assume, this is done elsewhere. Nonetheless, the NPE happens at the ResultSet#next() call according to the StackTrace
Answer: In your addHeadId() method, connection instance is not created. Try this sample;
  public ResultSet addHeadId() throws SQLException {

     try {
        Connection con = DriverManager.getConnection(url,username,password);
        ResultSet rs;
        String query = "select * from department_heads";
        Statement stmt = con.createStatement();
        rs = stmt.executeQuery(query);
     } catch (Exception e) {
         e.printStackTrace();
     }
     return rs;

}

Don't forget to instantiate url, username and password.


How to change the spool/direct print setting via code?

Question: I need to change the setting in the print properties that specifies either: 1. "Spool print documents..." or 2. "Print directly to the printer."
In this answer J... indicates that this can be done using the PrintQueue Class. How?

MSDN PrintQueue.isDirect (ReadOnly Property) says this: "This property can be set only
  through the Windows common print dialog."

I assume that applies specifically to .net and may not be true in the absolute sense. So how to change the spool/print direct setting via code?
Comment: Well, there's always... http://www.undocprint.org/winspool/registry  You'll need administrator rights to modify the registry key in question, of course, but this would be one way to do it.
Comment: That was an error in my previous post - I've corrected it.  You cannot change the print mode (spool/direct) using that class.  You may be able to do it using native WinAPI calls, probably in an elevated application only, I'm not sure.  It's probably not something your application should be doing, however.  This is a system-wide setting and it will cause all applications to lose print spool functionality - this is something that would seriously irritate users who make any use of printing.  If you need to ensure serialization of printed documents it's best to manage this yourself.
Comment: @J... OK not surprised. This is for a one-off application used in a dedicated computer not used for other purposes. So system-wide is no problem and irritating users is not a problem either. Of course I am pursuing other options simultaneously, but if I had this capability it would be seriously helpful.
Comment: Great! I'd say this qualifies as an answer.
Answer: From comment of J...
Quoting from: Windows Spooler Registry

Various printer options can be set via the windows registry. Each
  installed printer has a subkey in the following Registry path:
  HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers\
Under this there is a attributes bitmap, in the value Attributes :
  REG_DWORD 0002 (0x0002) Direct: Document to be sent directly to the
  printer.
The spooler service might need to be restarted, for the changes to
  take effect.

Note that this registry value contains multiple attributes. See Windows Spooler Registry for more details.
Warning Serious problems might occur if you modify the registry incorrectly by using Registry Editor or by using another method. Modify the registry at your own risk.


How do I hide a jquery dialog until content is retrieved?

Question: I have a button's onclick set to use the following function EditContact. This function sets up a jquery dialog, gets the data from the server and displays it. Everything works but I would like to get it to work a little better. Right now the empty dialog pops up for the time it takes the code to go and fetch the content from the server then the dialog populates with the content. My question is how can I get the dialog to not pop up until the content has been received.
function EditContact() {
        $('#editContactView').dialog({
            modal: true,
            width: 'auto',
            position: ['top', 'center'],
            resizable: false,
            autoOpen: false,
            open: function (event) {
                var szAction = "Content url for this example";
                $(this).load(szAction,
                        function (response, status, xhr) {
                            $('#editContactView').dialog('open');
                            return false;
                        });
            }
        });

        $('#editContactView').dialog('open');

    }

Answer: You are calling .dialog('open') twice: in the end of the code and in the callback for the loading.
As JavaScript is asynchronous, it runs the line $('#editContactView').dialog('open'); in the end before the data is received.
Removing this line should solve the problem.
Comment: that was the first thing I tried and it did not work. Thanks for helping out.
Answer: I think you should be able to essentially turn what you have inside out and and open the dialog on $().load() completion. Something like this might do it:
function editContact() {
    var szAction = "Content url for this example";
    $(this).load(szAction, function (response, status, xhr) {
        $('#editContactView').dialog({
            modal: true,
            width: 'auto',
            position: ['top', 'center'],
            resizable: false
        });
    });
}

Edit:
Notice I removed the {autoOpen: false}. This will create it and open it in one shot after you receive the content.
Comment: I think this is close to what needs to be done but right now it is not working for me. I will post back when I get it working.
Comment: I think `$(this).load()` should actually be `$('#editContactView').load()` in this case.
Comment: I had a syntax error that was causing my problems, this solution worked. thanks for the input.


Run schedule every five minutes (like 00:05, 00:10...) in laravel

Question: I want to run the schedule every five minutes.
like 12:00, 12:05, 12:10...n
I'm using the Schedule Frequency Options :
->everyFiveMinutes();
But sometime it will start 12:02, 12:07, 12:12...n It's wrong for me.
So how can I run schedule every five mins special mins like +5?
Answer: try this
 $schedule->command('your:job')->cron('5 0 * * *');

The command in this like will be executed at the five minutes of every day (0h05 or 12h05am) and so on.
Answer: You have to express this in cron notation:
$schedule->command('my:command')->cron('0,5,10,15,20,25,30,35,40,45,50,55 * * * *');


What are the differences in gameplay between Modern Warfare 3 and Battlefield 3?

Question: I'm not asking for an opinion of which is better, but rather, what are the ACTUAL differences between the two games gameplay? they are very similar, how do they differ?
Does one have killstreaks and the other a different system that's similar? Do both have weapon customisation that allows you to enter matches with different load-outs, or do you start with default equipment in one?
Answer: There are actually several differences, almost too many to list, but I'll give it my best shot! Here's a brief rundown of the type of gameplay for each game.
Battlefield 3

Large maps capable of 12vs12 matches (Xbox 360/PS3), or 32v32 (PC)
Vehicle warfare consisting of boats, jets, tanks, and HMMWVs
Four Classes to choose from (Recon, Support, Assault, Engineer)
Generally slower paced battles due to the size of the maps
Able to play with your friends in Squads of 4
Gametypes include Rush (Assault/Defend objective), Conquest (Capture points and hold them), Team Deathmatch, Squad Deathmatch (Up to 4 squads of up to 4 players compete for the highest score), Squad Rush (Rush, but with one squad of 4 vs another squad of 4), and Hardcore gametypes (All game modes with limited HUD, friendly fire, and faster deaths)
Destructible environments (Able to destroy entire buildings in some cases, killing anyone caught inside)

Modern Warfare 3

Smaller maps allowing for more twitch-based gunplay
Kill Confirmed mode (Your kill doesn't count until you collect a dogtag dropped by your target)
Kill Streaks
Perks enabling faster acquisition of kill streak rewards, sprinting longer distances, able to swap weapons/reload faster, etc.
No vehicles

There are more differences, but I can't think of any more off the top of my head. Here are some similarities between the two:

High level of customization, with each weapon having several unlocks (extended mags, grips, sights, etc.)
Complete challenges to earn XP and advance in Rank, unlocking additional weapons

While both games are extremely fun in their own ways, it really depends on what you're looking for in a shooter.

I would like to note that this image is in no way attempting to show which of the two are better, but rather it is meant to show the theoretical age groups you're more likely to be playing with in each game.
Comment: Also, why were the bullets spaced differently? I tried fixing it, but had no luck.
Comment: Actually the map size and number of players is not really relevant. you make it sound as if they are not considered both small. Surely MW3 is smaller but nowadays 32 vs 32 is average. 12 vs 12 can't be considered anything but small.
Comment: Thanks for that. I forgot that the PC had 32v32 compared to 360s 12v12.
Comment: ah ok, i never played BF3, but i always knew it had pretty big maps. There was something weird about it having just 12 vs 12.
Comment: I haven't played MW3 yet but based on previous COD titles the level of destruction you can cause is a significant difference between the titles.
Comment: @tQuarella: 64v64? 64-player map is 32v32.
Comment: @Tristan: I'd add to that a point, about weapons, their attachments  and their behavior in BF3 being more realistic. Each weapon in BF exists and is widely used in real life (maybe with exception of Mk3A1, which IRL is only prototype). On contrary in MW3 you have more exotic weapons, attachments are not modeled after real-life ones, behavior is highly unrealistic (quick scoping, no bullet drop etc).
Comment: @vartec herp and a'derp.  You are correct.
Comment: MW3 has a **maximum** of 18 players in a server.  That's what killed it for me - even CS 1.6 can have 32 players (64 with mods).
Answer: Tristan's answer covers most of it, but I'll elaborate on some more differences:

Team play vs individual play: In BF3 there is lot of items and actions that are meant for helping out your teammates, not you directly. You have enemies spotting. You have Assault healing and reviving, you have Support proving ammo, you have Recon laser designating targets, you have Engineer fixing vehicles. On the other hand in MW3 it's all about getting more individual kills, some MW3 players even get annoyed at getting their kills "stolen" by teammate.
Tactics vs reflexes: In BF3 you can get impressive results using tactical moves like flanking or getting nice elevated position overlooking the objective. With maps varying in size so much, lot depends on choice of attachments, as it's quite different to engage enemy at distance to engaging in CQB. On the other hand in MW3 it's more about being in constant movement and being quicker to get headshot than your opponent, most players have their set of favorite attachments which they'll use on any map, as they are all what you'd consider CQB by BF3 standards.
Objectives and score vs kills and streaks: Most good BF3 players play objectives (capturing flags in Conquest, arming/disarming m-coms in Rush), there are no kill streaks and ppl camping for high K/D rather than playing objectives are frowned upon. You can get to be MVP with much less kills than other players, as playing objectives is worth lots of points. In MW3 however in most game types win depends on amount of kills, so in MW3 it's perfectly valid winning strategy to go high K/D and get even more kills using kill streak bonuses.
Realistic weapons and attachments: Although this doesn't directly affect gameplay, some people do find it important for weapons to be modeled after real-life ones. This is the case of weapons in BF3. They are modeled after ones that are commonly used, also in single/co-op correct factions use correct weapons, so you have for example Iranians using KH2002, Specnaz using AS Val and AN-94 etc. The attachments are also modeled after real life ones. Their behavior is more realistic. On the other hand in MW3 you have some quite exotic weapons, in the single/co-op the opposition uses totally mismatched weapons (Specnaz using FAMAS??). Weapons' behavior is highly unrealistic (quick-scoping, no bullet drop), and most of the attachments are not modeled after any real-life ones.

Of course that doesn't make either of them less fun. It just depends on what kind of gameplay are you looking for. If it's fast paced, individualistic simple shooter, then it's MW3, if it's slower paced, more complicated and realistic tactical shooter, then it's BF3.
Answer: There are a great many differences between the two games.
For example, Battlefield:3 is much more open. It is considered more realistic because it has a whole new level of game play. Most of your game-play environment can "blow up". There are vehicles and planes. The game has bigger maps and different game modes. Call of Duty on the other hand traditionally has smaller maps with some planes/helicopters but they are awarded through kill streaks.
In both games you can have customized classes however in battlefield you have 4 main classes that you can customize weapons geared towards that specific 'type'. Such as Engineer class will have sub machine guns mainly with repair tools and rocket launchers. While the sniper class would have sniper rifles and detection gear. Both games have weapon customization and each specific gun can be leveled up to unlock things like new sights for the weapons.
So to sum up:
Battlefield: 3 -Bigger maps, More 'realism', no kill streaks, tons of vehicle combat, and speicalization benifits. Typically slower paced gameplay.
Call of Duty: Modern Warefare: 3- Smaller maps, Kill streaks with each planes, etc. Less vehicles. Typically faster paced gameplay.
Planes in battlefield:

Killstreaks in Modern Warefare


Bodyparser breaking fresh installation of adonis 4.1

Question:
email@example.com start /usr/src/app
node server.js

Error: Cannot find module '@adonisjs/bodyparser/providers/BodyParserProvider'
Require stack:

/usr/src/app/node_modules/require-stack/src/index.js
/usr/src/app/node_modules/require-stack/index.js
/usr/src/app/node_modules/@adonisjs/fold/src/Ioc/index.js
/usr/src/app/node_modules/@adonisjs/fold/index.js
/usr/src/app/server.js

1 requireStack
/usr/src/app/node_modules/require-stack/src/index.js:44
2 anonymous
/usr/src/app/node_modules/@adonisjs/fold/src/Registrar/index.js:104
3 arrayMap
/usr/src/app/node_modules/lodash/lodash.js:653
4 Function.map
/usr/src/app/node_modules/lodash/lodash.js:9622
5 interceptor
/usr/src/app/node_modules/lodash/lodash.js:17094
6 thru
/usr/src/app/node_modules/lodash/lodash.js:8859
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! email@example.com start: node server.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/node/.npm/_logs/2021-03-25T00_06_01_885Z-debug.log
Answer: The problem is npm is installing the wrong version from body-parser, due to a recent push.
As a workaround:

go to package.json

you can replace the ^ with ~
"@adonisjs/bodyparser": "~2.0.9",

Since we prefixed the version with ~, NPM retrieved the latest patch version under the 2.0.9 minor version, which turned out to be 2.0.9 itself
For more info: https://github.com/adonisjs/bodyparser/issues/43


Ejector Pit & Sump Pit Combined - Whats a good backup option?

Question: Here in Chicago we have a combined sewer and storm drain system - as a result it's not uncommon to have sump pits and ejector pits combined - which is the case in my basement. The ejector then handles the sump pumping, as well as removing the basement sewage.
My ejector services the basement bathrooms and shower as well as any rain seepage from the drain tiles, but since it's a combined system I am terrified of an overflow.
The good news is that if there is an overflow, its likely to be just my home's waste & the clear storm water, but that's still enough to ruin a basement.
My question is, what backup systems would you recommend for this type of setup? The ejector is currently mains powered (plugged in), so if I lose power, I essentially have no sump pump.
I'm considering a water powered backup sump pump, but am concerned about any potential sludge or remaining waste clogging a system that is not built for any solids/semi solids.
Any brilliant ideas?
Comment: Water powered backup sump pumps are available, and are quite useful if you're connected to a municipal water supply.  I'm not sure if water powered ejector pumps exist. If they do, that's the route I'd take.
Answer: Computer UPSes are super cheap these days.  See if you can find one rated for the watts that your system needs with a good margin.  They are readily available up to 1500 less than $500, and they'd just plug in in line inbetween the equipment and an outlet.  Most of them self test every day and alarm on failure of the battery or of mains power failure so you'd know if the breaker flipped.  Make sure the one you buy doesn't do a self-shutdown when its running on battery and can't detect a load.  That used to be more common.
Comment: Uninterrupted Power Supplies (UPS) aren't typically designed for extended use when on battery, so an extended power outage could be a problem. This could be especially troublesome during a storm, where the power is out and the pump is doing a lot of work.  The batteries also don't tend to last long, and require frequent replacement (which can be quite expensive).


How to achieve timeout handling in blocking DatagramChannel without using selectors

Question: I get a feeling that I am missing something really obvious here.
The overall structure of my system makes me want to use a blocking DatagramChannel without Selectors, in order to keep things simple.
I am trying to achieve timeout handling by setting a timeout on the socket, but this seems to have no effect.
This pseudoized code gives a hint of what I am trying to achieve.

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(some address);
channel.socket().setSoTimeout(3000);
channel.send(outBuffer, peerAddress);

channel.receive(inBuffer);

On the other side, I have a UDP server that gives five quick responses, and then, for testing purposes, delays about five seconds before delivering the sixth response.
The delay does not trigger a SocketTimeoutException. Why is that? The timeout set on the socket does not seem to be taken into consideration when calling channel.receive.
Regards,
Fredrik
Comment: You should consider accepting one of the given answers.
Comment: I've recently discovered that setSoTimeout() doesn't work for SocketChannel reads, and it looks like it doesn't work for DatagramChannels either. Why, I cannot imagine. Is there some reason you can't use a DatagramSocket?
Comment: No reason. Just thought DatagramChannel looks nicer.
Comment: It does, but it has this strange *lacuna.*
Answer: Apparently the issue of not being able to timeout is not a bug with DatagramChannel, but that:

Not a bug.  The read methods in SocketChannel (and DatagramChannel) do not
support timeouts.  If you need the timeout functionality then use the read
methods of the associated Socket (or DatagramSocket) object.

Link.
Comment: I have to agree with you there. I'm just learning SocketChannels myself so are we supposed to use a Selector instead?
Comment: Apparently, but that also forces you to use non-blocking mode. It remains bizarre. There is no reason for read timeouts not to be supported. A socket is a socket at the C layer.
Comment: This is quite strange, as the DatagramChannel doc says: Datagram channels support timeouts on read operations. If a datagram channel is in blocking mode, and a timeout period has been set by invoking its socket's setSoTimeout method, then a TimeoutException is thrown if a receive or read method is invoked but fails to complete before the timeout period expires.
Answer: This is what I did:
Create an Interrupter class
static private class Interrupter implements Runnable
{
    private final Thread th1;
    private volatile int wait=-1;
    private Interrupter(Thread ith1)
    {
        th1=ith1;
    }
    public void run()
    {
        while(true)
        {
            try{
                if( wait<0 ){ th1.join(); break; }
                else{ Thread.sleep(wait); th1.interrupt(); wait=-1; }
            } catch(Exception e){}
        }
    }
}

Setup the Interrupter
Interrupter ir1=new Interrupter(Thread.currentThread());
Thread th1=new Thread(ir1);
th1.start();
// We need this so that later the wait variable
// can be passed in successfully
while( th1.getState()!=Thread.State.WAITING );

Use the Interrupter
try{
    ir1.wait=waitTimeout;
    th1.interrupt();
    // Receive on the socket
    dc2.receive(bb2);
} catch(ClosedByInterruptException e){
    // (Timed out)
    Thread.interrupted();
    dc2.close();
    // Handle timeout here
    // ...
    // We need this so that later the wait variable
    // can be passed in successfully
    while( th1.getState()!=Thread.State.WAITING );
}
// Received packet
ir1.wait=-1;
th1.interrupt();
// We need this so that later the wait variable
// can be passed in successfully
while( th1.getState()!=Thread.State.WAITING );
Thread.interrupted();


I am currently trying to save a set of integers in a int array, by redefining string into numbers, then store it in the array

Question: I am trying to convert input text/numbers (string), which will include any characters, but I want to separate the numbers from the characters and store them into an integer array, once it is converted from a string.
I believe the problem is where the string is converting to an integer by use of stoi(), but I cannot seem to spot the problem.
Currently, the code accepts any input and turns it into a string, the string is then checked character by character, and all the numbers without separation with comma or space is added together, once a comma or space, or any other character separates the number, the number as a whole is added to the array, and then continues to check the string for more numbers.
Any ideas?
Input Example1: 12, 13, 15
    Input Example2: 12 13 15
        Input Example3: 12ab13cd15ef
Result in integer array: 0[12] 1[13] 2[15]
These numbers will be used in the specific order, by using the numbers within the array.
#include<iostream>
#include<string>
#include <sstream>
using namespace std;

int main()
{
    string datainput, str1, str3;
    cin >> datainput;
    int n = 0, raycount = 0, c;
    int myray[10];
    while (datainput[n])
    {
        if (datainput[n] == ('0') || datainput[n] == ('1') || datainput[n] == ('2') || datainput[n] == ('3') || datainput[n] == ('4') ||
            datainput[n] == ('5') || datainput[n] == ('6') || datainput[n] == ('7') || datainput[n] == ('8') || datainput[n] == ('9'))
        {
            str1 = datainput[n];
            str3 += str1;
        }
        else
        {
            c= stoi(str3);
            c >> myray[raycount];
            raycount++;
        }
        n++;
    }
    cout << myray[0] << endl;
    cout << myray[1] << endl;
    cout << myray[2] << endl;
    cout << myray[3] << endl;
    system("pause");
    return 0;
}

Answer: I see quite a few issues with your code.

Prior to C++11, while (datainput[n]) has undefined behavior once n reaches the end of the string.
The way you are checking for numeric digits can be greatly simplified using std::isdigit(), or even just a simple range check using the >= and <= operators.
You are not correctly accounting for numbers that are separated by other characters, or when the last number in the string is at the very end of the string.
The statement c >> myray[raycount]; needs to be changed to myray[raycount] = c; instead.  And you are not breaking your loop if raycount reaches the max capacity of myray[].
You are not resetting str3 back to an blank string after converting it with std::stoi().  You just keep appending new digits to the end of previous digits with no break in between numbers.

With that said, try something more like this instead:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string datainput, str3;
    cin >> datainput;

    int myray[10];
    int raycount = 0;

    bool gettingDigits = false;

    for (int n = 0; n < datainput.size(); ++n)
    {
        char ch = datainput[n];

        //if (isdigit(ch))
        if (ch >= '0' && ch <= '9')
        {
            if (!gettingDigits)
            {
                str3 = "";
                gettingDigits = true;
            }

            str3 += ch;
        }
        else
        {
            if (gettingDigits)
            {
                myray[raycount] = stoi(str3);
                raycount++;
                str3 = "";
                gettingDigits = false;
                if (raycount == 10) break;
            }
        }
    }

    if (gettingDigits && (raycount < 10))
    {
        myray[raycount] = stoi(str3);
        raycount++;
    }

    for (int n = 0; n < raycount; ++n)
        cout << myray[n] << endl;

    system("pause");
    return 0;
}

Live Demo
Alternatively:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string datainput, str3;
    cin >> datainput;

    int myray[10];
    int raycount = 0;

    string::size_type start = datainput.find_first_of("0123456789");
    string::size_type end;

    while (start != string::npos)
    {
        end = datainput.find_first_not_of("0123456789", start+1);
        if (end == string::npos)
        {
            str3 = datainput.substr(start);
            myray[raycount] = stoi(str3);
            raycount++;
            break;
        }

        str3 = datainput.substr(start, end-start);
        myray[raycount] = stoi(str3);
        raycount++;
        if (raycount == 10) break;

        start = datainput.find_first_of("0123456789", end+1);
    }

    for (int n = 0; n < raycount; ++n)
        cout << myray[n] << endl;

    system("pause");
    return 0;
}

Live Demo
Comment: Thank you for your input! I have applied some of the changes you suggested, and it is steps in the right direction. Also highly appreciate the other methods which will make the code easier. Resetting the strings and integer seemed to fix the stacking problem, but I am still stuck on getting all the numbers stacked into the array, and the conversion of the string to a number. I will browse through the code you posted and see if I further can solve my problem. :-)
Comment: @Daniel it would be helpful if you would edit your question to show the actual input you are typing in, and what the expected result should look like.
Comment: I have added 3 examples, which should produce the same result.
Comment: @Daniel I updated my answer. There was an error in my first example, which I have fixed.
Answer: So, you want to segregate numbers and characters into different arrays.
In if block, you are checking for characters, so, I suspect stoi() wouldn't work.
Better typecast it to an integer.
int temp[10];

if (datainput[n] == ('0') || ...) {
            temp[n] = int(datainput[n]);
        }

This way your temp array would contain the numbers.
Comment: I would be grateful if you tell me why is this answer downvoted ? Thanks.


If() vs. switch() - Same meaning but different behaviour?

Question: I would like to transform my if() conditional to switch() from this:
if($configuration['application'][$applicationName]['subdomain'] == true){
    foreach($configuration['language'] as $language){
        if($language['abbreviation'].'.'.$configuration['application'][$applicationName]['domain'] == $_SERVER['HTTP_HOST']){
            $_SESSION['language'] = $language['abbreviation'];
        }
    }

    // If no subdomain detected and redirection is enabled, set default language
    if(!isset($_SESSION['language'])){
        $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
    }
}
else {
    $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
}

To this:
switch($configuration['application'][$applicationName]['subdomain']){
    case true:
        foreach($configuration['language'] as $language){
            if($language['abbreviation'].'.'.$configuration['application'][$applicationName]['domain'] == $_SERVER['HTTP_HOST']){
                $_SESSION['language'] = $language['abbreviation'];
                break;
            }
        }
    default:
        $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
        break;
}

I think it should be the same but it behaves differently ...
Switch is not working properly ...
Comment: What type of data is stored in `$configuration['application'][$applicationName]['subdomain']`? Is it boolean really, or there is some kind of string or integer, which is implicitly casted to bool in `if` version?
Comment: The specific programming (PHP?) you're using might be important here; also a description of exactly how it's behaving differently (could the `break` that's been added to the `foreach` loop be cuasing a change in your expected behavior?).
Comment: Well I am using php and $configuration['application'][$applicationName]['subdomain'] is boolean (it is read from .ini and typecasted to bool) ... And the thing is that the code in foreach is executed and default is also executed (break doesn't really break the switch?)
Answer: I have reformatted your code, please check to make sure it is still correct.
As for your problem, to begin with you are missing a break; statement at the end of your case true: statement. (The break inside the foreach loop simply breaks out of that loop, not the case itself).
Comment: Well that is interesting, I thought that break should quit the switch (I think that this is the way it is done in c++) ... My intention was that if session is set in the true case it should quit the switch, otherwise it should continue to default case and then do the break...
Comment: I have just figured out that problem is the break inside foreach loop. It just does not work ... After the session is set in the if statement it continues to default and set the session again which is the problem.
Comment: @jzvelc: yep, that is why i mentioned you need another `break;` statement otherwise you will fall through to the next condition :)
Comment: Yeah but my point is that id the condition in foreach fails it should continue to default, otherwise not (or if config is set to false)


Why does this toilet valve have corrosion on it?

Question: I had a question about some corrosion on my toilet water supply line. I've provided a picture below.

What I was wondering are a few things.
1) What is the reason for this? Why would a valve start building up corrosion while my other bathrooms do not.
2) Is it something I need to worry about and replace or can I just wash it with some solution to remove the corrosion or if I don't replace it will it cause a bigger issue down the line.
Answer: I cannot answer whether it needs replacing, but I can tell you why this happens.
It happens because it gets cold and water condenses on it.
Whenever you flush your toilet, cold water runs through and cools it off. Then the hot, humid air around it condenses water on it, making it moist. Because this happens so often, it will be moist a lot of the time, and thus corrodes.
Why this doesn't happen other places: The toilet is the one thing that uses most cold water. Your shower and sink uses more warm water, and not as much, and thus aren't as exposed to this phenomenon.
Unless it leaks I think you can leave it on.
Comment: +1 Some plumbers send *tempered* water to toilets, a mix of cold and hot. The tempering valve is set once and left, often in a basement or crawl space. It does require having both hot and cold available, and does use a very small amount of power (to heat the hot water), but totally eliminates warm weather sweating and this type of corrosion. A significant project best left to new work and renovations.
Comment: @kitalda Thank you, so is this normal and why do I not see it on all the toilets in my house, I'm assuming it just depends on the location? Would you advise I clean it off or just let it be?
Comment: Maybe: 1) It is the most used toilet in the house? 2) It is in the same room as the most used shower (more humidity in the air)? 3) The parts are made from a different material that corrodes more easily? 4) Some cleaning agent has been used there, but not at the other toilets, that started the corrosion? 5) Any combination of the above?
If you can clean it off without damaging the part, sure, you can clean it, but if not, just let it be. If it gets worse (especially if rapidly) think about replacing it, but until then, no worries.
Comment: Actually @bib has a point, that technique isn't used where I live (seen as wasteful), but that might be a reason it is the only toilet doing this. If You have tempered water in your toilets, but the tempering on this toilet is broken or off (too cold), it could be the explanation you are looking for.


Disable field in the crud

Question: I need to update a record, but I want to display some fields as disabled for editing. I don't want to let the user edit a certain field, but I want to display them
Answer: If I understand your problem correctly then you may want to try something like this.
<code>CRUD::addField([
            'name' => 'nameOfYourField',
            'label' => 'nameOFLabel',
            'type' => 'number',
            'attributes' => [
               'readonly' => 'readonly',
             ],
        ]);
</code>
You can also use 'disabled' => 'disabled', but it depends what you want exatly to achieve with the values.
Check it out here

Disable field in the crud


Tomcat Error Too Many open files

Question: I want to know the exact problem of Too many files opened error. I went through google for solution but i could not get why this problem happens and how to solve the problem. is that some thing about ulimit value ?

stack error : SEVERE: Socket accept failed java.net.SocketException: Too many open files at java.net.PlainSocketImpl.socketAccept(Native Method) at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398) at java.net.ServerSocket.implAccept(ServerSocket.java:530) at java.net.ServerSocket.accept(ServerSocket.java:498) at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:61) at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:352) –  user2883376 yesterday
Linux server and this is my last update in the code to get messages based on language. ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml"); name = context.getMessage(key, null, locale); return name;
Any suggestions on this error ?
Comment: It looks like problem with ulimit. Please put more details, like OS and error message. Is there any stack error?
Comment: The OS may restrict the number of files a process can have open. Maybe you did not close files after you are done with them?
Comment: stack error : SEVERE: Socket accept failed
java.net.SocketException: Too many open files
        at java.net.PlainSocketImpl.socketAccept(Native Method)
        at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398)
        at java.net.ServerSocket.implAccept(ServerSocket.java:530)
        at java.net.ServerSocket.accept(ServerSocket.java:498)
        at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:61)
        at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:352)
Comment: Linux server and this is my last update in the code to get messages based on language. ApplicationContext context  = new ClassPathXmlApplicationContext("app-context.xml");
  name = context.getMessage(key, null, locale);
  return name;
Answer: The problem is almost certainly that you are leaking file handles somewhere in your code. I have Tomcats that stay up for months at a time without encountering this.
Comment: How to identify the file leaking. As i am using hibernate for ORM. is that about JDBC connections ? or reading the properties file ?
Answer: Although if "ulimit" is raised at some point down the line tomcat stops causing same error.
So in order to avoid this you can check list of open files for the application user on Linux using command "lsof -u username" or simply "lsof" and see if code related files are open ( eg..properties files ) if so kill those specific files using  # kill -9 lsof -t -u username  command for that specific tomcat user.
You need to fix your code to load those files writing simply in a static block of your classes. So that only one file loads even if multiple hits are made by any number of users.
Now you can re check after deploying new changes with the same lsof command and see. Only one file will be seen. This will permanently fix your issue without raising the ulimit each time.

Tomcat Error Too Many open files


Does Reaper shoot above and below him when using Death Blossom?

Question: If Reaper uses Death Blossom, will it damage people who are above or below him? Most of the time I see Reaper's dropping off a roof or wall before using Death Blossom, but could I instead stay on the roof just above the other team and use it and kill them, or use it to kill a Pharah that is hovering above me?
Comment: I saw this title and thought there was a new Last Starfighter game I missed =(
Comment: @StingyJack sorry to disappoint. It's just another blizzard game
Answer: Reapers ultimate actually hits everything around him in an 8 meter radius (360 degrees).

Quoting from my link:

Death Blossom is a very deadly short range damage dealer that does 360 degrees of damage all around Reaper.  Deathblossom is best used when there are a lot of clumped up enemies in a short radius, as it can wipe all of them out easily as long as they do not kill you first while executing Deathblossom.

For more info you can check this: Reaper strategy guide
People have also been talking in reddit
Quote from Reddit link:

Currently, Death Blossom's hitbox extends way above what it appears to hit. A reaper is able to ult on the ground and kill a pharah well above him. The hitbox needs to be changed to fit the animation or the animation needs to be adjusted to fit the hitboxes because it's extremely frustrating to play against.

It seems Reaper fires in all directions. His animation demonstrates that.
From this Ability Preview Video you can easily see flashes of red diagonally up and down. Demonstrating that he does fire up and down.
Comment: This doesn't answer the question. Radius could apply to either a circle or a sphere.
Comment: That is just some random guy's blog.  Where does he get his info?
Comment: @blueRaja-DannyPflughoeft I've updated my answer. I tried to include all evidence I could find.
Comment: @Lokuzt Upvoted. I'd be interested in seeing some definitive information on how high it reaches.
Comment: I'm very curious as to whether or not the AOE is a sphere or a cylinder, because if I ult on top of a payload, I want to hit all the targets on all the sides of the payload.
Answer: I was playing reaper last night when I panic ult'd; consequentially I have anecdotal evidence to proffer here. I was in the room to the left of that low spot at the very beginning of Watchpoint Gibraltar. I was located at ground level, the enemy Mei located almost at the top of the stair case leading up. Much to my surprise, my ult actually killed her.

So yes, it would appear as though reaper's ult has a considerable vertical hitbox at least above his character. Based on this along with Blizzard's 8-meter radius description, I would assume that it's an 8-meter radius sphere.
Answer: You can shoot bellow yourself:

And above: (Can't tell which one's on the payload but they get damaged too at 0M.45s

Comment: Die die die rains from above?
Comment: Not to be pedantic, but this only shows you can shoot below yourself, not above. I wonder if the AoE is a sphere or a cylinder, in either case.
Comment: @DanmakuGrazer I've added another clip that shows someone a bit above reaper.


Do we use hash functions for anything 'critical' under the assumption that collisions will never occur?

Question: I'm currently learning the basics of cryptography and started to wonder. I understand that if an attacker wanted to 'pretend to be you' they could theoretically find a collision for your password or whatever it may be that identifies you, then authenticate themselves with that hash value.
Are there any other less obvious uses for hash functions perhaps aside from information security where in the almost impossible off chance that a collision occurs something rather strange would happen? Or in fact are there any real world examples of when this has happened?
I wonder because from what I understand if we use a strong enough hash function we pretty much assume that a collision will certainly not happen... but what if it did? Do we ever use hash functions for anything 'critical'?
edit: This is purely a speculative question.
Answer: The amount of try would be so huge (as the associated time to process) that the login by an unknown user is unlikely probable.
In order to prevent that king of attack, you can put some security like interval between 3 false tries. That done, the time needed to process the entire attack with a result would be too long for the attacker.
See http://en.wikipedia.org/wiki/Brute-force_attack.
The hashing method can also be used to create CheckSum, see http://en.wikipedia.org/wiki/Checksum.
Comment: I understand how hash functions are used in day to day applications. Are there any examples of hash functions used outside of these cases?
Comment: @Titus Except cases listed here http://en.wikipedia.org/wiki/Hash_function#Description I don't know any other application.
Answer: Hash functions are also used to digitally sign documents. Assume you have got a document like a PDF and you want your boss to sign it. You would send it to him, he would sign it and you could send it over to someone else in his name.
Or you could prepare a special document that abuses a hash collision. You do not necessarily need a full hash collision. MD5 for example applies block by block of plain text to the hash. If you can find a collision for this single block you won.
Lets say "asdasd" causes a collision with "qweqwe".
You can create a PDF like so:
Headline

if("asdasd" == "asdasd")
  Good text...
else
  Evil text...

Your boss will see "Good text...". After you have his digital signature for this document you replace one "asdasd" by "qweqwe".
Headline

if("asdasd" == "qweqwe")
  Good text...
else
  Evil text...

Now you can send the evil PDF with a valid signature.
It is not as easy as I described but you get the idea I think.
Comment: This "block by block" property is rooted in the [Merkle–Damgård construction](http://en.wikipedia.org/wiki/Merkle–Damgård_construction), which is also used by SHA1 and the SHA2 family. However, only MD5 has been broken in practice.


Can't format a UTC date in PHP

Question: With a php app, I have a date like this '2019-07-22T04:44:43.843710438Z' and I can't figure out how to convert it to a date like this 7/22/2019 3:11 PM. strtotime just returns false, I tried a few time zones and nothing works. Here is my scratch pad of stuff I've been trying
<code> $timestamp = '2019-07-22T04:44:43.843710438Z';
//$reset = date_default_timezone_get();
//date_default_timezone_set('America/New_York');
//$stamp = strtotime($timestamp);
//date_default_timezone_set($reset);

$result = date_parse_from_format("j F Y G:i", $timestamp);
</code>
Comment: I'm not too familiar with ISO 8601 but it looks like the ending decimal doesn't comply with what PHP expects. https://stackoverflow.com/questions/22376415/how-to-convert-iso8601-to-date-format-in-php works if the decimal is only 2 places. `G:i` isn't going to have seconds anyway so might as well just trim it?
Answer: You'll have a much easier time (couldn't resist) working with the DateTime class (https://www.php.net/manual/en/class.datetime.php).
You're running into issues because the value you have isn't a timestamp so you can't use it like one.
The original time value uses nanosecond precision (9dp) which isn't supported by PHP. In order to use that time string with DateTime, you'll first have to truncate it to microseconds (6dp). It then has a method that will return your value in the desired format (https://www.php.net/manual/en/function.date.php).
<code>$time = '2019-07-22T04:44:43.843710438Z';
$time_micro_precision = substr($time, 0, -4) . 'Z'; // drop the last three digits to move from nanoseconds to microseconds.

$datetime = new DateTime($time_micro_precision);
echo $datetime->format('j/n/Y g:i A');
</code>
Comment: The time you have is down to nanosecond precision which to my knowledge PHP doesn't support. How you deal with this is going to depend on what you want to do with that time. I'm going to update my answer.
Comment: For this, I get
FATAL ERROR Uncaught Exception: DateTime::__construct(): Failed to parse time string (2019-07-22T04:44:43.843710438Z) at position 0 (2): The timezone could not be found in the database
Comment: @user204588 I hadn't looked too closely at the date in question. Where are you getting that from? It appears to be to 9dp.
Comment: It's from an external API
Comment: You should be able to use 8dp with DateTime. 8dp implies 100th of a microsecond which is more than 1 nanosecond. 8dp works with strtotime, which also supports microsecond precision
Comment: @NadirLatif Accepts and supports are two different things. You may be able to pass in a value to 8dp but it doesn't mean that it's going to recognise and work with that degree of precision. Take a look at `u` under possible date formats: https://www.php.net/manual/en/function.date.php
Answer: Using strtotime works if you restrict the timestamp to 2 decimal places. Try the following:
<code>$time      = "2019-07-22T04:44:43.843710438Z";
$temp_str = rtrim($time, "Z");
$temp_arr = explode(":", $temp_str);
$temp_str = number_format($temp_arr[count($temp_arr)-1], 8);
$time     = $temp_arr[0] . ":" . $temp_arr[1] . ":" . $temp_str . "Z";

$timestamp = strtotime($time);
echo date("m/d/Y H:i a", $timestamp);
</code>
Comment: as you can see in the answer above yours, using `DateTime` class is best. No need to use string manipulations like explode
Comment: Looks like even with DateTime, I have to remove decimal
Comment: DateTime and strtime both support microsecond precision. So 8 decimal places are supported by both. I have updated the answer so it allows 8 decimal places for the time. If you dont need the extra precision, you can remove the decimal places from the time stamp

Can't format a UTC date in PHP


How should I deal with an air conditioner that doesn't keep up?

Question: I've been having some minor trouble with my ac.  When it gets hotter, towards the afternoon, it will lose ground and only be able to cool two degrees higher than what the ac is set to. For example, if it is set to 76, the thermostat will read 78. While it's not unbearable or super uncomfortable, it is a little bit noticeable.  It didn't have any trouble the day before maintaining the set temperature, but today it was higher, despite the outside temperature being about the same.
I have changed my filter, put new batteries in the thermostat, made sure the heat pump is clean and free of debris and cleared away any grass or anything.
I would like to fix this but I wanted to ask for advice on my 3 ideas on what to do.  Should I...

Replace the thermostat? My partner had trouble with theirs in the winter (it was running all the time) and replacing the thermostat helped there. I was wondering if doing the same would help me.

Call out an ac repair person?

Understand that it is hot and over 90 degrees and this is just how it is and suck it up? (I understand that heat pumps can realistically only cool about 20 degrees and may struggle with the new higher temps in the Summer)

I really appreciate your time and advice.
Thank you
Comment: Is it really reaching 2° above what you set? Consistently, even after you change the setpoint or on a warmer/cooler day? For example you tell it to cool to 72°F when it's stable at 78° and set to 76° as in your question - what happens? Because if it's always off by the same amount, regardless of how hard you're asking it to work, it not a simple matter of it not being powerful enough. I suspect  the issue is going to be that it can't keep up, and the2° difference isn't actually a constant
Comment: You set it to 76 and you get 78 - if you set it to 70 do you get 72?
Comment: ... also, you say the outside temp was about the same, but what about the amount of sun you were getting - it will have to work harder to cool to the same temp if there's a lot of solar gain, compared to a cloudy day
Comment: @cybernard any formula like that must be making some hefty assumptions about both insulation and insolation.  As a rule of thumb it may apply to a typical house, but we don't know if the OP's house is typical.
Comment: When it's running (in cooling mode), do you get cold air out of the vents?
Comment: It did work the day before with a similar outside temperature, and not yesterday was 80 and today is 90?  If it was a fast change in how it worked, then it might change the answers.
Comment: If you have separate storm windows, and they are open so you can use the screens, close them when running the A/C - they slow heat movement through windows when it's hot out and cool in as well as when it's cold out and warm in. Consider more insulation for the house in general, but that's a quick one if it applies.
Comment: We had the exact same problem after buying our house.  The AC unit was brand new but the temp would creep above the set point in the summer.  This continued to happen until we replaced the windows.  Not the cheapest solutions (maybe not applicable to you) but it has never happened since.
Comment: How big is your house?  The generally accepted formula is 20btu for every square foot with an 8 foot ceiling.  So multiple that out, and compare it to how many BTU your AC unit can do.  If the BTU you calculate is greater than your AC unit then your AC unit is too small.  Only if the temperature sensor in the thermostat is broken will changing it actually help you.
Comment: What happens when you set the thermostat 2 degrees lower, to 74? Will the temperature drop to 76 or stay on 78?
Comment: I think the best solution for you is to update your insulation and when you redo your roof add a ridge vent. I added a ridge vent, upgraded the ventilation and put on new siding. My electric bill went down by over 30% this past year.
Comment: I had this problem sometimes in my condo; I'm on the top story and on hot days the roof would get so hot that my AC couldn't remove the heat fast enough.  When the HOA had a "cool roof coating" installed (read:  the roof was painted white) the problem went away.  That might not be an option for you, but in general better insulation would help, as it would reduce the rate at which heat enters your living area.
Comment: @ChrisH  I am sure it has many assumptions, but it establishes a minimum baseline.  If you house is leaky then that number only goes up from there.
Comment: @cybernard but it's not going to be a minimum baseline.  It will be some sort of average house in some sort of conditions regarded as typical at some time in the past.  If the OP's situation is only slightly worse than that average, they could easily get the effect seen, whether that's due to poor insulation or other flawed assumptions.  For that matter a single assumed value covering the whole USA is daft, unless the peak temperatures in a typical summer, and the insulation in houses are somehow correlated
Comment: I answered a somewhat related question a few days ago. This isn't a duplicate to that question, but very similar. https://diy.stackexchange.com/questions/277277/temperature-does-not-drop-to-the-set-thermostat-during-the-day/277328#277328
Answer: If the system is running (fan is blowing; condenser/compressor outdoors is running) then replacing the thermostat won't help any.
You've done well checking the filter and ensuring the outdoor unit is clean and clear of debris.
One other simple thing you can check is whether the coil above the furnace is freezing. Easiest way to do that is to look at the condensate drain after the system has been running a while. If there are drops or a small drizzle of water exiting then it's working; if the drain is dry then ice on the coil is likely. Ice means blockage of airflow, which means reduced ability to cool.
A system does have its limits; there does come a point at which the system can't cool any more and the indoor temperature will rise together with the outdoor temperature. It's tough to say whether yours is at that point; you'll probably need an on-site service person to evaluate that.
Comment: @DeanMacGregor Eventually, yes, but if the icing is only minor at this point then the airflow will be impeded only a small amount and the under-performance would be less severe.
Comment: If it's icing up it wouldn't be 78 in the house, it'd much hotter.
Answer: It depends.  If the A/C has a mechanical problem, have it fixed.  You'll know soon enough, if it suddenly got worse.
If the A/C is working properly and simply has never been able to adequately cool your house in these very high temperatures we are now experiencing, then you have 3 options.

Suffer.
Get a larger or supplemental A/C unit.
Cool your house with the power of your brain.  I.E. learn stuff about thermal mass, energy storage, insulation and air leakage (to see whether this trick is worth doing) and then pre-chill your house so the mass of the house is nice and cold before it starts becoming unbearable. Then you can - well not quite coast like in the video, but certainly reduce the need for the system to work so hard between 4 PM and 10 PM. Also good for the energy grid's stability.
Comment: @Dean yes, it depends on the thermal mass of the building, the insulation, where it is relative to building mass, the air leakiness of the building, and very importantly, solar gain, which depends on shading and roof/wall color.
Comment: Unless I missed it, that guy didn't mention what the outside temps are when he's coasting through the day without the inside temp getting higher than 77. I know that where I am (Florida), there's no chance I could coast through the day without my compressor running.
Answer: It's not the thermostat:
it just command call for cool (temp > set-point + hysteresis ) or "stop" if temp < set-point - hysteresis.
So if the AC starts and stops the thermostat is fine.
My ideas are:
• dirty condenser (if you can't see trough, wash it with water, avoid pressure wash, going the opposite direction as air, if you still can't see trough, call a tech and have it properly cleaned)
• dirty evaporator (causes low flow at vents, call AC tech)
• dirty filter (replace it yourself, its cheap and easy, also improves air quality inside)
• low refrigerant (call AC tech)
• undersized unit (deal with it or have the unit replaced with a bigger one)
You did whay you could, call AC tech to check pressures and clean the evaporator.
At last:
Check you dont have "economizer" open => these allow air change but waste lots of cool, closing them will keep the cold in.
Comment: The undersized unit could also be mitigated with new/additional insulation
Comment: Of course, insulation will help (specially if currently is poor).
Answer: If you have a large external unit, check that the air is blowing in the right direction:

Air is supposed to come out the top of this unit. I've had installers that reversed the fan direction and lowered its efficiency by a very large amount.
Call the installers to fix it since it is their responsibility, but it can also be DIY configured if you are inclined.
Comment: That's a good point! A failed start capacitor for the fan motor can have the same effect: when the power turns on the fan will sit motionless until some little disturbance, like wind, pushes it a little. If it gets pushed and started backward it'll continue running backward.
Answer: You have done the simple checks.  Now you need to have the system looked at by a service tech.
What you are describing is system that is low on refrigerant.  There are other causes of this behavior.  A tech will need to inspect the system to determine what the issue is.  You can play detective, but you will still need a tech to fix it.  (Special equipment is needed.)
Answer: Have someone come out to inspect and clean your air ducts. Make sure you go with a legitimate company.
EDIT:
Not sure why the down vote, so here's a link to EnergyStar.gov showing that repairing and cleaning will help.
Comment: I downvoted you because cleaning ducts has not been shown to improve air quality or the overall performance of a system. The Energy Star you linked to says to ensure your ducts are **sealed** which is a different thing entirely. [Here's the EPA on the topic of cleaning ducts](https://www.epa.gov/sites/default/files/2014-07/documents/airducts.pdf)
Comment: Not the downvoter, but it was probably because this is a DIY site and a one-sentence "call a company" response is the *opposite* of what people come to this site for.


Need help with understanding the Basis for a Topology

Question: I don't have a particular problem to share but I'm asking for assistance in describing a Basis or Sub-Basis for some Topology T.
So, if I have some set, say $\{a,b,c\}$ or $\{a,b\}$ what will the basis and sub-basis be?
I understand the definition of a Topology and how to find a topology for a given set $X$ but I'm having a hard time grasping the definition of Basis and Sub-basis for a topology.
I understand what the definition is saying but I'm having a really difficult time in seeing the visual representation of the definition. i.e. how to construct a basis with a given topology $T$ and set $X$.
All I'm looking for is some examples that gives me a good visual on how to construct any basis from some set $X$ and topology $T$.
Comment: I would refrain from saying "the basis" since a particular topology could have multiple bases. Same goes for a subbasis. As for the definition of a basis and subbasis, what definition are you currently working with?
Answer: I think there are two things going on here: given any point set, you can construct a collection of subsets which satisfies the definition for a basis, and this in turn generates a topology by just taking unions of these sets. On the other hand, you can have a set with a topology already given, and have to determine a subset of this topology which satisfies the axioms for a basis. The first case I think is clear: you just find subsets, take their unions, and this is a topology. If you want your topology to have certain properties (Hausdorffness, second countable, etc.), you just pick your basis elements specifically so that these axioms hold. Finding a basis given a topology is more difficult.
Although it is kind of a special example, take $\mathbb{R}^n$. Given any open set (euclidean) and an element $x\in U$, we just want to find a family of open sets $\{B_{\alpha}\}$ such that there is $\gamma$ such that $x\in B_{\gamma}\subset U$. In fact, I think there's a theorem in Munkres Topology section 13 which gives this result in more concrete language. Obviously, our example (or any metrizable space) has a given basis of open balls, and it is trivial to see that these actually satisfy the basis axioms (a proof of this is in chapter 2 of Rudin's Principles of Mathematical Analysis).
For more exotic topological spaces, the question is a bit more difficult, but certainly not impossible.
Let's take $X=\{a,b,c\}$. It's a problem in Munkres that this has $29$ topologies.
The most obvious two bases we can think up are $\mathcal{P}(X)$ (which is just the discrete topology) and just $X$ (which is just the indiscrete topology). Now suppose we want this set to be Hausdorff: First, each point must be closed, so our basis ought to include $\{b,c\},\{a,c\},\{b,c\}$. But then the axioms for bases requires that $\{b,c\}\cap\{a,c\}=\{c\}$ has to include a basis element. So $\{c\}$ must be a basis element. Similar reasoning shows $\{a\},\{b\}$ are also open, so we have shown that any basis with the points closed on this topology must be discrete. With that, let's just start by picking sets we want to be open. A basis has to cover the space. One example might be $\{a\}, \{b,c\}$. This is a good basis, and in fact generates the topology consisting of these two sets and $X,\emptyset$. Now, if we want $\{a,c\},\{b,c\}$ to be open, then we require that $\{c\}=\{a,c\}\cap \{b,c\}$ must be open, so this space generates the topology $\{\emptyset,\{c\},\{a,c\},\{b,c\},X\}$. We can keep going on by this: the idea is that we pick sets we'd like to be open, add sets until they cover the space, and then add sets such that for all $x\in B_1\cap B_2$ basis elements, there is basis element $x\in B_3\subset B_1\cap B_2$.
For a subbasis: the procedure is similar, except we only take finite intersections of sets, and add the set $X$ manually to gives a basis for a topology. So, really the above discussion also works for subbasis, except we don't need to worry about covering the space. Some examples of subbases on $X=\{a,b,c\}$ are $\{x\}$ for $x=a,b,c$, $\{x,y\}$ for $x\neq y=a,b,c$, and etc. So you see that in practice what we're doing when we're building a basis is that we're really building a subbasis by just ensuring we're closed under finite intersections, since we can always add the total space $X$ to cover the space. In fact, although you can determine a subbasis from a topology, I think it is much more common that we take a collection of sets we'd like to be open and make them into a subbasis, which in turn determines a topology for a space, whereas determining a basis is usually done after we already know what our topology is, so we can reduce topological proofs to proofs with basis sets which are more "well behaved" than a full topology.
Let's apply every above to the set $Y=\{a,b\}$. We want $\{a\}$ to be open? Then $\{a\},Y$ is a basis for $Y$, and this basis determines the Sierpenski space. In fact, this is really the only example: there are only $4$ topologies on this space, and two of them are essentially the same (in the above subbasis, just choose $\{b\}$ to be the set we want to be open).
Comment: I'm currently reading Munkres Topology 2nd edition and I'm just puzzled with coming up with examples that go along with the definition. I'm looking for basic examples like the two I gave above to help me understand the definition.
Comment: Oh I see. So basic examples of point sets and building bases on these, or examples of topological spaces and finding bases for them?
Comment: so basic examples of building bases and sub-bases. so like finding a bases and sub-basis for X = {a,b,c} or X = {a,b}.
Comment: @AlexanderKing Added an example.
Comment: Thanks. You wouldn't mind putting another explanation for X = {a,b}? then also mentioning about how to determine a sub-basis. These are the only things that I have a hard time grasping.
Comment: Sure, done. Hope that all helps.


Solving a linear system over $\mathbb{Z}_{5}$

Question: I would like to ask how to solve this matrix, if I substitute for z (x, y, z) z = 4, I can't calculate the matrix. I tried to adjust the matrix to this shape, but I don't know how to proceed.
$\left( {\begin{array}{ccc|c}
1 & 2 & 1 & 3\\
1 & 0 & 0 & 4\\
1 & 3 & 4 & 0
\end{array} } \right)$ in $\mathbb{Z}_{5}$
$\left( {\begin{array}{ccc|c}
1 & 2 & 1 & 3\\
0 & 1 & 3 & 2\\
0 & 0 & 0 & 0
\end{array} } \right)$
Comment: What do you mean with 'solve the matrix'?
Answer: start:
$\left( {\begin{array}{ccc|c}
1 & 2 & 1 & 3\\
1 & 0 & 0 & 4\\
1 & 3 & 4 & 0
\end{array} } \right)$
first steps: subtract 1st row from 2nd and 3rd, to eliminate the other 1's in the first column
$\left( {\begin{array}{ccc|c}
1 & 2 & 1 & 3\\
0 & 3 & 4 & 1\\
0 & 1 & 3 & 2
\end{array} } \right)$
where I use that $-1 \equiv 4, -2 \equiv 3, -3 \equiv 2$ in $\Bbb Z_5$.
The pivot 3 on place $(2,2)$ has an inverse 2 over $\Bbb Z_5$ so I multiply the 2nd row by $2$ (modulo $5$) to make for easier computations:
$\left( {\begin{array}{ccc|c}
1 & 2 & 1 & 3\\
0 & 1 & 3 & 2\\
0 & 1 & 3 & 2
\end{array} } \right)$
We subtract the two identical rows at the end to get:
$\left( {\begin{array}{ccc|c}
1 & 2 & 1 & 3\\
0 & 1 & 3 & 2\\
0 & 0 & 0 & 0
\end{array} } \right)$
So we have a consistent system (so there are solutions) that is  underdetermined. So there will be $5$ solutions, depending on the value we pick for the free variable $z$, we can solve it in terms of this free variable:
$y + 3z = 2$ so $y = 2-3z = 2 + 2z$
$x+2y+z = 3$ so $x+ 4z + 4+ z = 3$ so $x+4=3$ so $x=4$, as $5z\equiv 0$.
So we get the solutions $\{(4,2+2z, z) \mid z \in \Bbb Z_5\}$, a set of $5$ vectors, as expected.
Comment: The calculation of $x$ in the next to last line is wrong, you neglected the constant term in $y$. It should be $x=4\;$
Comment: @greg you're right. I'll fix it.
Answer: This is the linear system $Ax=b\;$ with
$$
A=\pmatrix{1 & 2 & 1 \\1 & 0 & 0 \\1 & 3 & 4}\qquad b = \pmatrix{3\\4\\0}
$$
Using ${\mathbb Z}_{5}$ arithmetic and examining the powers of $A^k$ one finds that
$$\eqalign{
A^5 &= A
 \quad&\big({\rm periodic}\big) \\
A^4 &\ne I
 \quad&\big({\rm not\,invertible}\big) \\
A^3 &= A^+
 \quad&\big({\rm generalized\,inverse}\big) \\
}$$
Using the generalized inverse, one can write the solution of the system as
$$\eqalign{
x &= A^+b + \left(I-A^+A\right)z \\
  &= A^3b + \left(I-A^4\right)z \\
}$$
where $z$ is an arbitrary vector and $(I-A^4)$ is the nullspace projector.
In terms of components, this becomes
$$\eqalign{
x &= \pmatrix{4&3&4\\4&0&0\\4&2&1}\pmatrix{3\\4\\0}
   + \pmatrix{0&0&0\\1&3&1\\3&4&3}\pmatrix{z_1\\z_2\\z_3} \\
  &= \pmatrix{4\\2\\0} + \pmatrix{0\\z_1+3z_2+z_3\\3z_1+4z_2+3z_3} \\
}$$
Check the result by setting $z_k=0\,$ to obtain
$$\eqalign{
Ax &= \pmatrix{1&2&1\\1&0&0\\1&3&4}\pmatrix{4\\2\\0}
   &= \pmatrix{3\\4\\0}
   &= b \\
}$$
To connect this with Henno's result note that
$$\eqalign{
\lambda &= 3z_1+4z_2+3z_3 \\
2\lambda &= 6z_1+8z_2+6z_3 \;\overset{{\mathbb Z}_{5}}{\longrightarrow}\; z_1+3z_2+z_3 \\
}$$


Python :function that takes an iterable argument and generates tuples

Question: I try to do something on python.
I try to write a function that takes an iterable argument and generates tuples of 2 elements:

the current iterable element
the number of times it has been generated since the beginning

Here is my code
liste = ['a','b','a','a','b']

compte = {}.fromkeys(set(liste),0)
for valeur in liste:
     compte[valeur] += 1

print(compte)

output :
{'b': 2, 'a': 3}

But I want to obtain "a:1" "b:1" "a:2" "a:3" and "b:2"
Thanks for help
Comment: You cannot have a dictionary with identical keys. Maybe a list is what you are looking for? Seems like order is important in the result.
Comment: Also note that calling fromkeys on an *instance* of dict creates that instance pointlessly; it's a class method.
Answer: Your expected result is a list, not a dictionary. A fix to your code would be to use your dict for counting, but appending to a list:
>>> liste = ['a','b','a','a','b']
>>>
>>> compte = dict.fromkeys(liste,0) #Or use a default dict
>>> result = []
>>> for valeur in liste:
...  compte[valeur] += 1
...  result.append((valeur,compte[valeur]))
...
>>> print(result)
[('a', 1), ('b', 1), ('a', 2), ('a', 3), ('b', 2)]

Answer: Use a generator function.
from collections import defaultdict

def with_running_count(values):
    counts = defaultdict(int)
    for value in values:
        counts[value] += 1
        yield value, counts[value]

>>> print(*with_running_count('abaab'))

('a', 1) ('b', 1) ('a', 2) ('a', 3) ('b', 2)

One advantage of using a generator over the other suggestions is that generators are lazy. That means that you can pass in iterators that return an endless (or very large) data stream, since the generator only consumes the input stream when needed.
# an endless iterator
coin = iter(lambda: random.choice(['heads', 'tails']), None)

# the running count will also be endless
toss = with_running_count(coin)

>>> next(toss), next(toss), next(toss)
(('tails', 1), ('tails', 2), ('heads', 1))

Answer: You can just modify your code in this way:
liste = ['a','b','a','a','b']

liste2 = []
compte = {}.fromkeys(set(liste),0)
for valeur in liste:
    compte[valeur] += 1
    liste2.append(valeur + ':' + str(compte[valeur]))

print(liste2)

It is important to say: what you are trying to do it is not a tuple, but a list, because it is mutable. Your compte variable is a dictionary.
Answer: You can initialize the dictionary with counts as you go:
liste = ['a','b','a','a','b']
compte = {}
result = []
for valeur in liste:
    compte[valeur] = compte.get(valeur, 0) + 1
    result.append((valeur, compte[valeur]))

print(result)

Answer: You can use Counter from collections module:
from collections import Counter

liste = ['a','b','a','a','b']

def counter(iterable):
    c = Counter()
    for i in iterable:
        c.update(i)
        yield i, c[i]

print(list(counter(liste)))

Outputs:
[('a', 1), ('b', 1), ('a', 2), ('a', 3), ('b', 2)]


Blank pokestop / gym photo disc issue

Question: So today I went to the neighboring town for some  needs there I saw a pokestop and another gym which had blank photo discs

These pokestop and gym are new, these weren't there a month before , and I didn't nominate it.
What makes it happen so? I have created 2 stops and a gym in my town, all containing proper photo disc !
Comment: This is common if the game didn't download the image yet (e.g. because the internet connection is somewhat bad over there).
Comment: @Sumurai , even after an hour or two, it remains same, I don't think it's network problem
Answer: On May 5 2021, Niantic did a batch import of new waypoints from some third-party database. This import was not done correctly, and included a large number of waypoints that did not meet quality standards, which among other things included many not having a photo attached.
You can read more information about this here.
Comment: thanks this solved my doubt
Comment: Can I add a photo to the pokestop and gym? I doubt because they are third party assets .
Comment: @SubhaJeetSikdar Typically waypoints added from third-party databases allow for adding photos and editing the title/description unless they're part of a sponsor deal, which these are presumably not. So you should be able to add a photo.
Comment: Thank you so much

Blank pokestop / gym photo disc issue


Pulseaudio static crackle in 5.1 analog

Question: I realize this is a repeated question, I just was not able to rectify the issue myself.
Anyways, I have a laptop running Ubuntu 13.04.  It does not have a 5.1 sound card installed, but I have 5.1 speakers.  So I purchased a USB sound card (Sound Blaster X Fi).
It works 'out of the box' with pulseaudio, only issue is any output other than stereo will cause static crackling.  I've attempted to remove pulseaudio and use ALSA with gnome-alsamixer and even xfe4-mixer, neither correctly installed and would revert to my laptops speakers.
Currently just running Pulseaudio in stereo output, but it's a waste.  If I can't fix this, probably going to go back to Windows 7.
Answer: In /etc/pulse/default.pa, change this line:
load-module module-udev-detect

to:
load-module module-udev-detect tsched=0

This switches pulseaudio to the older scheduling mode and gets rid of the glitches.
Hope it helps!
Comment: Alas it does not
Comment: I just found out that I can solve the problem in another way: changing the resample method on ```/etc/pulse/daemon.conf``` to ```resample-method = speex-float-1``` does the job as well, but works better for different programs.
Comment: It does work for me, however. Thanks for the tip.
Comment: Thanks, I have been gettin a TON of audio crackles on Arch here. It became very noticeable when trying to use Bitwig Studio and a midi controller, just unbearable when creating music. So I just tried this `tsched-0` and it didn't have an effect immediately, but I restarted and appears to have had a big difference. I have heard 1 crackle so far in about 10 minutes, not enough for LIVE usage but good for tinkering for now. Hoping this sticks and doesn't get worse with `uptime` increasing.
Comment: K, static crackle came back big time, 38 minutes of `uptime` now. I'll try the resample method next.
Comment: resample-method = speex-float-1 was commented out like `; resample-method = speex-float-1`, uncommented and ran `pulseaudio --kill` (which restarts it, I learned) and still have the crackle. I wonder if I should just switch to JACK or maybe it is something to do with my Thinkpad Thunderbolt dock that I am taking sound out into a mixer from.
Comment: I do somehow feel like this may be due to my previous usage of `paprefs` which allowed me to simultaneous output to my headphone jack and a USB speakerphone (multiple outputs). I uninstalled `paprefs` the other day because I got a Yamaha Mixer for this task which works better (paprefs would drift on the sync). And I seem to notice that the "simultaneous output" output is still present and should be gone. And when the crackle hits, my main Thinkpad output is completely gone from the system, although still visible with `alsamixer` and controllable there too.
Comment: Before I dig even further though, I am running everything on an old grounded outlet from a home built in 1950. So I'll try running an extension cord from a grounded outlet first, then next step is to update BIOS for the Thinkpad dock. Sorry to rubber duck here, not the right place.

Pulseaudio static crackle in 5.1 analog