text:
Q: Stop Load data from .json if when data already load I have 2 fragment( Fragment A and fragment B) with functions to load data using .json.
When I click fragment A, the data will load, and when I click fragment B the data will load too.
When I click fragment A another time, the data is reloaded and duplicated (appended with the data from the first click).
How to stop loading data if data is already loaded?
example image
here my fragment code
fragment_a.java
public class fragment_a extends Fragment {
    // Log tag
    private static final String TAG = MovieFragment1.class.getSimpleName();

    // Movies json url
    private static final String url = "http://.......";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    public MovieFragment1() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_list, container, false);
        // Inflate the layout for this fragment

        final ListView listView = (ListView) rootView.findViewById(R.id.list);
        adapter = new CustomListAdapter(getActivity(), movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(getActivity());
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                if (obj.getString("tipe").equals("chest")){
                                movie.setTitle(obj.getString("name"));
                                movie.setThumbnailUrl(obj.getString("images1"));
                                //movie.setDescribe(obj.getString("describe"));
                                //movie.setRating(((Number) obj.get("rating"))
                                //        .doubleValue());
                                movie.setYear(obj.getInt("id"));
                                movie.setTipe(obj.getString("tipe"));

                                /*// Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);*/

                                // adding movie to movies array
                                movieList.add(movie);
                            }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

fragment_b.java
public class fragment_b extends Fragment {
    // Log tag
    private static final String TAG = MovieFragment1.class.getSimpleName();

    // Movies json url
    private static final String url = "http://......";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    public MovieFragment1() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_list, container, false);
        // Inflate the layout for this fragment

        final ListView listView = (ListView) rootView.findViewById(R.id.list);
        adapter = new CustomListAdapter(getActivity(), movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(getActivity());
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                if (obj.getString("tipe").equals("forearm")){
                                movie.setTitle(obj.getString("name"));
                                movie.setThumbnailUrl(obj.getString("images1"));
                                //movie.setDescribe(obj.getString("describe"));
                                //movie.setRating(((Number) obj.get("rating"))
                                //        .doubleValue());
                                movie.setYear(obj.getInt("id"));
                                movie.setTipe(obj.getString("tipe"));

                                /*// Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);*/

                                // adding movie to movies array
                                movieList.add(movie);
                            }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

tabfragment.java (fragment adapter)
public class TabFragment extends Fragment {

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /**
         *Inflate tab_layout and setup Views.
         */
        View x =  inflater.inflate(R.layout.tab_layout,null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 : return new fragment_a();
                case 1 : return new HomeFragment();
                case 2 : return new fragment_b();
            }
            return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "Chest";
                case 1 :
                    return "Movie";
                case 2 :
                    return "Forearm";
            }
            return null;
        }
    }

}

