text:
Q: In a Java HttpsURLConnection POST, I can't read the response from the server I'm trying to do an HTTPS POST using this sample code:
http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/
About half way down there is a commented line of code:
// System.out.println(response.toString());

The reason it is commented out is that the response appears to be garbage, either the wrong character set or encrypted.
I need the data returned from the POST.  Any suggestions on the correct way to do that?  The code from the site is copied below.
package com.mkyong;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HttpUrlConnectionExample {

  private List<String> cookies;
  private HttpsURLConnection conn;

  private final String USER_AGENT = "Mozilla/5.0";

  public static void main(String[] args) throws Exception {

  String url = "https://accounts.google.com/ServiceLoginAuth";
  String gmail = "https://mail.google.com/mail/";

  HttpUrlConnectionExample http = new HttpUrlConnectionExample();

  // make sure cookies is turn on
  CookieHandler.setDefault(new CookieManager());

  // 1. Send a "GET" request, so that you can extract the form's data.
  String page = http.GetPageContent(url);
  String postParams = http.getFormParams(page, "username@gmail.com", "password");

  // 2. Construct above post's content and then send a POST request for
  // authentication
  http.sendPost(url, postParams);

  // 3. success then go to gmail.
  String result = http.GetPageContent(gmail);
  System.out.println(result);
  }

  private void sendPost(String url, String postParams) throws Exception {

  URL obj = new URL(url);
  conn = (HttpsURLConnection) obj.openConnection();

  // Acts like a browser
  conn.setUseCaches(false);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("Host", "accounts.google.com");
  conn.setRequestProperty("User-Agent", USER_AGENT);
  conn.setRequestProperty("Accept",
    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  for (String cookie : this.cookies) {
    conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
  }
  conn.setRequestProperty("Connection", "keep-alive");
  conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
  conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

  conn.setDoOutput(true);
  conn.setDoInput(true);

  // Send post request
  DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
  wr.writeBytes(postParams);
  wr.flush();
  wr.close();

  int responseCode = conn.getResponseCode();
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post parameters : " + postParams);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in =
             new BufferedReader(new InputStreamReader(conn.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
  }
  in.close();
  // System.out.println(response.toString());

  }

  private String GetPageContent(String url) throws Exception {

  URL obj = new URL(url);
  conn = (HttpsURLConnection) obj.openConnection();

  // default is GET
  conn.setRequestMethod("GET");

  conn.setUseCaches(false);

  // act like a browser
  conn.setRequestProperty("User-Agent", USER_AGENT);
  conn.setRequestProperty("Accept",
    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  if (cookies != null) {
    for (String cookie : this.cookies) {
      conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
    }
  }
  int responseCode = conn.getResponseCode();
  System.out.println("\nSending 'GET' request to URL : " + url);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in =
            new BufferedReader(new InputStreamReader(conn.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
  }
  in.close();

  // Get the response cookies
  setCookies(conn.getHeaderFields().get("Set-Cookie"));

  return response.toString();

  }

  public String getFormParams(String html, String username, String password)
    throws UnsupportedEncodingException {

  System.out.println("Extracting form's data...");

  Document doc = Jsoup.parse(html);

  // Google form id
  Element loginform = doc.getElementById("gaia_loginform");
  Elements inputElements = loginform.getElementsByTag("input");
  List<String> paramList = new ArrayList<String>();
  for (Element inputElement : inputElements) {
    String key = inputElement.attr("name");
    String value = inputElement.attr("value");

    if (key.equals("Email"))
      value = username;
    else if (key.equals("Passwd"))
      value = password;
    paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
  }

  // build parameters list
  StringBuilder result = new StringBuilder();
  for (String param : paramList) {
    if (result.length() == 0) {
      result.append(param);
    } else {
      result.append("&" + param);
    }
  }
  return result.toString();
  }

  public List<String> getCookies() {
  return cookies;
  }

  public void setCookies(List<String> cookies) {
  this.cookies = cookies;
  }

}

A: I've solved the problem that I was specifically having, though I didn't identify the actual issue in the code above (I was working with a different site and slightly different code).  The server was returning a compressed response (as pyb speculated above), and I solved it by changing the "Accept-Encoding" property.


text:
Q: Is it possible to manipulate graphite data lies a couple of days in the past? I have a graph in graphite, which I would like to manipulate. I noticed that datapoints of this graph that are already a couple of days in the past need to be corrected, because they are wrong.
I tried to send the correct data with the older timestamps in order to overwrite the old data, but the data won't change. Does anyone have an idea?
Just to provide some more information:
xFilesFactor = 0.3
Aggregationmethod = average

Storage schema: 1m:1d,5m:30d,1h:3y

A: Why it doesn't work for you-
Storage-Aggregation config 'works on' new metric files. So any changes in this config will only affect newly-created metric files and not the ones that already exist.
./whisper-info.py /opt/graphite/storage/whisper/stats/dev/hulk/getupdate.wsp for example will tell you the effective storage and aggregation schema on ground zero.
Editing these can be as straightforward as-
/whisper-resize.py {} --xFilesFactor=0.0 --aggregationMethod=sum 10s:1d 60s:30d 600s:365d <file_path>
I used the following scripts to change aggregation-schema of my already existing metrics-
$ find /opt/graphite/storage/whisper/stats/timers/production/ | grep .wsp > ~/timers
$ cat ~/timers | xargs -I{} sudo /opt/graphite/whisper-scripts/whisper-resize.py {} --xFilesFactor=0.0 --aggregationMethod=sum 10s:1d 60s:30d 600s:365d
You can get these whisper scripts in the installation dump from here.
The timestamp, perhaps has to be the same as the step.
Eg- If the retention is- XXX30 xxx50 xxx70 xxx90 and you send the new metric to xxx60, it will not be reflected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: javascript enable disable radio button on click and select only one at a time I am trying to do this.
I have 3 radio buttons,

*

*If click on a radio and it's set, next time i click on it. It should
be unchecked/rest.

I want to do in standard javascript without jquery as can't have that at the moment.
Here's my code so far.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">

  <script type="text/javascript">

   function toggle(radioBtn)
   {
     if(radioBtn.checked)
     {
       radioBtn.checked = false;
     }
     else
     {
      radioBtn.checked = true;
     }

     // only select one at a time.

   }

  </script>
 </head>

 <body>
 <form id="myForm" name="myForm">
  <input type="radio" name="radioBtn" id="radioBtn1"    value="A" onClick="toggle(this);" />
<input type="radio" name="radioBtn" id="radioBtn1"    value="B" onClick="toggle(this);"/>
<input type="radio" name="radioBtn" id="radioBtn1"    value="C" onClick="toggle(this);"/>
</form>
 </body>
</html>

Please help. Your help will be appreciated.
Thanks

A: You could just do something simple and straight forward inline, like this:
<input type="radio" name="radioBtn" id="radioBtn1" value="A" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" />
<input type="radio" name="radioBtn" id="radioBtn2" value="B" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/>
<input type="radio" name="radioBtn" id="radioBtn3" value="C" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/>

A: Keep a record of which radioButton is checked and which isn't (can be done with hidden fields or an array) and set the checked/unchecked accordinally

A: You can get around the browser's default behavior for radio buttons and achieve the toggle effect you're after by creating an additional 'hidden' radio button, and simulating a click event for it when the user toggles off one of the visible buttons. See a working example in this jsFiddle: http://jsfiddle.net/k73Nt/

A: This might not be a solution which will go into the book for being clean but i got it working.
http://jsfiddle.net/C9At9/3/
HTML:
<input type="radio" name="radioBtn" id="radioBtn1" value="A" onmouseup="toggle(this);"/>
<input type="radio" name="radioBtn" id="radioBtn2" value="A" onmouseup="toggle(this);" />
<input type="radio" name="radioBtn" id="radioBtn3" value="A" onmouseup="toggle(this);"/>

Javascript:
function toggle(radioBtn)
 {
   if(radioBtn.checked)
   {
     setTimeout("disableRadio('"+radioBtn.id+"')",10);
   } else {
     radioBtn.checked = true;
   }
 }

function disableRadio(radioId) {
    el = window.document.getElementById(radioId);
    el.checked = false;
}

Your code wasn't working because the javascript setter gets overruled by html click events or something. I don't know how to explain it the correct way but having a delay solves your problem.
Hope this helps out!


text:
Q: Redundancy requests with Retrofit I need to build in redundancy into my app where if a server is down it will try a backup redundancy server upon failure of the first request.
Aside from doing
Call<LoginResult> loginCall = apiInterface.login(....);
loginCall.enqueue(new Callback<LoginResult>() {
    @Override
    public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
        if(response.isSuccessful){
            //do normal stuff
        }else{
            //try second url
        }
    }

    @Override
    public void onFailure(Call<LoginResult> call, Throwable t) {
        //Try second url
    }
}

I don't see a clean way to do this. Creating another retrofit request inside the error block or non-successful block would add a lot of code complexity.
Is there an easier way to handle this in Retrofit or OkHttp?

A: I have here an option with OkHttp interceptors. The idea is that if the request fails you replace the url and execute the request again.
The following is an api client to the OpenWeather Api. If you want to try out the example you'll need to sign up and get an api key. It should be free so I hope this is ok.
I'll post here the full code and then walk you through it.
private final static String API_KEY = "<API KEY HERE>";

private static class Weather {
  @SerializedName("id")
  @Expose
  private String id;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }
}

private static final String GOOD_HOST = "api.openweathermap.org";
private static final String BAD_ENDPOINT = "https://api.aaaaaaaaaaa.org";

interface WeatherApiClient {
  @GET("/data/2.5/weather")
  Call<Weather> get(
    @Query("q") String query,
    @Query("appid") String apiKey);
}

private static class ReplicaServerInterceptor implements Interceptor {
  @Override public okhttp3.Response intercept(Chain chain)
                        throws IOException {
     try {
       okhttp3.Response response = chain.proceed(chain.request());
       return response;
     } catch (IOException e) {

     // Let's build a new request based on the old one
     Request failedRequest = chain.request();

     HttpUrl replicaUrl = failedRequest.url()
        .newBuilder()
        .host(GOOD_HOST)
        .build();

     okhttp3.Request request = failedRequest.newBuilder()
        .url(replicaUrl)
        .build();

     return chain.proceed(request);
   }
 }
}

public static void main(String[] args) {
  OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new ReplicaServerInterceptor())
    .build();

  Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BAD_ENDPOINT)
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build();

  WeatherApiClient weatherApiClient =
            retrofit.create(WeatherApiClient.class);

  weatherApiClient.get("Lisbon,pt", API_KEY)
    .enqueue(new Callback<Weather>() {
      @Override public void onResponse(
             Call<Weather> call,
             Response<Weather> response) {
        // This might be null sometimes because
        // the api is not super reliable, but I didn't
        // add code for this
        System.out.println(response.body().id);
      }

      @Override public void onFailure(
              Call<Weather> call,
              Throwable t) {
        t.printStackTrace();
      }
    });
}

To be able to fake a server failure I prepare retrofit to call a non existent url - BAD_ENDPOINT. This will trigger the catch clause inside the interceptor.
The interceptor itself is obviously the key thing here. It intercepts every call from retrofit and executes the call. If the call throws an error because the server is down, then it will raise an IOException. Here I copy the request being made and change the url.
Changing the url means changing the host:
HttpUrl replicaUrl = failedRequest.url()
  .newBuilder()
  .host(GOOD_HOST)
  .build();

If you just call url(<some url>) in the request builder, everything gets replaced. Query parameters, protocol, etc. This way, we preserve these from the original request.
(OkHttp offers newBuilder methods which copy the data from the current object and let you just edit what you want. Just like kotlin's copy. This is why we can simply change the url and be safe that everything else remains the same)
I then build the new request with the url and execute it:
okhttp3.Request request = failedRequest.newBuilder()
  .url(replicaUrl)
  .build();

return chain.proceed(request);

Interceptors work on a chain pattern, that's why calling proceed will call the next interceptor on the chain. In this case we just need to actually make the request.
I didn't bother copying the entire weather resource, so I'm just using the id. I think that's not the main focus of the question
As I said before, this is meant as a proof of concept. As you noticed I'm try-catching the execution of the call, but in your case it might be that the call actually succeeds executing, but the http response is not a 2XX. The okhttp response objects have methods that help you checking if the response was successful namely - isSuccessful(). The idea is the same - Build a new request and carry on if it's not successful.
I didn't bother treating any errors from the replica in this example. They'll just be forwarded to the retrofit client.
As you can see retrofit has no clue where the response is coming from. This might or not be good. Also, the response body needs to be the same from both servers, which I guess it's the case.
Lastly I'm sorry for the awkward okhttp3.Response name spacing there. I was using both Response from retrofit and okhttp and hence had to avoid the name clash.
Versions used for this example: Retrofit 2.3.0 and the okhttp bundled with that


text:
Q: Linux, the only way to GAIN root access is executing a setuid-root file? Is my assumption true, that on Unix/Linux, the only way to GAIN root access is to execute a setuid-root file?
In other words, the system calls setuid(), setgid() are all about DROPPING privileges?
Please note that my question is not about exploits.

A: That's true. The only way for a non-root process (assuming it's running a non-setuid program) to become root is to exec a setuid program. If it's running a set-uid root program, then its effective uid is root and real uid is whoever ran it. It can then do setuid(0) to make its real uid 0.


text:
Q: Docstring for batch_norm() does not match latest code in tensorflow.contrib.layers I am trying to use the latest batch_norm() and found it here: batch_norm. If I use help(tf.contrib.layers.batch_norm) from IPython, I see the following docstring of interest:

Note: When is_training is True the moving_mean and moving_variance
  need to be
      updated, by default the update_ops are placed in tf.GraphKeys.UPDATE_OPS so they need to be added as a dependency to
  the train_op, example:

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
if update_ops:
    updates = tf.group(*update_ops)
    total_loss = control_flow_ops.with_dependencies([updates], total_loss)

However the source code at batch_norm has the following docstring which has been corrected.

Note: When is_training is True the moving_mean and moving_variance
  need to be   updated, by default the update_ops are placed in
  tf.GraphKeys.UPDATE_OPS so   they need to be added as a dependency
  to the train_op, example:

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
  train_op = optimizer.minimize(loss)

Using tf.__version__ from IPython prompt, I get '0.12.1'. How can I tell if the code I am running is the same as the latest in tf.contrib.layers? If only the docstring changed and the code is the same, I would rather not upgrade or reinstall tensorflow as I have everything working well with GPU. My install is inside of a mini conda environment and tensorflow was originally installed with pip from inside this environment. Also, if I do need a different version, what is the best way to get it and then test that I have the matching version from tf.contrib.layers?

A: I was able to verify that I did not have the latest code by doing a diff on the file of interest with my local copy. I did this by first downloading the file layers.py from Github at layers.py. I clicked on the raw button and then saved the image to a local directory. In my case the local copy was located in my miniconda directory under site-packages. At that point it was apparent that my version of tensorflow needed to be updated so I installed the latest version. This install broke an existing miniconda environment however which was unexpected. See installing tensorflow...


text:
Q: ViewModel Observer not working when activity is backstacked I have 2 activities:
A: for listing an array list,
B: for inserting on the array list.
A is observing the array list:
playlistItemsViewModel.playlistItems.observe(this, { playlistItems ->
        Log.i("Received playlistItems", playlistItems.size.toString())
        adapter = PlaylistItemAdapter(playlistItems)
        binding.rvPlaylistItems.adapter = adapter
})

A is also observing when a new item is added:
playlistItemsViewModel.newItem.observe(this, { newItem ->
       Log.i("newItem >>>", newItem.toString())
       adapter.addPlaylistItem(newItem)
})

To add a new item I start an intent B where playlistItemsViewModel.submitVideoItem(item) does its work, but the activity A is paused so it does not receive the posted value, when the back button is pressed and A is resumed, it still does not receive anything.
When playlistItemsViewModel.submitVideoItem(item) works inside A, the MutableLiveData newItem postValue posts successfully. Basically, when you add a new playlist item in activity B it is inserted on the activity A that is paused back on the stack.
What am I missing?

A: I am understanding when Activity B inserts a new value for the variable newItem then when returning to Activity A you want to update it.
If it were me I would use startActivityForResult() and onActivityResult() this would be more appropriate.
https://developer.android.com/training/basics/intents/result
As for LiveData, you can read it here to better understand the problem you are having.
https://developer.android.com/topic/libraries/architecture/livedata

A: You can not share a same instance of ViewModel between Activities you can only share viewmodel between Fragments and that too by an Activity's Context . (You can confirm this by printing the viewmodel Object in Logs in A and B, you will get 2 instances)
The problem here is your Activities A and B holding a different instances of ViewModel so it will never work .
For a Solution you can switch to Fragments or if its too much for you then can go for ActivityResultApi.


text:
Q: When trying to install windows 7 I got an error of "operating system not found" how could I fix it? This is the complete error I get when I try to boot from DVD
For Atheros PCIE Ethernet controller v1.0.0.5(01/22/09)
Check cable connection!
PXE-M0F: Existing Intel PXE ROM.
Operating system no found

What could be the problem. Could it by my windows 7 disk?

A: By default your PC might be set for booting only from HDD and Network.
   PXE-M0F: Existing Intel PXE ROM.

The former message tells you the Network boot failed.
Just enable booting from DVD at bios level and you'll be fine.


text:
Q: R- Excluding random numbers that have already been generated So I'm working on a webscraping script in R and because the particular website I'm scraping doesn't take too kindly to people who scrape their data in large volumes, I have broken down my loop to handle only 10 links at a time. I still want to go through all the links, however, just in a random and slow manner.
productLink # A list of all the links that I'll be scraping
 x<- length(productLink)
 randomNum <- sample(1:x, 10)
library(rvest)

for(i in 1:10){
url <- productLink[randomNum[i]]
specs <- url %>%
  html() %>%
  html_nodes("h5") %>%
  html_text()
specs

message<- "\n                Temporarily unavailable\n            "

if(specs == message){
  print("Item unavailable")
}
else{
  print("Item available")
}

}

Now the next time I run this for-loop I want to exclude all the random numbered indices that have already been tried in the previous running of the loop. That way this for loop runs through 10 new links each time until all the links have been used. There is another aspect to this that I'd like some input on. Since I can raise alarm flags by brute force scraping the particular company's website, is there any way I can slow down this loop so that it only runs every couple of minutes? I'm thinking of a timeout function or such where the code runs the for-loop once, waits a few minutes then runs it again (with new links each time as mentioned above). Any ideas?

A: Use something like this. Loop over all the product index randomly.
for (i in sample(1:x)){
  <Your code here>
  # Sleep for 120 seconds
  Sys.sleep(120)
}

And if you want to do 10 at a time. Sleep for 120 seconds every 10 executions.
n = 1
for (i in sample(1:x)){
  # Sleep for 120 seconds every 10 runs
  if (n == 10) {Sys.sleep(120); n = 0}
  n = n+1
  <Your code here>
}


text:
Q: Convert Formula's references to values in formula in Excel VBA Is it possible using VBA to convert the formula =n2+m2 into its actual values on another sheet. For example cell m2 is 0, and n2 is 96,879 on sheet1. I'd like to have on sheet2 a formula be inserted in cell a1 for example, that is =0+96879. It is an audit trail of sorts. This would actually be performed on a large range, but that is the general idea. I've been looking for hours and come up with nothing.

A: In sheet 2 A1 enter
 =Sheet1!n2&"+"&Sheet1!m2

If you want the = Sign to Then just do
="="&Sheet1!n2&"+"&Sheet1!m2

A: Yes and no.  It's possible, but it's a pretty gnarly task.
Refer to this link, for some discussion about various methods:
Does Excel have a built in method for parsing formulas? (ie: to obtain a list of included RANGE references)


text:
Q: How to set up a server system if all you want is on demand "Burst" Bandwidth a few times a year? We are looking for the a good way to set up a server system that is "on call" and will only be used a few (but random) times a year. It needs to be super powerful with high server capacity and super high bandwidth but we'd rather not pay an arm and a leg to have dedicated servers around the clock. Are there options out there in the managed hosting world that could fill that need? We would need to have the ability to activate the system and begin running scripts with very little notice ahead of time.

A: Yes, absolutely. I am assuming that "very little notice" is acceptable if it is in the order of 2-3 minutes (the time it takes to boot-up a machine).
Provision high power server(s) based on your needs. Keep them in the SHUTDOWN state (machine powered off). Whenever, you want to make use of the computing power, boot it up and use. You will be charged only for the amount of time that the server is RUNNING. Your data and server state would be preserved. The only charges that you would be paying for would be for storage which is extremely low. Here is the pricing calculator that you can use to estimate your costs.


text:
Q: If I transfer my character to Xbox One, can I continue playing on the 360? If I transfer my GTA 5 profile from an Xbox One to an Xbox 360, can I still play on the 360 and still get money and RP?

A: You can still play on your 360, and rank up and get money, yes, but what you do on your 360 after the point of transfer, will not count for your Xbox One character.
For example, if you transfer your 360 level 50 character to Xbox One, and then play your Xbox one character for a while, ranking it up to 60, your Xbox 360 character will still be level 50. This goes both ways.


text:
Q: Multiple data sources with different timeintervalls in the same table I have this situation:
Until recently I had a table in my db which got updated through a python script (running as a cronjob).
I've handled this the following way (commands in mysqldb-python):
DROP TABLE tmp IF EXISTS
CREATE TABLE tmp LIKE original
INSERT INTO tmp...
DROP TABLE original
ALTER TABLE tmp RENAME TO original

Now I have 2 sources of data for the same table. The table is going to be updated from the 2 sources in different timeintervalls (source 1 each 'x minutes', source 2 each 'y minutes'). I can't create a tmp table and insert the data there because the data from the other source isn't going to be included. I thought about adding a field Sourceto the table and then in the scripts:
DELETE FROM original WHERE Source = 'currentsource'
INSERT INTO original ...

Problem with this method is that the ID AUTO_INCREMENT doesn't reset. I don't particularly want to check for the current max ID and set the increment if there's a better solution.
Which solution would you suggest?


text:
Q: How to add a URL parameter by default in ASP.NET Core I'm working on a project where I need to access the windows username from the URL string from the launch of the app. I'm trying to get it to add the "?windowsusername=name" to the URL as soon as the app launches. If I redirect it to another action, it messes my routing up. Is there a way to get this added on launch? I am passing it in from the Startup.cs file and I know it's getting passed in because I can reference it using Razor. However, it's not being added to the URL string. Here's what I've tried in my Startup.cs file:
app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{windowsUsername}",
                    defaults: new { controller = "Home", action = "Index", windowsUsername = "name" });
            });

