How to find the index of element (and a few other things)

Question: I was writing a code that would substitute some random 17 character strings into a single alphabet, and I can't find a way. Basically, what I'm trying to do is this:
char strings[] = {
    "L-nIbhm5<z:92~+,x",
    "9bC5f0q@qA(RKZ>|r",
    "9bC5f0q@qA(RKZ>|r",
    "k=5,ln(08IAl(gGAK",
    "|N,8]dGu)'^MaYpu[",
    "!&,Y*nz8C*,J}{+d]",
    "Us9%^%?n5!~e@@*+@",
    "zF8,1KV#¥]$k?|9R#",
    "0B4>=nioEjp>4rhgi",
}

char alphabet[]{
    "a","b","c","d","e","f","g","h","i",
}

replace(std::string str){
    /**get str and then see the index of the corresponding string in strings[], and replace the string with alphabet[index number], while deleting the original string part that was replaced**/

int main(){
    cin >> std::string replace;
    replace(replace);

example input: L-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|r9bC5f0q@qA(RKZ>|r
expected output: abc
EDIT:
New Code
Changes from the original code
It also has a bigger array than the simplified version(previous code). It displays the structure of the full program.(where the strings are routed to and why)
Basically What it's doing
getting input from user, put it in the input variable, input goes through algorithm() function untouched, and then goes to the replace function and is replaced. It then the replaced string gets returned back through the original route to the main function, where it is displayed.
I've kept the arrays a string type because the const char* gave me a segmentation error.
std::string Subs[53]=
{
    "LQlMv]G5^^1kcm?fk",
    "7W^S;/vB(6%I|w[fl",
    "<w7>4f//Z55ZxK'z.",
    "_W5g(lu<pTu3^_A7n",
    "OfLm%8:EF}0V1?BSS",
    "|+E6t,AZ~XewXP17T",
    "L-nIbhm5<z:92~+,x",
    "L-nIbhm5<z:92~+,x",
    "9bC5f0q@qA(RKZ>|r",
    "9bC5f0q@qA(RKZ>|r",
    "k=5,ln(08IAl(gGAK",
    "|N,8]dGu)'^MaYpu[",
    "!&,Y*nz8C*,J}{+d]",
    "Us9%^%?n5!~e@@*+@",
    "zF8,1KV#¥]$k?|9R#",
    "0B4>=nioEjp>4rhgi",
    "EG@0[W9.N4i~E<f3x",
    "(0Pwkk&IPchJHs.7A",
    "7XgmQ6fW<|J+NY[m0",
    ".g4CwX/DU!!~!zbtZ",
    "+_U'qn_/9Fo|gT/!n",
    "=0s(mYh&F%y=MBS5(",
    "cg71(}bo+Q5P8F[T6",
    "lc|a\%5.9pOpooU+QR",
    "E_(3A:o+.]qL3MYA6",
    "H@O'X_RiVS@8l0bKD",
    "Y1gbGD`~8d>HSWN35",
    "LQlMv]G5^^1kcm?fk",
    "T4}gI;`BFVfhw=-sf",
    "6BHMA0IRix]/=(jht",
    "yS$=@Jdpp?P2k6SMQ",
    "t1~|kkh+>4d>}OQ`a",
    "2Y-\\CU\"944yBluWD5",
    "'M\\ZbIX5{`Xd;qi!o",
    "?N+RtVqj_r(C5@#0\"",
    "2;*Livh?V$X/8z@Md",
    ")IN|7FOs2l-mAM[d@",
    "(~f268J},xXrK'Rp'",
    "&r/qf9fFHnzV!RzH/",
    "}naDRH4p$NI2a).t,",
    "{8DM+7!.Mge|~fnO|",
    ")r[@nI0YDH>6cE38p",
    "(0Pwkk&IPchJHs.7A",
    ")r[@nI0YDH>6cE38p",
    "8M-=cQFQ,pPo7eu=p",
    "0PHw=/|(tZ1}FHm/'",
    "[su`'0Oybc.\"-/W5)",
    "1uHl[IC7Sr#NUJV;I",
    "8z8%,jK0CDOkJz8I?",
    "3Ao2yXDN%YzpE&Suy",
    "zNs`7E'e/$i8VqaUL",
    "bzHmA^K2>7`UZ?!AO",
};

std::string Alphabet[53] =
{
    " ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","r","w","x","y","z",
    "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
};

std::string replace(std::string rep) {
    int len = sizeof(Subs)/sizeof(Subs[0]);
    std::stringstream ss1;
    for(int i = 0; i < len; i++) {
        if (rep.find(Subs[i]) != std::string::npos) {
            ss1 << Subs[i];
        }
    }
    std::string input = ss1.str();
    return input;
}

std::string algorithm(std::string input)
{
    //some other algorithms come here(not relative to this question)
    input = replace(input);
    return input;
}

int main(void){
    int ed;
    std::cin >> ed;

    if(ed == 1){
//different function(not relative to the question)
        }
    else if(ed == 0){
        std::string input;
        std::cin >> input;
        input = algorithm(input);
        std::cout << input << std::endl;
    }

    else{
        std::cout << "1 or 0" << std::endl;
        main();
    }

return 0;
}

example input: L-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|r9bC5f0q@qA(RKZ>|r
expected output: abc
actual output: L-nIbhm5<z:92~+,xL-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|r9bC5f0q@qA(RKZ>|r
Sorry it's become long.
Answer: There are few mistakes in above code :

char array initialization is not correct.
method body for main and replace method is not closed.
Currently by default return type of replace method is int.

There is string#find method which can be helpful here.
I have tried to make those fixes and here is updated code in C++17 :
#include <iostream>
#include <sstream>
using namespace std;

const char *strings[9] = {
    "L-nIbhm5<z:92~+,x",
    "9bC5f0q@qA(RKZ>|r",
    "9bC5f0q@qA(RKZ>|r",
    "k=5,ln(08IAl(gGAK",
    "|N,8]dGu)'^MaYpu[",
    "!&,Y*nz8C*,J}{+d]",
    "Us9%^%?n5!~e@@*+@",
    "zF8,1KV#¥]$k?|9R#",
    "0B4>=nioEjp>4rhgi"
};

const char *alphabet[9] = {
    "a","b","c","d","e","f","g","h","i"
};

void replace(std::string rep) {
    int len = sizeof(strings)/sizeof(strings[0]);
    std::stringstream ss1;
    for(int i = 0; i < len; i++) {
        if (rep.find(strings[i]) != std::string::npos) {
            ss1 << alphabet[i];
        }
    }
    std::cout << ss1.str();
}

int main(){
    std::string rep;
    cin >> rep;
    replace(rep);
}

For reference : https://onlinegdb.com/Bd9DXSPAa
Note - Above code is just for reference, please make sure to add all test cases handling.
Comment: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/)
Comment: okay just to try quickly i added that, now we can replace it with `#include `. Updated the code.
Comment: the code runs when it's standalone exactly the way you wrote it, but when I try to add more elements into the array(like the whole alphabet worth, it doesn't work(not an error, it just comes out as fghiZ)
Comment: Can you add that example in question with sample input and output ?
Comment: i've edited the question so that it outlines the complete image of the whole program. i've also added the actual input and output and expected output. it has a different output as my previous comment, which is because my previous comment was a standalone, and the edited answer is a whole. I wanted to put the standalone program into the edit as well, but figured the edit would become too long.
Answer: I made a c++17 version for your code.
Replacing 'c' style arrays and pointers with C++ style containers, iterators.
And using std::string::replace function. Use the standardlibrary if you can,
its tested and well documented.
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

// std::vector/std::array instead of 'c' style arrays.
// allows us to us range based for loops later.
std::vector<std::string> strings =
{
        "L-nIbhm5<z:92~+,x",
        "9bC5f0q@qA(RKZ>|r",
        "k=5,ln(08IAl(gGAK",
        "|N,8]dGu)'^MaYpu[",
        "!&,Y*nz8C*,J}{+d]",
        "Us9%^%?n5!~e@@*+@",
        //"zF8,1KV#¥]$k?|9R#", // <<== I commented out this line, ¥ is not a valid charcter in my environment
        "0B4>=nioEjp>4rhgi"
};

// a string is already an array of characters.
std::string alphabet{ "abcdefghijkl" };

std::string replace_with_alphabet(const std::string& input)
{
    std::string retval{ input };
    std::size_t index{ 0 };

    // range based for, it will keep the order of the vector.
    for (const auto& str : strings)
    {
        // look if you can find any of the predefined strings
        // in the input strings.
        const size_t pos = retval.find(str, 0);

        // if found
        if (pos != std::string::npos)
        {
            // get the next character from the alphabet
            std::string replacement{ alphabet[index++] };

            // use std::string::replace for replacing the substring
            const size_t len = str.length();
            retval.replace(pos, len, replacement, 0);
        }
    }

    return retval;
};

/**get str and then see the index of the corresponding string in strings[], and replace the string with alphabet[index number], while deleting the original string part that was replaced**/
int main()
{
    auto output = replace_with_alphabet("L-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|rk=5,ln(08IAl(gGAK");
    std::cout << output << std::endl;
}

Comment: You can also use for range on C-arrays.
Comment: By modifying `retval` in place, you might have issues if inserted element is in a match of another replacement


How to indicate that an element is "new" in a list

Question: I was wondering if you had any clever idea of how to show that an element in a list is new.
In my case I'm displaying a list of documents and I want the user to see which ones are new since their last visit on that page.
I can think of 2 ways:

By adding a "new" label or badge (but I really want to avoid that)
By putting text in bold and background lighter that for other documents so it stands out. For example it's what Gmail does to show which emails are new since last time.
By choosing a different background colour for those items. In my case we are really limited with colours...

Can you think of any other way? Have you got examples to show?
In my case new elements will always be at the top of the list.
Many thanks
Comment: I'd like to answer here but I'll just observe that the constraint you are really grappling with is **layout-specific** (since you don't want the site to appear too cluttered).  So without seeing a screenshot or wireframe of the layout so we can understand the specifics, it's hard to design an answer.
Comment: I'll second @tohster. There are really only two ways to signal this to a user: you can either change the content by adding some sort of tag or change the layout by making it visually distinct. The latter can be done in a myriad of ways but is entirely dependent on the look-and-feel of the rest of the page.
Comment: If it is important that the effect is persistent (as opposed to showing a fading out new badge or fading background color) you could consider just adding a subtle separator to the list - like this http://imgur.com/Zpg7jRP
Answer: I suggest you to show the 'added date' as additional attribute (column) to the documents and color the date of the new entries:

Alternatively you can set the text of the date bold.
Comment: And replace recent enough dates with phrases like "Today", "Yesterday", "Last Tuesday"
Comment: And provide a Sort by Date option.
Comment: To some users, bolded or coloured differently could just as well mean "modified" or "changed".  I don't really feel that cuts the bill, but may have been the right solution for @RaphaëlleM
Comment: _... phrases like "Today", "Yesterday", "Last Tuesday"_ **AND** a tooltip for each of them that shows the absolute full date! (OTH, TBH, I'm an  engineer. I'm used to read and interpret numbers. I fervently hate these relative phrases but if one must... And I consider it advantageous when there's also the weekday prior to the date.)
Answer: As it happens with Gmail interface, the 'newness' of unread emails is differentiated by a momentary 'new' tag that hides itself after a few seconds. That's how gmail tells today's unread emails apart from yesterday's unread emails. However, this doesn't apply to your case.
The solution to my mind is a simple timestamp, visible in each row, for example '2 hours ago'. Background colour variations can help but they are not the most accessible options out there.
Since you are putting the newest messages at the top anyway, the timestamp would help differentiate how new the item is.
A simple horizontal line below the last 'new' item could also help in visually differentiating new from the old. In your case, I presume the user doesn't need to interact with the items, and the 'newness' will be gone once the page is refreshed.
Comment: I would upvote your answer, but I don't want to ruin your rep.
Comment: Dude, your reputation is 1,337
Comment: He's going to have to start submitting some off-topic answers now.
Comment: @AndrewHoffman not anymore, how sad is that.
Answer: "If you want sex just say it"

Or in other words - convey information in the clearest, and most direct and concise way (rather than using nth degree semantics).
Visual features will constitute nth degree semantics.
You stated that new documents are always at the top of the list. If new documents are indeed of real interest to users, just give it to them:

download bmml source – Wireframes created with Balsamiq Mockups
Answer: I'm against of using "new", that does not add enough value to an updated item in a list that frequently has added items. Using timestamps like: "1h", "2d" is going be an standard, so people can recognize it, they have the same experience in their social networks app such as facebook, twitter, and gmail, you can also see this representation form in Android and iOS. So by using this feature next to a title of the list item, we can let users quickly catch that this is new and also it is newer than the other item. So a lot of valuable information just with 2 characters: "1s" (1 second ago)
Comment: Also we have done user testing in this feature and this works the best compare to other options.
Comment: Works really well if there is a lot of new content all the time.
Answer: I love this way:
Transform the background of element to a light yellow and fade it to the default background color after some seconds.
Comment: Please expand on why you recommend that so that people can understand your reasoning.
Comment: It's not about whether it's common or not.  It's about the reasoning behind the suggestion, so that other readers can understand the principles you're applying rather than just knowing "use x in y situation".
Comment: This is exactly what I was looking for! Thanks a lot
Comment: Sorry. For ME this is the most common way to do this. So, the element gives a highlight when created, and after some time, it will go back to the default UI.
Answer: You could use a faded background animation (I think Wordpress uses it in the admin panel).
It would work as follows:

The user lands on the page the page
The new items in the the list are highlighted by a background colour (and perhaps even the label new)
Over a period of 3 seconds (or less) the highlight and the new label fade to the background colour of the other items (presumably white) never to be seen again

The user can then interact with the list with all items being visually equal whilst being notified of which are new.
Since this relies heavily on short term memory success depends on how many items the list has, how many new items are added and how important it is for a user to remember which items are new.
Comment: -1 Please don't do this, please don't rely on the user seeing (and also noticing) something before it goes away by itself. I've been "had" by sites that did this, when I opened their pages in a separate tab and didn't look at it until later. (Simple use case: [Morning Coffee](https://addons.mozilla.org/en-us/firefox/addon/morning-coffee/) plugin)
Comment: good idea, thank you. However I'm not sure it would work for me here. I need an effect that will last in time, at least until the page is refreshed.

The behaviour you're describing here works really well when the users have just added an item to the list themselves though.
Comment: It's possible to have the fade only begin when the tab gains focus - but it's still worth reconsidering since you're unlikely to know which list items are on the page and which aren't yet scrolled down to (of course, you could check for that too...)
Answer: There may be a problem with defining new to the user.
Users typically comprehend a date/time for posting, and a freshness seal.
You can define a new that is different than that, but you can't expect your users to see it the same way, and that can be a problem for product owners if that isn't what they want new to mean.
If you over complicate that, you may end up confusing them. I've heard of it described like buying milk.

Has it been opened?
Whats the expiration date?

Except when the something doesn't expire, use the most relevant date, when you received it, or when it was shipped.
I like the color coding idea for things that arrived today, or replacing the date part with Today when the relevant date is today.
For that freshness seal, I'd just go with what people are used to. Look to Outlook, iphone mail, gmail, or inbox for inspiration for that. You want to be intuitive, and being intuitive usually corresponds with conforming to the expectations that the major players have established.
Answer:
By adding a "new" label or badge (but I really want to avoid that)

Well, you could add an "old" label or badge and apply it to all the -other- documents.
Seriously, if you are going to display the newer documents first anyways, you can simply use a vertical divider with an "older documents" a label. Or a plain vertical divider without a label, I'm sure 99% of users will figure out what that means after only a few times using the site.
Answer: It depends on the application.
Here is a general list of techniques that can be used, mixed, or not applied at all to indicate the user that content is new:

Apply bolded type
Decrease or increase font size
Adjust, increase, or decrease spacing between new content
Append or prepend "new" label to new content
Append or prepend message, with count of new items by list of content
Format timestamps in relative, friendly way to the user's current time

The first question you should ask is whether to include "new" elements in your UI in the first place.  Do your users benefit from knowing the new content that has recently been added? If so, in what context? The way users interact with new content varies for every app.  Users also vary widely in their perception of modified content; some users may well interpret bolded text as "changed" or "modified content", while others may interpret such text as content which has not been saved yet; moreover, some users may become confused or flustered at changes between items on the list.
If, after usability research, you determine that including new elements does, indeed, help the user, then work out the specific user flow. Try to isolate a couple user stories.  Ultimately, there is no substitute for performing user research, and any combination of the above techniques may prove to be the most beneficial to your users.
Look at the following table, which employs method 6, and ask yourself if you can immediately find the newest content:

Sometimes, simply stating the modified date of a record is sufficient to convey its "newness".  But ultimately, conveying the newest records will depend on the application.


How to Stop Rotating Gallery On Click

Question: I am having trouble modifying this widget to stop rotating once clicked. Does anyone have any idea how to add this functionality? Any help would be greatly appreciated.
Thanks in Advance.

Mike

Here is the link to the widget:
http://stromasys.29kdev.com/jcoverflip/
Here is the Javascript:

Comment: @Oriol are you familiar with how to add this functionality? I ask because you were able to help me out with this same widget not too long ago. I would really appreciate any help or suggestions.

Thanks.

- Mike
Answer: Just attach the event handler to any DOM Element:
$("a.stop").click(function(){
    clearInterval(timer);
    return false;
});

And the HTML for the same is:
Stop

If you wanna attach to the image, then this is the code:
$(".ui-jcoverflip--item img").click(function(){
    clearInterval(timer);
    return false;
});

Comment: Thanks Praveen,
So how would I attach the event handler to the DOM Element in the code listed above?
Comment: I cant seem to get it to work. Am i doing adding the code in right?

http://stromasys.29kdev.com/jcoverflip/index01.html

How to Stop Rotating Gallery On Click


Will ceiling junction box support fan mounting?

Question: Will current ceiling junction box support fan? Not exactly sure if a fan was mounted to it prior as I recently moved into this apartment. Somewhat older of an apartment and box doesn't directly state if fan is supported or not. Figured it was better to check first.
Comment: Is there a joist behind the box, perchance?
Comment: I'd change those 2 drywall screws to something less brittle.
Comment: Duplicate of https://diy.stackexchange.com/questions/145104/will-this-existing-outlet-box-support-a-23-lb-ceiling-fan/145105#145105
Comment: Do you already have the fan? My experience is with Hunter fans, both the very heavy old ones and the new much lighter ones. If you are installing the latter, the kit comes with *two* purpose designed wood screws which go into a ceiling joist or other sound wood. If you would be installing of of the old heavy fans, you would pry out the center knockout, drill a hole for a single very heavy hook. These would go *through* holes in the metal "pancake" box, or around the box, into the wood joist.  This box itself does not support the weight of the fan.  What kind of fan are you mounting?
Comment: @JimStewart it is a new Hampton Bay Hawkins 44 inch think it is around 15-20lbs. https://www.homedepot.com/p/Hampton-Bay-Hawkins-44-in-Brushed-Nickel-Ceiling-Fan-YG204-BN-D/303007304
Comment: Read the instructions and examine the parts in detail before you start. Determine the thickness of the wood structure above the drywall ceiling. You might have to use the holes currently occupied by the two drywall screws for heavy wood screws (if that is in the parts kit) for the fan bracket. If so, put screws in the open holes (to hold the box to the ceiling) and then remove the drywall screws.  If
Comment: It may be that the fan bracket is designed to *cover* the pancake box and the two heavy screws would be *outside* the box.
Comment: @JimStewart https://imgur.com/a/7FbL9c2
Comment: *Some* ceiling boxes are rated to support a fan with screws/bolts into something that looks like those tabs, but a standard pancake box like you have is not rated for a fan. The threads in the tabs are not rated to hold the weight and vibration of a fan. And if the fan is hung from the box, then the box must be attached to the structure with screws that are rated to hold up the weight of the fan. Certainly drywall screws would not be allowed.
Comment: Your shallow ceiling box (aka "pancake" box) *appears to me* to be just a standard pancake box rated for a light weight fixture, but I could be wrong. If it is rated for a fan, there should be some indication on the box. The parts and instructions for Hunter fans of about the same weight as your fan direct the installer to drive some special wood screws into ceiling joists and not to depend on the existing *standard* box to support the fan. I expect the Hampton Bay fan to have the same setup. Read the instructions carefully.
Comment: @JimStewart Thanks for the help. Will return and just get a light fixture
Comment: (Our internet has been down for almost 12 hours.) The hardware with your fan will allow mounting over your pancake box, but just not directly to the pancake box.
Answer: Mount the fan to the joist or block behind the box, not the box
The two screws in the back of the box in line with the mounting tabs appear to land in a joist or cross-block in the ceiling.  I would attach the fan to that using two 1/4" by 3" structural wood screws (not drywall, deck, or lag screws -- look for something with an ICC-ES or IAPMO rating, such as a FastenMaster TimberLok or Simpson Strong-Drive SDS) through the fan bracket and ceiling finish board into the structural member.
Comment: I recently did this for two new fan installs in my house and it worked fine. My fans came with two sets of screws, one set for going into a metal box but the other were long wood screws meant to mount to a stud like this so if your fan kit came with their kind of screw it should work.
Answer: It may, but I concur with brhans. Drywall screws are very easy to snap right off and they (at a minimum) should be replaced by even just Deck Screws, which have the shear resistance of nails.
But, as with ANY apartment, call the Landlord and get their written approval and/or have them perform the installation and ALL electrical modifications...as is likely in your contract.


Android background Service crash while It swipe out

Question: When i remove my app from task manager.0 process and 1 service left. App do crash again and again what should i do to resolve it? This is my service class. I want to ask one more thing the difference between OnStart() method and OnStartCommand() method?
package com.example.vaccinationsystem;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.TabHost.OnTabChangeListener;

@SuppressLint("Override")
public class BackgroundServices extends Service {

String userId;
SoapObject request;
PropertyInfo p_userId;
SoapSerializationEnvelope envelope;
HttpTransportSE httpTransport;
SoapPrimitive response;
ArrayList<String> listRec;
String s;
int totalDifference;
int countNotification = 0;

private static final String METHOD_NAME = "Alerts";
private static final String NAMESPACE = "http://org.fyp.ws";
private static final String SOAP_ACTION = "http://org.fyp.ws/Alerts";
private static final String URL = StaticIP.ipAddress
        + "GeneralUserServices?wsdl";

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

// @Override
// public void onCreate() {
//
// Toast.makeText(this, "Congrats! MyService Created",
// Toast.LENGTH_LONG).show();
// // Log.d(TAG, "onCreate");
// }

@Override
public void onStart(Intent intent, int startId) {

    userId = intent.getExtras().getString("user_Id");
    listRec = new ArrayList<String>();
    request = new SoapObject(NAMESPACE, METHOD_NAME);
    p_userId = new PropertyInfo();
    envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    httpTransport = new HttpTransportSE(URL);

    p_userId.setName("userId");// Define the variable name in the web
    p_userId.setValue(userId);// Define value for fname variable
    p_userId.setType(String.class);// Define the type of the variable
    request.addProperty(p_userId);// Pass properties to the variable

    envelope.setOutputSoapObject(request);

    try {

        httpTransport.call(SOAP_ACTION, envelope);
        response = (SoapPrimitive) envelope.getResponse();
        // Toast.makeText(getApplicationContext(), response.toString(),
        // Toast.LENGTH_LONG).show();

        String[] row = response.toString().split("`");

        for (int i = 0; i < row.length; i++) {

            String[] record = row[i].split("~");
            // totalDifference = 0;
            Calendar c = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            String curDate = df.format(c.getTime()).toString();
            String visitDate = record[1];

            java.util.Date cD = df.parse(curDate);
            java.util.Date vD = df.parse(visitDate);

            Calendar cCurDate = Calendar.getInstance();
            cCurDate.setTime(cD);
            cCurDate.add(Calendar.DAY_OF_YEAR, 0);
            java.util.Date newCurDate = cCurDate.getTime();

            Calendar cNotificationStartVisitDate = Calendar.getInstance();
            cNotificationStartVisitDate.setTime(vD);
            cNotificationStartVisitDate.add(Calendar.DAY_OF_YEAR, -15);
            java.util.Date notificationStartDate = cNotificationStartVisitDate
                    .getTime();

            Calendar cOrignalVisitDate = Calendar.getInstance();
            cOrignalVisitDate.setTime(vD);
            cOrignalVisitDate.add(Calendar.DAY_OF_YEAR, 0);
            java.util.Date newOriDateVisitDate = cOrignalVisitDate
                    .getTime();
            totalDifference = 0;

            if (notificationStartDate.before(newCurDate)) {

                while (newOriDateVisitDate.after(newCurDate)) {
                    cOrignalVisitDate.add(Calendar.DAY_OF_YEAR, -1);
                    newOriDateVisitDate = cOrignalVisitDate.getTime();
                    totalDifference++;
                    s = "left";
                }
                while (newOriDateVisitDate.before(newCurDate)) {
                    cOrignalVisitDate.add(Calendar.DAY_OF_YEAR, +1);
                    newOriDateVisitDate = cOrignalVisitDate.getTime();
                    totalDifference++;
                    s = "ago";
                }
                countNotification++;
                listRec.add(record[2] + " Vaccine due: " + String.valueOf(totalDifference)
                        + " days " + s);

            }

        }

        for (int j = 0; j < countNotification; j++) {

            NotificationManager nm = (NotificationManager) getApplicationContext()
                    .getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
            Notification note = new Notification(R.drawable.nav_down,
                    "Vaccination ALerts!", System.currentTimeMillis());
            Intent inNotification = new Intent(this,GenUserFunction.class);
            inNotification.putExtra("user_id", userId);
            PendingIntent i =  PendingIntent.getActivity(getBaseContext(), 0,inNotification, 0);
            note.setLatestEventInfo(getApplicationContext(), "Vaccine       Due",
                    listRec.get(j), i);
            nm.notify(j, note);

        }

        // Toast.makeText(getApplicationContext(),
        // String.valueOf(listRec.size()), Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        // TODO: handle exception
        System.out.println(e.getMessage());

    }

    // Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();

    // Note: You can start a new thread and use it for long background
    // processing from here.
}

@Override
public void onDestroy() {

enter code here
    super.onDestroy();

    // Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
    // Log.d(TAG, "onDestroy");
}
   }

Comment: To resolve it you need to localize the error and then fix it.
Comment: can you post your service code?
Answer:
void onStart(Intent intent, int startId) is deprecated, you need to use int onStartCommand(Intent intent, int flags, int startId) instead.
onStart(...) is called from the onStartCommand(...) for backwards compatibility, and default implementation of the onStartCommand(...) returns the START_STICKY value. So, after the killing, yours service will be restarted by the system. When the service is restarted by the system, onStart(...) method can be called with a null intent object, and intent.getExtras().getString("user_Id") throws the NullPointerException, and service will be crashed, and restarted by the system...

As conclusion: you need to check the intent object for null befor using it.


Wireless won't stay connected. Macbook Broadcom 4321 wireless card. Lubuntu 19.10

Question: Fresh install of Lubuntu 19.10 on early 2008 MacBook. Brand new to linux. Finally found/installed the correct wireless driver - used chili55's extensive post on which driver to install based on pci id. Now I have wireless, but it doesn't stay connected. Please help.
edit : $ lspci -nnk | grep 0280 -A3
02:00.0 Network controller [0280]: Broadcom Inc. and subsidiaries BCM4321 802.11a/b/g/n [14e4:4328] (rev 03)
        Subsystem: Apple Inc. AirPort Extreme [106b:0088]
        Kernel driver in use: wl
        Kernel modules: ssb, wl

$ nmcli device wifi list
IN-USE  SSID                 MODE   CHAN  RATE        SIGNAL  BARS  SECURITY
        ICE VAN #55          Infra  3     195 Mbit/s  100     ▂▄▆█  WPA2
        Antici               Infra  157   195 Mbit/s  100     ▂▄▆█  WPA1 WPA2
        LAN SOLO             Infra  36    195 Mbit/s  95      ▂▄▆█  WPA2
        Johns                Infra  7     130 Mbit/s  32      ▂▄__  WPA1 WPA2
        MySpectrumWiFi42-2G  Infra  6     195 Mbit/s  30      ▂___  WPA2
        Evets1               Infra  4     195 Mbit/s  29      ▂___  WPA2
        TP-LINK_AP_0156      Infra  3     405 Mbit/s  27      ▂___  WPA2
        Gordon Network       Infra  9     405 Mbit/s  25      ▂___  WPA2
        MySpectrumWiFiCD-2G  Infra  5     260 Mbit/s  22      ▂___  WPA2
        --                   Infra  9     130 Mbit/s  22      ▂___  WPA2
        MySpectrumWiFi10-2G  Infra  11    195 Mbit/s  22      ▂___  WPA2
        ATT3N8z959           Infra  11    130 Mbit/s  20      ▂___  WPA2
        WIFIF4C3B3           Infra  1     195 Mbit/s  19      ▂___  WPA2
        mycci12              Infra  1     195 Mbit/s  17      ▂___  WPA1 WPA2
        Broncos              Infra  10    130 Mbit/s  17      ▂___  WPA1 WPA2
        Amped_AP300          Infra  1     270 Mbit/s  15      ▂___  WPA1
lines 1-17/17 (END)...skipping...
IN-USE  SSID                 MODE   CHAN  RATE        SIGNAL  BARS  SECURITY
        ICE VAN #55          Infra  3     195 Mbit/s  100     ▂▄▆█  WPA2
        Antici               Infra  157   195 Mbit/s  100     ▂▄▆█  WPA1 WPA2
        LAN SOLO             Infra  36    195 Mbit/s  95      ▂▄▆█  WPA2
        Johns                Infra  7     130 Mbit/s  32      ▂▄__  WPA1 WPA2
        MySpectrumWiFi42-2G  Infra  6     195 Mbit/s  30      ▂___  WPA2
        Evets1               Infra  4     195 Mbit/s  29      ▂___  WPA2
        TP-LINK_AP_0156      Infra  3     405 Mbit/s  27      ▂___  WPA2
        Gordon Network       Infra  9     405 Mbit/s  25      ▂___  WPA2
        MySpectrumWiFiCD-2G  Infra  5     260 Mbit/s  22      ▂___  WPA2
        --                   Infra  9     130 Mbit/s  22      ▂___  WPA2
        MySpectrumWiFi10-2G  Infra  11    195 Mbit/s  22      ▂___  WPA2
        ATT3N8z959           Infra  11    130 Mbit/s  20      ▂___  WPA2
        WIFIF4C3B3           Infra  1     195 Mbit/s  19      ▂___  WPA2
        mycci12              Infra  1     195 Mbit/s  17      ▂___  WPA1 WPA2
        Broncos              Infra  10    130 Mbit/s  17      ▂___  WPA1 WPA2
        Amped_AP300          Infra  1     270 Mbit/s  15      ▂___  WPA1

Comment: Please edit your question to show the result of these terminal commands: `lspci -nnk | grep 0280 -A3` and also: `nmcli device wifi list` Welcome to Ask Ubuntu.
Answer: Here are several steps that I recommend. First, disable power saving in Network Manager; from the terminal:
sudo sed -i 's/3/2/' /etc/NetworkManager/conf.d/*

Next, check the settings in the router. WPA2-AES is preferred; not any WPA and WPA2 mixed mode and certainly not TKIP. Second, if your router is capable of N speeds, you may have better connectivity with a channel width of 20 MHz in the 2.4 GHz band instead of automatic 20/40 MHz, although it is likely to affect N speeds. I also have better luck with a fixed channel, either 1, 6 or 11, rather than automatic channel selection. Also, be certain the router is not set to use N speeds only; auto B, G and N is preferred. After making these changes, reboot the router.
Then set your regulatory domain explicitly. Check yours:
sudo iw reg get

If you get 00, that is a one-size-maybe-fits-all setting. Find yours here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Then set it temporarily:
sudo iw reg set IS

Of course, substitute your country code if not Iceland. Set it permanently:
Code:
    sudo nano /etc/default/crda
Change the last line to read:
REGDOMAIN=IS

Proofread carefully, save (Ctrl+o followed by Enter) and close (Ctrl+x) the text editor.


Is it possible that |$\mathbb R$| is an inaccessible cardinal?

Question: I know that |$\mathbb R$| can be any cardinal with cofinaly not equal to $\aleph_0$. Does this include inaccessible cardinals?
And what would be the consequences if |$\mathbb R$| = $\kappa$?
Answer: It depends what you mean by "inaccessible" - strongly inaccessible or weakly inaccessible.
Since a strongly inaccessible $\kappa$ is by definition uncountable and bigger than $2^\lambda$ for every $\lambda<\kappa$, we can't have $\vert\mathbb{R}\vert$ be strongly inaccessible.
On the other hand, we can have $\vert\mathbb{R}\vert$ be weakly inaccessible (that is, a regular limit cardinal), at least assuming that the existence of weakly inaccessible cardinals is consistent with ZFC. The proof that this is possible uses forcing, but if you've already seen forcing then here's the outline:

Suppose $V$ is a model of ZFC with an inaccessible cardinal $\kappa$.
Consider $L^V$, that is, $V$'s version of the constructible universe.
In $L^V$, the Continuum Hypothesis holds and $\kappa$ is still weakly inaccessible - so in $L^V$ we have $2^{\aleph_0}<\kappa$.
Now we force: add $\kappa$-many Cohen reals. Since this forcing is c.c.c., it preserves cardinals and cofinalities, so $\kappa$ remains a weakly inaccessible cardinal; but now $2^{\aleph_0}=\kappa$. (Actually, all that's obvious is that $2^{\aleph_0}\ge\kappa$; it takes an argument, using "nice names," to show that in fact we have equality. This isn't hard but it's worth pointing out.)

Meanwhile, as far as consequences of $2^{\aleph_0}$ being weakly inaccessible go, I'm not aware of any big ones beyond the obvious (e.g. CH isn't true).

Some further comments:

In the proof sketch above, why did I need to pass to $L$ instead of working in $V$? Well, we could have in $V$ that $2^{\aleph_0}>\kappa$, in which case adding $\kappa$-many Cohen reals won't make $2^{\aleph_0}=\kappa$. Instead, if we want to handle this case without going to $L$ we need to collapse a cardinal: force with the set of partial maps from $\kappa$ to $\mathbb{R}$ whose domains have cardinality $<\kappa$. Since this is $(<\kappa)$-closed, $\kappa$ will stay weakly inaccessible.
What if I try to run the same argument as above, but with $\kappa$ strongly inaccessible? Well, now in the last bullet point, I need to argue somehow that $\kappa$ remains strongly inaccessible after forcing, and this breaks down: specifically, there is no reason to have $2^\lambda<\kappa$ for all $\lambda<\kappa$ after we force.
Finally, it's worth pointing out that there are senses in which $\kappa=\vert\mathbb{R}\vert$ can "appear" strongly inaccessible (or more): namely, by looking at $\kappa$ in an inner model $M$ (e.g. $M=L$). This inner model could be much smaller than $V$, and in particular it could be wrong about how the powerset function works: we'll always have $(2^\lambda)^M\le (2^\lambda)^V$, but not necessarily conversely. So it's totally possible to have e.g. "$2^{\aleph_0}$ is strongly inaccessible in $L$" (in fact, this will be true whenever $2^{\aleph_0}$ is weakly inaccessible, since weakly inaccessible cardinals are strongly inaccessible in $L$ since $L$ satisfies the GCH!). If you're interested in understanding how properties can differ between an inner model and the whole model, the term to look for is "absoluteness."


anylogic- The right block to simulate the work-in-progress (WIP) in a manufacturing line with push requests

Question: I am still new to AnyLogic. I am trying to resolve a simulation problem with AnyLogic, but I don't know how to do it.
This is the problem: There is a single product which will be processed at two machines. Each  machine has its own operator(s). Also, there is before and after the machines some work-in-progress (WIP).
How can I modelize this problem with a simple flowchart block? (eg.agent, queue, delay, service and sink)
also, I want to know what block should I use to model the WIP? queue or delay?
what exactly is the difference between these blocks (queue. delay and the service)in terms of duty?
Is it right to use the following blocks to model such a process:
(source, queue, delay, service, queue1, delay1, service1, sink respectively).
Many thanks for your time and help!
Comment: Hi Marjan, welcome to SO! Can you specify what WIP means in your case? Is it a place where parts are just waiting, like a buffer before and after process? Or is it a place where actual work is done (pre-/postprocessing)? Is there a fixed time the part has to stay in WIP or just until next station is free? Is order of importance or just plain FIFO?
Comment: Hi Florian, thanks a lot! The three categories of stock are raw materials, work-in-progress (WIP) and finished goods. I mean work in progress or process: a piece of work or product that has been begun but is not finished or ready ( in a manufacturing line). These parts have to stay in a place (eg.boxs) just until next station is free. Order is FIFO.
Answer: Process Flow with WIP
You can model it like this:

Your WIP is now inside the queues of the two Service blocks, service1 and service2. You can for example get the current WIP for the first station by calling service.queueSize().
Note: the Service block is nothing other than a combination of a Queue block, a Delay block and some optional resource functionality (Seize and Release). If you use the Service block, normally no additional Queue, Delay,Seize and Release is needed, because it already "contains" one of each.
The following two process flows are doing the same functionality, just split up in several modules in the second one. This is sometimes handy or even necessary in some special situations:

To be completely accurate: the 'Seize'-block again contains a queue on its own which can be also seen by the little queue sign inside the block symbol. So in the second example flow, the 'Queue' block would not be needed. It is just to illustrate the possibilites to split up the functionality of the combined blocks to as many as possible "single-use" blocks.

Additional Ressources
The following materials might help you for your further process modeling in AnyLogic:

AnyLogic documentation on Process Modeling Library
Process Modeling Tutorial.
Go to Help/Example Models in AnyLogic and search for models with Process Modelling Library, you'll find lots of good examples.
Comment: Note that actually the Seize block already includes a queue (which is what the block icon tries to show) so a Service block is actually only a Seize -- Delay -- Release sequence; your Queue blocks in your second example flow are superfluous.
Comment: Now, if someone does not use the service block,  can they use  queue, seize, delay and release blocks instead? Is it true?
Comment: Yes, that's it. I added this in the answer as well for clarification. Look at the second image with the 2 process flows, they are doing the same.


Get value of multiple checkbox & echo in email

Question: Getting trouble on adding multiple checkbox value within mail body due to my low knowledge in PHP.
I know that it possible to show/echo checkbox by array with foreach loop but i don't know to echo it within mail body. I want to echo it within $message.
HTML Code sample-
<input type="checkbox" name="color[]"  value="Value1"> Title1
<input type="checkbox" name="color[]"  value="Value2"> Title2
<input type="checkbox" name="color[]"  value="Value3"> Title3
<input type="checkbox" name="color[]"  value="Value4"> Title4
<input type="checkbox" name="color[]"  value="Value5"> Title5

PHP Code-
<?php

$to = "firstname.lastname@example.com";
$fromEmail = "email@example.com";
$fromName = "Arif Khan";
$subject = "Contact Email";
$message = "Hey, Someone Sent you a Contact Message through your Website.

    Details Below-
    Name: $_POST[fname] $_POST[lname]
    Email Address: $_POST[email]
    Contact Number: $_POST[contact1] $_POST[contact2] $_POST[contact3]
    Zip Code: $_POST[zip]
    Best Time To Contact: $_POST[besttime]
    Payment Plan Options: $_POST[payment_plan]
    MUA: $_POST[mua]
    Shoot Concept:
    Shoot Concept(Other): $_POST[shootother]";

$headers = "From:" . $fromName . " " . $fromEmail;

$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent to: $to";
}
else{
echo "Error in Email sending";
}
?>

Answer: You can simply do,
$colors = isset($_POST['color']) ? implode(",",$_POST['color']) : '';

And now you can use this $colors (you will get all selected colors as comma separeted) in your email message body part.
$message = "Hey, Someone Sent you a Contact Message through your Website.

Details Below-
Name: $_POST[fname] $_POST[lname]
Colors: $colors
Email Address: $_POST[email]
Contact Number: $_POST[contact1] $_POST[contact2] $_POST[contact3]
Zip Code: $_POST[zip]
Best Time To Contact: $_POST[besttime]
Payment Plan Options: $_POST[payment_plan]
MUA: $_POST[mua]
Shoot Concept:
Shoot Concept(Other): $_POST[shootother]";

Comment: how can i implement it with $message, i want it in mail body. Thanks
Comment: see my updated answer, I have added `$colors` in message body.
Comment: Parse error: syntax error, unexpected '=' in /home/arifkpi/public_html/arif/project/cform/form_action.php on line 8                         Line 8- $color= isset($_POST['color']) = implode(", ",$_POST['color']) : '';
Comment: Just update but new error, Warning: implode(): Invalid arguments passed in /home/arifkpi/public_html/arif/project/cform/form_action.php on line 8
Comment: Can you post output of `$_POST['color']` ?
Comment: In that I can't see any field with name `color`. Have you added colors multi-check box in your html ?
Comment: I use shoot[] there instead of color[] & same on php page too
Comment: Yes, did it but error. Warning: implode(): Invalid arguments passed in /home/arifkpi/public_html/arif/project/cform/form_action.php on line 8
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/51089/discussion-between-rikesh-and-arifix)
Answer: Try this
if(isset($_POST['color'])) {
    $message.= implode(',', $_POST['color']);
}

Comment: Warning: implode(): Invalid arguments passed in /home/arifkpi/public_html/arif/project/cform/form_action.php on line 22         Your code is on line 22


Best cost efficient plug-in heating devices / radiators

Question: We moved to a 2-bedroom apartment that has baseboard heating devices installed. Our first electricity bill was huge (around $400) and we only used 3 of them and not all day long.
Here is a pic of the baseboard heaters we have installed:

We would like to buy some plug-in radiator that are good for heating a 1070 sq feet apartment but as cost/energy efficient as possible. What are the recommended solutions?
Answer: Electrical baseboard heaters and plug-in resistance heaters are already 100% efficient, in that 100% of the electrical energy that goes into them is turned into heat. Whether it's a ceramic heater, oil-filled radiator, or radiant heater, they all are 100% efficient.
However, as you found out, even at 100% efficiency, electrical resistance heating is expensive.
This is why many people that need to use electrical heating will use a heat pump, which can actually be more than 100% efficient because instead of creating heat directly from the electricity, they pump heat from outside the house to inside the house. But this is not a simple retrofit, so you can't simply replace your baseboard heaters with a central heat pump system (though if you live in a relatively mild climate, you can find window unit heatpumps that might be more efficient than a baseboard heater)
One thing that might help would be to turn down the baseboard heaters, and use radiant heaters in places where you want targeted warmth. For example, if when you're in the livingroom you spend most of the time on the couch, you could turn down the thermostat in that room and use a radiant heater in front of the couch (but a safe distance away) to keep you warm even if the rest of the room is not comfortably warm.
Comment: Thanks! What about oil radiators? Arent they a better solution than baseboard?
Comment: Oil radiators are no better, unless your baseboard heaters are located directly under windows or on walls that leak heat like a sieve. Look into insulation.


How to upgrade x.org?

Question: I need xorg-server version 2:184.108.40.2062-1ubuntu3 installed because it contains a fix:
xorg-server (2:188.8.131.522-1ubuntu3) natty; urgency=low

  * Add 207_dga_master_device.patch: Cherrypick from upstream xserver git
    to fix crash with a bluetooth keyboard when using XBMC full screen.
    (LP: #597895)
 -- Bryce Harrington <email address hidden> Thu, 06 Jan 2011 12:17:16 -0800

And I need that for my xbmc to work properly, but on my machine it shows: xorg-server 2:1.9.0-0ubuntu7.1 when I run X -version
Any ideas? I can't find any packages to install and apt-get says it's already the most current version...
Answer: The easiest way to get the fix is to use the xorg edgers PPA:
https://launchpad.net/~xorg-edgers/+archive/ppa
The PPA is built for testing and for fixing obscure bugs with certain releases. It currently has xorg version 2:18.104.22.1681+git20101129 and you may be looking for 902 instead of 901, but try it because it'll get you most of the way there and it's likely it'll be updated anyway.
What ever you do, don't compile yourself. If you feel the urge to DIY, please build some deb packages for yourself instead. More details here:
https://edge.launchpad.net/~xorg-edgers

How to upgrade x.org?


Why isn't my map being updated?

Question: Pretty new to clojure so be kind.
(def state {:currentPosition "1"})

(while (not= (state :currentPosition) "2") ; this is true
  (assoc state :currentPosition "2") ;
)

This causes an infinite loop and it wont run but I don't understand why. The condition
 (not= (state :currentPosition) "2")

is true
therefore, the loop starts, then inside the loop, I am updating the state. Why doesn't the loop end and just stalls light table? Thanks
Comment: Ben, Piotr's answer is correct given what you specifically asked.  You may know this, but the kind of thing you're doing is not idiomatic.  (Sometimes you need to do this kind of thing anyway, which is why atoms exist.)  It's fine to do things the way you're used to doing them when you very first learn the language, but you'll want to learn Clojure-style coding strategies pretty quickly.  It can be kind of awkward at first, but once you get used to functional programming, it's beautiful and fun (imho).  If I'm telling you things you already have heard, just ignore this comment.
Comment: I totally agree, i'm trying to program 'normally'. It's just a real big change to what i'm used to lol
Answer: Clojure datastructures are immutable so (assoc state :currentPosition "2") doesn't mutate the object assigned to state var but just returns a new version of a map.
If you want to modify values in your vars you need to wrap them in one of Clojure's refs. You could for example use atom:
(def state (atom {:currentPosition 1}))

(reset! state {:currentPosition 2})
@state ;; => {:currentPosition 2}

(swap! state update :currentPosition inc)
@state ;; => {:currentPosition 3}

Comment: nevermind, just got it!  (not=  (@state :currentPosition) "2")  thanks very much
Comment: In one place you have `2` and in the other `"2"`
Comment: hey I can't test if it works because when I try to do:  (not= (state :currentPosition) "2")    it says Atom cannot be cast to IFn  Any ideas? thank you again
Comment: When you want to read a value from an atom you need to `deref` it: `(deref currentPosition)`. There is also a shorthand version: `@currentPosition`
Comment: Great! I see what you mean about the deref but I think I had to deref the object, not the currentPosition like so: (not= ((deref state) :currentPosition) "2")   how do you mean with the @currentPosition
Comment: Hey, it' sstill not working in the loop :(   here is code if you'd like a look https://codeshare.io/3lAfX

Why isn't my map being updated?


Is it okay to use brass inserts in a plastic reverse osmosis pipe?

Question: I've learned that letting metal contact reverse osmosis filtered water is generally a bad idea as it corrodes the metals and leaches them into the clean water supply.
However, I'm having a hard time finding a fully plastic 1/4-in compression fitting (1/4-in female to 1/4-in male) to connect my RO line to my refrigerator.  Should I be concerned about the copper insert that will be in contact with the RO-filtered water?  Will it affect the integrity of the connection and/or the water quality?
Comment: Ha, thanks Ecnerwal.  I usually change a few unimportant words when editing something like that.  I certainly want to keep leeches out of the fresh water supply though.  Corrected.
Answer: Here are some that appear to be fully-plastic, and/or plastic + stainless steel
Without knowing what particular fitting you need (1/4 compression to what?), hard to get more specific than that. Full plastic fittings are out there, and really are what you want, as RO & DI water do love to eat anything that will  give them ions. My reading on the above fittings is that the stainless (which is as good a choice as you get in metal, though aluminum may also work well from what I recall of an old lab D.I.W. system) is not in the normally wetted path.
Here is another supplier's nylon/polypro fittings:
Comment: Yup those are the fittings used, I think I seen them in local local hardware store also. I won't mention the names but the national chain stores should carry them. Incredibly easy to install, nice even, square cut on the pipe, push it on fully, done.
Comment: I did find one at Lowe's after writing this, but the threaded end of the compression fitting was oddly the wrong size once I got home.  The package had been unopened but was clearly marked 1/4-in.  I think the threaded end was actually 3/8 or 1/2.  Incidentally, I think I'm going to cut the plastic hose on my fridge and just get a push-fit union because I think they probably already used metal ferrules inside the compression fitting attached to the fridge hose at the factory.


Proving inequality $\frac{2a}{3a^2+b^2+2ac} +\frac{2b}{3b^2+c^2+2ab}+\frac{2c}{3c^2+a^2+2bc}\le\frac{3}{a+b+c}$

Question: $a,b,c$ are real positive numbers ,what is the proof that :
$$\frac{2a}{3a^2+b^2+2ac} +\frac{2b}{3b^2+c^2+2ab}+\frac{2c}{3c^2+a^2+2bc}\le\frac{3}{a+b+c}$$
Answer: Hint: Prove that
$$
\frac{2a}{3a^2+b^2+2ac}\leq\frac{1}{a+b+c}
$$
Comment: Additional hint if OP is unsatisfied:  Note that $2ab\leq a^2+b^2$ since squares are always positive, that is $0\leq (a-b)^2$.
Answer: I just follow the very good hint from Norbert's answer
$$\frac{2 a}{3 a^{2}+b^{2}+2 a c} \leq \frac{1}{a+b+c}$$
Since $a, b, c$ are real positive numbers, $2 a, 2 b, 2 c$ and $(a+b+c)$ are also real positive numbers
$$2 a(a+b+c) \leq 3 a^{2}+b^{2}+2 a c\\
2 a^{2}+2 a b+2 a c \leq 3 a^{2}+b^{2}+2 a c \\
2 a b \leq a^{2}+b^{2}\\
a^{2}+b^{2}-2 a b \geq 0\\
(a-b)^{2} \geq 0 $$ This is always true, thus $$\frac{2 a}{3 a^{2}+b^{2}+2 a c} \leq \frac{1}{a+b+c}$$
Similarly, we have $$\frac{2 b}{3 b^{2}+c^{2}+2 a b} \leq \frac{1}{a+b+c}$$
and $$\frac{2 c}{3 c^{2}+a^{2}+2 b c} \leq \frac{1}{a+b+c}$$
Therefore $$\frac{2 a}{3 a^{2}+b^{2}+2 a c}+\frac{2 b}{3 b^{2}+c^{2}+2 a b}+\frac{2 c}{3 c^{2}+a^{2}+2 b c} \leq \frac{3}{a+b+c}$$
Comment: Apart from the fact that you wrote the proof backwards without saying so (instead of the ususal "we know X therefore Y and we can conclude Z" your proof should read "we want to prove Z which will follow if Y for which it will suffice that X which is true), it is also unusual to post jour answer as jpeg file.
Comment: Here you can find [complete faq](http://meta.math.stackexchange.com/questions/107/faq-for-math-stackexchange/117#117) on writing formulas. And please, don't post complete solutions.
Comment: Sorry about posting my answer as jpg file. I am a new user of this website. I had been trying to write equations in my post, but I didn't know how to, hence I had to write in MS Word then captured it.
Answer: By AM-GM $$\sum_{cyc}\frac{2a}{3a^2+b^2+2ac}=\sum_{cyc}\frac{2a}{2a^2+a^2+b^2+2ac}\leq\sum_{cyc}\frac{2a}{2a^2+2ab+2ac}=\frac{3}{a+b+c}$$


How does one obtain the "black" camo in BF3?

Question: Playing around in Battlefield 3 I often see players (with a rank higher or equal to 42, I noticed) that wear a black suit that's very difficult to spot (i.e. a relatively long time and short distance before the orange triangle appears over the player's head).
Is it part of some expansion or does one obtain such camo at some rank? I can't find any clue about it.
Answer: Spec Ops camo is unlocked at level 42.
It doesn't have the special properties you listed (that being harder to spot for your teammates) it does however have the special property of making you harder to see if your enemy is using an IRNV scope.
While wearing it, the black parts of your camo (not your gun or the ammo pouches etc.) will not show any heat through an IRNV scope.
Comment: Since someone bumped this question - dug around a bit and found out that in addition to level 42, you need to have accumulated 1,400,000 points to unlock the Spec Ops Black Camo.
Comment: Ah, ok! I was convinced of that particular behaviour because I really perceived an increased difficulty in marking enemies. Evidently I am mistaken and my opponents (casually wearing that camo) are really good players. Thank you!


how to make single deep array out of couple arrays deep array

Question: I'm trying to get an array of arrays back from the function pasted at the bottom.
The problem is i'm stuck on when an array will be present multiple times.
An example what I would like to get back is:
[
  ['Batch', 'status', 'gewijzigd door', 'date', 'variable'],
  ['34', 'ready', 'projectname', '12-12-20', 'jerry'],
  ['34', 'ready', 'projectname', '12-12-20', 'john'],
  ['34', 'ready', 'projectname', '12-12-20', 'empty'],
  ['34', 'ready', 'projectname', '12-12-20', 'empty'],
  ['34', 'ready', 'projectname', '12-12-20', 'empty']
]

But if it contains a biebs property. Then I run into a problem shown below.
[
  ['Batch', 'status', 'gewijzigd door', 'date', 'variable'],
  [
    ['34', 'ready', 'projectname', '12-12-20', 'jerry'],
    ['34', 'ready', 'projectname', '12-12-20', 'john']
  ],
  ['34', 'ready', 'projectname', '12-12-20', 'empty'],
  ['34', 'ready', 'projectname', '12-12-20', 'empty'],
  ['34', 'ready', 'projectname', '12-12-20', 'empty'],
  [
    ['34', 'ready', 'projectname', '12-12-20', 'jerry'],
    ['34', 'ready', 'projectname', '12-12-20', 'john']
  ]
]

I'm stuck on how I can solve this or tackle this result.   .flat() would also flatten the ones i would like to keep.
or is my function not build up in the right way?
Code is pasted below
import {CreateUrls, RemoveLastSlash} from '../../utils/Tools';

const List = (file, { bronUrlSplit, migrStatus }) => {

  const batchMigratie = file.map(d => {
    const { urlBron, subSite } = CreateUrls(d.Url, 'est', parseInt(bronUrlSplit))

    if (d.hasOwnProperty('biebs')) {
      const biebs = d.biebs.split(',')

      const test = biebs.map(element => {
        return [d.Batch, migrStatus, d.Titel, RemoveLastSlash(urlBron), RemoveLastSlash(subSite), element ];
      });
      return test
    }

    return [d.Batch, migrStatus, d.Titel, RemoveLastSlash(urlBron), RemoveLastSlash(subSite), 'empty' ];
  })

  batchMigratie.forEach(element => {
    console.log('element', element)
  });

  return [
    ['Batch', 'status', 'gewijzigd door', 'date', 'variable'],
    ...batchMigratie
  ]
}

export default List

Comment: Data transformation questions should always include the input and expected output of the transformation process. Please edit your question to include both.
Comment: Why mix mutable & immutable actions. Just use reduce to rebuild it.
Answer: You could simply check for each array element if it contains another array. If yes, push each of its elements to  the result, else just the current element. Something like:

const arr = [
    ['Batch', 'status', 'gewijzigd door', 'date', 'variable'],
    [
        ['34', 'ready', 'projectname', '12-12-20', 'jerry'],
        ['34', 'ready', 'projectname', '12-12-20', 'john']
    ],
    ['34', 'ready', 'projectname', '12-12-20', 'empty'],
    ['34', 'ready', 'projectname', '12-12-20', 'empty'],
    ['34', 'ready', 'projectname', '12-12-20', 'empty'],
    [
        ['34', 'ready', 'projectname', '12-12-20', 'jerry'],
        ['34', 'ready', 'projectname', '12-12-20', 'john']
    ]
];

function isArrayOfArrays(a){
    return a.every(x => Array.isArray(x));
}

function flattenArray(arr) {
    const result = [];
    for (const currElement of arr) {
        if (isArrayOfArrays(currElement)) {
            for (let innerArray of currElement) {
                result.push(innerArray);
            }
        } else {
            result.push(currElement);
        }
    }
    return result;
}

console.log(flattenArray(arr));
Comment: thanks to your way of solving, i rewrote my code to not have the innerArray anymore. So i removed the problem itself :)


beautifulsoup not returning span results

Question: I'm learning bs4 and trying to scrape the span tag data from this website put them in a list but no results are returned what am I doing wrong?
import requests
import bs4

root_url = 'http://www.timeanddate.com'
index_url = root_url + '/astronomy/tonga/nukualofa'

response = requests.get(index_url)
soup = bs4.BeautifulSoup(response.text)
spans = soup.find_all('span', attrs={'id':'qfacts'})
for span in spans:
    print span.string

All span data from the webpage is in between this tag

Current Time: 16 Mar 2015 at
12:53:50 p.m.

Sunrise Today: 6:43
a.m. ↑ 93°
East

    Sunset Today: 6:56
p.m. ↑
268° West

Moonrise Today: 1:55
a.m. ↑
108° East

Moonset Today: 3:17
p.m. ↑
253° West

Daylight Hours:
12 hours, 13 minutes (-1m 13s)

Answer: Subtle mistake is that you are searching for span tags that have an id of "facts" when what you really want is to search for span tags within the div having that id.
Replace,
spans = soup.find_all('span', attrs={'id':'qfacts'})

with,
div = soup.find('div', attrs={'id': 'qfacts'})  # <-- div not span
spans = div.find_all('span')  # <-- now find the spans inside

Were you looking for divs having some class you would want to iterate those divs and find all spans inside but this is an id so a single find call should suffice.


iOS Daemon app will not start (Jailbreak) - how to debug?

Question: I'm building a daemon app for a jailbroken iPhone and followed the guidelines as described in several questions and answers here on stackoverflow and ofcourse Chris Alvares' webpage at http://chrisalvares.com/blog/38/creating-an-iphone-daemon-part-4/
Xcode and the project are patched by Jailcoder to make it run on my device.
One of the posts on here stated that nowadays it is no longer needed to use the open toolchain template. Uploading the app to the /Applications dir and adding a plist file in /System/Library/LaunchDaemons should be sufficient.
I have performed the above steps but the daemon is not started, or at least not running when i check. In the device logs that are available in Xcode organizer the name of the app or its bundle id are not to be found anywhere. I would at least expect an error with a reason why it won't start.
The contents of the plist file copied to /System/Library/LaunchDaemons:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Disabled</key>
        <false/>
        <key>Label</key>
        <string>dmn.NoUIDaemon.plist</string>
        <key>OnDemand</key>
        <false/>
        <key>ProgramArguments</key>
        <array>
            <string>/Applications/NoUIDaemon.app/NoUIDaemon</string>
            <string></string>
            <string></string>
        </array>
        <key>StandardErrorPath</key>
        <string>/dev/null</string>
    </dict>
    </plist>

Question: is there a way to debug why it won't start the daemon app? Or have i maybe missed a step besides uploading the app to /Applications and adding the plist file to the LaunchDaemons dir ?
EDIT:
Contents of my main routine:
int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

Error when launching /Applications/NoUIDaemon.app/NoUIDaemon :
R-iPod:/ root# /Applications/NoUIDaemon.app/NoUIDaemon
-sh: /Applications/NoUIDaemon.app/NoUIDaemon: Bad CPU type in executable

Note that the app does work without a problem when i run it on my device from Xcode.
Eventhough the daemon cannot be started manually, the answers to Nate's questions:
1) The plist file in LaunchDaemons is indeed named dmn.NoUIDaemon.plist
2) I made the 'mistake' of forgetting the .plist part in the Label contents, so i have tried it with both values, with and without .plist at the end, no difference ofcourse.
3) I have rebooted the device after installing both the app and the plist file using the reboot command
4) I've made sure all the permissions are the same (0775)
5) Will try this when the Bad CPU issue is resolved and it still doesn't work
FINAL EDIT:
To hide your Daemon app icon on the springboard, add the following to the Info.plist in your .app:
<key>SBAppTags</key>
<array>
    <string>hidden</string>
</array>

Comment: Can you login to your device as root via `ssh`, and just execute the command `/Applications/NoUIDameon.app/NoUIDaemon` at the command line?  Does this successfully run your daemon (check to see if it's running with `ps -Aef | grep NoUIDaemon`)?
Answer: As I said in my comment, first try to make sure your daemon executable is runnable:

login to your device as root, via ssh
execute the command /Applications/NoUIDameon.app/NoUIDaemon at the command line
check to see if it's running with ps -Aef | grep NoUIDaemon

If it's not running, I would check to make sure that your build process is fake code-signing the NoUIDaemon executable.  Jailbroken phones don't require a valid signature, but they still do require a signature.  Also, if it doesn't run (or stay running), it might help for you to post the code from your daemon's main program (e.g. main.m):
int main(int argc, char *argv[]) {
   // what's in here?
}

If that does work, and it runs when you start it manually (but not automatically), then check:

is the plist file above named dmn.NoUIDaemon.plist?
I think this is actually an error in Chris's blog, but the Label value in your plist should be <string>dmn.NoUIDaemon</string>, not <string>dmn.NoUIDaemon.plist</string>.  I don't think this would prevent your daemon from running, I think it's just being consistent with the naming convention of system launch daemons.
I don't think just installing the plist file in /System/Library/LaunchDaemons is enough to start the daemon.  You probably need to either reboot the phone, or manually launch the daemon with launchctl load -w /System/Library/LaunchDaemons/dmn.NoUIDaemon.plist
check to make sure the file permissions and ownership of your dmn.NoUIDaemon.plist are the same as the other launch daemon plists in /System/Library/LaunchDaemons.
I'm not sure if this is necessary, but I think the name of the daemon (the Label and the name of the plist file) are supposed to match the bundle ID specified in your NoUIDaemon-Info.plist file.  So, the Info.plist should have:

    <key>CFBundleExecutable</key>
    <string>NoUIDaemon</string>
    <key>CFBundleIdentifier</key>
    <string>dmn.${PRODUCT_NAME:rfc1034identifier}</string>

or
    <key>CFBundleExecutable</key>
    <string>NoUIDaemon</string>
    <key>CFBundleIdentifier</key>
    <string>dmn.NoUIDaemon</string>

Update:
Also, I don't think your daemon's main program should have a call to UIApplicationMain.  It's not supposed to be a UIApplication.  It's supposed to be a background process, right?  If you look on Page 1 of Chris's blog, it shows an example.  Here's an example from one of mine:
int main(int argc, char *argv[]) {
   @autoreleasepool {
      SignalMonitor* daemon = [[SignalMonitor alloc] init];

      // start a timer so that the process does not exit.
      NSTimer* timer = [[NSTimer alloc] initWithFireDate: [NSDate date]
                                                interval: 1.0
                                                  target: daemon
                                                selector: @selector(setup:)
                                                userInfo: nil
                                                 repeats: NO];

      NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
      [runLoop addTimer: timer forMode: NSDefaultRunLoopMode];
      [runLoop run];
   }

   return 0;
}

Also, here's a copy of my daemon's plist file (Info.plist), with your daemon name in it:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>CFBundleDevelopmentRegion</key>
        <string>English</string>
        <key>CFBundleExecutable</key>
        <string>NoUIDaemon</string>
        <key>CFBundleIdentifier</key>
        <string>dmn.NoUIDaemon</string>
        <key>CFBundleInfoDictionaryVersion</key>
        <string>6.0</string>
        <key>CFBundleName</key>
        <string>${PRODUCT_NAME}</string>
        <key>CFBundlePackageType</key>
        <string>APPL</string>
        <key>CFBundleShortVersionString</key>
        <string>1.0</string>
        <key>CFBundleSignature</key>
        <string>????</string>
        <key>CFBundleVersion</key>
        <string>1.0-0</string>
        <key>LSRequiresIPhoneOS</key>
        <true/>
        <key>LSApplicationCategoryType</key>
        <string></string>
</dict>
</plist>

Comment: Thanks for all the help here Nate. Will try to get the icon hidden by experimenting with the Info.plist you posted. If that doesn't work I will post a new question as i understand that is required here. Thanks again :) +1
Comment: for anyone interested in hiding the icon on springboard, see the final edit in my question
Comment: R-iPod:/ root# /Applications/NoUIDaemon.app/NoUIDaemon
-sh: /Applications/NoUIDaemon.app/NoUIDaemon: Bad CPU type in executable
Comment: Thats the error i get when executing through ssh. The device is an iPod Touch 4G (i believe that's an arm7 device) and the project is set to arm7 architecture. When i run the app through the debugger it also works fine - i would expect this to fail as well if the 'CPU type is bad'.
Comment: added contents of main routine in my original question
Comment: I have also answered your other questions there, and of course a big thanks for the help so far :)
Comment: @Ronald, ok, so maybe somehow what you're installing on your iPod is the executable built for the **simulator** (Intel architecture).  Can you `cd` to the directory where your `NoUIDaemon` executable is and run `lipo -info NoUIDaemon`?  Lipo will tell you which architectures are present in the executable.  In your case, it should be `armv7`.  (You can also use the `file` command, or `otool -hv` on your executable to get the same info).  Also, see my update above.
Comment: @Ronald, I know you're still stuck on getting the executable to run at all, but I should also mention that the **ownership** on the dmn.NoUIDaemon.plist file should also match the other plists, not just the *permissions*.
Comment: Yes that was indeed the case. The 'file' command returned i386. Having connected my device and selecting build again, i copied the new binary to my device and the same command now returned 'acorn'. Not sure why that's not saying armv7, but checking the running apps after a reboot i can see my UIDaemon running :) Thank you !!
Comment: Thanks also for the snippet of your daemon, will definitely be using that in mine. You think that's the reason iOS shows a visible icon on the springboard for this app? I would expect no icon to show up, just like for instance the SSH daemon.
Comment: @Ronald,  I'm not exactly sure.  All of my daemons have been bundled with a UI Application (so, in my .app folder, there's two executables, the app and the daemon).  It might be using some of the information in the daemon's plist to determine if it should show in SpringBoard.  You can take a look at one of my daemon plists (update above), and experiment.  Clearly, things like icons don't need to be specified in daemon plists.  Try removing everything you don't need.
Comment: It was long time ago thatI saw such a good/interesting question and an excellent answer on StackOverflow. Definitely a +1 for both of you!
Comment: @H2CO3, Thanks.  The credit definitely goes to Chris Alvares.  I've probably referenced this blog post in a dozen different answers.  Hard to find good jailbreak reference material, but that's a great one!


How to word UIAlertView YES/NO or Continue/Cancel questions on iPhone?

Question: I'm implementing an option in one of my iPhone apps that would put one of my existing controllers into a new mode of operation. Instead of tapping on icons to add events within the app, the controller would now edit the icons themselves, so the user can change their border colors and titles.
This is an optional feature that I would like to explain to the user. I plan on doing the following:

Making the icons shake, like iPhone home screen
Displaying a "Would you like to continue" dialog each time the user
returns to the screen, until the user cancels.

I'm thinking of how I can word this dialog to make it clearer to the user that the app is still in edit mode and am wandering what should I do with the button titles of the alert dialog. I'm struggling with:

the wording of the dialog title
last sentence in the attached screenshot
Button titles that respond to the question

I can ask a question in the form of "Would you like to stop editing now?" and have YES/NO answers
Or I can keep the dialog in the form of Would you like to [Action verb] with options of [Action Verb]/Cancel
Which approach is more user friendly and is better/quicker understood by iPhone users?
What should the title say for a dialog like this one?
Thank you for your input!
Comment: Could you please add more information about the scenario you are facing here please. If your concern is that Alert View is being shown again and again for small edits and you are searching for suitable text that will not irk users, try avoiding the Alert View only. Like Gmail auto save popup, decide things for users and give him auto close popup with an undo option.
Answer: Usually, when you want to warn somebody or ask them a question for verification or confirmation in real life, it follows the pattern of a statement followed by a question. For example, "So you've ordered 2 grilled chicken sandwiches, medium fries, and 2 small drinks. Will that be all?".
Another example is that of an ATM. For example, "Using this ATM will cause you to incur a service fee of $3.00. Continue?" And the options usually are "OK" and "Cancel".
Applying the same logic here, what if you change the title to a statement instead of a question? For example, instead of "Continue Editing?", you could say "You're editing events".
And then the following question could be "Do you want to continue editing?" with the answer options being "Yes" and "No".
Now read the whole thing again. It is more conversational and flows nicely.
Hope that helps.
Answer: Answer given above is excellent, I just want to notice, that in iOS apps, you should avoid using YES/NO answers in alert view.
You can find it in HIG

Use "OK" for a simple acceptance option if there is no better
  alternative. Avoid using "Yes" or "No."

I believe, that the reason for this is that user really have to understand the question until he is sure which one to select.
Read HIG especially part designated for Alerts, you can find answers to all your questions ;) iOS Humant Interface Guidelines


Strange window popping on Gnome

Question: A couple of days ago, when I came back to my computer after a couple of hours, the following window was on my desktop:

The title bar said "gnome-screensaver-dialog".  That's it.  I just clicked OK, and went on.
This has happened to me once before, but a long time ago.
Please note, I just have the plain blank screen as the screen saver.
Answer: When you go away from the computer it lock.  On the unlock password screen there is a button so that someone can leave a message.  Is this a case of somehow a blank message got left?
Comment: I'll try it tonight and see what happens.  Thanks!
Comment: This is properly what happened, i just tried leving a blank message for my self and it showed up like that. This may be worth a feature request/bug report for the gnome team.
Comment: Spot on! Try locking your desktop - leaving a blank message and then logging back in.
Answer: this is exactly the intended behavior.
It is there just in case someone needed you (or your computer) "while you were out". This way, they can leave you a message, without breaching into your computer for that.
Say you went to the restroom, and a co-worker wanted to have you look-up something for them, this way, they can just leave you a message and let you know without having to track you down or leave it on a post-it (which may not be available).
The only problem here is maybe we should have the devs add a title bar or other such information to the message that will let the user know it is a "while you were out" message, as opposed to just "something from gnome-screensaver".

Strange window popping on Gnome


Python: Converting a list of sets to a set

Question: I am working on a programming project involving DFAs, and I've come across an error I can't seem to figure out how to bypass.
In this section of code:
from DFA import *

def DAWG():
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
                'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                'y', 'z']
    f = open('lexicontest.txt', 'r')
    dictionary = list(f)
    accepts = []
    for i in dictionary:
        if len(i) >= 3:
            accepts.append(i)
    D = from_word_list(accepts, alphabet)
    newStates = frozenset(D.mn_classes())

I get this error:
Traceback (most recent call last):
 File "...\DAWG.py", line 31, in <module>
DAWG()
  File "...\DAWG.py", line 19, in DAWG
newStates = frozenset(D.mn_classes())
TypeError: unhashable type: 'set'

This is because the method mn_classes() returns a list whose elements are sets. I am looking for a way to convert this list into a set, but I cannot do so right now because sets must be hashable. If anyone could give me advice on how to convert this list into a set, it would be greatly appreciated.
I am using a DFA library designed by Andrew Badr found here and here. This is the code for the method mn_classes():
def mn_classes(self):
    """Returns a partition of self.states into Myhill-Nerode equivalence classes."""
    changed = True
    classes = []
    if self.accepts != []:
        classes.append(self.accepts)
    #nonaccepts = filter(lambda x: x not in self.accepts, self.states)
    nonaccepts = [x for x in self.states if x not in self.accepts]
    if nonaccepts != []:
        classes.append(str(nonaccepts))
    while changed:
        changed = False
        for cl in classes:
            local_change = False
            for alpha in self.alphabet:
                next_class = None
                new_class = []
                for state in cl:
                    next = self.delta(state, alpha)
                    if next_class == None:
                        for c in classes:
                            if next in c:
                                next_class = c
                    elif next not in next_class:
                        new_class.append(state)
                        changed = True
                        local_change = True
                if local_change == True:
                    old_class = []
                    for c in cl:
                        if c not in new_class:
                            old_class.append(c)
                    classes.remove(cl)
                    classes.append(old_class)
                    classes.append(new_class)
                    break
    return classes

Comment: On an unrelated note, please don't use `from x import *` unless you really need to. It creates ambiguity and potentially causes name collisions while offering no real benefit in most situations.
Comment: Instead do `import DFA`, then reference things as `DFA.function_name` (this is general preferred as it offers the most clarity). In some cases, one example being where the name of something might be too long to be convenient, `from DFA.sub_package.sub_sub_package import function_name` is also fine. There's a few other things like aliasing that can be done, but basically `import module_name` should be your bread and butter.
Comment: Do you want to convert the list of sets into a set of sets or into a set of whatever the elements of the sets in the list are?
Comment: What are you doing with the set? If you're just checking for redundancy, you can write any custom hashing function you want and then add the hashed results to the set.
Comment: @jwodder: I would like to use the list as a set of sets, so that I can create a new DFA with each state being a set of states. This DFA implementation stores the states as a set, so I would need a set of sets to create a new DFA.
Comment: @TimWilder: I am trying to use the set to create a new DFA whose states are each sets of other states.
And as for your suggestion, how else would I import all the information from the DFA.py file? I am fairly new to using Python so I apologize for any foolish errors in my code like that one.
Answer: Your mn_class code looks suspicious to me, especially classes.append(str(nonaccepts)) seems not to be a set in a list. Followint part is also dubious:
if next_class == None:
    for c in classes:
        if next in c:
            next_class = c

Answering the quesition your asked, "If anyone could give me advice on how to convert this list into a set" modulo "mn_classes() returns a list whose elements are sets" you can use DAWG approach, i.e. return list of frozensets in mn_classes:
return map(frosenset, classes)

Comment: I couldn't tell you about the validity of the `mn_class` code as I did not write this library and have not used it before attempting to use it on this project. I wish I understood it all better but I am basically winging it.

I tried your suggestion of using `return map(frozenset, classes)` and was met with the error `File "...\DAWG.py", line 22, in delta
    next = q+c
TypeError: unsupported operand type(s) for +: 'frozenset' and 'str'`

when it was doing the `pretty_print` function.
Comment: And this was after I added this code to the bottom of the program:
    `D = from_word_list(accepts, alphabet)
    newStates = set(D.mn_classes())
    #D.pretty_print()
    def delta(q, c):
        next = q+c
        if next in fwl:
            return next
        else:
            return sink
    N = DFA(newStates, alphabet, delta, '', accepts)
    N.pretty_print()`


How to play dota 2 turbo offline?

Question: I am new to Dota and I liked playing the Turbo mode. Also it is great for trying out new heroes. Is there a way to play Dota turbo offline with bots ?
Also, can I play the other unranked game modes like draft pick and mutation offline?
Answer: Without access to the internet:
You will need to use console commands to set up your game. Enable the console by right-clicking Dota 2 in your steam library, selecting 'properties', then typing "-console" in the 'launch options' field.
Open the console by using the default key of "\"
You can then input the commands below -- or save them as a config file to load up easily next time.
con_enable 1                                    //these are all just setup commands
sv_cheats 1
sv_lan 1
sv_hibernate_when_empty 0
dota_quit_on_hibernate_after_lobby 0
dota_quit_after_game 0
dota_bot_set_difficulty 3                       //these set bot difficulty:
dota_bot_match_difficulty 3
dota_bot_practice_difficulty 3
dota_bot_practice_gamemode 23                   //game mode selector
dota_bot_match_use_matchmaking 0
dota_bot_practice_start 1
dota_bot_match_solo 1
dota_bot_disable 0
dota_force_gamemode 23
dota_lobby_browser_selected_gamemode 23
dota_heropicker_ap_select_time 999
map dota                                        //actually starts the game

Save these commands in a text file, and name it turbo.cfg (or something else .cfg) Place the file in C:\SteamLibrary\steamapps\common\dota 2 beta\game\dota\cfg
or wherever your dota installation is located.
Start up dota, open the console, and type exec turbo or whatever you named your file. This will start a turbo game with bots for you.
Credit to u/aveyo for this information.
To change the bot difficulty: on the lines with dota_bot_something_difficulty, change the number to 0 for passive, 1 for easy, 2 for medium, 3 for hard, and 4 for unfair.
This will always put you on radiant team. I don't know how to allow selection of team.
Also, I tried mutation mode (game mode 24) but it did not seem to work. Hero picker screen said mutation, but nothing seemed different.

If you do have access to the internet
use the Custom Lobby Feature in the Play Dota tab.

Edit the options at the bottom:

Select Turbo mode (or captain's mode, all pick, mutation, whatever), and Fill empty Slots with Bots. You can customize bot difficulty separately for each team.

Start it up, and you're ready to go!
Comment: sorry for being REALLY late :) , it worked. Thank you.
Comment: Thanks @Roijan Eskor. Is there a way I can do this while being offline ? I can't create custom lobbies while being offline.
Comment: @VishnuVS I think so. Will test this when I get home this evening
Comment: @VishnuVS Added information to the answer.

How to play dota 2 turbo offline?


Cocoa/ObjC: high memory usage on loading a lot of images when GC enabled?

Question: I coded a simple picture viewer which just slides randomly through pictures in ~/Pictures.
For each new transition, I am creating and loading the NSImage, then create a new NSImageView and set it as a new subview and the old subview is removed.
This is basically all. The memory is constantly raising with every new picture and I wonder why. I would have expected that it would stay very low and always mostly constant.
I tried to debug it and the profiler tool doesn't find any leaked memory, so I guess it is still referenced or more complicated. Most memory is taken from the function ImageIO_malloc, though.
The full (relevant) code can be seen here (much simplified already -- most of the functionality removed, however the leak remains).
ARC is disabled.
The interesting bit: When I disable the ObjC GC, it is as expected. It stays (relatively) low.
Comment: ARC *and* GC? What, specifically, is your GC setting set to? And what mode is your screensaver module running under when you run it?
Comment: @PeterHosey: GC is set to supported. I run this code for testing purpose in an application bundle and not as a screensaver at all. But in both cases, I get the same behavior. But also, with my last edit to the question and a much more simplified test case, this might be irrelevant now.
Comment: You can run the code in ScreenSaverEngine itself from Xcode: http://www.mactech.com/articles/mactech/Vol.21/21.06/SaveOurScreens/index.html See under "Debugging Tips". The exact steps are different now, but the procedure overall is similar; the biggest difference is, in Xcode 4, you edit the scheme. Besides removing any possibility of a bug in your custom harness, this also will enable you to tell whether SSE still runs under GC or not.
Comment: @PeterHosey: Wether it runs as screensaver or not is not really related to my question. For testing purpose, I anyway have coded a standalone app around it. And for now, I would like to have the memory problem fixed in there.
Comment: Determining whether the screensaver is being run under reference-counting or GC is vital to doing that. It affects the set of tools available to you and the sets of possible problems and solutions.
Comment: @PeterHosey: In my app, I can just enable or disable the GC and/or ARC. It doesn't really matter. The leak is always there.
Comment: You can't be building that code with ARC as-is, because ARC won't let you call "release".

It doesn't look like you're releasing the NSString in "fn" to me...
Comment: @AndrewHodgkinson: He removed the `release` message in a later version of the code on GitHub. As for releasing `fn`: Either ARC or GC should take care of that for him.
Answer: did you try to set newImageView to autorelease?
Comment: Yea, just tried that, no difference. (And btw., shouldn't that anyway not really matter at all with ARC?)
Comment: yes but you never know, obj-c does always surprise you with mem leaks and undocumented issues/bugs :(
Comment: aahh, do you have NSZombie enabled? that could be the blame
Comment: What's NSZombie? You mean the memory debug option for ObjC zombie objects? That's disabled.
Comment: yes NSZombieEnabled is that option. That gave me kind of a headache once. because it collects all the objects and never release em, btw the ARC shall take care of releasing items when needed.
Comment: did you also try yo set nextImage = nil in your load function? maybe the release is not working b/c of ARC so setting it to nil will ensure the drop of the obj from the memory
Comment: I completely disabled ARC now.


How to make my small grid ship hover?

Question: I built a new flying miner, designed to scrape gravity-level layers off of things, mostly so I can cut into hillsides and build platforms, but also to shave boulders without leaving the landscape too ugly.
The drills are suspended on hinges, so that they can swing to an upright and locked position for takeoff/landing. Now that they're installed, however, I notice that my ship will fail to achieve a stable hover, and instead slowly glide to the ground.
I assume it's because the drills are on subgrids, and the fly-by-wire isn't factoring in their mass when determining how much thrust to apply to counter gravity, but it's definitely NOT because I don't have enough thrust - when I hit spacebar this thing leaps off the pad.
How do I get this thing to reliably hover? I don't want to use thrust override because when I start drilling, the mass of the drills will change and I'll begin descending, ruining the level flight path I want the drills to take.
Right now all I can think of is to install a script on it, but I don't know if a script already exists of if I need to learn C# and make one.  Anything I'm missing here?
Answer: I'm not going to accept this answer, because it's not complete, but I have found a hack-job answer to this:
First of all, thrust override is a nonstarter: if any thrusters have override set, the inertia damper completely shuts off (google for videos of cats having a leash put on for a graphical representation of what this is like).
Putting thrusters on the subgrid itself did the trick... sort of.  This is probably good enough for subgrids that remain aligned in critical axes with the root grid, but in my particular case the drills are on hinges with a 180-degree range of motion.  Slapping two thrusters on each drill - one pointed retrograde to the drillhead, the other prograde - and switching them on/off based on the orientation of the drills is the functional hack that I have going right now.
The process is: Fly with retrograde thrusters on and drills in upright position. Gain altitude over target. Turn off retrograde thrusters, activate hinges. Wait for drills to lock into downward, 'drilling' position.  Turn on prograde thrusters, descend to target and begin drilling.
The process is reversed once you're full of ore.
Obviously this isn't necessary for spacecraft, because you can move the ship in any direction so drill orientation becomes moot.

How to make my small grid ship hover?


Why file in public directory are not ignored?

Question: In my Laravel 5 project in root dir there is  a file .gitignore, which has rules:
/node_modules

/public/client_secret.json
/public/.htaccess

but running
git add .

command I see that 2 files above are in git modifications, but I expected they would be ignored.
Proposed url has a lot of options, I am not sure which is valid for me.
Which is right way?
Comment: Have these files been previously committed to your Git repo?
Comment: Possible duplicate of [How to make Git "forget" about a file that was tracked but is now in .gitignore?](https://stackoverflow.com/questions/1274057/how-to-make-git-forget-about-a-file-that-was-tracked-but-is-now-in-gitignore)
Comment: @JakeWorth - Of course they have; why else would get show them as modified (rather than new)?
Comment: Which 2 were not ignored? You can [edit] the question. Welcome to Stack Overflow btw!
Comment: Please note: the gitignore is case sensitive!
Answer:
Save your local and server files you want to exclude from git
Run at your local (in root of your app):
git rm --cached public/.htaccess
git rm --cached public/client_secret.json

After pushing these files would be removed, restore them
mannually
These files would be excluded from git
Answer: .gitignore only ignores untracked files.
Since these files show up as modified (not new) that means they are already being tracked, so you can't ignore them.
Some people will tell you tricks using index flags; this is not how they are meant to be used, and using them in that way will likely cause other problems.
If the files are not meant to be in the repo, you could remove them from the index and commit the removal.  This can be a bit risky, because git will think that part of what it should do when moving from an older commit to the now-current one is to delete the file from the working folder.  You could avoid that by editing history to look like the files were never checked in, but that requires coordinating a history rewrite with your team.  (You would use filter-branch most likely; you can search SO for existing Q&A that document this procedure thoroughly if you want more information.)
If the files are meant to be there, and you simply don't want to record when they change (because they contain local changes), then what I would do depends on the project's build tooling.  Generally I would set things up so that I didn't need to store the modified files in the work tree (or at least not in the checked-in copies of the filles).  Again I woudl search for existing Q&A that cover this topic in detail.


Change keyboard shortcut to "Run Script" in Atom IDE

Question: In the "Script" package, The keyboard shortcut to "Run Script" is shift+ctrl+b.
Does anyone know how to change this to a custom shortcut?
I have script 3.14.1 installed in Atom (with Windows 10 64bit)
Answer: go to "Settings", "Packages", find the "script" package and click "Settings".
at the top, select "View Code" button.

In the new window that pops up, expand the "keymaps" folder and open the "script.cson" file.
Find the shortcut for 'script:run' (line 15) and type in your preferred shortcut.
Save the file.
That's it!
Comment: Still ctr-b triggers 'fuzzy-finder:toggle-buffer-finder'. Is it because of native! ?
Answer: The previous answer (from mark jay) didn't work for me. What worked is using the keymap.cson of the atom editor:

And there just add, e.g. (to run with Alt-R):
'atom-text-editor':
    'alt-r': 'script:run'

Then it was working just fine. You can similarly modify any other Atom shortcuts here too.


clojurescript error on including google dependency

Question: I have cljs page where I require a google closure dependency -
<code>(ns pm.client.models
  (:require  [google.pubsub.PubSub :as pubsub]))
</code>
This is the error I see on the loading the html page. The error is logged in the browser's js console -
<code>goog.require could not find: goog.storage.mechanism.HTML5LocalStorage
goog.requireclient.js:96
(anonymous function)client.js:20191
client.js:98Uncaught Error: goog.require could not find: goog.storage.mechanism.HTML5LocalStorage
goog.requireclient.js:98
(anonymous function)
</code>
I dont see any error on compiling the clojurescript using cljs-build.
Comment: Is the cljs-build configured with :optimizations :advanced?
Answer: It looks like you don't have a Google Closure jar with the HTML5LocalStorage lib inside.
It might be either caused by some issues with paths to a third-party jar (unlikely since it's your project that requires it) or because the path (or the name) has changed in the release. Make sure you're not referencing paths from dev release but actually using final release.
Unpack the jar and grep around to see if/where HTML5LocalStorage is.