A: Just wrap your movieRequest with
if(movieList.isEmpty()){
    JsonArrayRequest movieReq = new JsonArrayRequest(url, ... ETC...
    // etc
}

But remember that with this approach your data will not update if it is changed on server, to make it updatable you must clear movieList before filling it every time instead:
movieList.clear();


text:
Q: Replace text at specific position in string using VBA I want to replace a substring (substring_a) with another substring (substring_b) within a string by specifying the position and length of substring_a.
I'm trying to use the Mid function, but it doesn't seem to work unless substring_b is equal to or longer than substring_a
Here is my code:
Sub Test_Mid()
Dim starting_text As String
Dim replacement_text As String

starting_text = "Long Starting Text"
replacement_text = "End"

Mid(starting_text, 6, 8) = replacement_text
MsgBox (starting_text)

End Sub

I want the code to return "Long End Text", but instead it returns "Long Endrting Text".
How do I fix this?
Note: The above is an illustrative example. I can't use the Replace function directly with the replacement_text because in my actual macro, replacement_text is variable.

A: You are making a simple thing overly complex. All that is needed is a simple replace.
starting_text = Replace(starting_text, "Starting", "End")

To replace just the 1st occurrence, use this:
starting_text = Replace(starting_text, "Starting", "End", 1, 1)

Or if it's just one occurrence, starting at a specific location, use this:
starting_text = Replace(starting_text, "Starting", "End", Instr(starting_text, "Starting"), 1)

Or if it's just one occurrence, starting at a specific location, and you dont want it to be case sensitive, use this:
starting_text = Replace(starting_text, "Starting", "End", Instr(starting_text, "Starting", vbTextCompare), 1, vbTextCompare)

VBA Replace Function

A: Below is my solution:
Sub Test_Mid()
Dim starting_text As String
Dim replacement_text As String
Dim replaced_text As String

starting_text = "Long Starting Text"
replacement_text = "End"

replaced_text = Mid(starting_text, 6, 8)
starting_text = Replace(starting_text, replaced_text, replacement_text)

MsgBox (starting_text)

End Sub

Note: For the example code here, @brax's solution is more efficient, but this code above shows how to replace text at a specific position (which is what I need for my actual use case).

A: Replacing a string in string in VBA is an easy taks, if Replace() is used.
Anyway, if Replace() is to be omitted, then it becomes more interesting. Theoretically, the string could be splitted always into 3 parts:

First Part - String To Replace - Last Part

Even when the FirstPart or/and the LastPart are with length 0, the division is to be made. Then, removing StringToReplace from the string completely and in its position, write the new string. The position is determinted with IsStr. It could be used as a function, using error handlers to return the initial expression, if the find is not part of the string:
Function Replace2(expression As String, find As String, replace As String) As String

    On Error GoTo replace2_Error

    Replace2 = expression
    Dim position As Long: position = InStr(1, expression, find)
    Replace2 = Left(expression, position - 1)
    Replace2 = Replace2 & Mid(expression, position + Len(find))
    Replace2 = Left(Replace2, position - 1) & _
                    replace & _
                    Right(Replace2, Len(Replace2) - position + 1)

    Exit Function

replace2_Error:
    Replace2 = expression
End Function

And the tests of the function:
Sub TestMe()

    Debug.Print Replace2("1", "", "")
    Debug.Print Replace2("1", "", "2")
    Debug.Print Replace2("", "3", "")
    Debug.Print Replace2("32", "a", "")
    Debug.Print Replace2("My Very Interesting Long Starting Text", "Starting", "Ending")
    Debug.Print Replace2("My Very Interesting Long Text Starting", "Starting", "Ending")
    Debug.Print Replace2("Starting My Very Interesting Long Text", "Starting", "Ending")

End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: An error with for loop I am working on problem of string manipulation.Following is my code snippet.
I am really not sure why my code control is not going inside IF loop.
public class test{

public static void main(String args[]) {
    Scanner scan = new Scanner(System.in);
    int searchVariable = scan.nextInt();
    int numberOfValues = scan.nextInt();
    scan.nextLine();
    while (numberOfValues-- != 0) {
        String strg = scan.nextLine();
        String[] arrayInt = strg.split(" ");
        for (int i = 0; i < arrayInt.length; i++) {
            //   System.out.println("test 1===");
           // System.out.println("i value" + i);
           // System.out.println("i " + strg.charAt(i));
           // System.out.println(searchVariable);
            if (searchVariable==strg.charAt(i)) {
                System.out.println("===>");
                System.out.println("index " + i);
                return;
            }

        }
    }
}

}
Input
4
6
1 4 5 7 9 12
Output
output should be 4.
As i am writing this code for finding integer 4 in the third line of input.
Problem
Program control is not going inside the loop if (searchVariable==strg.charAt(i))
.Please help!!

A: The is problem in your logic: What you actually want is
if (searchVariable==Integer.parseInt(arrayInt[i]))...

A: When java compares different objects, it checks different aspects, one of them is their type.
For example, the char '1' is different from the integer 1 and therefore '1'==1 will return false.
char c = '1';
System.out.println(c==1); //false

When comparing char to integer you should use parsing or the method Character.getNumericValue(c):
System.out.println(Character.getNumericValue(c)==1); //true

Also note that when java compares char to integer it uses the ascii value of the char, therefore ,char 'a' equals to the integer 97 and '1' equals integer value of 49: (and so on..)
System.out.println(c==49); //true


text:
Q: Are there no DNS entries for static pi-hole dhcp hostnames? A pi-hole instance is also acting as the DHCP server in my network. I assigned static IP addresses for some of my devices (eg. an octopi server with Hostname "octopi" and IP address "192.168.1.40"). The pi-hole domain name is set to "lan". But when trying to ping "octopi.lan" from my computer (where the pi-hole is set as it's DNS) the name cannot be resolved. Are additional configuration steps necessary?
Thanks!

A: Somehow the problem went away without changing anything - just waiting some hours.


text:
Q: Are "on" and "about" absolute synonyms? Are these two sentences synonymous?

I need your advice on this issue.
I need your advice about this issue.

Do they exactly mean the same thing? Or are there slight nuances between the two words? I always thought they were absolute synonyms unless they were used as part of a phrasal verb.

A: In the phrase you give, "on" and "about" are exact synonyms to my ears (USA).
Of course in other contexts, "about" and "on" are often very different. e.g. "sitting on the table", "laughing about a joke", etc.


text:
Q: ParseException trying to format date prior to insertion into database I am connecting to an Access 2010 database from eclipse using a jdbc:odbc connection.  I wrote a method to format date values before inserting them into a table in the database.  However, the stack trace is printing out the following when I try to run it:
java.text.ParseException: Unparseable date: "dateString"

Here is the line of code that calls the method, and which is firing the error:
ps.setDate(5,formatDate("10/1/2013"));//For October 1, 2013

Here is the method itself:
static Date formatDate(String dateString){
    java.sql.Date sqlDate = null;
    try{
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
        java.util.Date parsed = format.parse("dateString");
        sqlDate = new java.sql.Date(parsed.getTime());
    }
    catch(ParseException pe){pe.printStackTrace();}
        return sqlDate;
    }

Can someone show me how to fix this so that the data is parsed correctly before insertion into the MS Access database?

A: Remove the quotes from the parse method so that its using the dateString variable rather than a String literal
Date parsed = format.parse(dateString);


text:
Q: How can I grab a button's click event in a DaisyUI Collapse title? I'm trying to do something like this: https://stackblitz.com/edit/daisyui-sveltekit-furm6v?file=src%2Froutes%2F%2Bpage.svelte
Here's the code from it:

Daisy attempt

  <input type="checkbox" />

    Click me to show/hide content
    <button on:click|stopPropagation={() => alert('saved')} class='btn btn-error'>save changes</button>

hello

Native components solution

    Click me to show/hide content
    <button on:click|stopPropagation={() => alert('saved')} class='btn btn-error'>save changes</button>

  details

I'm not sure if/how to get the button's click handler to run. Any advice?
Thanks
I've tried using z-index but I suppose that's only for display not event handling.
I've tried stopPropagation on the button but that didn't work either.

A: So the issue right now is that the input element is covering the title div, which is why your clicks are not reaching the button. To fix this we can just change the order a bit and mess with the pointer events.
.collapse-title {
  z-index: 10;
  pointer-events: none;
}
.collapse-title button {
  pointer-events: all;
}

this will make sure that the title covers the input, but that clicks fall though to the input while not falling through the button.


text:
Q: Display encoded character python 3 on debian I would like to display the Multiplication sign on my consol with Python3.
His hexa code is D8 and he is encoding with ISO 8859-1 but all tests are negative.
Thanks for your help.
print(×) #(work on mac, doesn't work on debian)

I also try unicode('\xd7', errors='ignore') but nothing
(Sorry for my bad english)
EDIT: I also tried
b'\xd7'.decode('ISO-8859-1')

but nothing

A: No problem on Ubuntu 14.04:
$ cat /tmp/x.py
print("×")
$ python3.4 /tmp/x.py
×


text:
Q: Bypass ISP Block is there anyway I can bypass ISP block to access website? I'm aware of proxy online but the flash video cannot play. I tried using open source dns but it seems to still use ISP's proxy.

A: Any decent VPN provider can give you a VPN access with an IP outside your provider block.


text:
Q: What is Uri.LocalPath defined to do with non local paths? The docs for Uri.LocalPath don't say what happens if you feed it a non local path like http://stackoverflow.com/. Does anyone know of a source that gives the official spec for how it handle this?
I'm wanting to know what kind of gotchas and corner cases it might have so I can't be sure I've got thing right by just trying things.
(alternately does anyone known of a robust way to check if a Uri is or is not local? Particularly, is it something I can access via the file-system)

A: You're violating the pre-conditions by using it on a Uri that is not a "file name".  Thus, as I see it, it can return whatever it pleases.
To see if a Uri is a filename, use Uri.IsFile


text:
Q: jQuery: Grab the next  with a specific class in a table row I have this HTML structure (excerpt):

    <select id="test1" class="pub_chooser">
        <option value="99">All Publications</option>
        <option value="40">Contract</option>
        <option value="21">Student</option>
    </select>

    <select id="thing1" class="ev_chooser"></select>

This is hooked up to an AJAX function to populate the second <select> when an option is clicked.
I'm also allowing users to clone() the table row. I now need to target the second <select> in my AJAX function.
How can I reliably get the next .ev_chooser <select> element when the pub_chooser <select> is clicked?
I've tried this to no avail:
corresponding_select = $('select .ev_chooser').nextAll();

Any tips?
-Matt

A: This will give you the last select.
$('select.ev_chooser:last')

Or just search within the cloned element:
var clonedOBJECT = $(whatEverYouClone).clone();
var theSelect= $( 'select.ev_chooser', clonedOBJECT );

A: corresponding_select = $('pub_chooser').closest('td').siblings().children('.ev_chooser');

A: Get rid of the space in the selector:
$('select.ev_chooser')

If you have space between select and the class, it searches all children of select for any element with class "ev_chooser".


text:
Q: Consulta Sql para traer datos si existen o no segun la relacion Tengo todos los meses y en cada mes, hay unos datos (Matriculas), dado el caso que no haya datos en ese mes quiero que ese mes aparezca con un cero. Ésta es la consulta que tengo:
Select meses.mes as MES,
       SUM(cantidad) as MAT
       FROM vista_matriculas_todas
       join meses
            on meses.id = vista_matriculas_todas.mes_corte
       where vista_matriculas_todas.ano_inf = 2017
       group by vista_matriculas_todas.mes_corte,
                 meses.mes,
                 vista_matriculas_todas.mes_corte

Por ejemplo, quiero obtener este resultado:
Enero       174738
Febrero     0
Marzo       10344
Abril       0
Mayo        0
Junio       0
Julio       0
Agosto      0
Septiembre  0
Octubre     0
Noviembre   0
Diciembre   0

A: Si en meses tienes los 12 posibles meses de un año, esto es lo que podrías hacer:
Select m.mes                            as MES,
       SUM(coalesce(vmt.cantidad,0))    as MAT
       FROM meses m
       LEFT JOIN vista_matriculas_todas vmt
            on m.id = vmt.mes_corte
            and vmt.ano_inf = 2017
       GROUP BY  m.mes

*

*Nota que en vez de hacer un simple JOIN (inner) hacemos un LEFT esto nos asegura que independientemente que tengamos registros para dicho mes en vista_matriculas_todas, el mes seguirá apareciendo

*Lo único que resta hacer es en caso de no tener registros en un mes retornar 0 mediante SUM(coalesce(vmt.cantidad,0))


text:
Q: Quickest way to get squad points in COD: Ghosts? I'm having a hard time trying out different guns and equipment because I don't have enough squad points.  One trick I tried is unlocking different squad members in order to try different initial loadouts, but the selection is limited.
Is there a good way to get a lot of squad points quickly?

A: The only way I know of to acquire squad points (besides basically just playing) is by taking advantage of the Operations. By completing Operations you can earn extra squad points for each one completed. Depending on your style of play some will be easier and some more difficult, but if you really work at it they can significantly increase how many squad points you have.

A: Play local play where you set the game up yourself (team members, enemy bots, map choice), this mode allows you to choose from all weapons, attachments, perks, etc.. So try out everything ahead of time, before wasting your squad points!

A: To get more squad points playing squads try using the last perk on the bottom right hand corner with any sub.

A: Playing squads will earn you a lot more squad points than multiplayer.

A: I think playing Gun Game gives you 4 squad points every game.

A: Operations, field operations, just playing these are the main ways I get most of my squad points. I have around 320 right now.


text:
Q: How to pass map key in JavaScript method call? I am working on a task that requires to display a map key into an alert box.  How can I get the map key in the alert box.
I have tried the below code but I can't change the HTML.

    <c:forEach items="${sessionScope.trackingMap}" var="mcMAP">

          ${mcMAP.key}

        <%-- --${mcMAP.value} --%>

    </c:forEach>

This is JavaScript:
function setAmcValue(amc) {
   alert(amc);
   $("#mc1").empty().html(amc);
}

I want mcMAP.key as amc value

A: we just need to change
 onclick="setAmcValue(${mcMAP.value});" to onclick="setAmcValue('${mcMAP.key}');" and its start working.


text:
Q: Grouping certain rows into one row in sqlite This is the query that got me this result.
 SELECT
    country,
    COUNT(DISTINCT(customer_id)) total_customers
FROM customer c
GROUP BY 1
ORDER BY 2 DESC

    country   total_customers

1   India       2
2   Portugal    2
3   Argentina   1
4   Australia   1
5   Austria     1
6   Belgium     1
7   Chile       1

How can I group all the 1's  into a category Others?
Desired output:
   country   customers
1   India       2
2   Portugal    2
3   Others      5

A: Use case and group by, twice:
select (case when total_customers = 1 then 'Others' else country end) as country,
       sum(total_customers) as customers
from (select country,
             count(distinct customer_id) as total_customers
      from customer c
      group by country
     ) c
group by (case when total_customers = 1 then 'Others' else country end);

A: You need case with group by clause :
select (case when customers = 1 then 'Others' else country end) country,
       sum(customers) customers
from table t
group by (case when customers = 1 then 'Others' else country end);

EDIT : For instance the preceding query would be implemented with subquery.
But, for this you can do :
select (case when country in ('India','Portugal') then country else 'others' end) as country,
       count(distinct customer_id) as customers
from table t
group by (case when country in ('India','Portugal') then country else 'others' end)

A: You have to put your query in another query to aggregate again. GROUP BY a CASE, that returns the country or 'Other' based on the count. The ORDER BY gets a little tricky as you'd have to reuse the aforementioned case in it, to sort Others after all other countries. First check if the CASE returns 'Others', then returns a higher value, else a lower one. Then sort by the CASE.
It should look something like:
SELECT CASE x.total_customers
         WHEN 1 THEN
           'Others'
         ELSE
           x.country
       END country,
       sum(total_customers) total_customers
       FROM (SELECT c.country,
                    count(DISTINCT c.customer_id) total_customers
                    FROM customer c
                    GROUP BY c.country) x
       GROUP BY CASE x.total_customers
                  WHEN 1 THEN
                    'Others'
                  ELSE
                    x.country
                END
       ORDER BY CASE
                  WHEN CASE x.total_customers
                         WHEN 1 THEN
                           'Others'
                         ELSE
                           x.country
                        END = 'Others' THEN
                    1
                  ELSE
                    -1
                END,
                CASE x.total_customers
                  WHEN 1 THEN
                    'Others'
                  ELSE
                    x.country
                END;

(Untested, as no DDL or sample data was provided.)

A: Try this:
select case when customers not in ('India',
'Portugal') then 'Others' else country end as country,
       sum(customers) as customers
from t
group by case when customers not in ('India',
'Portugal') then 'Others' else country end


text:
Q: i don't want to use std::copy...his this the right for-loop alternative? i'm trying to not use STL. i have this line in my code:
std::copy(buffer_, buffer_ + size_ + 1, new_buffer)

if i want to NOT use copy, is this the right equivalent?
for (int i = 0; i < (size_ + 1); i++){
    new_buffer[i] = buffer[i];
}

or is that totally wrong? or is it off by one? or something else?
thanks!

A: Okay, the two code-samples you have will give the same result.
However, you will have an off-by-one error if you use size_ + 1. Just size_ is the correct value since it already points to one past the last element.

A: It's not clear whether what you wrote works. The copy version works if buffer_ is any random-access and new_buffer is any output iterator. Your manual version only works if buffer_ is a pointer.
Other than that, your manual version is functionally equivalent. If the types are POD, though, you could probably do better with memcpy (subject to checking for overlaps).
Note that your buffer, the way you wrote it, has size size_ + 1.

A: This is how I would do it, since it's easier to reuse with general iterators (much like std::copy), because the code that is specific to the iterator type (random access) is outside of the loop:
buffer_type* begin = buffer; // EDIT: buffer_type is whatever type buffer contains.
buffer_type* end = buffer + size + 1; // EDIT: usually this would be 'buffer + size'
buffer_type* out = new_buffer; // EDIT: don't want to lose the pointer to new_buffer!

while(buffer != end) {
  *out = *begin
  ++begin; ++new_buffer;
}

So you wouldn't have to change the loop if you decided to use some other type of iterator.
Some code checking utilities might complain about this because they think you are going to incur an access violation, but that's not the case since the last dereference happens before the last incrementing.
The choice of size for a variable name is kind of confusing here, BTW.  It implies that buffer + size would be one past the end of buffer, since you start labeling elements of an array at zero, but you start counting them at one, so the last element will be at index size - 1 typically.
Also, if you are going to use a for loop and the indexing operator you should use an unsigned int to index.  Negative indices are legal, but I don't think you intend to allow them here.


text:
Q: How to redirect page into iframe using jQuery On my website I have a jQuery script which fades in the body of page, and then when a user clicks on a relative link the body fades out and redirects the user to the new page and the script then starts again.
My colleague advised me it would be better to have the main content put into an iframe in order to stop having the whole body refreshing when changing pages, but the problem is that when a user clicks on a relative link the iframe fades out but instead of the new page targeting the iframe it just opens up the page.
How do I fix this? I think the error occurs after the line $("body").fadeIn(2000);.

    Home

A: Use document.getElementById("iframe").src to change the src attribute of the iframe, and setting it to the clicked link href.
Also you should get the href by using $(this).attr("href");

    Home

A: you can't change location of iframe window because many times it's not allowed. Due to security reasons
some websites set X-Frame-Options to SAMEORIGIN you can test this, just change
//your syntax is wrong here see below for correct

window.location = linkLocation
to
//correct way to change the location of iframe window

window.frames['yourframeName'].location=linkLocation
and 's link href to http://www.google.com
now see the error in the console.
hence your syntax is wrong you are not changing the location of your iframe you are changing loacation of your main page (window) which contains the targeted iframe. So the correction to get your work done is
function redirectPage() {
        $('iframe').attr('src',linkLocation);
        $('iframe').fadeIn()
    }


text:
Q: Android Geocoder *suddenly* not returning street address, only city I have some simple code to return an address from latitude/longitude coordinates.
It used to work just fine yesterday, nothing has changed, but today it returns the city instead of the street address.
I know I can dig deeper into the Address class and explicitly call getThoroughfare(), but that would just return null.
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
    List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
    return addresses.get(0).getAddressLine(0);
}

No emulators, Nexus 5.
Update: it's magic, today the geocoder is working fine again! Note that the longitude/latitude coordinates have remained exactly the same this whole time. Perhaps I'll rely on getThroughfare() to get the street address, but account for the fact that it may not return me a value.

A: This is due to a reliability issue in the Geocoder service.
The longitude/latitude coordinates have remained exactly the same in my unit tests, and from time to time only the city is returned instead of a full address.
Don't rely on the Geocoder service to always return a full address!


text:
Q: Why React Hooks Must Be Named With "use"? In the ReactJS docs, they specify this rule:

A custom Hook is a JavaScript function whose name starts with "use" and that may call other Hooks

I couldn't find any explanation for this naming convention, and why it has to be strictly enforced. Are there actual compile/transpile stages which depend on this naming? Is it an "aesthetic/semantic" guideline enforced with a heavy hand?


text:
Q: Angular select using ng-options and ng-selected I am having an issue with a select. I have a profile view that utilizes the profileCtrl. In that controller I get the users info from the db and put it into scope. I also use a service to grab all the info from the config table in the db and insert that into rootScope. My question and answers come from the config table (rootScope) the user's selected answer comes from the user info (scope). I need a select that preselects whatever answer the user has in the db. Below is my code.
Profile Controller:
app.controller('profileCtrl', function ($scope, $log, $http, $timeout, Data, Auth, dataShare, $sessionStorage, $rootScope, $confirm) {
    $timeout(function() {

      // get user's info from db and put it into scope
      Data.get('profile/'+$rootScope.user.uid).then(function(data){
        $scope.profs = data.data;
        $scope.buttonText = 'Update Profile';
      });

    }, 100);

    // get the configs from the configs service and put it in the rootScope
    dataShare.getconfigs().then(function(data){
        $rootScope.configs = data;

        // get the answers from the config table for the select's options
        $scope.availableAnswers = [
            { answer: $rootScope.configs[0].a1 },
            { answer: $rootScope.configs[0].a2 },
            { answer: $rootScope.configs[0].a3 },
            { answer: $rootScope.configs[0].a4 },
            { answer: $rootScope.configs[0].a5 }
          ];
    });

    // function executed on change from the select
    $scope.selectedItemChanged = function() {
      $log.log($scope.selectedAnswer);
    }

    // inline edit title
    $scope.updateUser = function(data) {
      Data.put('config/'+data.id, {profile_page_title:data.profile_page_title}).then(function (result) {
          Data.toast(result);
      });
    };

    $scope.saveProfile = function (profile) {

        profile.roles = $rootScope.user.roles;

        if(profile.uid.length > 0){
            Data.put('profile/'+profile.uid, profile).then(function (result) {
              $sessionStorage.user = profile;
              $rootScope.user = $sessionStorage.user;
              Data.toast(result);
            });
        }else{
            Data.post('profile', profile).then(function (result) {
              $rootScope.name = profile.name
              Data.toast(result);
            });
        }

    };
});

HTML: (I have condensed the code to be read easily)

{{configs[0].question}}

      {{profs[0].answer}}

      <select ng-model="selectedAnswer" ng-change="selectedItemChanged()" ng-options="a.answer for a in availableAnswers">

      </select>

A: Alright, so I made a plunk, and this is what I came up with. This will set the select option if the professor's current answer exists in the list.
The reason ng-init didn't work is because the selectedAnswer model is actually expecting to see an object with property 'answer'. In other words, selectedAnswer is the entire object, not just the answer itself.
https://plnkr.co/edit/CRraZXY2jsmiV1oJx6VN?p=preview
    $scope.profs = [
        { answer: 'answer2' }
      ]

    $scope.availableAnswers = [
          { answer: 'answer1' },
          { answer: 'answer2' },
          { answer: 'answer3' },
        ];

   angular.forEach($scope.availableAnswers, function(availableAnswer){

     if ($scope.profs[0].answer === availableAnswer.answer)
      $scope.selectedAnswer = availableAnswer
   });

-- Old Answer --

Have you tried ng-init?
ng-init="selectedAnswer = profs[0].answer"

A: I have made a very complex plunkr, I was a bit slower than @brianslattery I guess.
Here's my take:
https://plnkr.co/edit/5fnB6oWrZ9WhujN7eH0T?p=preview

{{configs[0].question}}

    Answer: {{profile.answer}}

    <select name="selector" ng-model="profile.answer" ng-change="selectedItemChanged(profile)" ng-options="a as a.answer for a in availableAnswers track by a.answer">

    </select>

The app will look something like this:
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($rootScope, $scope, $timeout, $log, $filter) {

  $timeout(function() {
    // get user's info from db and put it into scope
    $scope.profs = [ { name: 'prof1', answer: 'a3' }, { name: 'prof2', answer: 'a2' } ];
    $scope.buttonText = 'Update Profile';
    appendAnswerObjects();
  }, 100);

  // get the configs from the configs service and put it in the rootScope
  $timeout(function(data){
    $rootScope.configs = [ { question: 'Question?', a1: 'a1', a2: 'a2', a3: 'a3', a4: 'a4', a5: 'a5' } ];

    // get the answers from the config table for the select's options
    $scope.availableAnswers = [
      { answer: $rootScope.configs[0].a1 },
      { answer: $rootScope.configs[0].a2 },
      { answer: $rootScope.configs[0].a3 },
      { answer: $rootScope.configs[0].a4 },
      { answer: $rootScope.configs[0].a5 }
    ];

    appendAnswerObjects();
  }, 200);

  // function executed on change from the select
  $scope.selectedItemChanged = function(profile) {
    $log.log(profile);
  }

  function appendAnswerObjects() {
    if($scope.profs && $scope.profs.length && $scope.availableAnswers && $scope.availableAnswers.length) {
      $scope.profs.forEach(function(profile) {
        profile.answer = $filter('filter')($scope.availableAnswers, { answer: profile.answer })[0];
      });
    }
  }

});