A: You should change your route to the following one:
 app.UseMvc(routes =>
 {
     routes.MapRoute(
         name: "default",
         template: "{controller}/{action}/{id?}",
         defaults: new { controller = "Home", action = "Index" });
 }

Then in the action you can access the username from id.
public ActionResult YourActionNameGoesHere(string id)
{

}

If you hit ControllerName/YourActionName/name then the id would has the value of name.


text:
Q: Why does the link to top of page not go to a named anchor in Internet Explorer? We have links in pages that should land a user on a specific page and scroll them to (a named anchor) near the middle of the page using the URL fragment #top. This works in every browser with the exception of Internet Explorer.
I am using Internet Explorer 11. As far as I know, this problem exists in all versions of IE.
This question is NOT about IE 8. The solution offered in a similar SO question doesn't work for me.
I've search all over and can't find examples of this being a problem and so I can't find solutions. In fact, I have found only one solution that describes the problem and provides a solution. However, their solution doesn't work for me.
I've moved little blocks of code here and there, but IE refuses to go to the named anchor. Why not?
A solution that doesn't work for us.
https://chrisjean.com/links-to-named-anchors-or-element-ids-fail-in-ie8/
Our link that should land the user in the middle of the page
http://www.av-iq.com/avcat/ctl1642/index.cfm?manufacturer=crestron-electronics&videos=6703#top
The named anchor on our page ...

Example links on our pages...

   next video

These do not work either ...


text:
Q: Code dosen't give output and keeps running I wanted to make a code that would give me all the answers to this question
My code:
import random
hen = 3
rooster = 5
boolean = True
lst = []
while boolean == True:
  dicti = {}
  qian = 100
  lst = []
  i = random.randint(1,12)
  i2 = random.randint(4,25)
  i3 = random.choice(list(range(3,85,3)))
  qian -= i3/3
  qian -= i2*hen
  qian -= i*rooster
  if qian == 0:
    if 15*i + 9*i2 + i3 == 300:
      dicti["chick"] = i3
      dicti["hen"] = i2
      dicti["rooster"] = i
      lst += [dicti]
  if len(lst) == 4:
    boolean = False

I have the ranges set up to the highest numbers in the answer section in the link I provided,
but it seems to be in a infinite loop, any ideas where I went wrong?
I am happy to any answer.
THANK YOU! :)

