Getting error Index 0 requested, with a size of 0 in android Sqlite when want to select

Question: I have an android application using SQLite database. I have a CardView and has data like name, cost and description. My CardView has an option menu to input data and update it. When the option menu clicked it will go to another activity. In that activity, it has a TextView that will be showing a same name in CardView.
This my code of my DB
 public ModelPemesanan getnamap(int selectionn){
    SQLiteDatabase db = this.getReadableDatabase();
    String cb = "SELECT * FROM " + TABLE_PEMESANAN + " WHERE " + KEY_ID_PEMESANAN + "= '" + selectionn + "'";
    Cursor cursor = db.rawQuery(cb, null);
    if (cursor != null)
        cursor.moveToFirst();

    ModelPemesanan modelPemesanan = new ModelPemesanan();
    modelPemesanan.set_namap(cursor.getString(1));
    modelPemesanan.set_lapak(cursor.getString(2));
    modelPemesanan.set_desk(cursor.getString(3));
    modelPemesanan.set_lapak(cursor.getString(4));
    modelPemesanan.set_total(Integer.parseInt(cursor.getString(6)));
    modelPemesanan.set_resi(cursor.getString(7));

    db.close();
    return modelPemesanan;
}

In my class that I use to input data
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_resi);

    init();

    simpan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            modelPemesanan.set_namap(nama.getText().toString());
            modelPemesanan.set_resi(nores.getText().toString());
            db.updateresi(modelPemesanan);
        }
    });

}

private void init() {
    pilih = getIntent().getIntExtra("id_pemesanan", 0);
    db = new Database(this);
    modelPemesanan = db.getnamap(pilih);

    judul = (TextView) findViewById(R.id.tvmasukkan);
    nama = (TextView) findViewById(R.id.tvnamapembeli);
    nores = (EditText) findViewById(R.id.etnoresi);
    simpan = (Button) findViewById(R.id.btsimpannoresi);
    lapak = (TextView) findViewById(R.id.tvnamalapak);

    nama.setText(modelPemesanan.get_namap());
}

In my adapter class, I am using an intent to pass the value of the index.
 holder.pop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            PopupMenu popup = new PopupMenu(context, holder.pop);
            popup.inflate(R.menu.menu_list);
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    db = new Database(context);
                    final int selectionn = listpemesanan.get(position).get_idp();
                    switch (item.getItemId()){
                        case R.id.input:
                            Intent i = new Intent(v.getContext(), ResiAct.class);
                            i.putExtra("id_pemesanan", selectionn);
                            context.startActivity(i);
                            break;

I used a select query in my database. Here's my logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.daringku/com.example.asus.daringku.ResiAct}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2345)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2405)
    at android.app.ActivityThread.access$800(ActivityThread.java:155)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5376)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
    Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
    at com.example.asus.daringku.Database.Database.getnamap(Database.java:279)
    at com.example.asus.daringku.ResiAct.init(ResiAct.java:44)
    at com.example.asus.daringku.ResiAct.onCreate(ResiAct.java:28)
    at android.app.Activity.performCreate(Activity.java:6021)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2405)
    at android.app.ActivityThread.access$800(ActivityThread.java:155)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5376)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

And this my XML
 <TextView
    android:id="@+id/tvmasukkan"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Masukkan Nomor Resi untuk : "
    android:textSize="20sp"
    android:padding="10dp"/>
<TextView
    android:id="@+id/tvnamapembeli"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="17sp"
    android:padding="10dp"
    android:text="NAMA"
    android:layout_below="@id/tvmasukkan"
    />
<TextView
    android:id="@+id/tvnamalapak"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/tvnamapembeli"
    android:padding="10dp"
    android:textSize="17sp"
    android:text="NAMA LAPAK"
    />
<EditText
    android:id="@+id/etnoresi"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Masukkan Nomor Resi"
    android:padding="10dp"
    android:layout_below="@id/tvnamalapak"/>
<Button
    android:id="@+id/btsimpannoresi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/etnoresi"
    android:layout_centerHorizontal="true"
    android:padding="10dp"
    android:text="simpan"/>