There are several issues to consider.  NgOptions likes to use objects rather than values.  Also, your 'ng repeat' is calling for profs[0] instead of using the now repeated profiles variable.
Other issue to consider is that your 'answer' would not be 'profile dependent', but will be one for the entire scope, I'm pretty sure that is NOT what you want.
So, the plunkr I created makes individual answers for each.  It also takes into account the possibility of getting either the profiles first or the available answers first, no matter which comes first, which is, I believe, Important.
Let me know if this helps.
Best regards,
Rafa.


text:
Q: UITableViewCell odd coloring issue: Why does this work:
- (void)tableView: (UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath: (NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor redColor];
}

but this doesn't?
- (void)tableView: (UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath: (NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor colorWithRed:250 green:100 blue:100 alpha:1];
}

Am I thus constrained to the pre-defined UIColor colours?

A: use:
cell.backgroundColor = [UIColor colorWithRed:250/255.0 green:100/255.0 blue:100/255.0 alpha:1];

They need to be float.

A: The values you specify are invalid. Color channel values are floats in the range 0.0f..1.0f.


text:
Q: Create New Column and changes number into barcode I am working on something where I need Excel to create a new column, and in that new column, take information from the previous column and change the number so there are asterisks around it, and also change the font.
I have a barcode 39 font that works when there are asterisks surrounding a number. I am new to coding in VBA (coding in general) and this is what I have so far:
 Private Sub CommandButton1_Click()

Sheets("Material Data").Range("D2").Select
ActiveCell.EntireColumn.Insert shift:=xlDown

For a = 2 To 16

Worksheets("Material Data").Cells(a, 4).Value = Worksheets("Material Data").Cells(a, 3).Value

Next

End Sub