A: the loop will never because the ending condition is unreachable due to the list being set empty at the beginning of the loop.
just cancel the line where the list is set empty inside the loop and it should work:
import random
hen = 3
rooster = 5
boolean = True
lst = []
while boolean == True:
    dicti = {}
    qian = 100
    i = random.randint(1,12)
    i2 = random.randint(4,25)
    i3 = random.choice(list(range(3,85,3)))
    qian -= i3/3
    qian -= i2*hen
    qian -= i*rooster
    if qian == 0:
        if 15*i + 9*i2 + i3 == 300:
            dicti["chick"] = i3
            dicti["hen"] = i2
            dicti["rooster"] = i
            lst += [dicti]
        if len(lst) == 4:
            boolean = False


text:
Q: Convert Byte-range to Time-range in html  I have some sever-side code that currently supports the http byte range requests without an issue. However, I want to be able to transcode the video file (which is located on-disk) on-the-fly with ffmpeg before I send the transcoded chunk to the client, but ffmpeg requires I give it a seek time whereas I get byte ranges from the client. How would I be able to figure out the time range (seek time) of a video file given the byte range from the client browser?
I have already looked at this question which assumes the server already knows the specified time.
I am open to using an html5 video player which supports the use of time ranges to request data instead of byte ranges, but I have been unable to find an implementation or figure out how the javascript side of buffering <video> works.

A: You can run ffprobe and analyze its output to identify the timestamps.
Basic command is
ffprobe -i in.mp4 -show_entries packet=pos,pts_time,flags -select_streams v -of compact=p=0:nk=1 -v 0

This produces
0.000000|48|K_
0.133333|956|__
0.066667|996|__
0.033333|1053|__
0.100000|1602|__
0.266667|1811|__
0.200000|2371|__
0.166667|2746|__
0.233333|3294|__
....

The first column is the video frame timestamp, the 2nd is the byte offset for that frame and the 3rd is whether the frame is a keyframe.
Since you can only cut video at keyframes, when copying the stream, you will either have to cut at a timestamp whose flag is K or use the argument in the command below:
ffmpeg -ss X -i in.mp4 -c copy -avoid_negative_ts make_zero out.mp4

This is not needed if you're transcoding the video stream.


text:
Q: Easy Django REST Framework Websocket Usage I have a an application that uses Angular for the frontend and communicates with an API running Django RF.
Now, let me try and outline what I'm trying to achieve in hopes of finding an easy solution.
When a user runs a report, a worker version of the API generates the report to prevent the main API from bogging down. The report runs for a couple seconds/minutes. The user refreshes the page and voila, their report is there.
What I'm trying to achieve is the elimination of the whole "user refreshes the page" portion of this process.
My goal is to do this via websockets.
I literally want something as simple as:

*

*WEB: "Hey API, I want this report. I'll wait."

*API: "Yo dog, you're reports done."

*WEB: "Cool, let me refresh my report list. Thanks bud."

Now, we start to venture into an area I'm unfamiliar with. Websockets can do this, right? I just need to create a connection and wait for the all-clear to be sent by the worker.
Now, here's where it gets hairy.
I've spent the better part of the day going through libraries and just can't find what I need. The closest I've come is this, but it clashes with restframework. I get hit with tons of 404 errors and I think it has to do with the way rf manages urls.
I literally need a simple event listener. There's got to be a better way, right? To clarify, I don't want to do something brute-force like silently ping the API for report status. That gets a tad hinky. I want the API to tell me when it's ready.

A: In a basic way, can use something like django-websocket-redis and use Django signals to pass the messages around. ws4redis handles alot of the tricky bit. However, websockets are weird and honestly I doubt you need them. You could just poll some route that has the job state. If you need to get it done fast, I would go that route.


text:
Q: VBA formula won't calculate I am new to VBA and trying to put a formula in that is essentially just a sum function.
It's basically: =sum(A1:A5)
And it works - except it doesn't. When I click on it, it shows that it's working (i.e. it highlights the sum range as if it's calculating), but nothing sums up when I start entering numbers?
I've put this into the code but it still doesn't work: Application.calculation = xlCalculationAutomatic
I've searched the site and google for a solution and it seems other people have had a similar problem but I can't find/understand the solution.
Thanks in advance for any help!

A: Try this answer https://stackoverflow.com/a/154439/10645228
So you're close - switch it off and on again!


text:
Q: When using scrapy shell, I get no data from response.xpath I am trying to scrape a betting site. However, when I check for the retrieved data in scrapy shell, I receive nothing.
The xpath to what I need is: //*[@id="yui_3_5_0_1_1562259076537_31330"] and when I write in the shell this is what I get:

In [18]: response.xpath ( '//*[@id="yui_3_5_0_1_1562259076537_31330"]')
Out[18]: []

The output is [] but I expected to be something from which I could extract the href.
When I use the "inspect" tool from Chrome, while the site is still loading, this id is outlined in purple. Does this mean that the site is using JavaScipt? And if this is true, is this the reason why scrapy does not find the item and returns []?

A: i try scraping the site just using Scrapy and this is my result.
This the items.py file
    import scrapy

    class LifeMatchsItem(scrapy.Item):

        Event = scrapy.Field() # Name of event
        Match = scrapy.Field() # Teams1 vs Team2
        Date = scrapy.Field()  # Date of Match

This is my Spider code

    import scrapy
    from LifeMatchesProject.items import LifeMatchsItem

    class LifeMatchesSpider(scrapy.Spider):
        name = 'life_matches'
        start_urls = ['http://www.betfair.com/sport/home#sscpl=ro/']

        custom_settings = {'FEED_EXPORT_ENCODING': 'utf-8'}

        def parse(self, response):
            for event in response.xpath('//div[contains(@class,"events-title")]'):
                for element in event.xpath('./following-sibling::ul[1]/li'):
                    item = LifeMatchsItem()
                    item['Event'] = event.xpath('./a/@title').get()
                    item['Match'] = element.xpath('.//div[contains(@class,"event-name-info")]/a/@data-event').get()
                    item['Date'] = element.xpath('normalize-space(.//div[contains(@class,"event-name-info")]/a//span[@class="date"]/text())').get()
                    yield item

And this is the result


text:
Q: How the solar system just stay around the Sun and sSun itself? I know that each and every planet stay with the solar system because of sun's gravitational field. What object has the gravity to hold our solar system while the boundless universe is all around the solar system?

A: The Sun and all the planets orbit the centre of the Milky Way galaxy as shown below.


text:
Q: php twitter grab retweet user info i am working on a project in php.

*

*When we post something on twitter, i want to grab the users who have re-tweeted my tweet and store it in my database. I want to work in php and mysql.

*If I post a question on my tweet, i want grab the answers and save the userinfo of all the users who gave the right answer.
Any suggestions on how to get started?? Thanks :)