Please help! Thank you.
Comment: Your query simply did not return any data. Also, don't assemble SQL statements like this (danger of SQL injection).
Comment: @Henry what will someone accomplish doing a SQL injection with Androids SQLite? The database is local and the user can anyway just get the database and modify it as he/she wants.
Comment: @HB even if there is not much damage done in this case it is bad habit to fall into. Imagine similar code used in other circumstances.
Comment: @Henry I can't think of any circumstance (with SQLite) that can cause any damage. I mean, if you use SQLite for what it was meant for (storing user data), SQL injection wouldn't bother me at all.
Answer: A size of 0 indicates that there are no extracted rows from which data can be extracted.
You should not attempt to extract data from a Cursor when there are no rows (you will get such an exception), as such you should check if there are any rows from which data can be extracted before trying to extract data from the Cursor.
Your code is checking a Cursor, returned from the rawQuery method, to see if it is null, probably in an attempt to avoid checking an empty Cursor. Checking for null is useless as a Cursor returned from the rawQuery method, even if it is empty, will not be null (it's count will be 0, if there are no rows).
You can check the number of rows using the Cursor getCount() method to see if there are 0 rows. However, the Cursor moveTo???? methods, such as the moveToFirst method, return true if the move could be made otherwise false. As you are using the moveToFirst method you simply need to check the result to see if the move was made, rather than check the number of rows.
As such you could use :-
public ModelPemesanan getnamap(int selectionn){
    SQLiteDatabase db = this.getReadableDatabase();
    String cb = "SELECT * FROM " + TABLE_PEMESANAN + " WHERE " + KEY_ID_PEMESANAN + "= '" + selectionn + "'";
    Cursor cursor = db.rawQuery(cb, null);
    ModelPemesanan modelPemesanan = new ModelPemesanan(); //<<<<<<<< MOVED HERE
    if (cursor.moveToFirst() {

        modelPemesanan.set_namap(cursor.getString(1));
        modelPemesanan.set_lapak(cursor.getString(2));
        modelPemesanan.set_desk(cursor.getString(3));
        modelPemesanan.set_lapak(cursor.getString(4));
        modelPemesanan.set_total(Integer.parseInt(cursor.getString(6)));
        modelPemesanan.set_resi(cursor.getString(7));
    }
    cursor.close() //<<<<<<<< YOU SHOULD ALWAYS CLOSE CURSORS WHEN DONE WITH THEM
    db.close();
    return modelPemesanan;
}

Note if there are no rows returned then the returned ModelPemesanan will will as it was constructed. So you should probably check it to determine if any data has been set.

However, the better/recommended approach, with android is use arguments to pass parameters (protects against SQL injection) and also the SQLiteDatabase convenience methods (builds the appropriate underlying SQL) when they can be used.
So the following would be recommended :-
public ModelPemesanan getnamap(int selectionn){
    SQLiteDatabase db = this.getReadableDatabase();
    String whereclause = KEY_ID_PEMESANAN + "=?";
    String[] whereargs = new String[]{String.valueOf(selectionn)};
    Cursor cursor = db.query(
        TABLE_PEMESANAN,
        null, //<<<< null = all columns, else String[] of columns to extract
        whereclause, //<<<< WHERE clause less WHERE keyword with ? for arguments (as per whereargs 1 for 1)
        whereargs, // <<<< arguments to replace ? placeholder on 1 for 1 basis
        null, // <<<< GROUP BY clause less GROUP BY keywords (null for no clause)
        null, // <<<< HAVING clause less HAVING keyword (null for no clause)
        null // <<<< ORDER BY clause less ORDER BY keywords (null for no clause)
    );
    ModelPemesanan modelPemesanan = new ModelPemesanan(); //<<<<<<<< MOVED HERE
    if (cursor.moveToFirst() {

        modelPemesanan.set_namap(cursor.getString(1));
        modelPemesanan.set_lapak(cursor.getString(2));
        modelPemesanan.set_desk(cursor.getString(3));
        modelPemesanan.set_lapak(cursor.getString(4));
        modelPemesanan.set_total(Integer.parseInt(cursor.getString(6)));
        modelPemesanan.set_resi(cursor.getString(7));
    }
    cursor.close() //<<<<<<<< YOU SHOULD ALWAYS CLOSE CURSORS WHEN DONE WITH THEM
    db.close();
    return modelPemesanan;
}

Your root issue is likely that the value being passed to the method, i.e. selectionn is not an existing id and thus you are extracting no rows. So you probably need to determine why this value is not matching any rows.
Comment: Thank you for you're answer. There is no error when I clicked the option menu. But in my textview that store a value it's don't show the value. What I must to do now?
Comment: @AnitaTata As per the last paragraph. You are likely not passing a value that matches an id in the table. You should tick this question as answered as it answers this question and then ask another question if you cannot ascertain why the value doesn't match a row.  *Hint put a breakpoint at this line `db = new Database(this);` run in debug mode and check the value of **pillih**. If that's not as expected then perhaps a breakpoint immediately after `final int selectionn = listpemesanan.get(position).get_idp();` along with checking the value of **selectionn** may show where the problem lies.*
Comment: In my post before, I try to passing a value that is a position of the cardview. Then i put in the variable 'pilih'. Am I wrong writing the code to using the intent?
Comment: @AnitaTata My guess is that you are not getting the correct value from the menu onClick (see 2nd part of hint in my previous comment).
Comment: @AnitaTata nothing wrong with using intent extras to pass data such as id's between activities. Does the item at that position have the correct id?
Comment: I know whats the problem. It's so embarrassing, I forgot to select the id of the value in my database. So it's passing a null value. Thank you so much for your help.


Is there any way a captured but non-ceded city can grow again?

Question: In Civ 6 an opponent has to cede a captured city to you for it to grow again.
Is there any way around this - including with Wonders or Civics or anything else?
I have now wiped out a civilization before he could cede his cities to me - am I now stuck forever with non-growing cities?
On a related note if you decide not to raze a city as soon as you capture it - is there any way to raze it later?
(I can see this leading to ridiculous anti-pattern moves like allowing a city to be captured so you can recapture it again and raze it).
On another related point if a non-ceded city is captured by a third party - do you need to cede it to them or does the original owner? And what if the original owner is dead?
Comment: I experienced that wiping out a civ automatically cedes all cities. Are you sure the growth-limiting factor is really occupation? (Not housing, for example)
Comment: I'm pretty sure thats not true... I'm almost positive I've captured cities that eventually grow again. The only thing is they tend to be unhappy for a while due to war weariness, but once that passes they are fine.
Comment: Hmm - do you have any idea how long this takes? Have you seen any documentation - would be interesting to know what the criteria is. When this happened had you defeated the civ completely? (perhaps that is a requirement for cities to grow again?).
Comment: The exact length depends on the situation. If you are no longer at war (doesn't matter if you defated the other civ) it goes back up faster.
Comment: Interesting. Hopefully some hard data on these timings will emerge. Having a permanently crippled city wouldn't be good.
Comment: I Captured Spains Capital, its only city. It has been growing since. (The war weariness was there for the start, cant remember how long though)
Comment: Now they do appear ceded - perhaps it just takes 1 turn to fix it. If you don't wipe them out what about then?
Answer:
I have now wiped out a civilization before he could cede his cities to
  me - am I now stuck forever with non-growing cities?

When a civilization is completely wiped out it automatically cedes all of their cities.

On a related note if you decide not to raze a city as soon as you
  capture it - is there any way to raze it later?

You must raze it immediately otherwise you need to get them to cede before the city will grow in population. As a side note you can force the city to grow with a worker removing resources such as the Jungle if it is close to another population in food.
NEW GAMEPLAY MECHANICS OR BUG FOR 'RISE AND FALL' EXPANSION
When making peace with an opponent the city automatically cedes even if you do not choose it in the trade screen. This is a major change, either they intended to remove the ceding system and forgot to remove it from the trading screen or they broke the ceding system.


Is there a recommended and consistent way of adding social buttons?

Question: I'm developing a small website which has half a dozen static text content pages and an image gallery, with one image per page/url (a dozen now, targeting a few hundred in the long run). I want to add social buttons, and it seems there are too many things to choose from. It's a simple website, I want my users to be able to use the most basic features, I don't want to make these buttons too visible or add too much to the page load time.
For Facebook, you can add a dynamic like button, share button and many others. By dynamic I mean that they count the number of likes/shares. You can also add a static share button, with your own design, by opening a certain sharing URL in a popup window.
Google+ has some similar things, a dynamic +1 with a counter, and the sharing popup window. And there are some other players, but I don't know any of them.
The different buttons are semantically different, they mean different things in different social sites, but I want a consistent behavior, if possible. Is there any guidance about that? If I want to add dynamic counter buttons, should those point to the main page of the website or each page individually?
Comment: and with "adding social buttons" you mean the dynamic or the static ones ? Because the dynamic ones are a service and a critical part of the branding of the given company, you are not allowed to modify any part of them, including the way they appear and work. So assuming that you are talking about the static ones, the trend now is to make them rounded, basically circles.
Comment: "Is there a recommended and consistent way of adding social buttons?" [It would seem that, according to Matt Mullenweg, the recommended way would be to avoid them](http://vimeo.com/17998118#t=832).
Comment: "I don't like" them is hardly a fair criticism.
Answer: Yes.
I just published Social Pins yesterday which provide exactly this: dynamic social badges with a consistent design.
Example to add a Tweet button: http://sopins.herokuapp.com/twitter/https://ux.stackexchange.com/pin.png
And this is what it renders like.
http://sopins.herokuapp.com/twitter/https://ux.stackexchange.com/pin.png http://sopins.herokuapp.com/twitter/https://ux.stackexchange.com/pin.png
(This IS a dynamic button)
Check out the full docs here: http://sopins.herokuapp.com/
Check out the source code here: https://github.com/karan/sopins
Comment: got a feeling this will be going against the brand guidelines for twitter, facebook, google+, etc. They like their social buttons styled a certain way.
Comment: why the downvote?
Comment: @Dave Haigh Can you provide a reference? I look at the feedly app in mobile and their share buttons are totally customized to the look and feel of the app
Comment: @Dave Haigh Did you mean the dynamic buttons must follow the branding guidelines? Good to see a reference..
Answer: A good example (I don't know if this is best practice) is Digg. They've picked three options, so the user isn't overwhelmed, and the options are clearly suggested and insitu, as opposed to ShareThis where the user has to dig around to find their preferred social button.
Comment: This approach feels a bit too "in your face" to me.
Comment: People still used Digg in 2014?
Answer: Yes, there is a recommended way, but not a consistent one
Unfortunately, that recommended way is probably not what you're expecting.  It's not a fixed layout (i.e. put buttons after the image, or in a console to the right).
Instead, it's a design approach that involves figuring out how you want to direct user flow across your content.

Typically, you will want to quickly visualize the desired user's workflow, which is something like: read title, look at image, decide whether to share.
That will help you figure out how to lay out your content.  The layout should promote smooth visual flow from the start to the end of the workflow.  This article has some notes on how users perceive and are influenced by layout flow.
In most viewing flows, social buttons should logically appear after the main content (or at least, after the user has read enough of the main content to make an informed decision on whether to share or not).

Sometimes sites put a permanent floating "share" console next to the content.  This can be effective too but users can often tune this out as background because they see it before they have a chance to read the content, so they cognitiviely dismiss it from the outset.

By focusing on your user flow instead of generic layout advice you are much more likely to figure out the right placement for your site.

Taking generic advice like "place the buttons at the bottom and make them square" is a little like taking a random drug prescription from a stranger without any regard for what your specific medical concerns are.
Answer: You'll be happy to learn that are a wide range of solutions to just this problem. Check out services like AddThis, AddToAny, and ShareThis. As their names suggest, they don't differ too much, but it's worth experimenting with each to find the one best fits your needs. You're asking for minimal functionality, and one may do a better job not pushing the glitter than the others. If none of them work, Google around, there are probably some other providers. Those are just the ones I know off the top of my head.


FSM to be regular with atleast two 0's and at most two 1's

Question: Is it possible to construct a FSM to prove that the set $X$ is regular, where
$$
X = \{s \in \{0,1\}^* \mid \text{$s$ contains at least two $0$'s and at most two $1$'s}\}\ ?
$$
Answer: It is possible, you could show it using regular expressions and closure properties.
Let $L_1 = (\Sigma^*\mathtt{0}\Sigma^*\mathtt{0}\Sigma^*)$ and $L_2 = (\Sigma^*\mathtt{1}\Sigma^*\mathtt{1}\Sigma^*\mathtt{1}\Sigma^*)$, then
$$X = \big\{s \in \Sigma^* \mid \#_\mathtt{0}(s) \geq 2, \#_\mathtt{1}(s) \leq 2\big\} = L_1 \cap L_2^c$$
If you want to construct the automaton, it could look like the one on the left side (the labels aren't provided intentionally, fill them out yourself).
$\hspace{50pt}$
Observe the connection between the left side automaton and a form of product of the two automatons presented at the right side (a state in the product is accepting only if both components are accepting states). In fact the left is $X$, while the right-up is $L_1$ and right-down is $L_2^c$; it's not a coincidence that the product of automatons and intersection of languages are connected.
I hope this helps $\ddot\smile$
Comment: i am trying to prove it by constructing a diagram of either  DFA or NFA
Comment: would the FSM have to be a DFA or an NFA. I keep trying to draw the diagram, and I always end up getting stuck
Comment: @user2510809 I've added a picture-hint.
Answer: You need to store in the finite state how many 0s and how many 1s have been seen.  So let the states be pairs of the form $\langle n_0, n_1\rangle$ where $n_0$ is the number of 0s and $n_1$ is the number of 1s seen so far, with $0\le n_0\le 2$ and $0\le n_1\le 3$.  The start state is $\color{green}{\langle 0,0\rangle}$.
On reading a 0, the machine makes a transition from $\langle n_0, n_1\rangle$ to $\langle n_0, n_1+1\rangle$, except that if $n_1 = 3$ it stays in the same state.  On reading a 1, the machine makes a transition from $\langle n_0, n_1\rangle$ to $\langle n_0+1, n_1\rangle$, except that if $n_0 = 2$ it stays in the same state.
The accepting states are exactly $\color{blue}{\langle 2,0\rangle},
\color{blue}{\langle 2,1\rangle}, $ and $\color{blue}{\langle 2,2\rangle}$ because these are the states where $n_0\ge 2$ and $n_1 \le 2$.


How do we play multiplayer minecraft on iPads?

Question: We have two iPads, and both of them have Minecraft PE. My son wants to connect the two and play with me. I have absolutely no idea what I am doing here, so I do not know how to do this.
One game says "Broadcast to LAN", and the other one says "Local Server Multiplayer". I have switched both to on.
What do I need to do to be able to play joined? We are both on the same WiFi.
Comment: Are you both on the same version? (Should say version at the bottom left of the title screen)
Comment: thank you, no we are not :P one is v0,12,2 alpha, and the other one is v0,12,3 alpha. Do I just update his then?
Comment: You'll need to update the one currently on 0.12.2, yep.
Comment: ok, done, thank you! What do I do now? Sorry, I have no clue! He made a new world, how do I find it?
Answer: Ensure :

You need to have Minecraft with the same version
You need to have the iPad connected to the same Wi-Fi
You need to have Broadcast to LAN turned on

Initiating

Load up your world on one of your iPad and turn Broadcast to Lan on
On the other iPad, click play and you should see the World name in the very bottom of the world selection menu including the hosting iPad IP. Click it to join

Doesn't work? Restart your iPad!
Comment: Thank you very much guys :) I figured it out! We had to turn the iPads' completely off, and restart, and now we are happy to go :)
Comment: Thank you, done everything you mention, but I am not able to find his world? It is not listed on my screen
Comment: In the settings, there should be an option to turn on Lan. Did you turn that on? I forgot to mention that into the answer
Comment: yes, both are on :) I have tried to go out of the game and back too, but I still do not get his on mine
Comment: Hold on a second! I'm testing things out. By normal, this should connect you both.
Comment: ok, thank you very much! I scroll down the list, and the name he made to his new world is not on the list. Does it need to be an old world?
Comment: @user128631 Make sure that the first user is still in the world you want to play on when the second user looks at the world selection list.
Comment: he is playing the game right now, and I am trying to find him, but it does not show on my screen
Comment: Same version, same Wi-fi and `Broadcast to Lan` on? Double check things out!
Comment: double checked, and everything is correct. It is same wifi, same update on the game, and both are on broadcast to LAN, and I still can not find his game
Comment: Well, I'm afraid I can't help you. I'm sorry. You can check this for what it supposed to do [Click me](https://www.youtube.com/watch?v=ElckEBo4frU)
Comment: Oh well. Normally, it doesn't need restart. But it will do! Don't forget tag this as a correct answer!
Comment: Don't know how to do that, but I will do my best. Thanks!
Comment: There should be a check mark on the left of my answer. Clicking it will mark my answer as a correct answer. Anywho, just ask more question if needed and answer if you know for sure!
Comment: A restart did the trick for us as well.
Answer: I had the same problem.. The problem was my router.. I had to enable a wifi guestzone, in the routers settings.. BTW the router is a DLINK DIR-865L.. I had 2 wifi connections, one 2.4 GHz and one 5 GHz connection.. NONE WORKED.. But when I enabled the guestzone, the 2 ipads found each other immediatly, when they both were connected on the guestzone wifi link.. Wich my router called dlink-guest.. Woked like a charm.. ;-)
Comment: I've seen a few flags on this question, and just want to remind folks that anything which [attempts to answer the question is an answer](http://meta.gaming.stackexchange.com/q/8357/8350). If you think it's a poor answer then downvote it, but don't flag it for deletion.


Can't open Terminal!

Question: I've customized the terminal to put a transparency. But I put a start command "dir" to see what happen, now I open the terminal ,he makes a dir and closes. Before I could to change the default profile .
How I can edit the profile o change to the Default profile?
Comment: for now, press control alt f1 to get a terminal
Answer: You need to remove the folder ~/.gconf/apps/gnome-terminal (where the profiles are stored), and log out and back in before opening the terminal again(!!).
If you open gnome-terminal before logging out/in, the existing profile settings will simply be recreated (including the error).
So:

remove the folder ~/.gconf/apps/gnome-terminal
log out and back in. You will lose the possible settings changes you made, but you will have your gnome-terminal back.

Note
from the GUI (nautilus) (since the terminal is not available :) )
~ stands for your home directory. If you browse (in nautilus) into your home directory and press Ctrl+H the folder .gconf becomes visible.

NB
This answer was written for 15.xx, no longer applicable from 16.04 and later.
Comment: There is no such directory
Comment: Downvote there is no such directory in 16.04. Please mention ubuntu version your solution is for.
Comment: Where is this directory?
Comment: @freaker see my updated answer.
Comment: @JulianLai nope, not in 16.04.
Comment: You should have mentioned the version. You can still mention it now.
Answer: By default, Ubuntu comes with 2 terminal emulators actually: one is gnome-terminal and the other is xterm, and as others suggested, there is always virtual tty consoles (which you can access through CtrlAltF3 , or really any f key from 1 to 6). Now, open xterm and run gnome-terminal -e 'YOLOSWAG' (note that  YOLOSWAG is just place holder, could be anything; the real purpose here is to bring up gnome-terminal complaining about a non-existent command being given to the -e flag, which stands for executing a command with gnome-terminal; read man gnome-terminal for more info on that). Now when you have gnome-terminal window open, you can right click and edit the profiles. Close the window (don't click relaunch) and reopen the gnome-terminal again.
In the image up above you can see that I've put custom command mkdir YOLO , which prevented the gnome-terminal window staying open (yes, in reality, your terminal was opening, just too fast and exited right away). I've called the terminal with the method described above.
Comment: Interesting idea :)
Answer: Before typing the following line: remember that Ctrl+Alt+F7 is your friend!  (This will bring you back here!)
Change to TTY2 with Ctrl+Alt+F2 and log in.
Install dconf-editor, because IMHO, a GUI is a good choice here:
sudo apt-get install dconf-editor

Now go back to TTY7 (normally) with Ctrl+Alt+F7.
Open the application with:
dconf-editor

and open this path in the tree:
org.gnome.Terminal.Legacy.Settings

Open the profiles as shown in the screenshot:

and revert your changes.
Done! :-)
Answer: if your gnome terminal isnt opening, try reinstalling it and if it doesnt work even then, install a different terminal emulator; i installed Konsole and it works just the same as the gnome-terminal. good luck.
Comment: This is a comment not an answer and should be posted as such.
Answer: Maybe something is wrong with your ~/.bashrc file, like containing

source ~/.profile

On my occasion, I just opened fish, and the terminal pops out correctly, then I checked my .bashrc file and deleted the wrong line.
Then the terminal is back to work again!
Maybe this way can help you, but please take it seriously, deleting wrong may have an effect on your system.
Answer: This is alternative software of built-in Terminal. I just copied suggestion form F1iX.
The alternative software is called "Termi-nator".
To install the software,

leave your graphical user session and switch to a plain terminal with CTRL+ALT+e.g. F3
Or ssh to the computer remotely (like ssh <user name>@<IP Address> at remote computer)
Log in and sudo apt-get install terminator
Switch back to your graphical session with CTRL+ALT+F1 or F2 (or other F-key depending on your setup)
Launch terminator
Optional (set as default: sudo apt update-alternatives --config x-terminal-emulator)

I had numerous issues such as Nvidia graphic card driver and Python version to Terminal malfunction, so instead of fixing and modifying them, I just installed the Termi-nator.

Can't open Terminal!


Can we specify a domain when redirect user to sign in with oauth2 in appengine?

Question: When we were using the UserService api, we can specify a domain when generate auth url. But when we switch to oauth2 (with google client library for java API), we are using AuthorizationCodeFlow.newAuthorizationUrl() to generate auth url, however we cannot specify any domain, so for example, if one customer already logged in with his gmail account in some other google sites, but he want to sign in our app with another google apps account, he has to  logout from google site since the authFlow always get the gmail account credential, we don't have a way to force him log in to a specific domain. We didn't have this issue when using UserService api.
Just want to know if there is any solution for this.
Comment: from the docs : Google Apps domains and appspot.com domains, including version-specific appspot.com domains, are supported. Note that authorization is associated with the domain used to access the endpoints: an access token produced using endpoints on one domain cannot be used to access the app using a different domain. If the access token came from a version-specific appspot.com domain, it can only be used to access that version of the app, and only at that domain.
Comment: Understand that the credential for one domain cannot be used in another. My problem is that we want to help customer to choose a proper account when sign in with oauth2. You know sometimes if user click the wrong account, or if he only logged in with gmail account but want to sign in with google apps account, he has to log out from google sites and login our app again which is not so convenience. We were using the appengine UserService API to generate auth url, and at that time we can speicify a domain so he will log in to the proper domain. I just want to check if we can do the same in oauth2
Answer: If you attach "hd=$domain" to the OAuth2 authorization request query parameters it will prompt user to login to that domain (if user not yet logged in) and/or optimize selection of the user's account in that domain.
Comment: Many thanks, it solved my problem. I found the oauth2 url parameters on google doc based on your answer, I didn't noticed that becaused I was using google client library for java and the "hd" parameter was not wrapped as "setXXX" method in AuthorizationCodeRequestUrl class. But now I can use AuthorizationCodeRequestUrl.put(field, value) method to set "hd" to restrict user login to specific domain now. Thanks again.


PES 2011 skills training

Question: While playing Pro Evolution Soccer 2011 ('Become a Legend' mode), under Personal -> Training I do not see any progress with respect to the skills I chose (in my case, 1-on-1) and the playing role (WF in my case).
Am I supposed to do something?
Answer: After selecting the new skill or role you want your Legend to learn you need to assign focus points to it (theres a bar just below the skill). A indicator for how many game weeks this will take to learn should appear next to it.
You may have to compromise focus points from your training in other areas to be able have enough to assign to the new skill training.

PES 2011 skills training


Filling gap beneath hardwood floor (between floorboard and foundation)

Question: There's a sizeable gap between the edge of hardwood flooring and the foundation by this fireplace:

You can see that the wooden base the strip of floor was nailed too ends about inch early:

As a result, many of the nails in the strip were justing stick out into space and the board is one bad step away from cracking in half. My first impulse is to cut shove a 2x1 in the gap so the board won't hang over the edge. Is there any reason not to do this? Is there a special kind of wood I'd want to use to avoid termite / other problems in the future?
Answer: That's a good solution if you can hammer the wood piece in tight enough and below the bottom of the flooring.
Also you could pour in a floor leveler to the same height as the existing floor. Once it's cured cut a strip of flooring so that there is a 3/8 inch gap between the piece and the fireplace apron. Glue it down with a construction adhesive.
You could also remove the trim pieces that frame the apron. Install wider trim pieces to cover the gap (leaving room for expansion). Apply colored caulking to fill expansion gap.


IF statement in mysql JOIN - Adding multiple conditions if condition success

Question: Here is the case:-
I want to join 2 tables. Lets say table a and b
SELECT *
FROM a
JOIN b ON a.id = b.id AND b.status = '1'

Here is the problem:
b.status = '1'

should only be added when
b.stage in (1, 3, 5, 6, 8)

How can I add such condition in ON clause ?
Like
ON a.id = b.id
CASE
   IF (b.stage in (1, 3, 5, 6, 8))
THEN
   AND b.status = '1'
END

Comment: well, you can always use boolean logic to bypass a clause like this: `AND ( b.status = '1' OR b.stage NOT IN (1, 3, 5, 6, 8) )`
Comment: Slight changes in question.
Answer: Your condition is logically the same as "either stage is not in the list or status is 1":
SELECT *
FROM a
JOIN b ON a.id = b.id
    AND (b.stage not in (1, 3, 5, 6, 8) OR b.status = '1')

Comment: Even after your slight changes, this query is what you want. Trust me. I've been coding SQL for 25 years *and* I studied Formal Logic as a subject in my degree.
Comment: @Sahal such queries can't be constructed within a pure sql-shell. Either use the boolean logic Bohemian and myself offered (and I still believe its exactly what you need) or you will need to let a "higher" logic (eg. stored procedure or any programming language) construct the query
Comment: I can not put `not in` there. Because I want (1, 3, 5, 6, 8) record also.
Comment: @Sahal its correct, you want to have those included, but only if they have b.status = 1. Its a "combined clause" and matches your requirements from your question
Comment: Can you be more specific? This query is exactly what you asked for. It is logically identical to only testing for `status=1` if `stage` is in the list.
Comment: Slight changes in question.
Comment: @Najzero I did some miss typo in my question. Please read after the text `LIKE`
Comment: @Sahal: Did you test this answer? It seems to be exactly what you asked for.
Comment: Hey @ypercube - I haven't forgotten about getting some examples together for that other question :)


How to get the object file in a static library with scons

Question: I am using scons to build my project. Now I got a problem.
I use
env.StaticLibrary('a', [a1.o, a2.o])
to get a static library "liba.a".
Now I pass "liba.a" to another part of my project, in the part, I will generate another static library named "libb.a", and this will merge "liba.a" with some other object files.
The code like this:
env.StaticLibrary('b', ['liba.a', 'b1.o', 'b2.o'] )
In this question
Linking static libraries, that share another static library  we know that we can not simply merge a static library into another static library, Because this may result in some symbol problems.
Now I want to solve this problem in this way:
First get the object file of 'liba.a'. Then merge this object files with new object files to generate the final 'libb.a'.
But I found I can not find a method or function to get the object files in a static library with scons.
Can anyone help me ?
Answer: Sounds like you just want to use the same object files for 2 different libraries.
You could do something like this:
env = Environment()

env.StaticLibrary('a', ['a1.o', 'a2.o'])
env.StaticLibrary('b', ['b1.o', 'b2.o', 'a1.o', 'a2.o'])

Additionally, instead of dealing with the Object files, you could directly specify the source files. In this case, SCons will only compile the source files once, as needed.
env.StaticLibrary('a', ['a1.c', 'a2.c'])
env.StaticLibrary('b', ['b1.c', 'b2.c', 'a1.c', 'a2.c'])

Also, remember that each SCons builder returns a list of targets (each being a SCons Node). The list may have one or several entries. So, for example, the following target variable will contain the library target, and all of the objects built:
target = env.StaticLibrary('a', ['a1.c', 'a2.c'])
for t in target: print str(t)

Comment: Thank you for your answer, it is helpful. I want to ask you one more question: Can you decompression a static library into some object files in SCons? I mean do like in command "ar -x liba.a".
Comment: @lee, you could do it by using the Command() builder or by calling os.system(). Use the 'AR' construction variable to get the 'ar' binary.. I dont understand why you would want to do this though, considering the objects used to create the library are available, either in the same dir as the source files, or in the variant_dir if you're using one.
Comment: Thank you again. I don`t want to do that in this way either, but in my company, I just take over a product, and in this product someone else just pass the static library to me, and I need to make a new static library within the former one. What is worse, I can not access the object file of the former one.
Comment: ,I found a way to get the source file of a static library. I have read the SCons.Node.Node source code, I found it has a attribution -- sources. It is a list which contains the object file address.


Presto SQL WHERE filter for a column that contains an array of structs

Question: In the following table, I want to filter for all rows that contain the name, Alice.
WITH data AS (
   SELECT  ARRAY[CAST(ROW('Bob') AS ROW(name VARCHAR))] AS users
   UNION ALL
   SELECT  ARRAY[CAST(ROW('Alice') AS ROW(name VARCHAR))] AS users
)
SELECT *
FROM data

+-----------------------------------------------------------------+
| users                                                           |
+-----------------------------------------------------------------+
| [{name=Bob}]                                                    |
| [{name=Alice}]                                                  |
+-----------------------------------------------------------------+

If users were a string I could say:
SELECT * from data where users like '%Alice%'
but users is an array of struct. array<struct<name:string>>
I'm executing the query on Amazon AWS Athena which uses Presto 0.172.
Answer: You can use one of the array-processing functions to select the relevant rows. any_match returns true if any of the elements in the array matches the given condition:
SELECT *
FROM data
WHERE any_match(users, user -> user.name = 'Alice')

Note that the answer involving CROSS JOIN and UNNEST only works if each array contains a single user.
Comment: The Presto version I'm using doesn't have `any_match`.

However, I found this: https://github.com/prestosql/presto/issues/1036

And, I changed this to: `WHERE contains(transform(users, user -> user.name = 'Alice'), true);`

That worked. :)
Answer: Something like this:
select t.*
from t cross join
     unnest(t.users) u(user)
where user.name = 'Alice';

I'm not sure what the "struct" looks like.  Perhaps you just want:
where user like '%Alice%'

Comment: This is more expensive than just checking in the array contains the name


Should I be worried, or is this a cosmetic issue? floor in 1935 apt building

Question: We live on the 4th floor of a pre-war, 1935 apartment building in NYC. On one outer wall, the oak floor is separated horizontally about 1/2" from the wall/baseboard. The floor is also little sunken all over the apartment, but that's not the issue. It looks like floorboard is missing, but its technically not. The wall is flat but must be pulling away. There is even an area where an ancient paper, dry-leaf-like material even sticks out at times! (see 2nd pic) What is that????
We've lived here 7 years with this problem, but i cant tell if it's getting worse or not. I just cant live with it anymore.
The white stuff in the cracks is boric acid i poured in after we started getting a waterbug vistor every night at the same time. The boric acid stopped it, thankfully, but it draws your eye right to the area.
The heater is just to the left of this area, and the floor and wall do get warm in one part. However, the area that has the biggest separation from the wall does not get hot at all, and is always cold to the touch.
I have zero DIY skills, and I dont even know who to call to fix this. Does it need "diagnosing" first? or will any "floor specialist" be able to fix this?
I want to know:
1) What is the world is holding the floor up, because when i shine a flashlight down, there doesnt seem to be anything connecting the floor to the outer wall!
I used to fill this crack with a piece of cardboard because its a perfect color match, but once a piece started falling in ( no subfloor here??), so i pulled it out, except for a piece in the corner.
2) Is this dangerous? Or can i just get something to fill this in?
3) How would i get a filler material like wood ( or cork?) to stay in place if theres nothing beneath it? I dont want to start ripping up my floor because one thing always leads to another in this building! And i'm sure there is lead paint underneath a few layers on my baseboards.
4) Could that ancient papery material sticking out be toxic/dangerous in any way? Anyone know what it is? I think my walls are lathe.
Here are the gruesome pix.
Thank you!!
Comment: My question is whether the floor is shrinking away from the wall or is the wall bowing out away from the floor.  The first case is annoying but probably not a serious problem.  The 2nd, however, could be a sign of an impending structural failure.  You indicated this is an apartment and by that I assume you mean you are a tenant.  In that case you may want to request that the landlord or the management company get someone to take a look.
Comment: it's an apt, but a co-op building, so i essentially own the apt. The superindendent didnt have much insight other than "fill it with matching floorboard".
Comment: When the building needs the brick repointed, or a pipe within a wall bursts, the co-op's main fund pays for it. But if i have to hire someone to rip up my floor to tell me whats happening under there - and its nothing, i dontknow. I honestly just want someone to stcikk a board in there if my floor isnt going to collapse. I just t=dont know how the board will stay up if there is nothing under it in that gap.
Comment: the paper is probably insulation; shredded newspaper soaked with boric acid (in water) as a fire retardant. i doubt it's dangerous, you likely have steel beams supporting the floors where you can't see. You can pull off the bottom trims and replace with something thicker to hide the gap.
Comment: i didnt know boric acid in paper was a fire retardant. It certainly didnt scare away the bugs before i poured it in there! I dont think i can pull off any part of the baseboard ( is that what you mean by trim?). Its been painted over for 80 years and will be a mess. I considered adding a quarter round but i'm afraid it will look ridiculous. also im worried about whats happening there...
Comment: @Whaddayathink So who is responsible for the structure itself?  I'm not familiar with a NYC co-op but it seems this may be more like a condominium where you own the space the but condominium association "owns" the structure and is responsible for its maintenance and repair.  Is there a "condo owners association" here?
Comment: Take a screwdriver and clean out the gap. The joists should run perpendicular to the floor boards and you should find them on 16" centers. If you don't find them, then (yikes? - or you're looking at the underlayment...) fill it with dark wood filler. If you do find them, you'll have to pull the baseboard and put a piece of flooring. *If your floor is going to collapse*, I can't say (but I doubt: is the house racked?), but you can either *fill at it* or *do it right*.
Comment: i'm too afraid to start scraping. I hadnt considerd that the joists would  be so far apart, so i can see how theyd be absent in the gaps. Its just weird that theres no subfloor or underlayment ( terms that are new to me). I think the floor is just sinking somewhat and pulled away from the wall. I really dont want to pull my baseboards, because theyve been painted over 100 times. id prefer to just slide a board in there, if possible! What type of specialist do i call? Are they just called floor specialists? any rec's for someone in NYC? Also, its an apt and i dont know what racked means- sorry!
Comment: boric acid won't repeal bugs, it has no smell. it will kill them if eaten or if powered granules cling to their oily skin and absorb. In terms of building up the trim, you might be able to find an additive combo that works. For example, i've see cove molding applied backwards, to hug an existing protruding ogee detail, on the back of that cove was affixed a shoe type molding. It sounds weird, but it looked fine once painted and caulked, and built up about 3/4". You might do the same with flat rectangular trim above your shoe, then something covering both the spacer and orig trim.
Answer: There are already so many elements to the original baseboards I think adding another one to the bottom, painted white, to cover the gap will look just fine. It will look different to the other walls but only minimally. fill the void with insulation first and lightly pin the new trim to the baseboard, not the floor.
It's a case of you'll know it's there, but it's unlikely anyone else would notice unless they have a particularly keen architectural eye!
My only caveat is to keep an eye on the problem just in case it is the outer wall bowing outwards. Don't forget the floor joists probably run into the wall so it doesn't want to be bowing outwards too much.
Answer: It almost looks as though that is not the original baseboard. My guess is that there were, at some point, baseboard radiators/heaters installed there and they were removed and replaced with something else, then they just slapped some plain baseboard where the heaters had been, not caring that it left a gap to the beginning of the flooring. It has been painted dozens of times since so it looks old now, but the way it doesn't really match well with the other moulding is what makes me think it was an afterthought.
Comment: Thanks, but this is the original baseboard. All of my photos are even of the same wall and baseboard. I can see how it looks different in some pix because of the angle, but the baseboard is the same all over my apt. i WISH this was the issue! . I have the orignal steam heater still intact as well. Thx for the idea though


Responsive design issues on Blackberry

Question: Note: the following issues are applicable only to blackberry - all other devices tested (multiple android models and iPhone OS) are not being affected by these issues.
Problem #1: Horizontal scrolling
I have the following meta tags in the head:
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=320, user-scalable=no" />

However, I'm still getting a huge side scroll - about twice the width of the page. I have overflow-x: hidden on the body and it's still scrolling regardless.
Problem #2: List floating issues
My navigation is comprised of an unordered list of links. I have the following css applied:
div#masthead nav ul li {
    background: #fff;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    display: inline;
    margin: 0 5px 5px 0;
    width: auto;
    float: left;
    text-align: center;
}

div#masthead nav ul li a {
    font-size: .9em;
    padding: 5px;
}

The width: auto is causing some problems on the blackberry. The links are stacking strangely:
https://i.stack.imgur.com/m0PXz.jpg (screenshot: top is how it looks on other phones, bottom is on the blackberry - please ignore the add this bar)
If I set a fixed pixel width on the li it solves the wrapping issue, but then doesn't give me a consistent margin-right after each list element.
Answer: Solution to horizontal scrolling:
I've just included a width: 100% on the body as well and this solved the horizontal scrolling issue.
Problem #2 still remains unsolved.

Responsive design issues on Blackberry


Image Filter by JHlabs in Android

Question: I applied several filter of androidjhlabs.jar and its work for me also.
Here is the filter that works:
GaussianFilter
ContrastFilter
InverFilter
GrayScalFilter
MarbleFilter
WeaveFilter
GainFilter
SolarFilter
HSBFilter
but i tried some other filter that cant give me proper output some image got converted into black some got converted into white that means i didn't know proper scale ,Randomness,Amount,Turbulence and Gridtype etc.
I tried water filter but its applied only in center point means not in hole image.
here is the code:
public static Bitmap setWaterFilter(Bitmap src)
{
int width=src.getWidth();

int height=src.getHeight();

int pixel;

WaterFilter filter=new WaterFilter();

int[] bittoarr = AndroidUtils.bitmapToIntArray(src);

int[] result=filter.filter(bittoarr, width, height);

Bitmap applied = Bitmap.createBitmap(result, width, height,

Config.ARGB_8888);

return applied;
}

and i passed source like this:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.px);
bitmap=Effects.setWaterFilter(bitmap);
im.setImageBitmap(bitmap);

Any one know how to solve it.means other filter also like BoxBlur,Crop also.
Comment: where it was imported in  AndroidUtils class
Answer: this is simple ;-) you just set more parameter to achieve you want like showen below for exaple:
use setRadius to set radius of your wave, use setCenter to point the center of wave, min value is 0 and max is 1 for width and height of your image source;
            WaterFilter waterFilter = new WaterFilter();
            waterFilter.setEdgeAction(TransformFilter.WRAP);
            waterFilter.setRadius(350.0f);
            waterFilter.setWavelength(8.0f);
            waterFilter.setAmplitude(0.6f);
            waterFilter.setCentre(0.5f, 0.5f);
            int[] src65 = AndroidUtils.bitmapToIntArray(inter);
            int width65 = inter.getWidth();
            int height65 = inter.getHeight();
            int[] dest65 = waterFilter.filter(src65, width65, height65);
            Bitmap destBitmap65 = Bitmap.createBitmap(dest65, width65, height65, Bitmap.Config.ARGB_8888);

Image Filter by JHlabs in Android


Convergence of characteristic function $\chi_{(n,\infty)}$

Question: I already know that $\chi_n := \chi_{(n,\infty)}$ converges (almost) everywhere to $0$, and I want to see if it converges almost uniformly too.
Fix $\varepsilon > 0$. It seems to me that $\chi_n$ does not converge in (Lebesgue) measure, because for any $N>0$, $n>N$ implies $\mu \{x \mid |\chi_n(x)| = 1\} > 0$. So by a theorem saying "convergence almost uniformly implies convergence in measure", the sequence $\{ \chi_n \}$ does not converge almost uniformly. Is this ok?
I also want to check the definition of almost uniform convergence too, and find a contradiction: if there were a set $E \subset \bf{R}$ such that $\mu(E) < \varepsilon$ and $\chi_n$ converging uniformly on $\mathbf{R} \setminus E$, then we require the existence of $N>0$ such that $n>N$ implies $\chi_n(x) = 0$ for all $x \in \mathbf{R} \setminus E$. I assume $E \subset (n, \infty)$ for otherwise the $E$ does not affect $\chi_n$ and $\chi_n$ does not converge almost uniformly. In some way I want to say that $(n, \infty) \setminus E$ still has nontrivial measure and hence no $N$ can ensure the almost uniform convergence. But I don't know how to formalise this (if it's even a good idea). Thanks in advance.
Comment: Why  not look at $$\sup_{x\in\mathbb {R} } |\chi_n(x) |$$for uniform convergence?
Answer: Your argument using convergence in measure is correct.
For the direct part, assume that $\left(\chi_n\right)_{n\geqslant 1}$ converges uniformly on some set $F$. Then $\sup_{x\in F}\left\lvert\chi_n(x)-\chi_{n+1}(x)\right\rvert\to 0 $ and since $\left\lvert\chi_n(x)-\chi_{n+1}(x)\right\rvert$ can take only the values $0$ and $1$, we establish the existence of an integer $N$ such that $\sup_{x\in F}\left\lvert\chi_n(x)-\chi_{n+1}(x)\right\rvert=0$ for $n\geqslant N$. Therefore, for each $n\geqslant N$,   $F\cap \left[n,n+1\right)=\emptyset$. This implies that the measure of the complement of $F$ is bigger than one (actually infinite) hence almost uniform convergence is not possible.


Issue with React Native Navigation

Question: I try to add React Native Navigation(StackNavigator) to my App, but it doesn´t work. I run:"npm install --save react-navigation" to add StackNavigator to my App, but  it is throwing error:
Starting Metro Bundler on port 19001.
Info
08:59
Tunnel ready.
Error
09:00
Unable to resolve "react-native-safe-area-context" from "node_modules\react-navigation-stack\lib\module\vendor\views\Stack\StackView.js"
Error
09:00
Building JavaScript bundle: error

Comment: what version of react-navigation are you using?
Comment: hello I`m using  V 4.3.9 of react-navigation
Answer: Please specify the react navigation version you're working with (I can update my answer for v5 too!). Assuming you're question is regarding react navigation v4,I'm trying to answer your question. Just installing the react-navigation package isn't sufficient(it requires some follow-up packages also to be installed). Follow these steps in order -
1) npm install react-navigation
2) Installing additional dependencies
(if using expo) expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view
(if using bare react-native setup) npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
Also, it seems that you want to create stack-navigator. For that, you have to install
npm install react-navigation-stack
After installing you can add the import as import {createStackNavigator} from 'react-navigation-stack';
Here is the official documentation (which has pretty clear steps to follow) : https://reactnavigation.org/docs/4.x/getting-started/
Answer: Sagar
I followed all the steps in order as you told, but React Navigation still doesn´t work.

Here is my App code :

// App.js

import React from 'react'
import Navigation from './Navigation/Navigation'

export default class App extends React.Component {
  render() {
    return (
      <Navigation/>
    )
  }
}

// Navigation/Navigation.js

import { createStackNavigator, createAppContainer } from 'react-navigation-stack'
import Search from '../Components/Search'

const SearchStackNavigator = createStackNavigator({
  Search: {
    screen: Search,
    navigationOptions: {
      title: 'Rechercher'
    }
  }
})

export default createAppContainer(SearchStackNavigator)

// Components/Search.js

import React from 'react'
import { StyleSheet, View, TextInput, Button, Text, FlatList, ActivityIndicator } from 'react-native'
import FilmItem from './FilmItem'
import { getFilmsFromApiWithSearchedText } from '../API/TMDBApi'
//Class Search/custome component
class Search extends React.Component {

  constructor(props) {
    super(props)
    this.searchedText = ""
    //initialise la page
    this.page = 0
    //initialise le nbr total des pages
    this.totalPages = 0
    this.state = {
      films: [],
      //gestion du boutton loading/boutton de charchement.

      isLoading: false
    }
  }

  _loadFilms() {

    if (this.searchedText.length > 0) {
      this.setState({ isLoading: true })
      //recup. tous les films correspendant au text tapé et incrinmente/ajoute une page achaque fois que le scroll est egale á 0.5
      getFilmsFromApiWithSearchedText(this.searchedText, this.page+1).then(data => {

          this.page = data.page

          this.totalPages = data.total_pages

          this.setState({
            //syntaxe E6 cici permet de creer une copie de chaque objet.Une copie de tableau de film deja recup,
            //et une copie des nouveaux films recup. de l´API
            films: [ ...this.state.films, ...data.results ],
            isLoading: false
          })
      })
    }
  }

  _searchTextInputChanged(text) {
    this.searchedText = text
  }

  _searchFilms() {
    this.page = 0
    this.totalPages = 0

    this.setState({
      films: [],
    }, () => {

      //vider le tab films
        this._loadFilms()
    })
  }
//fonction pour gerer le bouton de chargement
  _displayLoading() {
    if (this.state.isLoading) {//si les films sont en  cours de chargement affiche le bouton d´animation
      return (
        <View style={styles.loading_container}>
          <ActivityIndicator size='large' />
        </View>
      )
    }
  }

  render() {
    return (
      <View style={styles.main_container}>
        <TextInput
          style={styles.textinput}
          placeholder='Titre du film'

          onChangeText={(text) => this._searchTextInputChanged(text)}

          onSubmitEditing={() => this._searchFilms()}
        />
        <Button title='Rechercher' onPress={() => this._searchFilms()}/>
        <FlatList
          data={this.state.films}
          keyExtractor={(item) => item.id.toString()}
          renderItem={({item}) => <FilmItem film={item}/>}

          onEndReachedThreshold={0.5}
          onEndReached={() => {
              if (this.page < this.totalPages) {

                 this._loadFilms()
              }
          }}
        />

        {this._displayLoading()}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main_container: {
    flex: 1,
    marginTop: 20
  },
  textinput: {
    marginLeft: 5,
    marginRight: 5,
    height: 50,
    borderColor: '#000000',
    borderWidth: 1,
    paddingLeft: 5
  },
  loading_container: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 100,
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center'
  }
})

export default Search

// Components/FilmItem.js

import React from 'react'
import { StyleSheet, View, Text, Image } from 'react-native'

import { getImageFromApi } from '../API/TMDBApi'

class FilmItem extends React.Component {
  render() {

    const film = this.props.film
      //console.log(this.props);
    return (
      <View style={styles.main_container}>
        <Image

          style={styles.image}
          source={{uri: getImageFromApi(film.poster_path)}}
        />
        <View style={styles.content_container}>
          <View style={styles.header_container}>
            <Text style={styles.title_text}>{film.title}</Text>
            <Text style={styles.vote_text}>{film.vote_average}</Text>
          </View>
          <View style={styles.description_container}>
            <Text style={styles.description_text} numberOfLines={6}>{film.overview}</Text>
          </View>
          <View style={styles.date_container}>
            <Text style={styles.date_text}>Sorti le {film.release_date}</Text>
          </View>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main_container: {
    height: 190,
    flexDirection: 'row'
  },
  image: {
    width: 120,
    height: 180,
    margin: 5,
    backgroundColor: 'gray'
  },
  content_container: {
    flex: 1,
    margin: 5
  },
  header_container: {
    flex: 3,
    flexDirection: 'row'
  },
  title_text: {
    fontWeight: 'bold',
    fontSize: 20,
    flex: 1,
    flexWrap: 'wrap',
    paddingRight: 5
  },
  vote_text: {
    fontWeight: 'bold',
    fontSize: 26,
    color: '#666666'
  },
  description_container: {
    flex: 7
  },
  description_text: {
    fontStyle: 'italic',
    color: '#666666'
  },
  date_container: {
    flex: 1
  },
  date_text: {
    textAlign: 'right',
    fontSize: 14
  }
})

export default FilmItem

// API/TMDBApi.js

const API_TOKEN = "*******************";

export function getFilmsFromApiWithSearchedText (text, page) {
  const url = 'https://api.themoviedb.org/3/search/movie?api_key=' + API_TOKEN +
   '&language=fr&query=' + text + "&page=" + page
  return fetch(url)
    .then((response) => response.json())
    .catch((error) => console.error(error))
}

  export function getImageFromApi (name) {
    return 'https://image.tmdb.org/t/p/w300' + name
  }

Answer: I 've been facing the same kind of issue following this course at OpenClassroom where this cade has been extracted.
I've installed the dependencies ad Sagar suggested; but I 've also changed a bit the import of the react navigation module inside the code :

// Navigation/Navigation.js
import { createStackNavigator, createAppContainer } from
'react-navigation-stack'

that I have changed with :

import {createAppContainer} from 'react-navigation'

import {createStackNavigator} from 'react-navigation-stack'

As createAppContainer doesn't apear to be from React-navigation-stack.
I hope this could help ;-)
Kind regards,

Issue with React Native Navigation


understanding email validation using JavaScript

Question: I am new to JavaScript and found this JavaScript code in the internet that validates the given email (no issue with the code) -

Email Validation

<form name="form" method="post" onSubmit="return ValidateEmail()">
Enter an Email Address : <input type="text" name="email" size="30">

<input type="submit" name="Submit" value="Submit">
</form>

I have no issues with the code, but I somehow failed to understand what the regular expression /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ means. I don't understand what each and every part of regular expression means. Please enlighten me.
Comment: /^\w+([\.\+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)
Comment: ^^^^^^^^^^
Modified to be inclusive of the "+" character... for what it is worth. That allows the firstname.lastname@example.com format email addresses through.

...gmail allows you to append a "+anything" text chunk to your gmail account name. It isn't a gmail exclusive feature. No, I don't know an exhaustive list of which services allow it.
Comment: You think that's confusing...try this: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html. Validating an email w/ a regex is tricky...see: http://programmers.stackexchange.com/questions/78353/how-far-should-one-take-e-mail-address-validation
Comment: Notice - this regex will freeze your browser window if a long invalid email is passed to it.  See http://jsfiddle.net/ocqn35sm/
Answer:
The two forward-slashes /.../ contains a regexe.
The leading ^ and trailing $ match the beginning and the ending of the input string, respectively. That is, the entire input string shall match with this regexe, instead of a part of the input string.
\w+ matches 1 or more word characters (a-z, A-Z, 0-9 and underscore).
[.-] matches character . or -. We need to use . to represent . as . has special meaning in regexe. The \ is known as the escape code, which restore the original literal meaning of the following character.
[.-]? matches 0 or 1 occurrence of [.-].
Again, \w+ matches 1 or more word characters.
([.-]?\w+)* matches 0 or more occurrences of [.-]?\w+.
The sub-expression \w+([.-]?\w+)* is used to match the username in the email, before the @ sign. It begins with at least one word character (a-z, A-Z, 0-9 and underscore), followed by more word characters or . or -. However, a . or - must follow by a word character (a-z, A-Z, 0-9 and underscore). That is, the string cannot contain "..", "--", ".-" or "-.". Example of valid string are "a.1-2-3".
The @ matches itself.
Again, the sub-expression \w+([.-]?\w+)* is used to match the email domain name, with the same pattern as the username described above.
The sub-expression .\w{2,3} matches a . followed by two or three word characters, e.g., ".com", ".edu", ".us", ".uk", ".co".
(.\w{2,3})+ specifies that the above sub-expression shall occur one or more times, e.g., ".com", ".co.uk", ".edu.sg" etc.

Reference
Comment: In 8. this part is not entirely true -- "However, a . or - must follow by a word character" -- because you can have an email address where - is followed by @ -- for example like this firstname.lastname@example.com
Answer: Give a try here REGEX
you can find a detailed explanation.
Answer: Here's a break down of the regular expression piece-by-piece:

/^  => beginning of a line
\w+ => any word (letters, numbers, and underscores) repeated 1 or more times
([\.-]?\w+)* => a group of [an optional period (.) or dash (-) followed by any word repeated one or more times] that can be repeated 0 or more times
@\w+ => an at symbol (@) follow by any word repeated one or more times
([\.-]?\w+)* => a group of [an optional period or dash followed any word repeated 1 or more times] that can be repeated 0 or more times
(\.\w{2,3})+ => a group of [a period followed by any word that can be repeated 2-3 times] that can be repeated 1 or more times
$/ => the end of a line

By the way, here is a really good Introduction to Regular Expressions available on Codular.
Answer: Try this
E-mail: <input type="email" name="usremail">
It worked for me
Answer: here you go. a visualizer for regex
Regex Visualizer and A JS Fiddle Regex Explained
Answer: This validation code is WRONG for email addresses. In particular is does not allow addresses of the form email@example.com. This is widespread error found on many commercial websites (but not stackoverflow -- congratulations!).
Comment: /^\w+([\.\+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)

Modified to be inclusive of the "+" character... for what it is worth. That allows the firstname.lastname@example.com format email addresses through.

...gmail allows you to append a "+anything" text chunk to your gmail account name. It isn't a gmail exclusive feature. No, I don't know an exhaustive list of which services allow it.

Also, stop downvoting this Debbie Downer, he is spilling out truth. Maybe he is an asshole, but he is not wrong.
Comment: In order to allow longer TLDs (like `.domain`) I had to change the `{2,3}` to `{2,64}`
Answer: /^(\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+[,;]?[ ]?)+$/

this little beauty will allow you to enter one or more email addresses in a string, ending with a comma or semicolon, followed by an optional space.  :)
Answer: function validchat(){
    $('#btn-input-email').blur(function() {
        if($(this).val() != '') {
            var pattern = /^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i;
            if(pattern.test($(this).val())){
                $(this).css({'border' : '1px solid #569b44'});
                $('#valid').text('');
            } else {
                $(this).css({'border' : '1px solid #ff0000'});
                $('#valid').text('Не верно');
            }
        } else {
            $(this).css({'border' : '1px solid #ff0000'});
            $('#valid').text('Поле email не должно быть пустым');
        }
    });
    $("#btn-input-text").blur(function() {
        var textlength = $(this).val().trim().length;
        if( textlength < 2 ){
            $(this).css({'border' : '1px solid #ff0000'});
            $('#validtext').text('Минимум 2 символ');
        }else{
            $(this).css({'border' : '1px solid #569b44'});
            $('#validtext').text('');
        }
    });
    var valid = $('#valid').text();
    var validtext = $('#validtext').text();
    if((!valid || valid == '') && (!validtext || validtext == '')){
        return true;
    }
}
validchat();
function AjaxChat () {
    $('#btn-input-email , #btn-input-text').blur();
    var valid = validchat();
    if(valid){
        var email = $('#btn-input-email').val();
        var text  = $('#btn-input-text').val();

        var data = {
            email:email,
            text:text
        }

        $.ajax({
            url: location.origin+"/chat_block.php",
            //dataType: "json", ////Тип данных
            type: "POST",
            async: false,
            data: data,
            success: function(html) {
                if(!html || html == 'null') AjaxChat ();
                if (jQuery.html != "") {
                    var b_chat = $('.chat-customer').html();
                    var chat   = 'Вы: ';
                    var obj = $.parseJSON(html);
                    chat += '';
                    chat += obj['text'];
                    chat += '';
                    chat += '

';
                    $('.chat-customer').html(b_chat + chat);
                    $('#btn-input-text , #btn-input-email').val("");
                }
            },
            error: function() {
                //cosole.log('No result');
            }
        });
        $('#btn-input-email').remove();
    }
}


error in calling multidimensional array in cpp

Question: #include<iostream>
using namespace std;

void print_matrix(int* a, int row, int column)
{
    int i, j;
    for(i=0;i<row;++i)
    {
        cout<<"\n";
        for(j=0;j<column;++j)
        {
            int element= *((a+i*column)+j);
            cout<< element<<" " ;
        }
    }
}

int main()
{
    int row, column;
    row = column=3;
    column=2;
    int a[row][column];
    int i, j;
    cout<< "Enter the matrix\n";
    for(i=0;i<row;++i)
    {
        for(j=0;j<column;++j)
        {
            cin>> a[i][j];
        }
    }
    int* r = &a[0][0];
    print_matrix(r, row, column);
    **print_matrix(a, row, column); // error**

    system("pause");
    return 0;
}

the error is -- cannot convert int (*)[((unsigned int)((int)column))]' toint*' for argument 1' tovoid print_matrix(int*, int, int)'
Why do i get the error, as i think
the base address " a = &a[0][0] ", So i can call directly instead of having declaring a new int*r ?
Comment: `int a[row][column];` row/column are not const, that's invalid in C++
Answer: There are a few errors in your code.
To understand how pointers relate to multidimensional arrays, please refer to How do I use arrays in C++?, particularly multidimensional arrays and arrays of pointers. This will help you to understand what I have changed in your code to make it valid.
#include<iostream>

using namespace std;

template <size_t n>
void print_matrix(int (*a)[n], int row, int column)
{
    int i, j;
    for(i=0;i<row;++i)
    {
        cout<<"\n";
        for(j=0;j<column;++j)
        {
            std::cout << a[i][j] << " " ;
        }
    }
}

int main()
{
    const int row = 3, column = 2;
    int a[row][column];
    int i, j;
    cout<< "Enter the matrix\n";
    for(i=0;i<row;++i)
    {
        for(j=0;j<column;++j)
        {
            cin>> a[i][j];
        }
    }
    print_matrix(a, row, column);
}

Further to this, since you are using C++, you should avoid such static arrays and prefer std::vector (or Boost's matrix!) instead.


What are the best Screws for Brick for guttering (UK Building)

Question: My guttering I inherited when I moved it, finally has been blown off by Storm Henk.
What screws/anchors/plugs would be best for re-attaching it on an outside brick wall shown (Brick under the plastic trimming). This is a wall to a garage (converted to bedroom).
Current setup showing brick wall:

Current Screws - as you can see the current plugs didn't fit through:

Picture of wall:
Comment: Are you certain there's brick behind that metal fascia?  The existing screws appear to have some sort of plastic anchor?
Comment: Your "picture of wall" didn't quite make the cut. Please [edit] to add it in.
Answer: Two things you need to establish - 1) that there is actually brick behind that soffit & 2) how far in those anchors go. If there's brick, then longer anchors of the same type will be fine; the next size up if you want them to withstand the next storm, though as the last one managed to take entire roofs off in Manchester, you are going to be hard-pressed to be proof against that. Those anchors ought to be stronger than the gutter brackets if they're in the brick far enough & the original hole tolerance was good.
The reasoning behind using a large collared plug is so you're not squeezing the soffit against the wall - as there's usually a gap between it & the wall it's fixed to - but it does mean you need longer fixings to get enough of it into the wall itself. I'd go with something an inch longer than the current fixings.
It's hard to tell from the picture whether those are countersunk or mushroom head; I'd always be swayed towards mushroom head on plastic, countersunk if over-tightened can break the fixing. Square or Torx drive are much easier to use than cross-head [Phillips/Pozidriv].


make nautilus stop asking for password when mounting disk

Question: My desktop has another hard drive which I intend to use for data storage and the issue is that nautilus always asks for password when trying to mount that drive.
Same when I try and access the drive from the terminal, I get
ls: cannot open directory '/media/luca/Storage/': Permission denied

So basically, I always need to use sudo to perform file operations on this directory.
Now, is there a way to remove this restriction. How can I auto mount this drive without having to specify my password every time or having to use sudo every time I have to access files on this drive?
I am using ubuntu 18.04.
Comment: You can change the owner of the directory where the drive is mounted: `sudo chown -R luca:luca /media/luca/Storage/`. If you do an `ls -l` now it's probably owned by the root user.
Comment: glad it helped! posted as an answer.
Comment: Does this answer your question? [How to make partitions mount at startup?](https://askubuntu.com/a/375319/931617)
Comment: @guillermochamorro Thank you for the comment. The thing is it does mount it but asks me for password everytime I want to access it. How can I make it not ask for password everytime?
Comment: Thank you! This worked. Please write it as an answer so I can accept it :)
Answer: Change the owner of the directory where the drive is mounted to be your own user:
sudo chown -R luca:luca /media/luca/Storage/


required iPv6 compatibility - iOS app rejected by apple

Question:
after June 1, I submit my ionic app to itunes connect and I got the message from apple.
Apps are reviewed on an IPv6 network. Please ensure that your app supports IPv6 networks, as IPv6 compatibility is required.
For information about supporting IPv6 Networks, refer to Supporting iPv6 DNS64/NAT64 Networks.
For a networking overview, please see About Networking.
I have used AFNetworking for API call.
Please help to find out the solution for the same.
Thanks.
Answer: If you are using IPv4-specific APIs or hard-coded IP addresses, you will need to update your code, Although all NSURLSession and CFNetwork APIs(including NSURLConnection) already support IPV6
As mentioned by Apple:

At WWDC 2015 we announced the transition to IPv6-only network services
  in iOS 9. Starting June 1, 2016 all apps submitted to the App Store
  must support IPv6-only networking. Most apps will not require any
  changes because IPv6 is already supported by NSURLSession and
  CFNetwork APIs.
If your app uses IPv4-specific APIs or hard-coded IP addresses, you
  will need to make some changes.

Although. Apple also recommends not to use IP Address Literals, for long term (Not necessary)

Don't Use IP Address Literals

Make sure you aren't passing IPv4 address literals in dot notation to
  APIs such as getaddrinfo and SCNetworkReachabilityCreateWithName.
  Instead, use high-level network frameworks and address-agnostic
  versions of APIs, such as getaddrinfo and getnameinfo, and pass them
  hostnames or fully qualified domain names (FQDNs). See getaddrinfo(3)
  Mac OS X Developer Tools Manual Page and getnameinfo(3) Mac OS X
  Developer Tools Manual Page.
Note: In iOS 9 and OS X 10.11 and later, NSURLSession and CFNetwork
  automatically synthesize IPv6 addresses from IPv4 literals locally on
  devices operating on DNS64/NAT64 networks. However, you should still
  work to rid your code of IP address literals

If you are using AFNetworking Library, Please make sure to update it to version above 3.x, as they seem to have updated few of the things. --> AFNetworking Added support for IPv6 to Reachability.
For Detailed Info, please follow this link
Supporting IPv6-only Networks
ALSO, TO TEST
You can follow this detailed tutorial:
tutorial-how-to-test-your-app-for-ipv6-compatibility
Comment: I think, you should move over to AFNetworking latest release 3.1.0. They have updated few of the things. Added support for IPv6 to Reachability.-->   https://github.com/AFNetworking/AFNetworking/pull/3174
Comment: "Make Sure, you are not using IPv4-specific APIs or hard-coded IP addresses." Actually, this is not true. You can use whatever you want as long as your app works correctly on IPv6-only networks.
Comment: we have the same problem and we don't use AFNetworking. Our App is made with Cordova and is coded in Javascript and HTML. All webrequests are https requests for login. Our testscenario is like on this page: https://developer.apple.com/library/mac/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/UnderstandingandPreparingfortheIPv6Transition/UnderstandingandPreparingfortheIPv6Transition.html#//apple_ref/doc/uid/TP40010220-CH213-SW1

The only thing that is not IPV6 is the responding webserver. But if I understand the description right, the server don't have to be IPV6, too.
Comment: @gunjotsingh , I am using NSURLConnection for calling url , and getting nil response with IPv6 network , Please give me some solution for it.
Comment: thanks for reply. I am not using the hard coded IP Address in my app to call API. i have used http://www.xxxxxx.com/API/login.php , So now, what i have to change....?
Comment: Which API class or library are you using, for calling the URL? NSURLConnection or some other?
Comment: Yes, you are right! Thanks for pointing it out. I have updated my answer.
Comment: @BhaveshNayi, NSURLConnection works perfectly over IPv6 network. There should be some other issue behind nil response. Please try printing the NSError value.
Comment: @ DeeFour, you are right, Servers are not restricted to IPV6. DNS64/NAT64 translators already handles the access to IPV4 servers while  requesting from IPV6 network. Is your app working fine over NAT64 network, like mentioned in documentation?
Comment: @gunjotsingh connectionDidFinishLoading: is called but getting nil NSData response in IPv6 network , it's working fine in IPv4 network

json parsing code

    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions | NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:&error];