This creates a new column next to the existing one, and displays the existing numbers. I don't know how to make the new numbers have asterisks around them and have the font/size changed.
This is what the spreadsheet looks like. I basically need the material number to be turned into a barcode.
I know ="(asterisk)"&[MATERIAL]&"(asterisk)" adds the asterisks around the numbers. [can't actually put * or it will just italicize on stackoverflow]
Any help would be much appreciated!

A: Like this:
Private Sub CommandButton1_Click()

    Dim ws As Worksheet, a As Long

    Set ws = ThisWorkbook.Sheets("Material Data") 'use a worksheet variable
    ws.Range("D1").EntireColumn.Insert
    ws.Range("D1").Value = "Material Barcode"

    For a = 2 To 16
        With ws.Cells(a, 4)
            .Value = "*" & .Offset(0, -1).Value & "*"
            .Font.Name = "Arial" 'for example
            .Font.Size = 14
        End With
    Next

End Sub


text:
Q: What's the best way to test application API library in Ruby? Im developing a ruby API library for some web application (not rails based).
Library (in short overview) consists of the following objects:

*

*Client - main api class

*Request - module that handles all data transfers

*Item (record) - object with attributes (result of api operations)

Im having a hard time figuring out whats the best way to test such libraries?
Currently using RSpec2 and actual (live) requests. But also might use fixtures.
Any suggestions?

A: You can use WebMock to mock requests. It has RSpec helpers to aid you in your tests.
I haven't personally used WebMock, but once used Fakeweb to accomplish a similar task. The only disadvantage of using mock requests is that if the remote code changes,


text:
Q: Filebeat fails to start when output is set to file I am quite new to filebeat and the ELK stack. After succesfully building a Filebeat, Elastic and Kibana stack indexing apache access logfiles, I wanted to use Filebeat to send output to a file for testing purposes. However, I keep running into an error. Filebeat starts and then immediately exits again because it is looking for elastic.
The relevant part of the logfile is below.
2020-02-20T16:19:40.794+0100    WARN    beater/filebeat.go:152  Filebeat is unable to load the Ingest Node pipelines for the configured modules because the Elasticsearch output is not configured/enabled. If you have already loaded the Ingest Node pipelines or are using Logstash pipelines, you can ignore this warning.
2020-02-20T16:19:40.794+0100    ERROR   instance/beat.go:916    Exiting: Index management requested but the Elasticsearch output is not configured/enabled

Below is the filebeat.yml that is used.
#=========================== Filebeat inputs =============================

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - C:\Some\folder\*

#============================= Filebeat modules ===============================

filebeat.config.modules:
  path: C:\another\folder\*.yml
  reload.enabled: true

#------------------------------- File output -----------------------------------
output.file:
  enabled: true
  path: 'C:\Yet\another\folder\'
  filename: filebeat

I have also configured an apache.yml
- module: apache
  # Access logs
  access:
    enabled: true

    # Set custom paths for the log files. If left empty,
    # Filebeat will choose the paths depending on your OS.
    var.paths: ['C:\Some\Folder\2\Access*']

Filebeat keeps asking for the elastic output to be configured, but only one output can be configured at a time.
Is there a some option I need to set?
I am using Elastic stack 7.5

A: Probably Filebeat is trying to load template into Elasticsearch, but Elasticsearch output is not configured.
Disable automatic template loading  by adding following config to filebeat.yml file
setup.template.enabled: false

Hopefully, this will resolve your issue.

A: Apparently, kibana needs to be running for the output.file option to work.
After I started kibana.bat and ran .\filebeat.exe setup --dashboards. The error disappeared and filebeat could set its output to file.


text:
Q: Handle cancelled IAP transactions I'm using StoreKit for in-app purchases. I'm finding that the API is quirky in its behavior when the user presses the "Cancel" button.
For example, if I push Cancel on the "Confirm Your In App Purchase" screen, I get a SKPaymentTransactionStateFailed transaction with error.code == SKErrorPaymentCancelled as I'd expect.
But if I push Buy and then press Cancel, I get a Failed transaction with error.code == 0. The error.localizedDescription is "Cannot connect to iTunes Store" which is clearly a lie.
It's tempting to treat all Failed transactions as ignorable cancellations, but I can also clearly see that if the device is offline in airplane mode, I get a Failed transaction with no alert popup; I should really notify the user to explain the problem in that case.
I note that MKStoreKit assumes all failures are cancellations. MKStoreManager's failedTransaction method is never called; MKStoreObserver always calls transactionCanceled for all Failed transactions. The MKStoreManager.h comments recommend no error message for transactionCanceled, which makes sense, but then who will notify the user about Failed non-cancelled transactions?
What's the best practice for handling these failures? Should I swallow errors? Always show an error, even if it's redundant?

A: The previous answer is pretty close. MKStoreKit can automatically show error messages for valid error conditions like parental control turned on and such that.
Despite that, to handle purchase cancellations, I've also provided a delegate (starting from v3.5) called transactionCanceled in MKStoreKitDelegate.
Handle that and stop any activity spinners or progress hud on the view controller that makes the purchase call...

A: We have a pretty substantial user base buying stuff over mobile connections and only show alerts for
code != SKErrorPaymentCancelled && code != SKErrorPaymentNotAllowed

Apparently, it's the best you can do. I've also seen the weird behavior on cancellation that you mention, which is a framework bug as far as I can tell.

A: I just wanted to add that errors due to no internet connection should mostly be caught prior to any transaction using Apple's Reachability class IMO. This way you don't need to rely on Apple's API for a straight forward and common kind of error.

A: I think it's your responsibility and decision to where show the alert for cancelled transaction or not. But you should definitely finish it, otherwise it'll drop to Failed all the time. So should be something like this:
if (transaction.error.code == SKErrorPaymentCancelled) {
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} else {
    [self notifyError:transaction.error];
}

UPDATE:
Due to The Business of iPhone App Development: Making and Marketing Apps that Succeed we should finish transaction after any update to Failed state. Would be interesting to know if there are situations when we shouldn't.

A: Still have a one issue...
After clicking on Buy button it will show another Alert view and  ask about Account information.
if i did cancel there then it will goes into case SKErrorUnknown:
then
i cant show message like this
"Your purchase could not be completed. Please check your network settings and try again later."
- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
    switch (transaction.error.code) {
        case SKErrorUnknown:
            NSLog(@"SKErrorUnknown");
            break;
        case SKErrorClientInvalid:
            NSLog(@"SKErrorClientInvalid");
            break;
        case SKErrorPaymentCancelled:
            NSLog(@"SKErrorPaymentCancelled");
        break;
        case SKErrorPaymentInvalid:
            NSLog(@"SKErrorPaymentInvalid");
            break;
        case SKErrorPaymentNotAllowed:
            NSLog(@"SKErrorPaymentNotAllowed");
        break;
        default:
            NSLog(@"No Match Found for error");
            break;
    }
    NSLog(@"transaction.error.code %@",[transaction.error description]);
    if (transaction.error.code == SKErrorPaymentCancelled) {
        [[MKStoreManager sharedManager] transactionCanceled:transaction];
    } else {
        [[MKStoreManager sharedManager] failedTransaction:transaction];
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


text:
Q: Integrity constraint violation: 1062 Duplicate entry 'Portable tools' for key 'UNIQ_63B58042B36786B'" I'm trying to insert some data in a given table, i'm using Entity Repository to define a function that's create an entity if it's not existing, of find it if it's exist.
My entity file is as following:
             /**
      * SemanticTag
      *
     * @ORM\Table(name="Semantictag")
    *  @ORM\Entity(repositoryClass="VCycle\SemanticTagsBundle\Repository\SemanticTagRepository")
    */
    class SemanticTag
  {
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="title", type="string", length=255, unique=true)
 */
private $title;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="created_at", type="datetime")
 */
private $createdAt;

public function __construct()
{
    $this->createdAt = new \DateTime();
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set title
 *
 * @param string $title
 * @return SemanticTag
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string
 */
public function getTitle()
{
    return $this->title;
}

public function getNormalizedTitle()
{
    return mb_strtolower($this->title);
}

/**
 * Set createdAt
 *
 * @param \DateTime $createdAt
 * @return $this
 */
public function setCreatedAt(\DateTime $createdAt)
{
    $this->createdAt = $createdAt;

    return $this;
}

/**
 * Get createdAt
 *
 * @return \DateTime
 */
public function getCreatedAt()
{
    return $this->createdAt;
}
   }

my repositoty file is as follows:
      /**
 * SemanticTagRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
  class SemanticTagRepository extends EntityRepository
 {
/**
 * @param array $titles
 *
 * @return SemanticTag[]
 */
public function findOrCreateByTitles(array $titles)
{
    $Semantictags = $this->findBy(array('title' => $titles));
    /* @var $tags Tag[] */

    $SemantictagsCollection = array();
    foreach ($Semantictags as $Semantictag) {
        $SemantictagsCollection[$Semantictag->getNormalizedTitle()] = $Semantictag;
    }

    $normalizedTitles = array();
    foreach ($titles as $title) {
        $normalizedTitles[mb_strtolower($title)] = $title;
    }

    $SemantictagsToCreate = array_diff($normalizedTitles, array_keys($SemantictagsCollection));

    foreach ($SemantictagsToCreate as $title) {
        $Semantictag = new SemanticTag();
        $Semantictag->setTitle($title);
        $this->_em->persist($Semantictag);

        $SemantictagsCollection[$Semantictag->getNormalizedTitle()] = $Semantictag;
    }

    return $SemantictagsCollection;
}
}

I tried with:
        php app/console doctrine:cache:clear-metadata
        php app/console cache:clear

But it gives me always
            "message": "An exception occurred while executing 'INSERT INTO Semantictag (title, created_at) VALUES (?, ?)' with params [\"Portable tools\", \"2016-08-08 13:48:13\"]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Portable tools' for key 'UNIQ_63B58042B36786B'"

The other entity is as follows
               /**
   * Tag_Semantictag
   *
   * @ORM\Table(name="tag_semantictag",
   *     uniqueConstraints={
   *     @ORM\UniqueConstraint(name="UNIQ_tag_semantictag", columns= {"tag_id", "semantic_tag_id"})
   * })
    *  @ORM\Entity(repositoryClass="VCycle\TagsBundle\Repository\TagSemantictagRepository")
     */
   class TagSemantictag
   {
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="Tag", inversedBy="TagSemantictags")
 * @ORM\JoinColumn(name="tag_id", nullable=false, onDelete="CASCADE")
 *
 * @var Tag
 */
private $tag;

/**
 * @ORM\ManyToOne(targetEntity="VCycle\SemanticTagsBundle\Entity\SemanticTag")
 * @ORM\JoinColumn(name="semantic_tag_id", nullable=false, onDelete="CASCADE")
 *
 * @var SemanticTag
 */