A: Here is a full twitter API class that someone has built that might be useful as well.
http://brandontreb.com/the-only-twitter-api-php-class-you-will-ever-need/
UPDATED:
Here is a RESTful API service for pulling retweets of your items:
http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-retweets
You can use a pre-existing class or build your own. It will most likely require cURL and XML knowledge. But if you understand PHP, you should be able to knock this out fairly quick.


text:
Q: Normal compilation works, cross however using the same rootfs fails I have following problem. I try to run cross compilation however some targets fails due to very strange error:
cd /home/pawel/Development/src/hal/build/tests && /usr/local/bin/cmake -E cmake_link_script CMakeFiles/focuscontrollerraw_test.dir/link.txt --verbose=1
/opt/gcc-linaro-arm-linux-gnueabihf-4.8-2014.04_linux/bin/arm-linux-gnueabihf-g++  --sysroot=/mnt/quantum-ubuntu   -std=c++11 -Wall -pedantic -Wextra   CMakeFiles/focuscontrollerraw_test.dir/focuscontrollerraw_test.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/focuscontrollerraw.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/manager.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/focuscontroller.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/hardwareexception.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/i2c.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/illuminator.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/illuminatorcontroller.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/rgbilluminator.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/tiva.cpp.o CMakeFiles/focuscontrollerraw_test.dir/focuscontrollerraw_test_automoc.cpp.o  -o focuscontrollerraw_test -lm -lpthread -lglib-2.0 /mnt/quantum-ubuntu/usr/lib/arm-linux-gnueabihf/libQt5Gui.so.5.2.1 -lCppUTest -lCppUTestExt /mnt/quantum-ubuntu/usr/lib/arm-linux-gnueabihf/libQt5Core.so.5.2.1
/mnt/quantum-ubuntu/usr/lib/libEGL.so.1: undefined reference to `gcoOS_SwapBuffersGeneric_Async'
/mnt/quantum-ubuntu/usr/lib/libEGL.so.1: undefined reference to `gcoOS_DrawSurface'
/mnt/quantum-ubuntu/usr/lib/libEGL.so.1: undefined reference to `gcoOS_ResizeWindow'
collect2: error: ld returned 1 exit status

The same compilation using quemu work like a charm however very slow:
cd /root/hal/build/tests && /usr/local/bin/cmake -E cmake_link_script CMakeFiles/focuscontrollerraw_test.dir/link.txt --verbose=1
/usr/bin/c++    -std=c++11 -Wall -pedantic -Wextra   CMakeFiles/focuscontrollerraw_test.dir/focuscontrollerraw_test.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/focuscontrollerraw.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/i2c.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/illuminator.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/manager.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/rgbilluminator.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/tiva.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/focuscontroller.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/hardwareexception.cpp.o CMakeFiles/focuscontrollerraw_test.dir/__/src/illuminatorcontroller.cpp.o CMakeFiles/focuscontrollerraw_test.dir/focuscontrollerraw_test_automoc.cpp.o  -o focuscontrollerraw_test -lm -lpthread -lglib-2.0 /usr/lib/arm-linux-gnueabihf/libQt5Gui.so.5.2.1 -lCppUTest -lCppUTestExt /usr/lib/arm-linux-gnueabihf/libQt5Core.so.5.2.1

Below my toolchain file:
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

set(CMAKE_SYSROOT /mnt/quantum-ubuntu)

set(tools /opt/gcc-linaro-arm-linux-gnueabihf-4.8-2014.04_linux/bin/arm-linux-gnueabihf)
set(CMAKE_C_COMPILER ${tools}-gcc)
set(CMAKE_CXX_COMPILER ${tools}-g++)

set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)

and CMakeList.txt:
project(hal)
cmake_minimum_required(VERSION 3.5)
cmake_policy(SET CMP0015 NEW)
###########################
# COMPILATION DEFINITIONS #
###########################
add_definitions(-Wall)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Wextra")
if(NOT CMAKE_TOOLCHAIN_FILE)
    if(NOT CMAKE_PREFIX_PATH)
        set(QT5_DIR /opt/Qt5.3.2/5.3)
        set(CMAKE_PREFIX_PATH ${QT5_DIR}/gcc_64/lib/cmake)
        message(STATUS "Set CMAKE_PREFIX_PATH to default path defined in CMakeLists = ${CMAKE_PREFIX_PATH}")
    endif()
endif()
#####################################
# INCLUDE USED MACROS AND FUNCTIONS #
#####################################
file(GLOB CmakeModules CMake/modules/*.cmake)
foreach(Module ${CmakeModules})
    include(${Module})
endforeach(Module)
###########################
# ADD PROJECT DEFINITIONS #
###########################
set(CppUTest CppUTest CppUTestExt)
include_directories(${CMAKE_SYSROOT}/usr/local/include)
set(SrcDir ${CMAKE_CURRENT_SOURCE_DIR}/src)
set(MainTestsDir ${CMAKE_CURRENT_SOURCE_DIR}/tests)
set(MocksDir ${CMAKE_CURRENT_SOURCE_DIR}/mocks)
set(HalMocksDir ${CMAKE_CURRENT_SOURCE_DIR}/hal_mocks)
file(GLOB_RECURSE SrcFiles src/*.cpp)
file(GLOB_RECURSE MocksFiles mocks/*.cpp)
file(GLOB_RECURSE HalMocksFiles hal_mocks/*.c hal_mocks/*.cpp)
file(GLOB_RECURSE HeadersFiles include/*.h)
file(GLOB_RECURSE ExceptionsFiles ../exception/*.h ../exception/*.cpp)
include_directories(include ../exception)
##################
# CONFIGURE LIBS #
##################
set(Libs m pthread glib-2.0)
# Configure Qt5
set(CMAKE_AUTOMOC ON)
set(Qt5Modules Core Gui)
configure_qt5("${Qt5Modules}")
# Remove below line if not use QT MOC
set(CMAKE_AUTOMOC ON)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GLIB_PKG glib-2.0)
include_directories(${GLIB_PKG_INCLUDE_DIRS})
######################
# TARGET DEFINITIONS #
######################
# Add fake targets to make visible all project's files in Qt Creator
add_custom_target(headers SOURCES ${HeadersFiles})
add_custom_target(sources SOURCES ${SrcFiles})
add_custom_target(mocks SOURCES ${MocksFiles})
add_custom_target(hal_mocks SOURCES ${HalMocksFiles})
# TEST DEFINITIONS
enable_testing()
set(TestTargets)
add_subdirectory(tests)
add_custom_target(check_deps DEPENDS ${TestTargets})
add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND} -VV DEPENDS check_deps)
# So target
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" )
add_library(hal SHARED ${SrcFiles})
target_link_libraries(hal ${Libs} )
#########################
# CONFIGURE INSTALLTION #
#########################
set(QUANTUM_INSTALL_DIR /opt/quantum)
# SET RPATH CONFIG
SET(CMAKE_SKIP_BUILD_RPATH  FALSE)
SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
SET(CMAKE_INSTALL_RPATH "${QUANTUM_INSTALL_DIR}/lib")
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

Any ideas what I'm doing wrong?


text:
Q: Upload Photo to server including location information (Lat/Long) Why is it so hard to upload a photo with Location data in its exif to the server? I am breaking my head not being able to solve this. Whenever I am sending the photo to the server all of its location information is being stripped off from the photo.
I have tried getting UIImage from the UIImagePickerController using both
NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];

and also UIImagePickerControllerOriginalImage.
Kindly someone help me

A: To preserve the exif info, you need to use the raw data, not just the UIImage. You can get it from the ALAsset's defaultRepresentation, something like this:
ALAssetRepresentation* representation = [myAsset defaultRepresentation];
int size = representation.size;
NSMutableData* data = [[NSMutableData alloc]initWithCapacity:size];
void* buffer = [data mutableBytes];
[representation getBytes:buffer fromOffset:0 length:size error:nil];
data = [NSMutableData dataWithBytes:buffer length:size];

I'm not near xcode to test it right now, but it should work.

A: You can use CLLocation to get the current location.
At the time of image upload to server you need to need to get the current location through CLLocationManager and update this location parameters to server with the captured image.
Please check the reference link for location update and how to upload photos


text:
Q: Test a method with JUnit How can I test this method :
public void updateTable() {
    try {
        String sql = "select * from userDetails";
        rs = st.executeQuery(sql);
        st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        table.setModel(DbUtils.resultSetToTableModel(rs));
    }
    catch(Exception e) {
    }

A: Few suggestions to make this more testable.
updateTable method is doing two things here.

*

*Execute query and get results

*Apply the result set to the table.

I would refactor to have two methods.

*

*public ResultSet getResultSetForQuery(String sql,Statement st)

*public Table updateTable(ResultSet rs)
Writing tests for the above two methods should be straightforward.

A: The two main points of any good test are:

*

*Check that it works well

*Localize the error if it's exist

Check that it works well
Localize the error if it's exist
In your case we cannot perform such a good testing to localize the error if it's exist because your method does too complex job. It wold be good to refactor your method into several methods to make it more readable and testable. I agree with @AjayGeorge about the way to separate that method.
And then you can write something like:
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.sql.ResultSet;

public class TestExample {

    @BeforeClass
    public static void setup() {
        // init your connection here
        // and insert data for tests
    }

    @AfterClass
    public static void cleanup() {
        // close connection
    }

    @Test
    public void testTableUpdate() {

        // initialize 'sqlQuery' and 'statement'

        ResultSet resultSet = getResultSetForQuery(sqlQuery, statement);

        // check 'resultSet' with JUnit methods like assertTrue

        updateTable(resultSet);

        // check that table is filled as you expected
    }

}

A: There are so many java libraries available to mock the large data to help testing database related methods. For example Mockito / EasyMock / JMock and more. You can make use of these libraries. You can mock the expected results using the tools and you can test your methods with the expected results.

A: JUnit: In general, you write a test class like the following and annotate the method(s) that contains you test with @Test. If you want to write a test that has to fail, you can use the 'expected' attribute of the annotation. If you know your test might be running for too long and want it to timeout after a certain period of time, use the 'timeout' attribute in the annotation.
If you have certain logic for initialization before each test method, you put that into another method and annotate that one with @Before. Likewise, to free stuff up, you use @After. For initialization that is to be run once per test class, use the annotation @BeforeClass and make sure that method is public and static - same story with @AfterClass.
In general, in each test method you go like this: Execute some of your code and then make assertions about what you would expect to be the case. In my example, I am testing the method 'myAdd' and I expect that 1+1 adds up to two 2.
public class MyTest {
  @Test
  public void testAddition() {
    int sum = myAdd(1, 1);
    assertEquals(2, sum);
  }
}

This example is based on JUnit: https://github.com/junit-team/junit/wiki
There are alternatives, like TestNG: http://testng.org/doc/index.html
If you want to test the behaviour of a certain class in relation to its depdencies, a mock framework is recommended. Examples include: jmock, mockito, etc


text:
Q: I can't display my table (codeigniter) I have searched this site for the answer, but all the answers i got didn't work.
MODEL:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_product extends CI_Model
{
    function __construct()
    {
         // Initialization of class
        parent::__construct();
    }
    function viewauction()
    {
        $query = $this->db->select('*')->from('producten')->get();
        return $query->result();
    }
}

CONTROLLER:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller
{
    function __construct()
    {
         // Initialization of class
        parent::__construct();
    }
    public function index()
    {
        $this->load->model('model_product');
        $data ['query'] = $this->model_product->viewauction();
        $this->load->view('header');
        $this->load->view('welcome_message', $data);
        $this->load->view('footer');
    }
}

VIEW:

        Naam
        Beschrijving
        Prijs
        Vooraad
        Categorie

        <?php foreach($query as $row): ?>

        <?php echo $row->naam; ?>
            <?php echo $row->beschrijving; ?>
            <?php echo $row->prijs; ?>
            <?php echo $row->producten_op_voorraad; ?>
            <?php echo $row->categorie; ?>

        <?php endforeach; ?>

I get a empty output. no error's
I have 1 item in the table.
To be sure here is the database file:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = '127.0.0.1';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = 'webshop';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

A: it seems a type in table name make sure table with producten name is present in db
and your config is missing $db['default']['username'] = ''; you need to a username, generally it will be $db['default']['username'] = 'root'; on localhost
$query = $this->db->select('*')->from('producten')->get();

you can get result using just
$query = $this->db->get('producten');

A: In your model, try this:
function viewauction()
{
    $query = $this->db->get('producten');
    return $query->result();
}

Note that $this->db->get('tablename') is the standard syntax of select * from table query in Codeogniter Active Records Class. Please check this out: https://ellislab.com/codeigniter/user-guide/database/active_record.html
Additionally, you can try this in your controller, to check whether all the data are coming from your query inside the array $data['query']:
$data ['query'] = $this->model_product->viewauction();
//do the following to check whether you got the data correctly from your query and inside the array.
$echo "
";
print_r();
die();

Edit - 1:
If my solution doesn't work, then I'm pretty sure the problem is with your database config file. I've a few observations and questions:

*

*Why are you using the address '127.0.0.1' in your database default hostname? Isn't 'localhost' a better option?

*Why don't you have a username for your database? Usually in mysql the default username is root. I think you should set $db['default']['username'] = 'root';

*Is your database name correct? Is it really 'webshop'?

I'm pretty much sure the problem is somewhere out here. Please check.

A: I would attack the problem from the root up, and FIRST OF ALL, activate the debug database. As you're in localhost AND ONLY WHEN YOU'RE IN LOCALHOST, active the debug database from codeigniter: Change this line in your config dabase.php:
$db['default']['db_debug'] = TRUE;

And run it again, if there exists a database problem it'll arise.
If not, go checking where you have problems:
First: Make sure your query will take results: As @Shaiful Islam points out, first check what sql sentence you run, and if that gives you back result:
function viewauction()
{
   $query = $this->db->select('*')->from('producten')->get();

   $results = $query->result();

   echo $this->db->last_query();

   return $results;
}

This will give you back the SQL you're running, and you can run it directly and check if you're receiving results from the SQL.
Second: If you run the SQL and get data, print it in the controller to check if they work correctly:
public function index()
{
    $this->load->model('model_product');
    $data ['query'] = $this->model_product->viewauction();

    // Check the data:
    var_dump( $data['query'] );

    $this->load->view('header');
    $this->load->view('welcome_message', $data);
    $this->load->view('footer');
}

Third: If above went well, last thing is checking data in the view: In the first line of the file, write:
<?php var_dump($query); ?>

With all that, you should know where the data are missed, and with that, it'll be easy to know where the problem is.


text:
Q: crystal reports 10, asp classic, iis 7.5: http error 401 I have an ancient report written using Crystal Reports < 10 (it should be version 8 or 9) currently filled by an ASP classic application depending on Crystal Engine 10; the application is hosted on a Windows Server 2003 R2 machine that must be upgraded so I have to move the application while waiting for it to be rewritten.
The application itself is running ok on the new server (Win 2008 R2/IIS 7.5, this specific version is a requirement), only the reports are broken, show no data at all, nothing on the screen but report controls (zoom, send, print, export); the odd thing is that I can export the report as PDF and once downloaded open it and read the expected data.
Using developer tools of IE I notice that the ASP page called by the CR component to load the data (the file is RDCrptserver10.asp) fails to load with a 401 authentication error message for no apparent reason: the page is in the same folder as the other pages that I browse to make the report load and has the very same permission of the other pages.
Trying to access the url of that page directly (cut & paste from developer tool into browser bar) IE produces a generic error message 'page unavailable' and not a 401 error.
Moreover in both cases (direct url access and rtp load) the IIS log has a 200 success entry (yes, IIS say that the page was shipped successfully in both cases).
I'm stuck because after checking all that comes to my mind I can't have the report to work on the new server.
My checks and attempts:
- odbc data source: the name is correct, tested user & pass working ok. also should the source be broken i would not be able to download the file as PDF with actual and up to date data
- path of files: there are no 404 errors, double checked that required files are in place and accessible
- completely removed authentication for the folder containing the relevant files (the app is in a company intranet with integrated windows authentication) but still get a 401 error when loading the report
- checked the ntfs and iis permission of the involved files
- double checked the software version of the crystal engine to be the same currently installed on the old server
- the component called by the ASP page to load the report exists on the server
- there is no error in the event viewer
Does anyone experienced similar issues with crystal/asp on iis 7.5?

A: I found a solution to the issue in a really unexpected way: some  Response.Flush() dropped here and there in the RDCrptserver10.asp page allowed the report to be filled successfully on the new server.
the old code running successfully since ages is:
Response.AddHeader "CONTENT-LENGTH", lenb(temp)
Response.ContentType = EPFMIMETYPE
Response.BinaryWrite temp

to make it run on the new server it has to be changed as follows:
Response.AddHeader "CONTENT-LENGTH", lenb(temp)
Response.ContentType = EPFMIMETYPE
Response.BinaryWrite temp
Response.Flush

in the above page there are many block similar to that one with minor variation in parameters and/or ContentType depending on the different input but adding a flush after each BinaryWrite fixed the issue, 401 failure and all.
I'm still puzzled by the 401 error but at least now it works...


text:
Q: How to add 1 to each letter in a string and print? I am trying to access each character in a string and add 1 to it before printing out the text. Eg. my code will prompt the user for a text ie. hello and it should print that text plus 1 character(i.e. output "ifmmp" when the input is "hello"). From my code below, instead of a for loop, I am trying to use a while loop to do this however I am running into some issues and it doesn't seem to print the response. Any help greatly appreciated.
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])

{
    // If
    if (argc == 2 && (atoi(argv[1]) > 0))
     for(int i = 0, len = strlen(argv[1]); i < len; i++)
        {
            char n = argv[1][i];
            int digit = isdigit(n);

            if (!digit)
            {
                printf("Usage: ./caesar key\n");
                return 1;
            }

            else
            {
              string plain = get_string("plaintext: ");
              int k = 0;
              int len_plain = strlen(plain);
              while (len_plain > k)
                    k++;
                    char cipher = plain[k];

                    {
                         printf("%c\n", cipher);
                    }
            }
        }
    else
    {
       printf("Usage: ./caesar key\n");
       return 1;
    }
}

A: Your question seems to be:

am trying to access each character in a string and add 1 to it before printing out the text

That can be done in many different ways - here is one example:
#include <stdio.h>

int main(void) {
    char str[10] = "hello";
    int i = 0;
    while(str[i])
    {
        ++str[i];  // Add 1
        ++i;
    }
    printf("%s\n", str);
    return 0;
}

Output:
ifmmp


text:
Q: how to combine and compare two variables dynamically in bash? i have variable $var and $var2. I created a random number via rand=$((RANDOM % 10)).
now if I want to combine $var and $var2 and assign value of $rand to them:-
#! /bin/bash

rand=$((RANDOM % 10))
var2=1

var_$var2="$rand"

And i want to compare them too:-
[[ $var_$var2 -eq 0 ]] && echo "Its zero"

This obviously doesn't work, then how exactly can I declare and Compare two variable dynamically?

A: You have a couple of choices.
Do to exactly what you want, you can use the eval statement to take the result of an expression and execute it as a shell command. For example:
eval selected=\$x$randomnum
if [[ $selected == $player ]]; then
   ...
fi

The expression passed to the eval statement becomes selected=$x1, which we then evalute, setting selected to the value of $x1.

But a better structure for this would be to use an array variable instead of a series of named variables, something like:
randomnum=$(( RANDOM % 10 ))
x=( 1 1 1 1 1 0 0 0 0 0 )
player1 = 1

if [[ ${x[$randomnum]} == $player1 ]]; then
    ...
fi

A: You need to do this :-
#!/bin/bash

a='1'
b=5
c="${a}${b}"
echo $c

d=15

if [[ $c == $d ]]; then
        echo "it end!"
    fi


text:
Q: Unexpected token in build output I'm new to Travis and getting this error in the build output:
Setting environment variables from .travis.yml

$ export DOCKER_COMPOSE_VERSION=1.23.1

0.01s$ source ~/virtualenv/python3.6/bin/activate

$ python --version

Python 3.6.3

$ pip --version

pip 9.0.1 from /home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages (python 3.6)
before_install.1

0.01s$ sudo rm /usr/local/bin/docker-compose
before_install.2

0.13s$ curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-'uname -s'-'uname -m' > docker-compose
before_install.3

0.00s$ chmod +x docker-compose
before_install.4

0.01s$ sudo mv docker-compose /usr/local/bin
install

10.72s$ pip install -r requirements.txt

0.02s$ docker-compose up -d --build

/usr/local/bin/docker-compose: line 1: syntax error near unexpected token `<'