getting parsing error becauseof nil receivedData : The data couldn't be read because it isn't in the correct format

it's all working fine in IPv4 network , also in IPv6 connectionDidFinishLoading: called but why getting nil response ?
Comment: Can you please try opening google.com in your safari, while using IPv6 network? This could be an internet sharing issue.
Comment: @gunjotsingh my app is rejected. Reason: We discovered one or more bugs in your app when reviewed on iPhone running iOS 9.3.4 on Wi-Fi connected to an IPv6 network. We tested it in NAT64 network (setup from mac) and it's working fine , but Apple review team have an issue with IPv6 network.

Specifically, the app content failed to load.
Comment: @Bhavesh I will need to get my hands on your code, to verify! Can you please create a sample project, to replicate the issue?
Comment: @gunjotsingh  I have a same problem, I check with NAT64 network and its working fine and Apple is still rejected my app with same reason. Do you have any idea?
Comment: @ Nirmalsinh - Then, i think you should contact them for more issue details! If it is working fine for you on NAT64, then there is no problem!  FYI, if you any server response timeout issues in your app, then also they will report it as same issue.
Comment: I'm using Alamofire  '4.0' still apple rejected my app saying  **Please run your app on a device while connected to an IPv6 network (all apps must support IPv6) to identify any issues, then revise and resubmit your app for review.**
Comment: Nij, i don't think there is any issue in Alamofire 4.0, but app rejection could have been caused by some other part of your code!
Comment: @gunjotsingh i m not using AFnetworking in my app and still app store reject my app with this info information on how to symbolicate and read a crash log, please see Tech Note TN2151 Understanding and Analyzing Application Crash Reports.
Comment: @gunjotsingh i m using NSURLSession for call webservice in my app
Comment: @HimanshuMoradiya, In your case, App rejection seem to be caused by App  Crash and not because of ipv6 support. Please use this for reference https://developer.apple.com/library/content/technotes/tn2151/_index.html
Answer: Solution for Apple app rejection due to IPv6 Network
My internet reachability check for IPv6 is not working well.It always shows absence of network.when I use this code ,apple approved my app within 24 hours. THANKS
Change the following line in code in AFNetworking Library in Class AFNetworkReachabilityManager
CHANGE AF_INET TO AF_INET6;
<code>+ (instancetype)sharedManager {
    static AFNetworkReachabilityManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        struct sockaddr_in address;
        bzero(&address, sizeof(address));
        address.sin_len = sizeof(address);
        address.sin_family = AF_INET6;  //Change AF_INET TO AF_INET6
        _sharedManager = [self managerForAddress:&address];
    });

    return _sharedManager;
}
</code>
EDIT:
<code>$ grep -nr 'AF_INET*' .
./Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m:122:        address.sin_family = AF_INET;