private $semantictag;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="created_at", type="datetime")
 */
private $createdAt;

public function __construct()
{
    $this->createdAt = new \DateTime();
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

function getTag() {
    return $this->tag;
}

function getSemantictag() {
    return $this->semantictag;
}

function setTag(Tag $tag) {
    $this->tag = $tag;
}

function setSemantictag(SemanticTag $semantictag) {
    $this->semantictag = $semantictag;
}

/**
 * Set createdAt
 *
 * @param \DateTime $createdAt
 * @return Tag_SemanticTag
 */
public function setCreatedAt(\DateTime $createdAt)
{
    $this->createdAt = $createdAt;

    return $this;
}

/**
 * Get createdAt
 *
 * @return \DateTime
 */
public function getCreatedAt()
{
    return $this->createdAt;
}

}

A: You are doing another insert with the same combination of columns that are already in database. Some existing record has a Portable tools title. You need to create unique title for each entity you want to insert.


text:
Q: Android Studio gradle Received status code 400 from server: Bad Request When I tried to sync my project all libraries return 400 error code.
for example :
Error:A problem occurred configuring project ':app'.
Could not resolve all files for configuration ':app:classpath'.
Could not download gradle-retrolambda.jar (me.tatarka:gradle-retrolambda:3.7.0)
Could not get resource 'https://jcenter.bintray.com/me/tatarka/gradle-retrolambda/3.7.0/gradle-retrolambda-3.7.0.jar'.
Could not HEAD 'https://jcenter.bintray.com/me/tatarka/gradle-retrolambda/3.7.0/gradle-retrolambda-3.7.0.jar'. Received status code 400 from server: Bad Request

A: Check to see if the agent has been set up for your computer's C:\Users\***\.gradle gradle.properties file.Delete the last four lines if you have the following code.

systemProp.https.proxyPort=80
systemProp.http.proxyHost=mirrors.neusoft.edu.cn
systemProp.https.proxyHost=mirrors.neusoft.edu.cn
systemProp.http.proxyPort=80

A: for anyone who has my problem.i fixed the issue by deleting proxies was set in gradle.properties file


text:
Q: How to copy a file in using a string that has %UserProfile% in C# I am trying to copy a file using this -
 private void button1_Click(object sender, EventArgs e)
    {
        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        if (File.Exists(@"C:\Users\%UserProfile%\AppData\Roaming\.minecraft\bin\minecraft.jar"))
            try
            {
                File.Copy(@"C:\Users\%UserProfile%\AppData\Roaming\.minecraft\bin\minecraft.jar", @"C:\Users\%UserProfile%\Documents\MinecraftBackup\minecraft.jar", true);
            }

and it won't work unless I change %UserProfile% to my actual username, how do i fix this?

A: Instead of:
C:\Users\%UserProfile%\AppData\Roaming\.minecraft\bin\minecraft.jar

try
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
             @".minecraft\bin\minecraft.jar")

In fact, any time you see "C:\Users\%UserProfile%\AppData\Roaming\", you should use "Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)".

A: var s = @"C:\Users\%UserProfile%\AppData\Roaming\";
var s2 = Environment.ExpandEnvironmentVariables(s);

s2 has expanded data

A: The %userprofile% variable includes the full path, all the way back to the root of the drive.
C:\Windows\System32>echo %userprofile%
C:\Users\[myusername]


text:
Q: Python/Blender. ImportError: No module named 'ODS_Studio' I have put a python script ODS_Studio.py into /home/$user/Downloads/script_addon_2-7x/addons/ however Blender cannot load the ODS module.
File "/home/$user/Downloads/script_addon_2-7x/addons/ODS_Studio.py", line 65, in <module>
    from ODS import register, unregister
zipimport.ZipImportError: can't find module 'ODS'

Why can't it find the module if it's in the right spot?
###########################################################
# Blender Modelling Environment for Architecture
# ODS_Studio.py

import bpy
import os
import sys

def load_depends(depends):
    for depend in depends:
        # sys.modules[depend].__addon_enabled__
        if not depend in bpy.context.user_preferences.addons:
            bpy.ops.wm.addon_enable(module=depend)

def import_lib(path):
    lib = path.split("/")[-1]
    mod = lib.replace("ODS_Studio","ODS")
    mod = mod.replace(".a","")
    try:
        M = __import__(mod)
    except ImportError:
        print("Unable to import module %s"%mod)
    return None

def load_libraries(paths):
    for path in paths:
        for sPath in bpy.utils.script_paths():
            absPath = '%s/%s'%(sPath, path)
            if not os.path.exists(absPath):
                print("%s not found"%path)
                continue
            if not absPath in sys.path:
                print("Found library: %s"%path)
                sys.path.insert(0, absPath)
                import_lib(path)
                break
    bpy.utils.refresh_script_paths()
    return None

load_libraries(['addons/ODS_Studio.a'])

from ODS import register, unregister

if __name__ == "__main__":
    register()

A: The ODS Studio modules for Blender currently only work with Blender version 2.63a. Updates for the latest version of Blender will come in the next few weeks.
Ensure that you have downloaded the latest modules from here.
Ensure that you extract all of the *.py and *.a files into your 2.63/scripts/addons folder and not into a subdirectory.
Restart Blender and you should be able to activate the modules without a problem on any platform.


text:
Q: WebDriver.io no console output I am using the following stack to run several tests:
NodeJs
Selenium standalone
geckodriver thought I use chrome
webdriver.io
mocha
chai