This is strange because there is < nowhere in my docker-compose files. Why am I seeing this error ?

A: The problem doesn't come from your docker-compose.yml project file but from from the docker-compose file itself, which has not been properly downloaded; namely it is not a binary, but a HTML file (hence the < character you got):
$ export DOCKER_COMPOSE_VERSION=1.24.1
$ curl -L https://github.com/docker/compose/releases/download\
  /${DOCKER_COMPOSE_VERSION}/docker-compose-'uname -s'-'uname -m' > docker-compose

$ file docker-compose
docker-compose: HTML document, ASCII text, with CRLF line terminators

$ head docker-compose
<!DOCTYPE html><title>Malformed request</title>
<body>We didn't receive a proper request from your browser. Please contact us if the problem persists.</body>
</html>

To solve this, you should fix your script by using the command substitution $(uname -s), instead of 'uname -s':
$ curl -L https://github.com/docker/compose/releases/download\
  /${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m) > docker-compose

$ file docker-compose
docker-compose: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (...)


text:
Q: Linear programming, Help! Can someone please help me.
I have a function
f[x_] := 3*(x - Pi/2)*(Sin[4*x])^2 + 2*Cos[3*x]

and I need to find coefficients of function
g[x_]:= c1 + c2*x + c3*x^2 + c4*x^4