replace

AF_INET; to AF_INET6;
</code>
Comment: You should not use reachability checks at all. http://stackoverflow.com/questions/12490578/should-i-listen-for-reachability-updates-in-each-uiviewcontroller#12490864
Comment: The apple recommended solution to this is to stop checking the internet access and handle the failures gracefully.
Comment: An observation: sockaddr_in stores IPv4 address, and if you put the sin_family (shared field in sockaddr_* structures) to AF_INET6, then the code that gets this as an argument, assumes the structure is the sockaddr_in6, which has larger size.
Comment: this worked for me. actually you need to change AF_INET to AF_INET6 in the whole workspace where ever you have used. great. thanks a lot for saving a lot of time.
Comment: I have a  problem when i check the internet access prior to hitting api.It always shows the messge of internet unavailable.
Comment: Best solution for apple app approval
Comment: Thanks mahesh Agrawal
Comment: @MaheshAgrawal Just fixing AF_INET to AF_INET6 resolved your issue?
Answer: Actually i am calling API using AFNetworking Library.
I have just replace the AFNetworkReachabilityManager classes from Github with my existing classes. And apple doesn't have problem any more.
And my app works now.
Comment: Is this something from a plugin or an ootb thing to change in cordova? where should it be changed?
Comment: I did it same. But apple is still rejected my app.
Comment: http://stackoverflow.com/q/43028924/285594 - still its refusing even its fixed in the APP.
Answer: Remove dot notation from API URL because IPv6 network not allowed dot notation in URL. I removed from API URL and its work for me.