So after all my first_test.js is:
describe ('Website url test ', () => {
  it('should have a title ', () => {
    browser.call((done) => {
      browser.url('http://webdriver.io');
      var title = browser.getTitle();
      expect(title).to.be.equal('WebdriverIO - WebDriver bindings for Node.js')
      done();
    })
  })

And the output in the console is:Incorrect console output

But it should be like this for the passing tests as well: Correct console output

Is something in Mocha config that I should change so that the passing tests would produce the same optical outcome?

A: This behavior was caused by the reporter chosen (in my case dot).
I changed to spec and I have a very verbose output now.

A: WebdriverIO supports a great variety of reporters:

*

*Dot: which is the default reporter for WDIO, a lightweight console reporter that outputs a green, or red dot ('.') for a passing, respectively failing test case;

*Spec: which just outputs in the console a step-by-step breakdown of the test cases you previously ran. This output will reside strictly in the console, unless you want to pipe your entire console log-stack via the logOutput: './<yourLogFolderPath>/' attribute from the wdio.conf.js file;

*Json: which generates a .json report of the tests your previously ran. It's very well suited for people who already have a test results dashboard where they analyze their regression results (passing tests, failing tests, run-time, etc.) and just need to parse the data from somewhere. You can configure the path where you want the .json report to be generated via:
reporterOptions: {
    outputDir: './<yourLogFolderPath>'
  }
Note: The Json reporter will populate the path given with WDIO-<timestamp>.json reports. If you want to pipe said .json to some other software for parsing, then you will need to go inside the library and change the naming convention so that you always get your results in the same file as opposed to a dynamically generated one.

*

*Allure: Allure is one of the best reporter choices, especially if you don't have the makings of a test results dashboard in place as it generates one for you. You can check out this answer for a step-by-step breakdown;

!!! BUT as a best practice, no reporter should outweigh the importance of setting your logLevel  (inside the wdio.conf.js file) to debug (logLevel: 'debug') for wdio-v5, or verbose (logLevel: 'verbose') for wdio-v4.
When debugging (I presume that was the reason purpose with the reporting), it's crucial that you get to the root of the problem in the fastest way possible and that is by looking at the REST calls made by your tests during run-time.
Hope this give a clearer overview to people starting with WebdriverIO and who need more info regarding which of these reporters is best suited for what scenario/situation.
Cheers!


text:
Q: Retry settings for subscriber in pubsub/spring-cloud-gcp-pubsub I have a spring service subcribing for messages from a topic in the google cloud pubsub (pulling).
I have tried to set those configuration in my profile config. like this to manage retries of messages:
spring:
  cloud:
    gcp:
      pubsub:
        subscriber:
          retry:
            max-attempts: 2
            retry-delay-multiplier: 5
            initial-retry-delay-seconds: 1
            max-retry-delay-seconds: 10
            jittered: false

The problem that i receive all messages all the time and it's not deleted after 2 retries like my configuration.
I tried with nack() message but it's not working

A: Per the Pull subscription Doc, you'll need to ack() the messages you receive using the returned ack ID so that the messages in the subscription will go away, or it will stay in the queue for up to 7 days and get deleted then.


text:
Q: Compiling and linking subproject library with CMake I have 2 projects (prj1 and prj2). One (prj2) depends on the other (prj1) that is a static library. I arrive to compile them separately with CMake.
But I needed to integrate one (prj1) to the other one (prj2). So I would like CMake to compile the static library (prj1) before the other (prj2) and then link the static library. I tried things, but id did not work.

*

*prj1 "core" is https://gitlab.com/RyDroid/PlanetWars2dRT-core

*prj2 "SDL2" is https://gitlab.com/RyDroid/PlanetWars2dRT-SDL2/ (see branch adding-core)

In prj2, externals/core is a git submodule (for non git users, you can see this directory as a copy-paste of prj1).
I tried (without success) this CMakeLists.txt in prj2 "SDL2":
cmake_minimum_required(VERSION 2.8)

if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR
    "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
  set(CMAKE_CXX_FLAGS       "-Wall -Wextra -Wformat=2 -Wpedantic -D_FORTIFY_SOURCE=2")
  set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
  # TODO
endif()

set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
# if (CMAKE_VERSION VERSION_LESS "3.1")
#   if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR
#       CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
#     set (CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
#   endif()
# else()
#   set(CMAKE_CXX_STANDARD 11)
# endif()

project(PlanetWars2dRT-SDL2)

# Version number
set(VERSION_MAJOR "0")
set(VERSION_MINOR "0")
set(VERSION_MICRO "0")

# Configure a header file to pass some of the CMake settings
# to the source code.
configure_file (
  "src/compilation_config.h.in"
  "${PROJECT_BINARY_DIR}/compilation_config.h"
  )
# Add the binary tree to the search path for include files
# so that we will find compilation_config.h
include_directories("${PROJECT_BINARY_DIR}")

set(LIBRARY_OUTPUT_PATH    lib/${CMAKE_BUILD_TYPE})
set(EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE})

include_directories(src/)
file(
  GLOB_RECURSE
  source_files
  src/*
  )
add_executable(planet-wars-2d-rt-sdl2 ${source_files})

#include(ExternalProject)
#ExternalProject_Add(PlanetWars2dRT PREFIX externals/core/)
include_directories(externals/core/src/utils/ externals/core/src/specific/)
add_subdirectory(externals/core/)
#find_package(PlanetWars2dRT-core REQUIRED)

include(FindPkgConfig)
pkg_search_module(SDL2 REQUIRED sdl2)
pkg_search_module(SDL2GFX REQUIRED SDL2_gfx)
include_directories(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS})
target_link_libraries(
  planet-wars-2d-rt-sdl2
  planet-wars-2d-rt-core
  ${SDL2_LIBRARIES} ${SDL2GFX_LIBRARIES}
  )

That is a simplified version of the tree of prj2:
.
├── build (with CMake stuff generated with "cmake ..")
├── CMakeLists.txt
├── externals
│   └── core
│       ├── build (with CMake stuff generated with "cmake ..")
│       ├── CMakeLists.txt
│       ├── makefile
│       └── src
├── makefile
├── README.md
└── src
    ├── compilation_config.h.in
    └── planet-wars-2d-rt-sdl2.cpp

How can I compile the library of prj1 "core" in prj2 "SDL2" with CMake, and then link the library of prj1 with prj2 (again with CMake)?
If your solution does not work with a non GNU/Linux OS, it is not a big problem. Note: my PC is running on Debian GNU/Linux 8 "Jessie".
Regards.

A: I cannot access your repo https://gitlab.com/RyDroid/PlanetWars2dRT-SDL2/, perhaps the servers are down for maintenance. If I understand your problem correctly, you may create a structure like that:
root/

*

*CMakeLists.txt // 1

*src/

*

*CMakeLists.txt // 2

*main.cpp

*SDL2/

*

*some sources

*CMakeLists.txt // 3

*core/

*

*some sources

*CMakeLists.txt // 4

In the CMakeLists.txt [1] you should declare your project name, required packages, common flags, include paths etc.:
cmake_minimum_required( VERSION 2.x )
project(name)

include_directories(inc inc/core inc/SDL2 inc/SthElse)

add_subdirectory(src)

In CMakeLists.txt [2] for subdir src you should declare your main executable and also add subdirs with your prj1 and prj2
 add_subdirectory(core)
 add_subdirectory(SDL2)
 add_executable(main main.cpp)
 target_link_libraries(main core SDL2 SomeOtherLib)

Finally, in your CMakeLists.txt [3] && [4] in your lib dirs you should declare static libraries:
 add_library(core STATIC ${YourSourceFiles})

This approach always worked for me. If you used to compile and run "core" and "SDL2" as standalone binaries, perhaps you will have to reorganize them a little bit.

A: Both project have a file "compilation_config.h". At compilation time, the wrong was taken so compilation failed, because the code used was #include "compilation_config.h" that was ambigous.
So I created a "include/project-name" dir in both project and I changed the include path : "prj1/compilation_config.h" or "prj2/compilation_config.h". Thanks to that there was no ambiguity anymore, so it works now!


text:
Q: How to prevent page "jump" if anchor is in the URL when page loads? How to prevent with jQuery default browser behavior, jump to anchor if anchor is in the link when page loads?
var myLink = document.location.toString();

if (myLink.match('#')) {
 $('html, body').animate({ scrollTop: 0 }, 0); // OR
 $(window).scrollTop();
}

Or.... can't find solution... searched... and searched

A: use return false / event.preventDefault on your links
var myLink = document.location.toString();

if (myLink.match('#')) {
    $('html, body').animate({ scrollTop: 0 }, 0); // OR
    $(window).scrollTop();
    return false;
}

Or do you mean that you want o smooth scroll to the position of the ID you are refering to in your hash sign?
after reading your comments ignore this message.
maybe like this: http://jsbin.com/ajafor/4#hello

A: link Text
$(function()
{
    $('a.link').attr('href','javascript:void(0);')
});

or add manually
link Text

A: I did this by including localScroll and scrollTo, then simply call:
$(function () { $.localScroll(); });


text:
Q: Access of Cookies on server side I am designing a web application front end I am making use of HTML and at back-end I am using a servlet.At front end side I am storing some values in cookies that are to be used on the server side (i.e in servlet)
Now my question is :  How do I get the values of cookies in servlets.
Please help me with this.

A: HttpServletRequest has method getCookies(), it will return you array of cookies, so just look for your cookie. I assume you already know how to set cookie using servelt response.

A: Cookies are sent with every request to the web app, and should thus be used very rarely. You should probably use request (get/post) parameters, and store values that must persist for a whole user session in the HttpSession object.
Now, to answer your specific question: everything coming from the client browser is stored in the HttpServletRequest object. Browse the javadoc for this class (part of the Java Enterprise Edition - Java EE javadoc), and you'll find a method named getCookies(). Follow the links, and you'll find how to extract the cookies you're interested in, and get their value.


text:
Q: Empty activity showing no screen on Android Emulator I've just begun Android development and set up my Android Studio and Emulator up with minimum version of the project API as KitKat and maximum version as Oreo (8.0). I created an empty activity to start of with and wanted to test it out but when I run it I only get the following screen (it is literally transparent):

I've already changed my emulated performance graphics to Hardware - GLES 2.0. I've also tried cold booting and cancelling the saved state but to no avail. Here are the other AVD settings:

I would appreciate any help as I am very eager to get started. Thank you!

A: Okay try to create a new virtual device.
And if then also it doesn't work then you can also run your application on your real device


text:
Q: FPC exitcode 201 while using ansistring. String does not do that I have a question. I wrote this little program and it was working perfectly, until I changed s and s2 from string to ansistring. I need to use ansistring, because it will be way longer than 255 characters. Thanks for your response.
    {$H+}
program Test;
uses Crt;
var s,s2:string;
    konec,radek:boolean;
    i,a,z:integer;
begin
  ClrScr;
  s:='';
  s2:='';
  i:=0;
  a:=0;
  z:=1;
  konec:=false;
  radek:=false;
  repeat
    s2:='';
    readln(s2);
    s:=s+s2;
  until s2='';
  while konec=false do begin
    while radek=false do begin
      a:=a+1;
      if length(s)+1=a then begin
        radek:=true;
        s:='';
        if a<60 then writeln(s2);
      end;
      if not (a=length(s)+1) then begin
      if s[a]=' ' then
        i:=a;
      s2:=s2+s[a];
      if not (s[a]=' ') then
      if a=60 then begin
        radek:=true;
        delete(s2,i,60-i+1);
        writeln(s2);
        s2:='';
        delete(s,z,i);
      end;
      if (s[a]=' ') and (a=60) then begin
        radek:=true;
    writeln(s2);
    s2:='';
    delete(s,z,i);
      end;
      end;
    end;
    radek:=false;
    a:=0;
    if (s='') then konec:=true;
  end;
  readkey;
end.

A: The core thing to know is that shortstring often has no problem with out of bounds string access (s[a] when a is not in the allowed range  (a>=1) and  (a<=length(s)) )
You set S to '' in this code:
 if length(s)+1=a then begin
    radek:=true;
    s:='';
    if a<60 then writeln(s2);
  end;

but you don't reset "a". So the following condition is true and the s[a] access bombs out.
  if not (a=length(s)+1) then begin
  if s[a]=' ' then
    i:=a;

How to solve this is left as an exercise to the reader.
Learn to use range checks and you find issues like this in a minute (hint add -Cr -gl to the commandline)


text:
Q: Access an element inside a dynamically-created, cross-domain iFrame? I want to access an element inside an iFrame, but because of the way the iFrame is being called, I am not succeeding.
This is the target page (www1.k9webprotection.com/...).
The iframe is on a different subdomain:
<iframe src="http://license.k9webprotection.com/..." ...></iframe>

Setting a timeout or an event listener for when the iframe is loaded, did not help.

A: Both documents are placed on different (sub)domains, by default they are not able to interact via javascript.
You must set the domain of both documents to the same value.
Put this somewhere in the <head/> of both pages:
<script  type="text/javascript">
document.domain='k9webprotection.com'
</script>

...then wait for the onload-event of the iframe and you should be able to access the document inside the iframe from the parent page(and vice versa).
Sample-Script for GreaseMonkey(simply overwrites the body of the iframe):
// ==UserScript==
// @name        k9
// @namespace   k9
// @include     http://www1.k9webprotection.com/get-k9-web-protection-free
// @include     http://license.k9webprotection.com/license.jsp*
// @version     1
// @grant       none
// ==/UserScript==

document.domain= 'k9webprotection.com';
if(self===top){
  try{
    $('iframe.getk9iframe').load(function(){
       $('body',this.contentDocument)
        .text('gotcha')
          .css({background:'red',fontSize:'3em'});
    });
    alert("I'm the document in the top-window");
  }
  catch(e){}
}


text:
Q: Using GDAL in C++. Create multiple GDALDatasets using a GDALDriver produces error 4 not recognised as a supported file format I am trying to create multiple GDALDataset objects. All of them are supposed to be in the .tif format, so for all of them I use the same GDALDriver.
I am working in C++ (Visual Studio) and when I build the solution there are no errors. But when I run it, I get the following error:
Error 4 'filename.tif' not recognised as a supported file format
The weird thing is that f I run the code consecutive times without changing anything, the GDALDataset for which I get the error change randomly. Sometimes I get the error for 5 of the 10 I am creating, sometimes for 9, etc.
I also have an additional question. When I check the tutorials in the GDAL website, when they create an object they have two different ways. For instance, creating a GDALDataset they have this two formats:
GDALDataset* PredictionRaster = (GDALDataset *) IMGdriver->Create("PredictionRaster.tif",XSize,YSize,1,TempBnd->GetRasterDataType(),NULL);

or
GDALDataset* PredictionRaster =  IMGdriver->Create("PredictionRaster.tif",XSize,YSize,1,TempBnd->GetRasterDataType(),NULL);

What is the (GDALDataset *) right after the assignment operator?
I also saw that in the initialization of the driver:
GDALDriver* IMGdriver = GetGDALDriverManager()->GetDriverByName("GTiff");

or
GDALDriver* IMGdriver = (GDALDriver*) GetGDALDriverManager()->GetDriverByName("GTiff");

Here are two images showing how the error is random executing exactly the same code and the same build:

For reference, here is the code I am talking about:
#include "stdafx.h"
#include <string>
#include <vector>
#include <array>
#include <iostream>
#include <cassert>
#include <sstream>
#include "gdal_priv.h"
#include "gdal_alg.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include <ogr_spatialref.h>
#include <cmath>
#include <math.h>

class LC_Raster
{
private:
    std::string m_parentProductName;
    int m_year;
    std::string m_rasterName;
    GDALDataset* m_SourceRasterDS;

public:
    LC_Raster(): m_parentProductName("NLCD"), m_year(2001)
    {
        std::stringstream os;
        os << m_year;

        std::string yearAsString;
        os >> yearAsString;

        m_rasterName = "Recon_" + m_parentProductName + "_" + yearAsString + ".tif";

        m_SourceRasterDS = (GDALDataset*) GDALOpen(m_rasterName.c_str(),GA_ReadOnly);
    }
    LC_Raster(std::string parentProductName , int year ): m_parentProductName(parentProductName), m_year(year)
    {
        std::stringstream os;
        os << m_year;

        std::string yearAsString;
        os >> yearAsString;

        m_rasterName = "Recon_" + m_parentProductName + "_" + yearAsString + ".tif";

        m_SourceRasterDS = (GDALDataset*) GDALOpen(m_rasterName.c_str(),GA_ReadOnly);
    }

    void setProductName (std::string name)
    {
        m_parentProductName = name;
    }

    void setRasterYear (int year)
    {
        m_year = year;
    }

    std::string getParentProductName () {return m_parentProductName; }
    int getRasterYear () {return m_year; }
    std::string getFileName () {return m_rasterName; }
    GDALDataset* getRasterGDAL () {return m_SourceRasterDS; }
};

class LC_Product
{
private:
    std::string m_productName;
    std::vector<int> m_productYears;
    int m_numberOfRasetrs;
    std::vector<LC_Raster> m_rastersOfProduct;

public:
    LC_Product(): m_productName("Default_NLCD")
    {
        int arrayYearsNLCD[] = {2001,2006,2011};
        std::vector<int> yearsNLCD (arrayYearsNLCD, arrayYearsNLCD + sizeof(arrayYearsNLCD) / sizeof(int) );
        m_productYears = yearsNLCD;

        m_numberOfRasetrs = yearsNLCD.size();
        m_rastersOfProduct.resize(yearsNLCD.size());

        for (int iii=0; iii < yearsNLCD.size(); iii++)
        {
            m_rastersOfProduct[iii] = LC_Raster("NLCD",yearsNLCD[iii]);
        }

    }

    LC_Product(std::string productName, std::vector<int> productYears): m_productName(productName), m_productYears(productYears)
    {
        m_numberOfRasetrs = productYears.size();
        m_rastersOfProduct.resize(productYears.size());

        for (int iii=0; iii < productYears.size(); iii++)
        {
            m_rastersOfProduct[iii] = LC_Raster(productName,productYears[iii]);
        }

    }

    std::string getProductName () {return m_productName; }
    std::vector<int> getProductYears () {return m_productYears; }
    int getNumberOfRasters () {return m_numberOfRasetrs; }

    LC_Raster getRaster (int year)
    {
        for (int iii = 0; iii < m_productYears.size(); iii++)
        {
            if (m_productYears[iii] == year)
            {
                return m_rastersOfProduct[iii];
            }
        }

        bool yearNotFound = 0;

        assert (yearNotFound);
    }

    std::vector<int> calculateNeighboringYears (int yearToPredict, int deltaT)
    {
        std::vector <int> neighborYears;
        int numberOfNeighboringYears = neighborYears.size(); //This is the same as 0

        for (int iii=0; iii < m_productYears.size(); iii++)
        {
            if ((m_productYears[iii] >= (yearToPredict-deltaT)) && (m_productYears[iii] <= (yearToPredict+deltaT)))
            {
                numberOfNeighboringYears += 1;
                neighborYears.resize(numberOfNeighboringYears);
                neighborYears[numberOfNeighboringYears-1] = m_productYears[iii];
            }
        }

        return neighborYears;
    }
};

class LC_SetOfProducts
{
private:
    std::array<std::string,6> m_productNames;
    std::array<LC_Product,6> m_products;

public:
    LC_SetOfProducts()
    {
        m_productNames[0]="BC";
        m_productNames[1]="Hist";
        m_productNames[2]="LF";
        m_productNames[3]="MODIS";
        m_productNames[4]="NLCD";
        m_productNames[5]="NLCD92";
        //Vectors with the year of eahc product
        std::vector<int> yearsBC;
        for (int yearBC = 1938; yearBC <= 2005; yearBC++)
        {
            yearsBC.push_back(yearBC);
        }
        std::vector<int> yearsHist (1,1977);
        int arrayYearsLF[] = {2001,2008,2010,2012};
        std::vector<int> yearsLF (arrayYearsLF, arrayYearsLF + sizeof(arrayYearsLF) / sizeof(int) );
        std::vector<int> yearsMODIS;
        for (int yearMODIS = 2001; yearMODIS <= 2012; yearMODIS++)
        {
            yearsMODIS.push_back(yearMODIS);
        }
        int arrayYearsNLCD[] = {2001,2006,2011};
        std::vector<int> yearsNLCD (arrayYearsNLCD, arrayYearsNLCD + sizeof(arrayYearsNLCD) / sizeof(int) );
        std::vector<int> yearsNLCD92 (1,1992);

        //initilize array of products

        m_products[0] = LC_Product(m_productNames[0],yearsBC);
        m_products[1] = LC_Product(m_productNames[1],yearsHist);
        m_products[2] = LC_Product(m_productNames[2],yearsLF);
        m_products[3] = LC_Product(m_productNames[3],yearsMODIS);
        m_products[4] = LC_Product(m_productNames[4],yearsNLCD);
        m_products[5] = LC_Product(m_productNames[5],yearsNLCD92);

    }

    std::array<LC_Product,6> getArrayOfProducts () {return m_products; }
    std::array<std::string,6> getArrayOfProductNames () {return m_productNames; }

    LC_Product getProductFromName (std::string name)
    {
        for (int iii = 0; iii < m_products.size(); iii++)
        {
            if (m_productNames[iii] == name)
            {
                return m_products[iii];
            }
        }
        bool nameNotFound = 0;

        assert (nameNotFound);
    }
};

class Probability_Raster
{
private:
    int m_LC_type;
    GDALDataset* m_RasterDS;
    int m_XSize;
    int m_YSize;
    std::string m_fileName;

public:
    Probability_Raster( int LC_type, int XSize, int YSize, double GeoTransformProbability[6], const char *probabilityProjection, GDALDriver* IMGdriver): m_LC_type(LC_type), m_XSize(XSize), m_YSize(YSize)
    {
        std::stringstream os;
        os << LC_type;
        std::string LC_TypeAsString;
        os >> LC_TypeAsString;
        m_fileName = "ProbabilityRaster_" + LC_TypeAsString + ".tif";

        GDALDataset* ProbabilityRasterGDAL = IMGdriver->Create(m_fileName.c_str(),XSize,YSize,1,GDALDataType::GDT_Float32,NULL);

        ProbabilityRasterGDAL->SetGeoTransform(GeoTransformProbability);
        ProbabilityRasterGDAL->SetProjection(probabilityProjection);
        m_RasterDS = ProbabilityRasterGDAL;
    }

    int getLC_type () {return m_LC_type; }
    std::string getFileName () {return m_fileName; }
    GDALDataset* getRasterGDAL () {return m_RasterDS; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    //Register all the formats that the GDAL library supports, including .tif files
    GDALAllRegister();

    //Load the set of products used in this project: BC, Hist, NLCD, LF, MODIS, NLCD92
    LC_SetOfProducts products;

    //Define the size of neighboring window in meters and years
    double windSizeX = 500;
    double windSizeY = 500;
    double windSizeT = 5;

    //Create array with the LC classes (9 for this case)
    const int numOf_LC_classes = 9;
    std::array<int,numOf_LC_classes> LCclasses = {1,2,3,4,5,6,7,8,9};

    //
    /*Creation of empty raster where we would predict land cover*/
    //

    //In this case the raster has the same resolution and number of cells as NLCD
    //Number of cells in the new raster

    GDALRasterBand* TempBnd = products.getProductFromName("NLCD").getRaster(2001).getRasterGDAL()->GetRasterBand(1);
    int XSize = TempBnd->GetXSize();
    int YSize = TempBnd->GetYSize();

    std::cout << "The size of the prediction raster is (number of X cells, number of Y cells):\n";
    std::cout << XSize << ", " << YSize << "\n";

    //First, specify the driver (format) that the new raster would have (.tif again)
    //GDALDriver* IMGdriver = GetGDALDriverManager()->GetDriverByName("GTiff");
    GDALDriver* IMGdriver = GetGDALDriverManager()->GetDriverByName("GTiff");
    //Crate the GDAL raste robject for the prediction raster
    GDALDataset* PredictionRaster = (GDALDataset *) IMGdriver->Create("PredictionRaster.tif",XSize,YSize,1,TempBnd->GetRasterDataType(),NULL);

    //Create the geotransformation for the prediction raster (it is taken from NLCD product and can be modified)
    //Geotransformation has the coordinates of top left corner, and the resolution of the raster
    double GeoTransformPrediction[6];
    products.getProductFromName("NLCD").getRaster(2001).getRasterGDAL()->GetGeoTransform(GeoTransformPrediction);
    /*GeoTransformPrediction[1]=1000; //Uncomment if you want to change cell size of prediction raster*/
    /*GeoTransformPrediction[5]=-1500; //Uncomment if you want to change cell size of prediction raster*/
    PredictionRaster->SetGeoTransform(GeoTransformPrediction);

    //Create the projection for the prediction raster (it is taken from NLCD product)
    const char *predictionProjection = products.getProductFromName("NLCD").getRaster(2001).getRasterGDAL()->GetProjectionRef();
    PredictionRaster->SetProjection(predictionProjection);

    //
    /*Creation of empty rasters where we would predict probabilities for each land cover category (one raster per category)*/
//

    std::vector<Probability_Raster> vectorOfProbabilityRasters;

    for (int iii = 0; iii < numOf_LC_classes; iii++)
    {
        vectorOfProbabilityRasters.push_back(Probability_Raster( (iii+1),  XSize,  YSize, GeoTransformPrediction, predictionProjection, IMGdriver ));
        std::cout << vectorOfProbabilityRasters[iii].getFileName() << "\n";
    }

    return 0;
}


text:
Q: Is there somewhere I can go to easily 'catch up' to current events? Sometimes players in wow take long breaks of gameplay. Is there somewhere that can help mitigate the lack of information obtained during such breaks about where people should be? (zones, dungeons, ect)
Is there somewhere, in or out of game, that I can visit and find out where a toon (max level) should be doing stuff.
I'd rather avoid asking other players if possible, to minimize possible flameadge.

A: If you are looking for out-of-game information that you can use to help you catch up, I suggest sites such as WoW Insider and MMO-Champion.
WoW Insider is a blog oriented towards casual players and has pretty good guides for all classes and specs.
MMO-Champion has a billboard format that presents the latest news pertaining to World of Warcraft, focusing on end-game, future patches and expansions.
The website Icy Veins has very good guides oriented to the hardcore player and deals with a lot of theorycrafting.
Max DPS is a great site that parses your character's armory and outputs a list of armor and weapons that would potentially increase your healing, tanking or damage performance in raids. Information on where to get such items is also provided.
Lastly, the World of Warcraft website and it's forums are a great source of information.
For solutions in-game, asking other people is always the best way to catch up on what you should be doing. Even if you are trying to avoid this, I would strongly suggest looking out for a guild with a good reputation and helpful players. These guilds are definitely rare, but trust me, they are out there.
Alternatively, the trade chat in main cities is filled with people looking for other players to engage in PVE and PVP combat. Just peeking into this channel will give you a good idea of what content are people tackling. A lot of acronyms are used when referring to instances and battlegrounds, so I suggest you check this page if you find yourself lost.
The Dungeon Journal is one of WoW's latests features and it can help you figure out what is the PVE content pertaining to the current expansion.
Billboards in main cities are meant to guide players into zones they should be leveling at or introduce high-level players to quest chains that might be of their interest.
The Dungeon, Raid and PVP matchmaking systems are also great ways to regain familiarity with the game. Looking for Raid and Looking for Dungeon enforce an item level cap that you must achieve before being able to queue. Be adviced that people you join will probably expect you to know what you are doing in certain encounters.

A: Solo Quest Hubs
For the Alliance, in Stormwind there is a Hero's Call board near the auction house.  This board will have a quest sending you to a level appropriate hub.
Horde characters should check the Warchief's Command board, near the throne room in Orgrimmar.  It works the same way.
Dungeons and Raids
Look at the dungeon finder or raid finder.  It will show you dungeons or raids in your level range for you to queue for.  You can pick a dungeon, or just pick random to be matched with whoever is waiting - random gives a 5% buff and additional rewards.  Dungeon quests are now given inside the dungeon entrance.  You can also use the in-game Dungeon Journal to see boss abilities/phases and drops.
Zones
The in-game world map now shows suggested level ranges.

Guild
A second way to glean this information is to locate some sympathic ears in the game.  Due to guild xp and leveling, guilds want you.  Use the guild finder to find one or just wait - every nonguilded character I have gets spammed with invites.  Once invited, ask your questions - if they don't want to help, /gquit and on the next one.

Outside the game
A third approach is to do the research outside the game.  There are sites for researching current game content (I like thottbot for this).  There are news sites for upcoming content - mmo-champion is unbeatable.  If raid optimization is your thing, there's theorycrafting sites such as elitist jerks.  There's also podcasts such as The Instance - go Now and listen.
You could also ask your questions here on arQAde.


text:
Q: /usr/bin/ld: cannot find -lvtkGUISupportQt I'm trying to build a package i've found on github,when I run the command make, it gives me the error in the Title.
I'm working on Ubuntu 16.04, it seems that tere's a library missing but don't know how to fix the problem on Ubuntu.
Here's the complete message I'm getting:
hamza@hamza-Latitude-5590:~/rtabmap/build$ make
[  4%] Built hamza@hamza-Latitude-5590:~/rtabmap/build$ make
[  4%] Built target rtabmap_utilite
[  4%] Built target res_tool
[  4%] Linking CXX shared library ../../../bin/librtabmap_core.so
/usr/bin/ld: cannot find -lvtkGUISupportQt
collect2: error: ld returned 1 exit status
corelib/src/CMakeFiles/rtabmap_core.dir/build.make:3041: recipe for target '../bin/librtabmap_core.so.0.19.2' failed
make[2]: *** [../bin/librtabmap_core.so.0.19.2] Error 1
CMakeFiles/Makefile2:267: recipe for target 'corelib/src/CMakeFiles/rtabmap_core.dir/all' failed
make[1]: *** [corelib/src/CMakeFiles/rtabmap_core.dir/all] Error 2
Makefile:149: recipe for target 'all' failed
make: *** [all] Error 2
target rtabmap_utilite
[  4%] Built target res_tool
[  4%] Linking CXX shared library ../../../bin/librtabmap_core.so
/usr/bin/ld: cannot find -lvtkGUISupportQt
collect2: error: ld returned 1 exit status
corelib/src/CMakeFiles/rtabmap_core.dir/build.make:3041: recipe for target '../bin/librtabmap_core.so.0.19.2' failed
make[2]: *** [../bin/librtabmap_core.so.0.19.2] Error 1
CMakeFiles/Makefile2:267: recipe for target 'corelib/src/CMakeFiles/rtabmap_core.dir/all' failed
make[1]: *** [corelib/src/CMakeFiles/rtabmap_core.dir/all] Error 2
Makefile:149: recipe for target 'all' failed
make: *** [all] Error 2

A: What you are experiencing is the pcl version with QT plugin version issue.  the older version and new version are not compatible. I encounter this b4.
(1)Its either you build with the correct version pcl that all other package is ok with.
(2) or just user docker to install this rtabmap.  In this way, all condition will be fufilled.
follow the link here for detail walk through https://github.com/introlab/rtabmap/wiki/Installation#docker


text:
Q: Functional way to take element in a list until a limit in Scala The aim of the method is to take elements in a list until a limit is reached.
e.g.
I've come up with 2 different implementations
def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}