so that maximum absolute error of ( Abs[f[x] - g[x]]) is minimized. On the range of 0 <= x <= Pi.
Please help me, I'm desperate.

A: Sorry, I was away from my computer and could not write up an answer right away. I think this is what you want:
Generate some data points that FindFit can work with:
data = Table[{x, f[x]}, {x, 0, Pi, Pi/1000}];

Use FindFit with the infinity norm (see the docs of NormFunction for an example):
bestfit = FindFit[N@data, g[x], {c1, c2, c3, c4}, x, NormFunction -> (Norm[#1, Infinity] & )]

{c1 -> 0.880948, c2 -> -8.93938, c3 -> 6.25143, c4 -> -0.385789}

Notice that it is different when least squares is used:
FindFit[N@data, g[x], {c1, c2, c3, c4}, x]

{c1 -> 1.4222, c2 -> -10.3303, c3 -> 6.92248, c4 -> -0.409044}

Store the best-fit expression:
h = g[x] /. bestfit;

Compare:
Plot[{f[x], h}, {x, 0, Pi}]


text:
Q: Given a stochastic matrix $P$, find a markov chain $\{X_n\}$ having $P$ as its transition matrix
We know that ginen a (discrete time) markov chain $\{X_n\}$, its transition matrix is stochastic.
  Is the inverse true? I.e. given a stochastic matrix $P$, is there a (discrete time) markov chain $\{X_n\}$ having $P$ as its transition matrix?

Attempt. I believe so. We are dealing with an existence theorem, and my idea has been the use of Kolmogorov's extension theorem, since it guarantees the existance of a desired markov chain under certain properties. Am I on the right path?
Thanks for the help!


text:
Q: Why is this health bar not working in Unity2d My HealthBar script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthBar : MonoBehaviour
{

    public Slider slider;
    public Gradient gradient;
    public Image fill;

    public void SetMaxHealth(int health)
    {
        slider.maxValue = health;
        slider.value = health;

        fill.color = gradient.Evaluate(1f);
    }

    public void SetHealth(int health)
    {
        slider.value = health;

        fill.color = gradient.Evaluate(slider.normalizedValue);
    }

}

My Player script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public int maxHealth = 100;
    public int currentHealth;

    public HealthBar healthBar;

    private void Start()
    {
       currentHealth = maxHealth;
       healthBar.SetHealth(maxHealth);
    }

    private void Update()
    {
       if (currentHealth == 50)
       {
           healthBar.SetHealth(currentHealth);
       }

       if (currentHealth == 0)
       {
           Die();
        }
     }

     private void OnCollisionEnter2D(Collision2D collision)
     {
         if (collision.gameObject.CompareTag("Enemy"))
         {
             TakeDamage(50);
         }
     }

     void TakeDamage(int damage)
     {
         currentHealth -= damage;
     }

    void Die()
    {
       Destroy(gameObject);
       LevelManager.instance.Respawn();

       healthBar.SetHealth(maxHealth);
     }
 }

My LevelManager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;

public class LevelManager : MonoBehaviour {
    public static LevelManager instance;

    public Transform respawnPoint;
    public GameObject playerPrefab;

    public CinemachineVirtualCameraBase cam;

    [Header("Currency")]
    public int currency = 0;

    private void Awake() {
       instance = this;
    }

    public void Respawn() {
       GameObject player = Instantiate(playerPrefab,
       respawnPoint.position, Quaternion.identity);
       cam.Follow = player.transform;
    }

    public void IncreaseCurrency(int amount) {
       currency += amount;
    }
}

The errors that I am getting:
NullReferenceException: Object reference not set to an instance of an object
Player.Start () (at Assets/Scripts/Player.cs:15)

NullReferenceException: Object reference not set to an instance of an object
Player.Update () (at Assets/Scripts/Player.cs:22)

NullReferenceException: Object reference not set to an instance of an object
Player.Die () (at Assets/Scripts/Player.cs:49)
Player.Update () (at Assets/Scripts/Player.cs:27)

I have been trying to figure the problem out for a while. It works, when I die once. unfortunately, when I try die again,it doesn't work . The error message pops up, when I collide with the enemy.
How do I fix these errors pls help.

A: Is the healthBar being destroyed on death? It makes sense since we want to make the health bar disappear when the player dies but make sure to instantiate it again on respawn.

A: You should assign a HealthBar component to PlayerScript's healthBar property  from inspector.


text:
Q: SVG to After Effects workflow? I have a JavaScript chart component that outputs SVG. (It's kind of like an animated bar chart with a time slider.)
One of my clients would like to customize this animation further in After Effects - perhaps add some other background colors, depth etc.
What would be a good workflow for this?
(Let's say the timespan of the visualization is 30 years.
I could easily save one SVG file per year - then open these in illustrator. Resave the files as .ai for import into After Effects. Then I think After Effects can understand that this is a range of layered files and space the SVGs evenly on the timeline? Can it also add motion tweens inbetween the "years" for the vector objects (if each layer only has one object) to make the animation even smoother?)


text:
Q: How to power on a computer after a power failure? Background
I have a Ubiquiti Network Video Recorder (NVR) connected to an Eaton 3S 550 UPS. The NVR is basically a tiny PC running Debian, which records video from network cameras on the LAN. My goal is to always keep the NVR running, or if there is a power failure to shut it down properly.
Shutting it down properly turned out to be doable by installing NUT (Network Up Tools) which automatically issues a shutdown command when the UPS reaches 60% battery. The UPS is connected by USB to the NVR.
Turning it back on also turned out to be easy by setting the BIOS of the NVR to "Power on" on "AC connected". And since the UPS will automatically kill power to the mains outputs after the NVR has shut down (it detects this via USB), when the power comes back the UPS will switch on power to the mains output and the NVR will boot back up.
The Problem
However, there is one tricky scenario that I can't figure out how to handle. Imagine there is a power failure, the UPS battery reaches 60% and the NVR starts shutting down (which takes about 20-40 seconds). If the power comes back while the NVR is still shutting down, it will of course finish shutting down and power itself off - but since the UPS didn't turn off its mains output yet, the "AC connected" event won't occur, and the NVR will stay off. The only way to power it up again would be to manually press the power button or if there is another power failure long enough for the UPS to turn its mains output off , and then on when the power comes back.
How would one solve this?
What I've tried so far
I've played around with Wake On LAN, which is available in the BIOS but doesn't seem to work in real life (the ethernet port doesn't even have a light on when the NVR is powered off). My thinking was that some device, perhaps just a simple dedicated Arduino connected to mains (not on the UPS) could issue a WOL to the NVR either when it powers on or periodically every minute or so.
The "brute force" solution would be to build an Arduino rig with a servo that can push the power button on the NVR - which might work but be quite clumsy and a hassle to get right. The NVR is as mentioned a tiny PC running Debian, and I really want to avoid messing around with trying to open it up and connecting anything (e.g. an Arduino) straight to the power button solder points...
The Question
What other tricks could I try to either prevent this scenario from happening or to resolve it?


text:
Q: File reading using OpenCSV I use OpenCSV for CSV files reading and writing. It worked fine until I hsd to install earlier version of Java - i.e. Java 6. After installing it, my code stopped working:

Exception in thread "main" java.lang.UnsupportedClassVersionError:
  com/opencsv/CSVReader : Unsupported major.minor version 51.0  at
  java.lang.ClassLoader.defineClass1(Native Method)     at
  java.lang.ClassLoader.defineClassCond(Unknown Source)     at
  java.lang.ClassLoader.defineClass(Unknown Source)     at
  java.security.SecureClassLoader.defineClass(Unknown Source)

A: Check the version of the class file in your OpenCSV .jar dependency, for example:
javap -verbose -cp opencsv.jar com.opencsv.CSVReader | grep major

If this shows a version newer than 50 (= newer than Java 6) then you cannot use this jar.
You need to get a .jar file built with Java 6 or older. (If it can be built with Java 6 at all.)
I just confirmed that the latest version of the source code doesn't compile with Java 6,
as it uses Java 7 features (naturally).
But not too long ago, as of August 2014 the project was still on Java 5.
So if you download an older version of the jar it should work.
In other words, since you downgraded your Java version,
you also need to downgrade your OpenCSV dependency.
UPDATE
From SourceForge, version 2.3 contains a jar file that should be suitable for you:
$ javap -verbose -cp deploy/opencsv-2.3.jar au.com.bytecode.opencsv.CSVReader | grep major
  major version: 50

Note that the package name is a bit different from the current version.

A: When OpenCSV was upgraded to 3.0 the decision was made to upgrade to Java 7.  This was done for several reasons.  The main reason being that the largest reason was that the main fixes in 3.0 was to support the lazy checks in Lambdas that are in Grails (possibly Java 8) so it was requested the code be compiled in Java 7 because it is more optimal for Grails.  I allowed that because Oracle had announced it was dropping support for Java 7 in 2015 and Java 5 & 6 had long since been unsupported plus I had a small number of emails asking when I was going to port opencsv to java 7 (and only one for java 8 for some reason) so I felt that moving to java 7 was safe.  The last was that I develop using a mac and no longer have access to a java 5 compiler and I really did not feel good about pushing out a Java 5 version of opencsv built using java 7.
In hindsight seeing the issues that this caused (you are the third that I know of that cannot upgrade because of this) I would have left it at Java 5 and asked the Grails users to perform a performance test and myself build opencsv in a Ubuntu VM on my mac.   But since it is out I don't want to downgrade and possibly effect users as well.
If you cannot upgrade your project to java 7 you do have two options:  the first is that on the sourceforge and maven repositories you can download the older versions.  So 2.4 and earlier was built using java 5.  The other option is that you can download the code and build it yourself.  Thanks to KommradHomer the current code base is compatible with Java 6 and will build as is with a Java 6 compiler (you just need to change the pom file).

A: I am seeing the same issue. Please let me know which version of openCSV I can use to be compatible with java version "1.6.0_22" ? OpenCSV 2.3 does not work for me.


text:
Q: problem with react slick: import { baseUrl } from "./config After having imported everything and installed, I copy and paste any carousel of the code offered by the page, managing to work with the exception of this, the main problem being "baseUr"After having imported everything and installed, I copy and paste any carousel of the code offered by the page, managing to work with the exception of this, the main problem being the "baseUrl"
import React, { Component } from "react";
import Slider from "react-slick";
import { baseUrl } from "./config";

export default class CenterMode extends Component {
  render() {
    const settings = {
      customPaging: function(i) {
        return (

            <img src={`${baseUrl}/abstract0${i + 1}.jpg`} />

        );
      },
      dots: true,
      dotsClass: "slick-dots slick-thumb",
      infinite: true,
      speed: 500,
      slidesToShow: 1,
      slidesToScroll: 1
    };
    return (

Custom Paging

        <Slider {...settings}>

        </Slider>

    );
  }
}

enter image description here

A: You just need to create at the root of your project a config.js file like this:
config.js
export const baseUrl = window.location.origin + '/img';
// 'img' is the images folder in 'public' (project_name/public/img/)

In your slider component
import { baseUrl } from '../config';
// '../config' instead of './config'

Demo: Stackblitz


text:
Q: Finding duplicate strings in object using $.map From following code I am expecting that elist will contain each string in er only once. I mean elist will have unique value of er. But I am not getting unique strings in elist. Whats wrong here?
i = 0;
elist = "";
$.map(er, function(value, key){
    if ( isDuplicate(value, er, i) < 0 ) {
        elist += value;
    }
    $("#"+key).addClass('has-error');
    i += 1;
});

function isDuplicate(str, er_, offset){
    j = 0;
    return_val = -1

    $.map(er_, function(value, key){
        alert(j +'>'+offset+'------'+value+'=='+str);
        if ( j > offset && value == str){
            return_val = j;
            alert('matched');
        }
        j += 1;
    });

    return return_val;
}

A: You can use something more simple like this:
var arr=[];
$.map(er, function(value, key){
    if   ( arr.indexOf(value) == -1 )
   {arr.push(value);}
});
alert(arr.join());

http://jsfiddle.net/7cohow41/3/


text:
Q: If not being caught disord.py def check(m):
        return m.author == ctx.author and ctx.channel == m.channel

for index, i in enumerate(txtare):
    await ctx.send(f'What is the {txtare[index]}')
    try:

        variable = await client.wait_for('message',timeout=time_out, check=check)
        if variable.content == '!end':
            print(variable.content)
            return
        draw.text((x_axis[index], y_axis[index]),codecs.decode(str(variable.content), "unicode_escape"),(0,0,0),font=font2)
    except asyncio.TimeoutError:
        await ctx.send("Time out!")
        return

why isn't it stopping neither recognizing that I wrote !end
So to explain 'variable' is what the discord user sends the bot. then I want to check the variable.content (the content of the message) and if it says !end the command should stop


text:
Q: ggplot: How to display multiple groups via color and shape with point and line I want to draw a point-line chart of x-y-variables and highlight two groupings. I know some of the options to distinguish factors, like fill, shape, col or group. For the first group I would like to have color and for the second shape (which may or may not have the same color). And I need a legend to distinguish both groupings (which I already have). Perhaps I have to put aes in geom_line or geom_point, but I'm not sure. Since later on I would like to adjust size of the shapes (to better distinguish those).

*

*How to connect those points by colored lines?

*How to adjust size of the shape group?

Here is my code:
library(ggplot2)
data <- data.frame(id1=c(1,1,1,2,2,2,3,3,3,4,4,4),
                  id2=seq(1:3), year=seq(from=2007, to=2018, by=1),
                  variable=rep(c(5:8), each=3))

# two groups by color and shape, but it drops the line (seperate legends, thats nice)
ggplot(data, aes(x=year, y=variable, col=factor(id1), shape=factor(id2))) +
  geom_line() + geom_point()

A: Based on further information in comments from the OP, we are looking for something like this:
ggplot(data, aes(x=year, y=variable, col=factor(id1))) +
  geom_line() +
  geom_point(aes(shape=factor(id2), size = factor(id2))) +
  labs(shape = "group 2", colour = "group 1", size = "group 2")


text:
Q: Customer Balance Aging Report I am trying to build a report on SQL server which will provide a customer's average days of due settlement.
here's the sample table from which i want to generate report from

Customer
Date
Debit
Credit

abc
2021-04-01
10000
0

abc
2021-04-08
0
3000

abc
2021-05-02
1000
1000

abc
2021-06-09
0
2000

abc
2021-07-10
2000
1000

abc
2021-08-11
0
4000

abc
2021-09-10
0
3000

Here I am trying to generate a report that the customer abc had cleared the due to $10000 which he owed on 2021-04-01 was cleared on 2021-08-11 and which the customer took 132 days to clear and the second due ($1000) owed on 2021-05-02 was cleared on 2021-08-21 which took 101 days and the due of $2000 made on 2021-07-10 was cleared on 2021-09-10 which took 62 days to clear.
so the desired output is

Customer
settlement_days

abc
132

abc
101

abc
62

I tried to do this with SQL cursors but I was stuck after I got the result 132. Please find the code below
begin
        declare @date as date
        declare @debit as int
        declare @debit1 as int=0
        declare @credit as int
        declare @credit1 as int=0
        declare @balance as int=0
        declare @date1 as date
        declare @i as int=0
        declare @count as int
        declare @k as int=0

        declare closing scroll cursor for
        select convert(date,date),debit,credit from samples
        select  @count= count(debit) from samples
        open closing
        fetch next from closing into @date, @debit, @credit ;
        while @@FETCH_STATUS=0
        begin
        set @balance=@credit-@debit
        set @date1=@date
        set @debit1=@debit
        while @@FETCH_STATUS=0

        begin
                set @balance=@balance+@credit
                set @credit1=@credit1+@credit
                set @i=@i+@debit
                if (@k<=@debit1)
                begin
                    set @k=@k+@debit
                end

                if @balance>0
                begin
                        print(datediff(day,@date1,@date))
                        print (@credit1-@debit1)
                        print (@k)
                        break

                end
                fetch next from closing into @date, @debit, @credit;

        end
        fetch next from closing into @date, @debit, @credit;
        end

        close closing
        deallocate closing
end

I am stuck here about not knowing how to proceed further

A: Using window function sum() over () to find cumulative sum for Total Debit and Total Credit. After that find earliest date where Total Credit >= Total Debit. That's the settlement date
with
debit as
(
    select  *,
            -- cumulative sum
            sum(Debit) over(partition by Customer order by [Date]) as Dr
    from    samples s
    where   Debit   > 0
),
credit as
(
    select  *,
            -- cumulative sum
            sum(Credit) over(partition by Customer order by [Date]) as Cr
    from    samples s
    where   Credit  > 0
)
select  *, datediff(day, dr.[Date], cr.[Date]) as SettlementDays
from    debit dr
        cross apply
        (
            select  top 1 cr.[Date]
            from    credit cr
            where   cr.Customer  = dr.Customer
            and     cr.Cr       >= dr.Dr
        ) cr
order by dr.Customer, dr.[Date]

db<>fiddle demo


text:
Q: Simple Text Editor does not show the list of notes I was trying to run the code that I found here
http://www.androidauthority.com/lets-build-a-simple-text-editor-for-android-773774/
My problem is that when I add a new note, it is saved but when I try to display the list of saved notes it does not work as intended
this is the code:
public class Select extends AppCompatActivity {

private List<NoteBuilder> notesList = new ArrayList<>();
private NoteAdapter nAdapter;
private RecyclerView notesRecycler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent newNote = new Intent(Select.this, MainActivity.class);
            Select.this.startActivity(newNote);
        }
    });

    notesRecycler = (RecyclerView) findViewById(R.id.notes);

    nAdapter = new NoteAdapter(notesList);
    RecyclerView.LayoutManager mLayoutManager =
            new LinearLayoutManager(getApplicationContext());
    notesRecycler.setLayoutManager(mLayoutManager);
    notesRecycler.setItemAnimator(new DefaultItemAnimator());
    notesRecycler.setAdapter(nAdapter);

    prepareNotes();

}

private void prepareNotes() {
    File directory;
    directory = getFilesDir();
    File[] files = directory.listFiles();
    String theFile;
    for (int f = 1; f >= files.length;
         f++) {
        theFile = "Note" + f + ".txt";
        NoteBuilder note = new NoteBuilder(theFile, Open(theFile));
        notesList.add(note);
    }

}

public String Open(String fileName) {
    String content = "";
    try {
        InputStream in = openFileInput(fileName);
        if (in != null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(tmp);
            String str;
            StringBuilder buf = new StringBuilder();
            while ((str = reader.readLine()) != null) {
                buf.append(str + "\n");
            }
            in.close();

            content = buf.toString();
        }
    } catch (java.io.FileNotFoundException e) {
    } catch (Throwable t) {
        Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
    }

    return content;
}
}