Connection Pooling with VB.NET and orphaned connections

Question: I am a DBA, not a developer, and could use some insight. The development staff is using VB.NET to create web based applications with connections to a DB2 database. Please assume that the connection string in the web.config file is coded correctly.
I can see the number of orphaned connections from the web servers grow over time. By orphaned I mean that there is no activity associated with the connection for hours, yet I can see other connections being created and destroyed every couple of seconds.
I suspect that the connections are not being properly closed, but there are two different groups looking at the problem and so far haven't turned up anything. By the end of the day I can have hundreds of these connections - all of which are cleared when the application pool is reset every night. (This means it is NOT a database problem)
Is there a coding technique to ensure a connection is closed using vb.net on IIS v7+?
Am I seeing the symptom of another problem on IIS?
Comment: Any connections that are not released properly in the code will remain open until the user's [session times out](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx). People will become grouchy if you shorten that too much, but as a test you could shorten it a lot to demonstrate that there are abandoned open connections in the code that those pesky VB people need to root out. Everybody's session will likely get timed out when the app pool is reset (if they're using the default session approach).
Comment: In my experience, the other most frequent culprit is misuse of DataReaders (firehose cursors). Those must be manually [closed in code](http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx).
Comment: And finally, you might also find some expert guidance at the sister [DBA site](http://dba.stackexchange.com/)
Comment: Check with your developers and see if they're using `Using` blocks with the connections when they're doing database operations - the `Using` block will ensure the connection is closed and properly disposed.
Comment: Good points about the using blocks. However, in some situations the DataReader is returned to a calling method which reads the data and maps it into a custom object. In that case, you have to wait to close the DataReader later, after it has been read. This is often the source of connections left open, when the calling method reads the DataReader without closing it.
Answer: You need to have the developers implement the Dispose pattern, which is facilitated by the Using statement in VB.NET, like this (this is pertinent to SQL Server, but whatever connection object you are using for DB2 should work as well):
Using theConnection As New SqlConnection()
    '' Command, parameter logic goes here

End Using

By wrapping the connection object inside of a Using block, it will guarantee that the connection is closed and properly disposed of memory-wise, even if there is an exception in the code within the Using block.
Sounds like a code-review is in order for whoever is in charge of the developers.
Comment: I am having the Developers research the issue and so far they have not found anything in the code. The search continues...


Calculating the width of a font on screen

Question: --- CORRECTION: ---
I was using the correct method NSString sizeWithAttributes
 It appears my mistake was using the wrong attributes with it.
 FontDescriptor attributes have nothing to do with the size attributes used by this method.
I should have been using these attributes...
Attributes

I'm targeting iOS 8.  I'm on a MacBook with OS X 10.10
I've looked at countless stack overflow questions asking this question, and haven't found a single one that actually works, so I'm not sure why they are getting thumbs up. I've tried both depreciated methods, and current methods. I've tried all kinds of combinations and permutations of attributes with NSString sizeWithAttributes and nothing.
How do I know it's not working?  Because when I use a pixel measuring tool, the width it returns isn't nearly the width actually rendered on screen.
Also, the width returned is exactly the same regardless of what font size I use.
Here's some code I'm calling my sizing method with...
NSString *theString = @"Whose Your Daddy?";

CGFloat theResult = [self widthOfText:theString usingFontSize:[NSNumber numberWithFloat:12]];
NSLog(@"12 size = %f",theResult);

CGFloat theResult2 = [self widthOfText:theString usingFontSize:[NSNumber numberWithFloat:18]];
NSLog(@"18 size = %f",theResult2);

CGFloat theResult3 = [self widthOfText:theString usingFontSize:[NSNumber numberWithFloat:24]];
NSLog(@"24 size = %f",theResult3);

and here's the method that's evaluating the code above.  I left in 2 commented out variants fo the many many variants I tried ...
-(CGFloat)widthOfText:(NSString *)string usingFontSize:(NSNumber *)fontSize
{
    // UIFont *font = [UIFont systemFontOfSize:[fontSize floatValue]];
    // UIFont *font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:[fontSize floatValue]];
    NSDictionary *attributesDictionary = @{UIFontDescriptorFaceAttribute:@"HelveticaNeue-BoldItalic", UIFontDescriptorSizeAttribute:fontSize};

    CGSize stringSize = [string sizeWithAttributes:attributesDictionary];

    return stringSize.width;
}

Thanks
Answer: Here's my code which I use to calculate width of text, you just need to pass the text, font and maximum height supported as a parameter in the method and it will return you the perfect width value..
- (CGFloat)findWidthForText:(NSString *)text havingMaximumHeight:(CGFloat)heightValue andFont:(UIFont *)font {
    CGSize size = CGSizeZero;
    if (text) {
#ifdef __IPHONE_7_0
        CGRect frame = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, heightValue) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{ NSFontAttributeName:font } context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height + 1);
#else
        size = [text sizeWithFont:font constrainedToSize:CGSizeMake(CGFLOAT_MAX, heightValue) lineBreakMode:NSLineBreakByWordWrapping];
#endif
    }
    return size.width;
}