It is straightforward, but a mutable state is used.
def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.
Is there a better way ?

A: You could also do that in a single pass with a fold:
  def take(l: List[Int], limit: Int): List[Int] =
    l.fold((List.empty[Int], 0)) { case ((res, acc), next) =>
      if (acc + next > limit)
        (res, limit)
      else
        (next :: res, next + acc)
    }

Because the standard lists aren't lazy, and neither is fold, this will always traverse the entire list. One alternative would be to use cats' iteratorFoldM instead for an implementation that short circuits once the limit is reached.
You could also write the short circuiting fold directly using tail recursion, something along those lines:
def take(l: List[Int], limit: Int): List[Int] = {
  @annotation.tailrec
  def take0(list: List[Int], accList: List[Int], accSum: Int) : List[Int] =
    list match {
      case h :: t if accSum + h < limit =>
        take0(t, h :: accList, h + accSum)
      case _ => accList
    }
  take0(l, Nil, 0).reverse
}

Note that this second solution might be faster, but also less elegant as it requires additional effort to prove that the implementation terminates, something obvious when using a fold.

A: The first way is perfectly fine as the result of your function is still perfectly immutable.
On a side note, this is actually how many functions of the scala collection library are implemented, they create a mutable builder for efficiency and return an immutable collection out of it.