I am confused. What can be the problem here?
Code for saving the note:
public class MainActivity extends AppCompatActivity {
EditText EditText1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Save("Note1.txt");
        }
    });

    EditText1 = (EditText) findViewById(R.id.EditText1);
    EditText1.setText(Open("Note1.txt"));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

public void Save(String fileName) {
    try {
        OutputStreamWriter out =
            new OutputStreamWriter(openFileOutput(fileName, 0));
        out.write(EditText1.getText().toString());
        out.close();
        Toast.makeText(this, "Note saved!", Toast.LENGTH_SHORT).show();
    } catch (Throwable t) {
        Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
    }
}

public String Open(String fileName) {
    String content = "";
    if (FileExists(fileName)) {
        try {
            InputStream in = openFileInput(fileName);
            if ( in != null) {
                InputStreamReader tmp = new InputStreamReader( in );
                BufferedReader reader = new BufferedReader(tmp);
                String str;
                StringBuilder buf = new StringBuilder();
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n");
                } in .close();
                content = buf.toString();
            }
        } catch (java.io.FileNotFoundException e) {} catch (Throwable t) {
            Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    }
    return content;
}

public boolean FileExists(String fname) {
    File file = getBaseContext().getFileStreamPath(fname);
    return file.exists();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

A: You prepare the notes after setting it to the adapter. I think this will fix it:
prepareNotes(); //do this first? <<<<<<<
 notesRecycler = (RecyclerView) findViewById(R.id.notes);

nAdapter = new NoteAdapter(notesList);
RecyclerView.LayoutManager mLayoutManager =
        new LinearLayoutManager(getApplicationContext());
.....


text:
Q: Entity Framework SaveChanges Return Error. AddObject Does not set Primary Key I have a Property table and another is Detail table. Where I am using disconnected approach where multiple properties are added and then when we click the save button it will save changes to the database. This approach of not saving for every property added is because user can delete from the list also.
Here's what I am doing
foreach (Property P in Results)
{
  if(P.PropertyId==0 && P.EntityState==EntityState.Added)
    Repository.Properties.AddObject(P);
}

but when I try to save the data
public void Save()
{
  Repository.SaveChanges();
}

it returns error

Unable to determine the principal end of the 'database.FK_Details_Property'
  relationship. Multiple added entities may have the same primary key.

I think its because every time I call AddObject its primary key is 0 and I don't know what could solve this problem. Is this similar or sounds familiar to anyone who has encountered it?
Thanks in advance

A: its definitely identity column related here.
Assuming your using MS SQL
please check that on table your are inserting and any related ones
that the
1) Identity Specification = YES
2) Is Identity = YES
3) Identity Increment = 1
4) Identity Seed = 1
Its definitely trying to insert the PK for you, so you need to look around there. Make sure you check child tables also.
If you still have problems and your not using the code first method, try regenerate these tables in your EDMX also.