Try this method.. It works for me.. :)
Comment: Your's does actually work, and after researching it more, turns out mine WOULD have worked, but I was using the wrong attributes.  I noted that error in my original post above.
Answer: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *OptName_length = @" Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:17.0]};
CGRect rect = [OptName_length boundingRectWithSize:CGSizeMake(tableView.bounds.size.width-150.0, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:attributes
                                              context:nil];

CGSize requiredSize = rect.size;
return requiredSize.height +5.0f;
}

This is am used for tableview height you can also get width from this...
Change the CGSizeMake(tableView.bounds.size.width-150.0, MAXFLOAT) the value to your need.
For Height CGSizeMake(LablTextConstantWidth_InView, MAXFLOAT) // 50.0 some value
For Width CGSizeMake(MAXFLOAT,LablTextConstantHeight_InView)


London Underground Simulator won't start

Question: London Underground Simulator (World of Subways 3) won't start on my system! It worked earlier today when I changed the options and closed it. Now it shows as just a tiny window in the Top-Left of my screen.

System Specs:

AMD A6 6400K @ 3.9GHz, 6GiB RAM (1x 4GiB Crucial @1600MHz (Running at 1333MHz for compatibility) & 1x 2GiB G.SKILL @ 1333MHz), 1.75 TB storage (1x 750GB Seagate HDD @ 7200RPM, 1x 1TB Samsung HD103SJ @ 7200 RPM), ASUS GeForce GTX750 TI. Windows 7 Home Premium 64-bit