A: A functional way is to use recursive function and make sure it is stack safe.
If you just use basic scala:
    import scala.annotation.tailrec
    def take(l: List[Int], limit: Int) : List[Int] = {
      @tailrec
      def takeHelper(l:List[Int], limit:Int, r:List[Int]):List[Int] =
        l match {
            case h::t if (h <= limit ) =>  takeHelper(t, limit-h, r:+h)
            case _ =>  r
      }
      takeHelper(l, limit, Nil)
    }

If you can use scalaz Trampoline, it is a bit nicer:
import scalaz._
import scalaz.Scalaz._
import Free._
 def take(l: List[Int], limit: Int): Trampoline[List[Int]] = {

    l match {
      case h :: t if (h <= limit) => suspend(take(t, limit - h)).map(h :: _)

     case _                      => return_(Nil)
    }
  }
  println(take(List(1, 2, 3, 4, 0, 0, 1), 10).run)
  println(take(List.fill(10000)(1), 100000000).run)

A: if you want to extend your own customize way, you could also use something like:
def custom(con: => Boolean)(i: Int)(a: => List[Int])(body: => Unit): List[Int] = {
      if (con) {
        body
        custom(con)(i + 1)(a)(body)
      }
      else {
        a.slice(0, i)
      }
    }

then call it like this:
var j = 100
    val t = customTake(j > 80)(0)((0 to 99).toList) {
      j -= 1
    }
    println(t)

A: I think your second version is already pretty good.  You might tweak it a little, like this:
val sums = l.toStream.scanLeft(0){_ + _} drop 1
l zip sums takeWhile {_._2 <= limit} map (_._1)

This way you aren't dealing with indices, which is usually a little easier to follow.


text:
Q: How to print the subject of a single email using uid I'm looking to print the subject of a single email whose UID I already have using the python 2.7 imap libraries. It's pretty simple, I'm new to Python and am just having trouble using the library.
Here's what I have:
# Retrieve and store ID & UID for most recent email received

result, data = mail.search(None,'ALL') # search and return sequential ids
latest_id = data[0].split()[-1]

result, data = mail.uid('search', None, "ALL") # search and return uids instead
latest_uid = data[0].split()[-1]

Now I'm just looking to print the subject of the email identified by latest_uid.
Thanks for the help!

A: The way I would approach getting the subject is to fetch the entire message data using RFC 822 (email message standard format), and then convert it into a python email object using the email module.
Using RFC 822 will fetch the entire message, but if you only need the subject you can just fetch the header (commented out below). If you decide to only fetch for the header, just parse for the line that begins with Subject:.
The imaplib documentation https://pymotw.com/2/imaplib/ has a more in depth of what's happening in the code below.
import email, imaplib

# typ, msg_data = c.fetch('1', '(BODY.PEEK[HEADER])')
t, d = mail.fetch(latest_uid, '(RFC822)')

for res_part in d:
    if isinstance(res_part, tuple):
    msg = email.message_from_string(res_part[1])
    subject = msg['subject']