A: 1)You may want to check about a circular dependency. It may be between the two entities Save Product with detail entities or viceversa
Check here : http://social.msdn.microsoft.com/Forums/sk/adodotnetentityframework/thread/5ba666ff-0103-4a83-b4d0-743c16a99491
2)Be careful when you add Repository.Properties.AddObject(P); because in the code behind the P entity still has a reference to Detail table.
Make sure the detail related entity doesn't already save the objects that are linked to it.
If the Detail object has 3 properties , when you save Detail you will also save the 3 properties.

A: Just replace this code in your code:
foreach (Property P in Results)
{
  if(P.PropertyId==0 && P.EntityState==EntityState.Added)
  {
    var id = Repository.Properties.Max(p => (int?)p.PropertyId) ?? 0;
    P.PropertyId=++id;
    Repository.Properties.AddObject(P);
    Repository.SaveChanges();
  }
}

of course in the first line of file add:
using System.Linq;

for used in multi threading:
foreach (Property P in Results)
{
  if(P.PropertyId==0 && P.EntityState==EntityState.Added)
  {
       while(true){
         try{
            var id = Repository.Properties.Max(p => (int?)p.PropertyId) ?? 0;
            P.PropertyId=++id;
            Repository.Properties.AddObject(P);
            Repository.SaveChanges();
            break;
         }catch{
              continue;
         }
       }
  }
}

of course better first you creat new instance of 'property' object then assign field by field varible then call AddObject and SaveChanged!

A: Guid's are good for allowing you to create unique id without a database.
if your using int you will need to ensure that you have in the edmx model to be "Store Generated" for your primary key column.


text:
Q: How do I access variables in Main() from different method Im trying to access a the array fortune from my DisplayFortune method but it says it doesnt exist in the current context. Any help would be appreciated. Im new to c#.
static void Main()
{
    // Write your main here.
    string[] fortune = { "String 1", "String 2", "String 3", "String 4",
    "String 5", "String 6" };
    Random rand = new Random();
    int index = rand.Next(fortune.Length);
    WriteLine(fortune[index]);
    ReadLine();
}

public static void DisplayFortune(string first, string second)
{
    WriteLine(fortune[index]);

}

A: Explicitly pass that as method parameter like
public static void DisplayFortune(string first, string second, string[] fortune)
{
    WriteLine(fortune[index]);

}

A: Local variables like string[] fortune, Random rand, int index are not visble beyound the scope they are declared in (i.e. Main method).
When implementing DisplayFortune method, let's have a look which argument(s) we want:
 public static void DisplayFortune(/* what should we put here? */)
 {
     // we want:
     //   fortune
     //   index
     WriteLine(fortune[index]);
 }

Thus we can put
 public static void DisplayFortune(string[] fortune, int index)
 {
     WriteLine(fortune[index]);
 }

Finally, since it's a public method (everyone can call it), let's validate the input (what if I execute it as DisplayFortune(null, -1234)?):
 public static void DisplayFortune(string[] fortune, int index)
 {
     if (null == fortune)
         throw new ArgumentNullException(nameof(fortune));
     else if (index < fortune.GetLowerBound(0) || index > fortune.GetUpperBound(0))
         throw new ArgumentOutOfRangeException(nameof(index));

     WriteLine(fortune[index]);
 }

To call the method we should provide its arguments:
 static void Main()
 {
    string[] fortune = {
      "String 1", "String 2", "String 3", "String 4", "String 5", "String 6"
    };

    Random rand = new Random();
    int index = rand.Next(fortune.Length);

    ...
    DisplayFortune(fortune, index);
 }

A: Declare your fortune  variable outside of Main. Just below the class declaration.

A: You can't.
Else if you are making this variable a member of the class, such as :
// declaration outside of Main's scope
static string[] fortune;

static void Main()
{
    // Write your main here.
    fortune = { "String 1", "String 2", "String 3", "String 4",
    "String 5", "String 6" };
    Random rand = new Random();
    int index = rand.Next(fortune.Length);
    WriteLine(fortune[index]);
    ReadLine();
}

public static void DisplayFortune(string first, string second)
{
    WriteLine(fortune[index]);
}

Or if you pass this variable to the method directly, such as :
public static void DisplayFortune(string first, string second, string[] fortune)
{
    WriteLine(fortune[index]);
}

A: You cannot access a variable inside another method without taking it outside of the method scope.
So move the variable out from Main, and then you can access it.
Eg. pseudo code
int yourVaribale = 0;
static Main { yourVariable = 5; OtherMethod(); }...
static OtherMethod{ yourVariable = 10; }....

A: your function doesn't make anysense.
- Option 1 :
    Declare fortune as const outside anything
- Option 2 :
    Add array as displayFortune() parameters

A: There  are a few ways you can do this.
You can declare your variable Outside the Main function like this:
static  string[] fortune = { "String 1", "String 2", "String 3", "String 4",
"String 5", "String 6" };

another option is to pass the variable to the method:
public static void DisplayFortune(string first, string second, string[] fortune)
{
    WriteLine(fortune[index]);
}

A: So, in the code that you posted there are a few strange things. The reason you can't access the variable is because it's out of scope. Anywhere you see the curly brackets { } you're creating a scoped block. Variables declared within that block can only be referenced in the same block. So, you can't access the variable in another function unless it:

*

*Is declared at a higher scope

*Is passed into the function as a parameter

The second odd thing about the code is that you have two unused parameters in DisplayFortune. You should change those parameters to accept the array.
public static void DisplayFortune(string[] fortunes, int index)
{
    WriteLine(fortunes[index]);
}

Then, call it like DisplayFortune(fortunes, index); in Main.
I assume you're learning, so just to point out one more way to improve your code:

*

*Your DisplayFortune method shouldn't print the fortune - it should return it as a string, so your Main method can make use of it.

*List item

A: it's normal your array fortunes is in another scope , to resolve your problem there is two way .

*

*You need to declare your array fortunes outside Main method , in this case your array fortunes will be avaible for both method Main and DisplayFortune beceause all of them share the same level-class scope
// Level-Class Scope
static string[] fortune ;

static void Main()
{
    // Write your main here.
    fortune = new string[6];
    Random rand = new Random();
    int index = rand.Next(fortune.Length);
    Console.WriteLine(fortune[index]);
    Console.ReadLine();
}

public static void DisplayFortune(int index)
{
    Console.WriteLine(fortune[index]);
}

*The second way to resolve your probleme is to pass it as a parameter in DisplayFortune
Simple Method :
public static void DisplayFortune(string[] array, int index)
{
    Console.WriteLine(array[index]);
}

Extension Method :
public static void DisplayFortune(this string[] array, int index)
{
    Console.WriteLine(array[index]);
}

Best regards .


text:
Q: "snap install firefox" fails after 22.04 upgrade I used dpkg to remove Firefox and thus repair my broken dpkg system.  I then ran (as root) "snap install firefox".  This ultimately failed with
- Run hook connect-plug-host-hunspell of snap "firefox" (run hook "connect-plug-host-hunspell": cannot perform operation: mount --rbind /home /tmp/snap.rootfs_mkoSWT//home: Permission denied)

snap.rootfs_mkoSWT does exist in /tmp, but it is empty.  Executing the given mount command manually wins the expected "mount point does not exist", which it certainly does not.
This looks like a problem with the snap package, so I'm not sure what I can do about it.  Any suggestions?