I have uninstalled and reinstalled DirectX 9 and 10 (Both required for the game) with no luck. If anyone can help me out, I would be grateful. I have attempted to reinstall the game (and the Aerosoft launcher required to launch it) twice. I have also tried moving the game from my 1TB HDD to my main 750GB HDD and updated the Aerosoft launcher from 126.96.36.199 to 220.127.116.11 with no luck.
I just upgraded to Windows 10 and it still doesn't work.
Comment: What options did you change...? Those could be important.
Comment: @DangerZone I changed the Texture Quality and Amount of Passengers. I have attempted to reinstall the game twice which made no difference.
Comment: I have edited the question to be less about DirectX 9 and more about that specific game. Unless other DirectX 9 games also show this or a similar behaviour, I'd assume it to be the game, not a graphics API.
Comment: I suggest checking places like `%appdata%` and "My Documents" (including subfolders) for files related to the game, especially things that look like config files (e.g. `config.ini`, `user.cfg`). It might be that the un- and reinstall did not remove your config files. Deleting those should in theory reset your options.
Comment: @MrLemon I started getting an error message after using Vista compatibility settings: Failed to load '\shaders\FixedFunctionShaders.ShaderLib' The Game Engine will not start
Comment: @MrLemon Checked the Documents and `%appdata%` . In the Documents, there was `WoS3` (the game brand) but it was empty. I have currently got the game an a 2nd HDD. I'm gonna install it on my primary - see if that makes a difference.
Comment: Well, reinstalling on a different HDD didn't work. I'm starting to think maybe there's a few registry keys from the game pointing to a old runtime of DirectX for something that isn't supported anymore and after I changed the settings, I needed to use the runtime to launch the game? Just an idea...
Answer: I have Windows 10 now. All I did was update Aerosoft (Which was downloaded when I got WoS3 on Wind. 8.1). I opened up the menu for the game, and said I had to activate it. So I put my code in (the one inside the CD case) and activated it online. When it had activated it, it said it was ready to play, and I was able to play it.