text:
Q: Aestan Tray Menu Error i installed the wamp server 2.2e in windows xp. when i start the wamp server it displays the windows error(Aestan Tray Menu has encountered a problem and needs to close.  We are sorry for the inconvenience). Can anyone advise how to resolve this issue

A: Before you install Wamp!
If already installed, then UNINSTALL WAMP(you can backup folders WWW and BIN>mysql>data), and install MS PACKAGES at first:
Microsoft Visual C++ 2008 SP1 Redistributable Package !
 ( or 2010 or 2012 version..
in some cases, maybe .Net Framework is needed too?))
After that, install WAMP!

A: A few things to check:

*

*Have you installed the services? It can be a little temperamental the tray, but look for an install services batch file. This will get the apache and mysql services running

*Is your configuration OK? Particularly, check apache's config with httpd -t on the command line (make sure that you're in the apache/bin folder if httpd isn't in your path)

*Have you got the correct version (32bit versus 64bit)?

*Have you checked your wamp error logs?

*Have you got the pre-requisites installed, such as the Microsoft VC++ redistributable?

If you're still having trouble, checkout the official forum (such as this post http://forum.wampserver.com/read.php?2,53095) and post there for some decent help.

A: Migh be the same issue (have to install Microsoft Visual C++ 2008 Redistributable Package) :
Not able to launch WAMP - Aestan Tray Menu has stopped working

A: Try to install .Net framework Latest version.
 Link: http://www.microsoft.com/en-us/download/details.aspx?id=21
Before Installing WAMP make sure that you uninstalled old versions.


text:
Q: Visual Studio 2013 gives "Cannot add duplicate collection entry of type 'mimeMap'" I have a site that was built using Visual Studio 2010.  When I upgraded to Visual Studio 2013, on some pages I would get an error that said:

Cannot add duplicate collection entry of type 'mimeMap' with unique key attribute 'fileExtension' set to '.mp4'.

After some searching, I found a helpful post on a blog, but since the issue was a little different and I didn't find it on stackoverflow, I thought I'd post the question and answer here.

A: In my case, I solved the problem just by removing the line that was doing duplicate stuff:
 <configuration>
    (...)
    <system.webServer>
        <staticContent>
            <!--mimeMap fileExtension=".json" mimeType="application/json" /-->
        </staticContent>
    </system.webServer>
 </configuration>

A: Simply remove extension before add it.
<remove fileExtension=".mp4" />
<mimeMap fileExtension=".mp4" mimeType="video/mp4" />

A: The issue was that when I switched to Visual Studio 2013, the web server used for debugging changed.  Visual Studio 2013 uses IIS Express by default.  Although Visual Studio 2010 SP1 supports IIS Express, my installation was still using the default Visual Studio Development server.
Like IIS 7, Visual Studio Development Server did not define the mp4 mime type by default, so that's why we had it explicitly added in the web.config, like this:
<system.webServer>
<staticContent>
  <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
</staticContent>
</system.webServer>

IIS Express, on the other hand, is based on IIS 8, and IIS 8 defines the mp4 mime type, and many others, by default.  So when the mimeMap is explicitly set in the web.config, it is considered a duplicate.
If you DO NOT need to support IIS 7 in your production environment, then you can just completely remove the mimeMap tag from the web.config.  If you need to support BOTH IIS 7 and IIS 8, then you can use a remove tag for the mimeMap first and then set it again, like this:
<system.webServer>
<staticContent>
    <remove fileExtension=".mp4" />
    <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
</staticContent>
</system.webServer>

In IIS 7 the removal will do nothing since it isn't already defined, but in IIS 8 it will remove the original so that the new one is not a duplicate.  Thanks to Oliver Payen for his post on the IIS 7 and IIS 8 difference and the remove solution.

A: I just wanted to add some additional info in case there are people like me out there who are fumbling around in the dark. I don't really do this kind of development and inherited a site that I had to move from IIS 7.5 to IIS 10. When I copy the folders to the new server, I got an error like above.
This was the old web.config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".json" mimeType="text/plain" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
    </staticContent>
    <rewrite>
      <rules>
        <rule name="http fix" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{R:1}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Based on the info above, I removed this chunk of code:
<staticContent>
  <mimeMap fileExtension=".json" mimeType="text/plain" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
</staticContent>

And then all was well.  The site came up and worked fine.

A: go to
%windir%\system32\inetsrv\config\applicationHost.config backup this file and open in notepad and find duplicate entry  and remove this line

redpajama_set_name: RedPajamaStackExchange


text:
Q: The result of running time calculated by Python is not correct I trying to use time to record running time of this function, but i think the result is not correct, sometimes it will only cost 0s and the result is not stable.The first two result is for N=10000, the third one is N=30000
import time
def sumOfN(n):
    start=time.time()
    theSum=0
    for i in range(1,n+1):
        theSum=theSum+i
    end=time.time()
    return theSum,end-start
for i in range(5):
    print("Sum is %d required %10.7f seconds"%sumOfN(300000))

A: According to the Python manual:

time.time()
Return the time in seconds since the epoch as a floating
  point number. Note that even though the time is always returned as a
  floating point number, not all systems provide time with a better
  precision than 1 second. While this function normally returns
  non-decreasing values, it can return a lower value than a previous
  call if the system clock has been set back between the two calls.

(emphasis mine)
It seems the timer resolution of your system is not enough to correctly measure the elapsed time of the function.  It actually looks like the precision is about 0.016, about 1/60 of a second, which is typical of Windows systems.
your approach has the following two problems:

*

*time.time() returns the current time (as in time of day), which can vary by auto-adjusting processes such as NTP or if someone modifies it (either by hand or via code).  Use time.perf_counter() (or time.clock() in Python <3.3) instead.

*You are measuring one execution of the function.  This can give you very wrong results due to the non-deterministic nature of garbage collection, bytecode optimization, and other quirks of languages like Python.  You should look into the timeit module instead.


text:
Q: Required DatePicker in reactive form I have a reactive form with Datepicker

     Data Ativação

         <input id="field_dataAtivacao" type="text" class="form-control" name="dataAtivacao" ngbDatepicker #dataAtivacaoDp="ngbDatepicker" formControlName="dataAtivacao"/>

             <button type="button" class="btn btn-secondary" (click)="dataAtivacaoDp.toggle()">
                 <fa-icon [icon]="'calendar-alt'"></fa-icon>
             </button>

Form control without validator
editForm = this.fb.group({
    dataAtivacao: null,
});

The field is empty but always is required. I tried this solution but without success
EDIT
The above example works normally when I don't use the patch value method to update the form.
Like this example of the comments
The problem occurs when I need to update the form using the patchValue method.
this.editForm.patchValue({
    dataAtivacao: cliente.dataAtivacao,
});

When I change for null works normally but I need to show the date and allows update the form with the current selected
this.editForm.patchValue({
        dataAtivacao: null,
});

https://stackblitz.com/edit/angular-grybsk-vrnclb

A: Use this way
editForm = this.fb.group({
    dataAtivacao : ["", Validators.required]
})


text:
Q: prevent yui from adding id automatically how to disable yui from adding id to node automatically. like Y.one('#mynode').setHTML('some content');
I want the html looks like

some content

however, it shows like

some content

how I can make it looks like what I want

A: I had a look and decided it wasn't easily achievable, as this is how YUI works. You'll also find it adds IDs when event handlers fire (all the way up from the element which triggered the event, to the body, which can be confusing.
Can I ask though, why does it matter? Anything which already has an ID won't get it replaced. so it's only elements which had no ID assigned which are affected.


text:
Q: In Knockout.js, how to sort array In the ViewModel i have an observableArray and a computed which return the array managed in the view:
var operators = ko.observableArray([]);
    var records = ko.computed(function () {
        return operators();
    });

This is my sort method;
Order = function (data, event, colName) {
            var th = $('#th-' + colName),
                attr = th.data('sort');

            setAttribute(th, attr); //switch data-sort between 'asc' and 'desc'

            if (attr === 'asc') {
                operators = operators.sort(function (a, b) {
                    return (a.fullname === b.fullname) ? 0 : (a.fullname  b.fullname ? -1 : 1);
                });
            }
        };

And this is the view:

            Fullname

Well, the sort function work like a charm, in fact debugging with the browser i can see the array sorted in both ways, but the view is updated only the first time.
What should I do to fix this problem?

A: The problem is, you need to update the observableArray, and put the data back in that array.
A view doesn't update, if the observable isn't updated
Take a look at the JavaScript sort functionality ( https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort).


text:
Q: ¿Cómo eliminar definitivamente composer de Linux? ¿Cómo puedo eliminar definitivamente composer de linux? Estoy trabajando con Laravel y se me ha presentado un problema y he decidido eliminar composer definitivamente y empezar desde cero con la instalación.

A: Depende de cómo lo hayas instalado pero entiendo que lo habrás hecho a través del manual oficial.
En este caso es simple:
Tienes que eliminar el archivo composer.phar.
Eliminar la carpeta de cache: /home/<user>/.composer
El composer.phar lo puedes buscar con locate sino sabes dónde lo colocaste en la instalación con un locate composer.phar

A: Encontrar y eliminar. (si no lo instalaste con un gestor de paquetes como yum, apt-get o similar)
[root]# which composer
/path/composer
[root]# rm -f  /path/composer

A: Puedes hacer apt-get remove del paquete de manera que no dejas nada en el equipo


text:
Q: Append values of other records for a distinct values of a column if my database table is like:
  name    col_2
 Manish  352-103
 Manish  342-123
 ganesh  362-111
 ganesh  789-232
 abcd    456-231
 abcd    047-234

now i want it as:

  name      col-2
 Manish  352-103, 342-123
 ganesh  362-111, 789-232
 abcd    456-231, 047-234

(I need distinct values of name and  col-2 values must appended for the each distinct value of name)
Both column values are of type text

A: This solved the requirement in MySQL
select name, group_concat(col-2) from dbo.sample group by name

A: Try this :
select name, string_agg(concat(col-2, ', '))
    from dbo.Sample
    group by name


text:
Q: org.openqa.selenium.ElementNotVisibleException: element not visible with chrome=66.0.3359.139 and chromedriver=2.36.540470 I have to set value to "Gross Amount" field.But this field is having regular
 expressions on that and when we enter value and move to next field , the
 entered value is converting as "$1000.00" formate. Here is 1000 has given as
 example.
Below are keywords:
public boolean setValue(String LType, String Locator, String value,
    String Expected) {

    By by = null;
    if (LType.length() < 2) {
        by = By(Locator);
    } else {
        by = By(LType, Locator);
    }

    WebElement element = null;

    try {
        if ((element = isElementPresent(by)) != null) {

            element.sendKeys("value",value);
            return true;
        }
    } catch (Exception e) {
        logger.error("Exception while SendKeys on element" + LType + " " +
  Locator, e);
    }
    return false;
  }

public boolean isElementPresent(String LType, String Locator, String value,
String Expected) {

    By by = null;
    if (LType.length() < 2) {
        by = By(Locator);
    } else {
        by = By(LType, Locator);
    }
    WebElement element = null;
    try {

        if ((isElementPresent(by)) != null) {

            return true;
        }
    } catch (WebDriverException e) {
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0," +
   element.getLocation().y + ")");
        element.click();
        return true;
    } catch (Exception e) {
        logger.error("Exception while isElementPresent element" + LType + " "
 + Locator, e);
    }
    return false;
}

And HTML Code:This Html code is having some regular expressions

            Gross Amount

<input class="form-control" data-val="true" data-val-number="The field Gross Amount must be a number." data-val-regex="Field accepts a positive number with a maximum of 17 digits including 2 decimals." data-val-regex-pattern="\d{0,15}(\.\d{1,2})?" id="GrossAmount" name="GrossAmount" style="display: none;" type="text" value="">
<input class="form-control" id="GrossAmount_C" name="GrossAmount.C" style="display: block;" type="text" value="">

Code is working fine in debug mode and setting value where as in run mode it is
 not working
Error stack trace:
ERROR : 2018-06-14 18:12:33 : Driver.setNum():746 - Exception while SendKeys on element //input[@id='GrossAmount_C'] org.openqa.selenium.ElementNotVisibleException: element not visible (Session info: chrome=66.0.3359.139) (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91)

Request you to help on this.

A: You can try to click and enter value on focused element as given below.
driver.findElement(By.id("GrossAmount_C")).click();
driver.switchTo().activeElement().sendKeys("1000");

or
driver.switchTo().activeElement().sendKeys(Keys.chord("1000"));

A: This error message...
org.openqa.selenium.WebDriverException: unknown error: cannot focus element (Session info: chrome=66.0.3359.139) (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91)

...implies that the ChromeDriver v2.36 was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser v66.0 session.
Your main issue is the incompatibility between the version of the binaries you are using as follows:

*

*You are using chromedriver=2.36

*Release Notes of chromedriver=2.36 clearly mentions the following :

Supports Chrome v63-65

*

*You are using chrome=66.0

*Release Notes of ChromeDriver v2.40 clearly mentions the following :

Supports Chrome v66-68

*

*Your Selenium Client version is unknown to us.

So there is a clear mismatch between ChromeDriver v2.36 and the Chrome Browser v66.0
Solution

*

*Upgrade JDK to  recent levels JDK 8u171.

*Upgrade Selenium to  current levels Version 3.12.0.

*Upgrade ChromeDriver to  current ChromeDriver v2.40 level.

*Keep Chrome version between Chrome v66-68 levels. (as per ChromeDriver v2.40 release notes)

*Execute your @Test.

*Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.


text:
Q: MVC pass model object from controller to view I am trying to figure out how to pass the model object from controller to view in a following scenario:
<% Html.Action("GetRequest", "The_Controller", new { requestId = 12 }); %>
<% Html.RenderPartial("Request", ViewData.Model); %>

The action should, and it does, call the controller's method which looks up the Request object in the DB repository and returns a Request object.
The partial view, named Request, should receive the request object and display it.
The problem is that the ViewData.Model is always null?!
I have tried to figure it out, but with no success :(
The reason for this behavior is that I need to display a partial view inside the jQuery's modal dialog based on the requestId value provided by the jQGrid. I have reached the point where I open the dialog but can't get that model object instance.
Any help is appreciated.
The solution - With the help of Nick Larsen and Darin Dimitrov
The controller:
    [AcceptVerbs(HttpVerbs.Post)]
    [Authorize]
    public PartialViewResult GetRequest(string requestId)
    {
        Request request = DatabaseContext.GetRequest(Convert.ToInt32(requestId)) as Request;
        return PartialView("Request", request);
    }

The view's Javascript:
function OpenRequest(requestId) {

        var methodName = '<%= Url.Content("~")%>' + 'Controller/GetRequest/';
        var dataType = "html";
        var postData = { requestId: requestId };
        var contentType = "application/x-www-form-urlencoded"; ;
        var request = ContactServer(methodName, postData, dataType, contentType);

        $("#dialog").html(request);
        $("#dialog").dialog({ html: request, title: 'Request details...', width: 800, height: 600, modal: true, zindex: 300000, show: 'scale', resizable: false });

    }

A: You could have the controller action return the partial view:
<%= Html.Action("GetRequest", "The_Controller", new { requestId = 12 }) %>

And in your controller action:
public ActionResult GetRequest(int requestId)
{
    var request = _repository.GetRequest(requestId);
    return PartialView("Request", request);
}

This way the GetRequest action will pass the request object to the strongly typed Request.ascx partial view and include it in the page at the place you called Html.Action helper.

A: It's better to set it up where your view does not call your controller.  Load all of the data for the request in the action which calls this view and populate a view model with the needed data.  Once you have that, render the fields from the model.
As for your actual problem.  The action that calls this view in the first place populates the ViewData.Model for its context.  When you call the action method, the framework is creating a new context with its own ViewData which you dont have access to without a handle to that newly created context.

A: It seems that you've got all the necessary information, up front, to create a 'Request' object in your initial controller action method.
Suggest that:

*

*drop the <% Html.Action("GetRequest", "The_Controller", new { requestId = 12 }); %> altogether. We'll be prepopulating ViewData with all the data required to send to the Partial.

*in your initial controller method, you create a new ViewData entry, perhaps ViewData["SomeRequest"]

*prepopulate that as you need on the initial controller method, using requestId = 12 and email = "foo@bar", and all the other relevant pieces to create a 'Request' object, or whatever is needed in the Partial View named 'Request'.
i.e.  ViewData["SomeRequest"]= dbRepository.GetRequestById(intrequestId);

*in your View, call Html.RenderPartial("Request", ViewData["SomeRequest"]);


text:
Q: XPath in Google Sheets Our website has different code on mobile and desktop versions. We want to check HTML attributes through XPath (ImportlXML function). But as you can understand, sometimes they're different for different devices. And Google Sheets provides only data for desktop.
So, question is how I can see results of performing ImportlXML function (through XPath) for mobile using only Google Sheets?
Also, please, tell me query in Google Sheets, which give me all attributes of, for example, <a> tag.
P. S. Thanks a lot for helping me out with this problems.

A: IMPORTXML is able to access the static source code of your web page. In other words, if you dinamically build the DOM of your web page, it can't be accessed by IMPORTXML.


text:
Q: Show current user at top then other in slicer , Power BI I have a Table -

and an another table like -
.
So I am applying filter for UserName in url(powerbi report server url) and filtering only 'XYZ'. I have to use Users as slicer. Now, if the filter value matches with the Users then "My view" else values present in Users Like -

NOTE : There is not relationship between the two tables.


text:
Q: Scala Apache Spark simple application I am new to apache spark and I am trying to start a simple scala spark application. But I am having problem. It says Object apache is not a member of package org.
My application code is:
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object SimpleApp {
  def main(args: Array[String]) {
    val logFile = "YOUR_SPARK_HOME/README.md"
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println(s"Lines with a: $numAs, Lines with b: $numBs")
    sc.stop()
  }
}

My build.sbt file is:
name := "Simple Project"

version := "1.0"

scalaVersion := "2.11.7"

libraryDependencies += "org.apache.spark" %% "spark-core" % "2.0.2"

I ran sbt package from command line and all the required jars are downloaded.
Thanks for help.


text:
Q: C: scanf() storing memory address integer instead of integer value I'm writing a C program to take the marks of five subjects, calculate the average mark and associate a grade.
While scanning in subjects, I noticed unexpected behavior; the score integer variable that is scanned to is storing a memory address of an integer, instead of the value of the integer value.
When scanning in, for example, 95, from stdin, and then immediately printing it, my program prints a value of 32859.
I am not sure what the cause of this error is, and presume it may be to do with the fact that I'm using scanf() within a for loop. Please let me know if you have any ideas on how to fix my problem. Any tips help!
#define SUBJECTS 5

#include <stdio.h>

char * find_grade(float);

int main()
{
    int subject_score_sum;
    // Scan in the subjects
    for (int count = 0; count < SUBJECTS; count++)
    {
        int score;
        scanf("%d", &score);
        printf("%d\n", score);
        subject_score_sum += score;
        printf("%d\n", subject_score_sum);

    }

    float average_score = ((float)subject_score_sum / (float)SUBJECTS);

    printf("Average = %.2f\n%s\n", average_score, find_grade(average_score));

    return 0;
}

char * find_grade(float average_score)
{
    if(average_score >= 90)
    {
        return "Grade A";
    }
    else if(average_score >= 80)
    {
        return "Grade B";
    }
    else if(average_score >= 70)
    {
        return "Grade C";
    }
    else if(average_score >= 60)
    {
        return "Grade D";
    }
    else if(average_score >= 40)
    {
        return "Grade E";
    }
    else
    {
        return "Grade F";
    }
}

A: You never initialize the variable subject_score_sum.
Because of this, its value is undefined and printf("%d\n", subject_score_sum); just prints something.
Even worse: This undefined behavior means your compiler could compile this program into whatever it wants (even into ransomware encrypting all your files!).
Also, make sure to check the return value of scanf.
scanf returns the number of sucessfully read formatters (in your case, this should be 1).


text:
Q: How can I tell which page serves me? I am on a website. the URL reads something like https://somesite.com/serve
I need to tell the name of the page that is serving me.
Like index.html, index.htm, etc...

A: It is fundamentally impossible for you find that out.

A: You want to know the file that is being served. Well probably you are facing url rewrite  with htaccess or other techniques. To tell which file it is probably is impossible if only you manage to get framework (if it is framework) in which the page is made. Then you can read in documentation which is the file to which the requests are aimed. Most frameworks will have one or several of these files. For example codeignighter will have only index.php, while symfony 2 will have app.php and app_dev.php (and others if you want different environments). But normaly you cant know which file serves your request if url rewrite is made.

As mentioned @Dale you cant also beleave what urls say. Because you cant stick some extension at the end for it to look as file. Sometimes you can notice .php or more often .html / .htm at the end.

A: I'm not entirely sure what you mean. But I'm certain you can find it with $_SERVER (Documentation can be found here)
Good luck

A: If you just trying to find out the page name then you can do this:
<?php
$currentFile = $_SERVER["PHP_SELF"];
$parts = explode('/', $currentFile);
echo $parts[count($parts) - 1];
?>

A: probably then you have a .htaccess with rewrite rules which looks something like:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Else you probably would have query string instead which probably looked something like:
index.php?c=products&m=view&id=345

A: (Assuming server supports .htaccess, mod_rewrite, mod_headers)
Temporarily use .htaccess RewriteRule to reveal all or matching filenames in a header.
Example tags all php file headers with filename:
<IfModule mod_rewrite.c>
RewriteEngine on
    <IfModule mod_headers.c>
        RewriteRule .*\.php$ - [E=FILENAME:$0]
        <FilesMatch ".php$">
           Header set MY-COOL-FILENAME "filename=%{FILENAME}e"
        </FilesMatch>
    </IfModule>
</IfModule>

Links
Setting a filename inside the header with htaccess
View HTTP headers in Google Chrome?


text:
Q: node mysql data is changed in result I made a table with:
create table data_ids (id BIGINT(20) unsigned AUTO_INCREMENT PRIMARY KEY, data_id BIGINT(20) unsigned);

I added one row to it and when I
SELECT * FROM data_ids;

+----+--------------------+
| id | data_id            |
+----+--------------------+
|  1 | 260846479567093761 |
+----+--------------------+

As I expect considering that is the info I put in
But when I run
pool.query(`SELECT * from data_ids`, function(err, rows, fields) {
  if (err) {
    console.log(err);
  } else {
    console.log(rows);
  }
});

[ RowDataPacket {
    id: 1,
    data_id: 260846479567093760 } ]

What on earth is going on here?  Why is the data_id changed?

A: By default mysql will automatically cast values to an appropriate JavaScript type. In the case of numeric types, it will convert to a JavaScript number.
The problem with this is that JavaScript can only accurately represent integers up to Number.MAX_SAFE_INTEGER (9007199254740991) and your column value exceeds this maximum. You can disable the automatic type casting by setting typeCast: false in your connection or query config or you can supply your own function that converts values as you see fit.


text:
Q: IEnumerable as Out Parameter I'm trying to write a method, that would give, top 10 records and also total no. of records, from the table. Unable to figure out how to access the output parameters.
It gives an error - Using the generic type IEnumerable requires 1 type argument.
Please do Suggest if there is a better way.
DAL:
public void GetData(out IEnumerable<tblCountry> iList, out int rowCount)
{
  iList = DBContext.tblCountries.Where(c=>c.Id > 0).Take(10);
  rowCount = DBContext.tblCountries.Where(c=>c.Id > 0).Count();
}

BLL:
public void GetData(out IEnumerable<tblCountry> iList, out int rowCount)
{
  objDAL.GetData(out iList, out rowCount);
}

Code Behind:
objBLL.(out IEnumerable<tblCountry> iList, out int rowCount);//Error here

A: In your code behind you should first declare the 2 variables and then pass them as out parameters to the GetData method:
IEnumerable<tblCountry> iList;
int rowCount;
objBLL.GetData(out iList, out rowCount);

As an alternative approach you could design a model that will represent the result of this operation and having the method return this model:
public class MyModel
{
    public IEnumerable<tblCountry> Countries { get; set; }
    public int RowCount { get; set; }
}

and then:
public MyModel GetData()
{
    MyModel model = new MyModel();
    model.Countries = DBContext.tblCountries.Where(c=>c.Id > 0).Take(10);
    model.RowCount = DBContext.tblCountries.Where(c=>c.Id > 0).Count();
    return model;
}

and then call it like this:
MyModel model = objBLL.GetData();
// here you could use model.Countries and model.RowCount


text:
Q: Debian Wheezy IPv6 isn't configured with ifup post-up hook We recently set up a server on Debian Wheezy Beta 3 (x86_64) which has a native IPv6 connection.
We configured the eth0 interface to get the IPv6 configuration through some post-up hook commands in /etc/network/interfaces. The result is, that after the booting the system up, there is only IPv4 and an auto-configured link-local IPv6 address configured on the interface, as if the command has never been executed.
When we additionally place the commands after the call to ifup -a inside the /etc/init.d/networking init script, everything works as expected and we have a fully configured interface after booting up.
This is quite an ugly way to configure the interface. What are we doing wrong with the ifup post-up hooks? Or is this a bug?
Update: One additional fact is that I'm using a Dropbear SSH server to enable me to unlock my LUKS encrypted root file system. The Linux kernel is therefore given an IP address through the GRUB bootloader. That could mean that the IPv6 configuration is not done because eth0 is already up. I then tried to put an ifdown eth0 before ifup -a line in the /etc/init.d/networking script. It didn't change anything. Here an example of how it looked like:
ifdown eth0
if ifup -a $exclusions $verbose && ifup_hotplug $exclusions $verbose

Update: I set up a little script as post-up hook which configures the interface and writes the output to a log file. The result was that the log file was never written, which means the post-up hook wasn't called at all.
The section from /etc/network/interfaces looks like this (IP-addresses changed):
allow-hotplug eth0
iface eth0 inet static
        address 1.2.3.1
        netmask 255.255.255.192
        network 1.2.3.0
        broadcast 1.2.3.63
        gateway 1.2.3.62
        dns-nameservers 8.8.8.8
        dns-search mydomain.tld
        post-up ip -6 addr add 2001:db8:100:3022::2 dev eth0
        post-up ip -6 route add fe80::1 dev eth0
        post-up ip -6 route add default via fe80::1 dev eth0

I also tried it in this alternative way:
auto eth0
iface eth0 inet static
        address 1.2.3.1
        netmask 255.255.255.192
        network 1.2.3.0
        broadcast 1.2.3.63
        gateway 1.2.3.62
        dns-nameservers 8.8.8.8
        dns-search mydomain.tld

iface eth0 inet6 static
        address 2001:db8:100:3022::2
        netmask 64
        gateway fe80::1

What we added to /etc/init.d/networking:
…
case "$1" in
start)
        process_options
        check_ifstate

        if [ "$CONFIGURE_INTERFACES" = no ]
        then
            log_action_msg "Not configuring network interfaces, see /etc/default/networking"
            exit 0
        fi
        set -f
        exclusions=$(process_exclusions)
        log_action_begin_msg "Configuring network interfaces"
        if ifup -a $exclusions $verbose && ifup_hotplug $exclusions $verbose
        then
            # Our additions
            ip -6 addr add 2001:db8:100:3022::2 dev eth0
            ip -6 route add fe80::1 dev eth0
            ip -6 route add default via fe80::1 dev eth0

            log_action_end_msg $?
        else
            log_action_end_msg $?
        fi
        ;;
…

Update: The output of ip -6 address show eth0 after booting up is:
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
    inet6 fe80::abcd:abcd:abcd:abc/64 scope link
       valid_lft forever preferred_lft forever

A: I had the same issue that IPv6 configuration would fail when I would pass the ip parameter to the kernel. The problem is that the networking scripts try to add an IP address to the eth0 interface which is already there. This will of course fail and so further configuration is stopped.
The easiest solution was to simply remove the IPv4 part from /etc/network/interfaces since it's already configured through the ip parameter anyway:
auto eth0
iface eth0 inet6 static
        address 2001:db8:100:3022::2
        netmask 64
        gateway fe80::1

A: in debian wheezy I had to do something silly to get it to work.. sorry about the formatting, I don't really get this site's layout and it's late.
      auto lo
      iface lo inet loopback
      allow-hotplug eth0
      auto eth0 eth0:0 eth0:1 eth0:2
      iface eth0 inet static
      address 66.xxx.xxx.101
      netmask 255.255.255.0
      gateway 66.xxx.xxx.1

      iface eth0:0 inet static
      address 173.xxx.xxx.6
      netmask 255.255.255.0

      iface eth0:1 inet static
      address 192.xxx.xxx.180
      netmask 255.255.xxx.0

      iface eth0 inet6 static
      address fe80::xxxx:xxxx:xxxx:f48e
      netmask 64
      gateway fe80::1

      iface eth0:0 inet6 static
      address 2600:xxx::f03c:xxx:xxx:f48e
      netmask 64

      iface eth0:1 inet6 static
      address 2600:xxx:xxx:007a::1
      netmask 64

      iface eth0:2 inet6 static
      address 2600:xxx:xxx:007a::2
      netmask 64

this resulted in the following:
      eth0      Link encap:Ethernet  HWaddr bogus:mac
      inet addr:66.xxx.xxx.101  Bcast:66.xxx.xxx.255  Mask:255.255.255.0
      inet6 addr: 2600:xxx::f03c:xxx:xxx:f48e/64 Scope:Global
      inet6 addr: fe80::f03c:91ff:feae:f48e/64 Scope:Link
      inet6 addr: 2600:xxx:xxx:7a::2/64 Scope:Global
      inet6 addr: 2600:xxx:xxx:7a::1/64 Scope:Global
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:37908 errors:0 dropped:0 overruns:0 frame:0
      TX packets:30834 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:3201392 (3.0 MiB)  TX bytes:3735827 (3.5 MiB)

      eth0:0    Link encap:Ethernet  HWaddr bogus:mac
      inet addr:173.xxx.xxx.6  Bcast:173.xxx.xxx.255  Mask:255.255.255.0
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

      eth0:1    Link encap:Ethernet  HWaddr bogus:mac
      inet addr:192.xxx.xxx.180  Bcast:192.xxx.xxx.255  Mask:255.255.xxx.0
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

iproute2 is supposed to support declaring all of these (ipv4 at least) under eth0 instead of eth0:0...etc but that didn't work.. and even though I declared eth0:0 etc for ipv6 those all showed up under eth0 whereas they definitely didn't work when declared as eth0 specifically.


text:
Q: Writing to a TextView outside of a Fragment I am using a TextView inside of a Fragment.
I wish to update this TextView outside of the fragment (but also outside of an activity) from a callback class.
For example the user scrolls, the callback is called somewhere in my package, and I want the fragment view to be updated.
Can anybody explain how to do this? I did use a Local Broadcast Receiver but it wasn't fast enough in its updating.

A: Eventually looked at Otto but as we had Guava I implemented a singleton eventbus and used Guava publish/subscribe model to pass stuff around.
Otto however looks very similar.

A: EventBus is a nice and elegant way for communication between modules in Android apps. In this way you should register your fragment as a event subscriber, and post a this specific event from other part of your code. Keep in mind that only UI thread can work with Views.

A: I don't  exactly understand what you want to achieve and why BroadcastReceiver does not work for you, but you may either:
1) try using callbacks (if it is possible in your app design);
2) try using  this or that event bus implementation;
Both would work pretty fast without much overhead, compared to broadcasting.
In case 2 you won't have to maintain callback dependencies/references.

A: Use Otto: http://square.github.io/otto/
public class UpdateEvent {
    private String string;

    public UpdateListEvent(String string) {
        this.string = string;
    }

    public String getString() {
        return string;
    }
}

...
    ...
    public void update() {
       SingletonBus.INSTANCE.getBus().post(new UpdateListEvent(editText.getText().toString()));
    }
...

public class FragmentA extends Fragment {
    @Override
    public void onResume() {
        super.onResume();
        SingletonBus.INSTANCE.getBus().register(this);
    }

    @Override
    public void onPause() {
        SingletonBus.INSTANCE.getBus().unregister(this);
        super.onPause();
    }

    @Subscribe
    public void onUpdateEvent(UpdateEvent e) {
        //do something
    }
}

public enum SingletonBus {
    INSTANCE;

    private Bus bus;

    private SingletonBus() {
        this.bus = new Bus(ThreadEnforcer.ANY);
    }

    public Bus getBus() {
        return bus;
    }
}


text:
Q: How do I complete this andWhere Doctrine query? I'm assuming this is easy to do with Doctrine, however I have no clue how to do it. I'm sure I am missing something basic.
    Doctrine_Query::create()
                    ->from('Product p')
                    ->leftJoin('p.Category c' )
                    ->leftJoin('c.Image i')
                    ->where('p.name LIKE ?', '%'.$search.'%'),

which works, but I am trying to select the category and tried this, but it didn't work with error "Unknown column parent_id"
    Doctrine_Query::create()
                    ->from('Product p')
                    ->leftJoin('p.Category c' )
                    ->leftJoin('c.Image i')
                    ->where('p.name LIKE ?', '%'.$search.'%')
                    ->andWhere('c.parent_id NOT LIKE ?', '1'),

How do I change this Doctrine query to include the andWhere statement?

A: This is somewhat of a guess since I don't know your schema.  DQL queries use properties and not database column names.  I suspect that category has a property called parent?
So something like:
Doctrine_Query::create()
    ->select('p,c,i')  // Eager load
    ->from('Product p')
    ->leftJoin('p.Category c' )
    ->leftJoin('c.Image i')
    ->leftJoin('c.Parent parentCategory') // Join the parent entity
    ->where('p.name LIKE ?', '%'.$search.'%')
    ->andWhere('parentCategory.id NOT LIKE ?', '1'),


text:
Q: How to handle requests for non existing dynamic segments in Ember? If an user modifies the dynamic segment (object ID) in the URL of an Ember App with Ember Data, what's the best practice to handle these URLs as these might refer to non existing Model entries?
In a minimal example one can observe, that for each call with a non-existent ID (for example http://emberjs.jsbin.com/hurozaju/9#/color/30) there is an empty object added to the local ember data store. This is easily observable by the increasing number of "dots" in the output.
The error-action of App.ColorRoute redirects (as intended) to "colors" in case there is a 404 occurring while fetching the model by ID.
Why is there a "new" Object in the store?
Shouldn't the data be left unmodified?
Is there a chance to prevent the creation of new objects in this case?

A: I spend some time with this problem and i think this is ember-data beta-7 bug. Please report this issue in github.

A: here is example code how to work around this issue jsbin. This is tested with data-beta.7 and work and with data-beta.4 not working.

A: Sorry for not waiting as anounced...
This issue is now reported to ember-data on github.


text:
Q: My zshell breaks because oh-my-zsh cannot update When I reload my shell(on MacOS), I get the following error.
error[oh-my-zsh] Can't update: not a git repository. When I try to delete pyenv or to do something else,I get the error that the command i not found. For example
enter image description here What should I do to solve it?

A: If you recently updated Xcode, try to run in your Terminal as Normal User:
xcodebuild -runFirstLaunch

A: Temporary solution:
sudo rm -rf /Library/Developer/CommandLineTools && xcode-select --install

I don't know a permanent solution. This works till the next omz update...

A: Yes, the .zshrc file was broken and was adding wrong paths to the PATH variable. I deleted it and put the correct scripts.


text:
Q: Adding a Calculator to a Wordpress Page I have a calculator written in HTML, CSS, JS and JQuery all in separate files and I am wondering how I would add this to a single page on a wordpress site? Thanks in advance for the help.

A: You should look into creating a plugin for this and then inside of the plugin generating a shortcode for the output so you can place it almost anywhere you'd like inside wordpress.
Having it has a plugin will give you the flexibility of quickly making changes and the future chance to apply it easily to other sites.
Without seeing your code it's hard to give you a more detailed answer.
https://codex.wordpress.org/Writing_a_Plugin
https://codex.wordpress.org/Shortcode_API


text:
Q: Creating a new file in the root of an ext2 file system I am creating an application for Android which enables users to create encrypted LUKS partitions and then mount them to given directories on external memory.
For the partition to be usable I create an ext2 file system using the Busybox mkfs.ext2 command. The problem occurs once a user tries to create a file/directory at the root of the partition. For some reason it is impossible to create a file through Java as the "File.mkdirs()" method fails. However, it is possible to create this file through the command-line. And this error occurs only when at the root of the partition (i.e if I create a folder through the command line I am then able to create files within that folder through Java). Also, I am able to create a file if I create a vfat file system instead of ext2.
Any help would be greatly appreciated.
Harry
EDIT
Fixed. I was mounting the file system as root

A: My final solution to this problem was to create a vfat file system rather than ext2 as vfat doesn't have permissions etc... This worked for me as I did not need the extra security of permissions. However, if you need an ext2 file system which you need to mount as root but want it to be useable by other users I recomment looking into the mount ownmask option (man mount).


text:
Q: Setting opts of individual Elements in holoviews Holomaps Given a Holomap-like object (HoloMap, NdOverlay, ...) created by grouping by an additional kdim, is there a way to access specific sub-elements for individual styling? Given a HoloMap p:
p = hv.Dataset(([0, 1], [2, 2], ['a', 'b']), ['x', 'y', 'z']
              ).to(hv.Points, groupby='z')

is it possible to add individual style opts for z='a', z='b'? I've tried the group.label syntax but that didn't work.
If not, I reckon I would have to create a dictionary of the Elements and pass the group label explicitly?
hv.HoloMap({z_value: hv.Points(..., group=z_value) for z_value in ...})

A: You could index into the HoloMap and use the .opts method to apply the options without cloning, e.g.:
p = hv.Dataset(([0, 1], [2, 2], ['a', 'b']), ['x', 'y', 'z']
          ).to(hv.Points, groupby='z')
p['a'].opts(color='red')
p['b'].opts(color='blue')
p


text:
Q: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem. I got this error while installing ubuntu-restricted-extras:

E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

So I ran that in terminal:
vennesa@vennesa-ThinkPad-R61:~$ sudo dpkg --configure -a
Setting up update-notifier-common (0.126) ...
flashplugin-installer: downloading http://archive.canonical.com/pool/partner/a/adobe-flashplugin/adobe-flashplugin_11.2.202.270.orig.tar.gz

Since then I can't install any thing. What do I do?

A: I find out an easy way, if sudo dpkg --configure -a wasting so much of time in installing your file just give abort the process and give sudo dpkg --remove -a it will remove all the uninstalled files and if you want you can install it again by giving sudo apt-get install your_soft_name.

A: Upon returning to installing Gnome via sudo apt-get install ubuntu-desktop, that was cut off by a power outage and I experienced exactly this issue.
I chose to issue the sudo dpkg --configure -a and then lost my terminal window forever in Windows Hyper-V 2012 manager. I was able to connect to my Linux box using SSH (PuTTY) from my Windows 7 Pro client though no problem.

A: After searching a lot I got a satisfactory result:
I found some places saying to run commands:
sudo apt-get install -f
sudo dpkg --configure -a

But none of those above worked.
The solution that worked for me:
sudo dpkg --configure --pending

Hope I have helped.

A: If I understand correctly, you believe the terminal is freezing/not working once that flasplugin-installer: line appears.
However, Adobe Flash is a proprietary program with a license that doesn't allow direct distributing by Ubuntu. Because of this, flash updates using the flashplugin-installer, which downloads and installs the latest version of flash onto your computer.
So, when you see this line, and it doesn't appear to be doing anything, the terminal is actually downloading the latest version of flash flash. Wait a while, and it should continue.


text:
Q: Extracting a string from html tags in python Hopefully there isn't a duplicated question that I've looked over because I've been scouring this forum for someone who has posted to a similar to the one below...
Basically, I've created a python script that will scrape the callsigns of each ship from the url shown below and append them into a list. In short it works, however whenever I iterate through the list and display each element there seems to be a '[' and ']' between each of the callsigns. I've shown the output of my script below:
Output
***********************     Contents of 'listOfCallSigns' List     ***********************

0 ['311062900']
1 ['235056239']
2 ['305500000']
3 ['311063300']
4 ['236111791']
5 ['245639000']
6 ['235077805']
7 ['235011590']

As you can see, it shows the square brackets for each callsign. I have a feeling that this might be down to an encoding problem within the BeautifulSoup library.
Ideally, I want the output to be without any of the square brackets and just the callsign as a string.
***********************     Contents of 'listOfCallSigns' List     ***********************

0 311062900
1 235056239
2 305500000
3 311063300
4 236111791
5 245639000
6 235077805
7 235011590

This script I'm using currently is shown below:
My script
# Importing the modules needed to run the script
from bs4 import BeautifulSoup
import urllib2
import re
import requests
import pprint

# Declaring the url for the port of hull
url = "http://www.fleetmon.com/en/ports/Port_of_Hull_5898"

# Opening and reading the contents of the URL using the module 'urlib2'
# Scanning the entire webpage, finding a <table> tag with the id 'vessels_in_port_table' and finding all <tr> tags
portOfHull = urllib2.urlopen(url).read()
soup = BeautifulSoup(portOfHull)
table = soup.find("table", {'id': 'vessels_in_port_table'}).find_all("tr")

# Declaring a list to hold the call signs of each ship in the table
listOfCallSigns = []

# For each row in the table, using a regular expression to extract the first 9 numbers from each ship call-sign
# Adding each extracted call-sign to the 'listOfCallSigns' list
for i, row in enumerate(table):
    if i:
        listOfCallSigns.append(re.findall(r"\d{9}", str(row.find_all('td')[4])))

print "\n\n***********************     Contents of 'listOfCallSigns' List     ***********************\n"

# Printing each element of the 'listOfCallSigns' list
for i, row in enumerate(listOfCallSigns):
    print i, row

Does anyone know how to remove the square brackets surrounding each callsign and just display the string?
Thanks in advance! :)

A: Change the last lines to:
# Printing each element of the 'listOfCallSigns' list
for i, row in enumerate(listOfCallSigns):
    print i, row[0]  # <-- added a [0] here

Alternatively, you can also add the [0] here:
for i, row in enumerate(table):
    if i:
        listOfCallSigns.append(re.findall(r"\d{9}", str(row.find_all('td')[4]))[0]) <-- added a [0] here

The explanation here is that re.findall(...) returns a list (in your case, with a single element in it). So, listOfCallSigns ends up being a "list of sublists each containing a single string":
>>> listOfCallSigns
>>> [ ['311062900'], ['235056239'], ['311063300'], ['236111791'],
['245639000'], ['305500000'], ['235077805'], ['235011590'] ]

When you enumerate your listOfCallSigns, the row variable is basically the re.findall(...) that you appended earlier in the code (that's why you can add the [0] after either of them).
So row and re.findall(...) are both of type "list of string(s)" and look like this:
>>> row
>>> ['311062900']

And to get the string inside the list, you need access its first element, i.e.:
>>> row[0]
>>> '311062900'

Hope this helps!

A: This can also be done by stripping the unwanted characters from the string like so:
a = "string with bad characters []'] in here"
a = a.translate(None, "[]'")
print a


text:
Q: Linear algebra: Finding the number of parameters of a system given dimensions and rank Suppose the system Ax = b is consistent and A is a 6 x 7 matrix and rank(A) = 2. How many parameters does the system have?

A: Since the rank is the number of non zero rows, there will be 4 zero rows (the number of rows is 6, the rank is 2, another 4 are zero rows). Each zero row represents 1 parameter. Therefore there will be 4 parameters. Consistent means either many solutions or unique solution.


text:
Q: FFmpeg/AVconc - Capture Seamless Video I have several IP cams that I want to capture video from continuously.  I'm building a script that will wrap around ffmpeg to capture from the various RTSP sources.  But I'm struggling with how to capture and store the data.. specifically, how do I capture seamless clips?
To clarify, if I just run a command like this:
ffmpeg -i rtsp://ip_cam file.mp4

This is going to run forever until it fills up my hard drive (or until I hit some upper limit of ffmpeg or the filesystem).  So my thinking was to do something like this:
ffmpeg -i rtsp://ip_cam -fs 104857600 file-1.mp4

This would limit the files to 100MB each.  My wrapper script can start a new instance as soon as this one finishes:
ffmpeg -i rtsp://ip_cam -fs 104857600 file-2.mp4

And so on (I can have a separate process that will make sure to clear out the old files as needed to recover space).  The problem with this approach is that it takes 1-2 seconds for ffmpeg to start, which means during that time the camera in question isn't recording anything.
One additional thing to consider is that for each file, I need to know the start and stop timestamp, for instance, file-1.mp4 may refer to "2015-09-12 09:03:42" through "2015-09-12 11:24:21".  This way, if a user wants to retrieve a specific clip, I know where to get it.  And if I'm starting ffmpeg for each clip, and then it ends at the end of each clip, I can capture and store that information.  But if a suggested approach is to tell ffmpeg to run indefinitely while saving the output in separate chunks (if ffmpeg can do that), that may not work since I won't be able to collect this information.
Any insight would be appreciated.

A: Try the segment muxer.
ffmpeg -i rtsp://ip_cam -c copy -f segment -segment_list out.list -segment_time 900 \
-segment_atclocktime 1 -strftime 1 "%Y-%m-%d_%H-%M-%S.mkv"

*

*-segment_list Generate a list file.

*-segment_time Set segment duration. The value must be a duration specification. Default value is 2. Note that splitting may not be accurate, unless you force the reference stream key-frames at the given time. See the segment muxer documentation for more info.

*-segment_atclocktime If set to "1" split at regular clock time intervals starting from 00:00 o'clock. The time value specified in -segment_time is used for setting the length of the splitting interval. For example, with segment_time set to "900", this makes it possible to create files at 12:00 o'clock, 12:15, 12:30, etc.

*-strftime This allows segments to be named by time of file creation.
Example output file names:
$ ls -m1
2015-09-12_14-10-02.mkv
2015-09-12_14-10-14.mkv
2015-09-12_14-10-24.mkv
2015-09-12_14-10-34.mkv
2015-09-12_14-10-44.mkv
2015-09-12_14-10-54.mkv

See the docs for lots more options and info.


text:
Q: Azure, Angular JS, Sonar, Error Details java.lang.OutOfMemoryError: Java heap space we're getting "Error Details java.lang.OutOfMemoryError: Java heap space" on while running Sonar on Azure DevOps build for Angular JS project.
I'm not seeign any error message in Azure Pipeline, but I'm seeing this error in Sonar Dashboard.
I also tried by setting follwoing variables in Pipeline Variables Section, but still getting same error,
SONAR_RUNNER_OPTS -Xmx4096m -Xms4096m
SONAR_SCANNER_OPTS -Xmx4096m -Xms4096m
Can anyone help on this plz.
~Karthik


text:
Q: how await a hook after execute a query in apollo Gql and REACT? i have the follow problem, i want to execute a query that need and ID user, but i have consult the ID user from a hook, the code:
export default function useGetDatosPersonales() {

    const [viewer, refetchViewer] =  useViewer();
    const {data} = useQuery(qUsuario,{
        variables: {
            user: viewer && viewer.id
        }
    });
    const functionCall = (render) => {
       if(data !== null && data !== undefined){
           console.log(data.user.email);
        }
    }

    return [functionCall,data];

}

the query qUsuario is:
query qUsuario($user:ID!){
  user(id:$user){
    email,
    firstName,
    lastName,
  }
}

but in the first time i got the follow error:

[GraphQL error]: Variable "$user" of required type "ID!" was not
provided.

and then in few milliseconds later, the query works!
How i can say to the apollo that wait for the id before execute the query

A: You need to use useLazyQuery, because useQuery don't wait never.
Or you may use async-await syntax for use client instance directly and have full control under asynchronous.


text:
Q: SQL Query to get any column who's value can be Bit Would anybody be able to shed some light on how i go about getting only columns who's type are Bit ( bool ) without having to set limits on queries?
I am currently able to return every column but that will confuse the built in Query in my program if an int column gets selected.
SELECT COLUMN_NAME
FROM databasex.INFORMATION_SCHEMA.COLUMNS
WHERE [..?..]

any help or advice would be appreciated. thanks

A: select * from
information_schema.columns
 where data_type='bit'

A: If you're using SQL Server, you can query the sys.columns and sys.types views
SELECT
    OBJECT_NAME(c.OBJECT_ID) AS TableName,
    c.name AS ColumnName
FROM sys.columns AS c
JOIN sys.types AS t
    ON c.user_type_id = t.user_type_id
WHERE
    t.name = 'bit'


text:
Q: c++ accessing private members causes seg fault I'm writing a game in C++.
I have come across an error, the source of which I have yet to discover.
Whenever I try to access private members of the CollisionEngine class I take a seg fault.
By this using commands like this->is_previous_collision_x in one of the member functions of CollisionEngine.
Here is the valgrind output:
==23949== Memcheck, a memory error detector
==23949== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==23949== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==23949== Command: ./main
==23949==
==23949== Thread 2:
==23949== Syscall param writev(vector[...]) points to uninitialised byte(s)
==23949==    at 0x5CCB84D: ??? (in /usr/lib/libc-2.22.so)
==23949==    by 0x72E7DA8: ??? (in /usr/lib/libxcb.so.1.1.0)
==23949==    by 0x72E819C: ??? (in /usr/lib/libxcb.so.1.1.0)
==23949==    by 0x72E8224: xcb_writev (in /usr/lib/libxcb.so.1.1.0)
==23949==    by 0x6FDD18D: _XSend (in /usr/lib/libX11.so.6.3.0)
==23949==    by 0x6FDD681: _XReply (in /usr/lib/libX11.so.6.3.0)
==23949==    by 0x6FC8406: XInternAtom (in /usr/lib/libX11.so.6.3.0)
==23949==    by 0x4EEBE9B: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x4EECC8A: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x4EDF55F: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x4EDF36F: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x4E475FE: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==  Address 0x640d863 is 35 bytes inside a block of size 16,384 alloc'd
==23949==    at 0x4C2A987: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==23949==    by 0x6FCD4E1: XOpenDisplay (in /usr/lib/libX11.so.6.3.0)
==23949==    by 0x4EEACB4: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x4EDF330: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x4E475FE: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x40488D: Game::game_loop() (Game.cpp:131)
==23949==    by 0x4067FC: void std::_Mem_fn_base<void (Game::*)(), true>::operator()<, void>(Game*) const (in /home/element/games/medieval_explorer/src/main)
==23949==    by 0x40676A: void std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::_M_invoke<0ul>(std::_Index_tuple<0ul>) (functional:1531)
==23949==    by 0x406684: std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::operator()() (functional:1520)
==23949==    by 0x406623: std::thread::_Impl<std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)> >::_M_run() (thread:115)
==23949==    by 0x540D34F: execute_native_thread_routine (thread.cc:84)
==23949==    by 0x513E4A3: start_thread (in /usr/lib/libpthread-2.22.so)
==23949==  Uninitialised value was created by a stack allocation
==23949==    at 0x6FD87C0: XStoreColors (in /usr/lib/libX11.so.6.3.0)
==23949==
==23949== Invalid read of size 4
==23949==    at 0x40266A: GameWindow::get_pixel_color(SDL_Surface*, int, int) (GameWindow.cpp:174)
==23949==    by 0x40418C: CollisionEngine::collision_check_wall(GameState*, Character*) (CollisionEngine.cpp:83)
==23949==    by 0x404022: CollisionEngine::collision_check_player(GameState*) (CollisionEngine.cpp:35)
==23949==    by 0x403F4C: CollisionEngine::collision_check(GameState*) (CollisionEngine.cpp:12)
==23949==    by 0x404C1B: Game::advance_actual_state() (Game.cpp:276)
==23949==    by 0x40490A: Game::game_loop() (Game.cpp:145)
==23949==    by 0x4067FC: void std::_Mem_fn_base<void (Game::*)(), true>::operator()<, void>(Game*) const (in /home/element/games/medieval_explorer/src/main)
==23949==    by 0x40676A: void std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::_M_invoke<0ul>(std::_Index_tuple<0ul>) (functional:1531)
==23949==    by 0x406684: std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::operator()() (functional:1520)
==23949==    by 0x406623: std::thread::_Impl<std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)> >::_M_run() (thread:115)
==23949==    by 0x540D34F: execute_native_thread_routine (thread.cc:84)
==23949==    by 0x513E4A3: start_thread (in /usr/lib/libpthread-2.22.so)
==23949==  Address 0x63b2a10 is 0 bytes after a block of size 96 alloc'd
==23949==    at 0x4C2A987: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==23949==    by 0x4EDA0FF: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x403800: Graphics::surface_copy(SDL_Surface*) (Graphics.cpp:80)
==23949==    by 0x4035EC: Graphics::get_map(GID) (Graphics.cpp:31)
==23949==    by 0x401FC8: GameWindow::GameWindow(Graphics*, GameState*) (GameWindow.cpp:15)
==23949==    by 0x404511: Game::Game() (Game.cpp:47)
==23949==    by 0x404C45: main (main.cpp:39)
==23949==
==23949== Invalid read of size 4
==23949==    at 0x40266A: GameWindow::get_pixel_color(SDL_Surface*, int, int) (GameWindow.cpp:174)
==23949==    by 0x4022C3: GameWindow::draw_walls(SDL_Surface*, GameState*) (GameWindow.cpp:83)
==23949==    by 0x402041: GameWindow::draw(SDL_Surface*, GameState*) (GameWindow.cpp:24)
==23949==    by 0x404A16: Game::display_game_window() (Game.cpp:177)
==23949==    by 0x404916: Game::game_loop() (Game.cpp:149)
==23949==    by 0x4067FC: void std::_Mem_fn_base<void (Game::*)(), true>::operator()<, void>(Game*) const (in /home/element/games/medieval_explorer/src/main)
==23949==    by 0x40676A: void std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::_M_invoke<0ul>(std::_Index_tuple<0ul>) (functional:1531)
==23949==    by 0x406684: std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::operator()() (functional:1520)
==23949==    by 0x406623: std::thread::_Impl<std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)> >::_M_run() (thread:115)
==23949==    by 0x540D34F: execute_native_thread_routine (thread.cc:84)
==23949==    by 0x513E4A3: start_thread (in /usr/lib/libpthread-2.22.so)
==23949==    by 0x5CD313C: clone (in /usr/lib/libc-2.22.so)
==23949==  Address 0x63b2a10 is 0 bytes after a block of size 96 alloc'd
==23949==    at 0x4C2A987: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==23949==    by 0x4EDA0FF: ??? (in /usr/lib/libSDL2-2.0.so.0.2.1)
==23949==    by 0x403800: Graphics::surface_copy(SDL_Surface*) (Graphics.cpp:80)
==23949==    by 0x4035EC: Graphics::get_map(GID) (Graphics.cpp:31)
==23949==    by 0x401FC8: GameWindow::GameWindow(Graphics*, GameState*) (GameWindow.cpp:15)
==23949==    by 0x404511: Game::Game() (Game.cpp:47)
==23949==    by 0x404C45: main (main.cpp:39)
==23949==
==23949== Use of uninitialised value of size 8
==23949==    at 0x40444C: CollisionEngine::handle_wall_collision(GameState*, Character*) (CollisionEngine.cpp:155)
==23949==    by 0x40404D: CollisionEngine::collision_check_player(GameState*) (CollisionEngine.cpp:39)
==23949==    by 0x403F4C: CollisionEngine::collision_check(GameState*) (CollisionEngine.cpp:12)
==23949==    by 0x404C1B: Game::advance_actual_state() (Game.cpp:276)
==23949==    by 0x40490A: Game::game_loop() (Game.cpp:145)
==23949==    by 0x4067FC: void std::_Mem_fn_base<void (Game::*)(), true>::operator()<, void>(Game*) const (in /home/element/games/medieval_explorer/src/main)
==23949==    by 0x40676A: void std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::_M_invoke<0ul>(std::_Index_tuple<0ul>) (functional:1531)
==23949==    by 0x406684: std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::operator()() (functional:1520)
==23949==    by 0x406623: std::thread::_Impl<std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)> >::_M_run() (thread:115)
==23949==    by 0x540D34F: execute_native_thread_routine (thread.cc:84)
==23949==    by 0x513E4A3: start_thread (in /usr/lib/libpthread-2.22.so)
==23949==    by 0x5CD313C: clone (in /usr/lib/libc-2.22.so)
==23949==  Uninitialised value was created by a heap allocation
==23949==    at 0x4C29118: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==23949==    by 0x404C3A: main (main.cpp:39)
==23949==
==23949== Invalid read of size 1
==23949==    at 0x40444C: CollisionEngine::handle_wall_collision(GameState*, Character*) (CollisionEngine.cpp:155)
==23949==    by 0x40404D: CollisionEngine::collision_check_player(GameState*) (CollisionEngine.cpp:39)
==23949==    by 0x403F4C: CollisionEngine::collision_check(GameState*) (CollisionEngine.cpp:12)
==23949==    by 0x404C1B: Game::advance_actual_state() (Game.cpp:276)
==23949==    by 0x40490A: Game::game_loop() (Game.cpp:145)
==23949==    by 0x4067FC: void std::_Mem_fn_base<void (Game::*)(), true>::operator()<, void>(Game*) const (in /home/element/games/medieval_explorer/src/main)
==23949==    by 0x40676A: void std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::_M_invoke<0ul>(std::_Index_tuple<0ul>) (functional:1531)
==23949==    by 0x406684: std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::operator()() (functional:1520)
==23949==    by 0x406623: std::thread::_Impl<std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)> >::_M_run() (thread:115)
==23949==    by 0x540D34F: execute_native_thread_routine (thread.cc:84)
==23949==    by 0x513E4A3: start_thread (in /usr/lib/libpthread-2.22.so)
==23949==    by 0x5CD313C: clone (in /usr/lib/libc-2.22.so)
==23949==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==23949==
==23949==
==23949== Process terminating with default action of signal 11 (SIGSEGV)
==23949==  Access not within mapped region at address 0x0
==23949==    at 0x40444C: CollisionEngine::handle_wall_collision(GameState*, Character*) (CollisionEngine.cpp:155)
==23949==    by 0x40404D: CollisionEngine::collision_check_player(GameState*) (CollisionEngine.cpp:39)
==23949==    by 0x403F4C: CollisionEngine::collision_check(GameState*) (CollisionEngine.cpp:12)
==23949==    by 0x404C1B: Game::advance_actual_state() (Game.cpp:276)
==23949==    by 0x40490A: Game::game_loop() (Game.cpp:145)
==23949==    by 0x4067FC: void std::_Mem_fn_base<void (Game::*)(), true>::operator()<, void>(Game*) const (in /home/element/games/medieval_explorer/src/main)
==23949==    by 0x40676A: void std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::_M_invoke<0ul>(std::_Index_tuple<0ul>) (functional:1531)
==23949==    by 0x406684: std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)>::operator()() (functional:1520)
==23949==    by 0x406623: std::thread::_Impl<std::_Bind_simple<std::_Mem_fn<void (Game::*)()> (Game*)> >::_M_run() (thread:115)
==23949==    by 0x540D34F: execute_native_thread_routine (thread.cc:84)
==23949==    by 0x513E4A3: start_thread (in /usr/lib/libpthread-2.22.so)
==23949==    by 0x5CD313C: clone (in /usr/lib/libc-2.22.so)
==23949==  If you believe this happened as a result of a stack
==23949==  overflow in your program's main thread (unlikely but
==23949==  possible), you can try to increase the size of the
==23949==  main thread stack using the --main-stacksize= flag.
==23949==  The main thread stack size used in this run was 8388608.
==23949==
==23949== HEAP SUMMARY:
==23949==     in use at exit: 52,118,160 bytes in 43,092 blocks
==23949==   total heap usage: 111,139 allocs, 68,047 frees, 623,656,015 bytes allocated
==23949==
==23949== LEAK SUMMARY:
==23949==    definitely lost: 16,911,956 bytes in 147 blocks
==23949==    indirectly lost: 0 bytes in 0 blocks
==23949==      possibly lost: 26,050,169 bytes in 41,710 blocks
==23949==    still reachable: 9,156,035 bytes in 1,235 blocks
==23949==                       of which reachable via heuristic:
==23949==                         stdstring          : 401 bytes in 6 blocks
==23949==         suppressed: 0 bytes in 0 blocks
==23949== Rerun with --leak-check=full to see details of leaked memory
==23949==
==23949== For counts of detected and suppressed errors, rerun with: -v
==23949== ERROR SUMMARY: 351 errors from 5 contexts (suppressed: 0 from 0)

Here is the "handle_wall_collision" function where the code takes a segfault:
// character is in collision with walls, handle it
// only need to do one increment because the collision will be detected and handled again
void CollisionEngine::handle_wall_collision(GameState *game_state, Character *character){
    // move a character the opposite direction of their speed until there is no more collision
    // the until there is no more collision part is handled by the way this method is called
    // we know how far they have moved into the object is some multiple of their speed
    // get the sign of x_move_speed, y_move_speed
    int x_sign = (character->map_location->x_move_speed == 0) ? (0) : (character->map_location->x_move_speed/abs(character->map_location->x_move_speed));
    int y_sign = (character->map_location->y_move_speed == 0) ? (0) : (character->map_location->y_move_speed/abs(character->map_location->y_move_speed));

    // determine the direction of movement
    //if(abs(character->map_location->x_move_speed) > abs(character->map_location->y_move_speed)){
    if(this->is_previous_collision_x){
        character->map_location->x_location += -1*x_sign;
    }else{
        character->map_location->y_location += -1*y_sign;
    }

    //std::cout << "seg_fault_above" << std::flush;
}

Note, If I avoid using any member variables (basically anything which could be referenced by "this") than the code works fine.
I can use Member variables in constructor.
Edit:
Member this->is_previous_collision_x is initialized in the constructor:
CollisionEngine::CollisionEngine(){
    this->is_previous_collision_x = false;
}

This is the loop which calls the offending method:
// while there are collisions with the walls, handle them
do{
    wall_collision = collision_check_wall(actual_state, actual_state->get_player());

    if(wall_collision){
        //std::cout << " wall collision detected\n";
        handle_wall_collision(actual_state, actual_state->get_player());
    }
}while(wall_collision);

I'm using SDL2 library. I have made sure to use the methods provided by this library to destroy the textures/ surfaces /render I have made, but they still produce some of these errors.
Also importantly, Player is a Character.
Edit
I feel exceptionally dumb.
Game holds a *CollisionEngine as a private member
advance_actual_state() uses this pointer to call collision_engine->collision_check(game_state)
The issue was that this->collision_engine = new CollisionEngine()  was not being called in the constructor.

A: Access not within mapped region at address 0x0
Notice the 0x0 there? That means you tried to dereference a NULL pointer. Add lots of asserts to your code to try to catch it. For example, add assert (this != NULL); at function entry points.
It could also be character or character->mmap_location that's NULL. Add asserts for everything.
Perhaps this will work:
void CollisionEngine::handle_wall_collision(GameState *game_state, Character *character){

 if (this == NULL)
     std::cerr << "CE:hwc, this is NULL" << std::endl;
 if (character == NULL)
     std::cerr << "CE:hwc character is NULL" << std::endl;
 if (character->map_location == NULL)
     std::cerr << "CE:hwc map_location is NULL" << std::Endl;

 // rest of code here


text:
Q: Pre-load page assets with Ember.js and jQuery Okay, so I have a page that has some high-res images that look great when loaded (but not so great when users see half-loaded ones at initial page download). I've researched jquery pre-loading images (such as this very helpful Q/A here), but the thing is, my page is basically an app controlled by Ember.js -- so I'm not sure where to best insert the image-preloading code, and I can't seem to find any documentation on Ember.js code being run before page completes loading (the ready function might be too late for preloading images as it runs after the page is finished right?)
Bottom line: If I have Ember.js, where's the most optimal place to put image pre-loading code?

A: It doesn't matter, you can preload images at any time using javascript.
But you need to consider bandwidth consumption and possibly parallell download slots limitations in some browsers, so I advise against preloading many large images before your app and UI is complete.
Here is a minimal code example:
(new Image).src = 'preload.jpg';

A: Basically u want to write a function which needs to run before Emberjs Application class/object. So u can run that function either before creating or initializing Application object. I suggest you to do that before creating Application object.


text:
Q: Function that returns disjoint sublists I have to write a function that takes two arguments: a list list and an integer n. The function should return another list called result with sublists of length n. These sublists should contain all variations of elements from list, with no duplicates. Could someone help me how to approach this problem? Thanks in advance!

A: You have a list of numbers without duplicates. You want to create all sublists with given length, where the order matters and no duplicates in the sublist are allowed, for short: variations without repetition.
For safety, we first make sure that the original list contains no duplicates. Then we create all sublists with length n. Finally we create all permutations of the sublists:
variations[list_, n_] := Module[{d = Union[list]},
  d = Subsets[d, {n}];
  Flatten[Permutations /@ d, 1]
]

Here is a small test:
dat = Range[5];
variations[dat, 3]

A: You can use Permutations directly using the second argument to specify the length of sublists:
ClearAll[duplicateFreePermutations]

duplicateFreePermutations[lst_, n_] := Permutations[Union @ lst, {n}]

Examples:
duplicateFreePermutations[Range[5], 3]

duplicateFreePermutations[{a, b, b, c, c}, 3]

{{a, b, c}, {a, c, b}, {b, a, c}, {b, c, a}, {c, a, b}, {c, b, a}}


text:
Q: Get Peer IP Address and Port I manage to get the host information from particular requested network adapter using code below but i have no idea how to get peer ip address from host ip address.
struct sockaddr_in *sa = (struct sockaddr_in *)&item->ifr_addr;
    ipAddr = ntohl(*((u_int32_t *)&sa->sin_addr));
    if (pIpAddr != NULL)
    {
        *pIpAddr = ipAddr;
    }

    // Get the MAC address
    if ( ioctl(s, SIOCGIFHWADDR, item) < 0 )
    {
        printf("_GetMacAddress : SIOCGIFHWADDR failed!\n");
        return 0;
    }
    else
    {
        struct sockaddr *eth = (struct sockaddr *) &item->ifr_ifru.ifru_hwaddr;
        unsigned long *low = (unsigned long *)&eth->sa_data[2];
        unsigned short *high = (unsigned short*)&eth->sa_data[0];
        //printf("%s : MAC = 0x%04x, 0x%08x", ntohs(*high), ntohl(*low));

        printf("Interface %8s : IP %3d.%3d.%3d.%3d : MAC = %02x:%02x:%02x:%02x:%02x:%02x\n",
            item->ifr_name,
            ((ipAddr >> 24)&0xff), ((ipAddr >> 16)&0xff), ((ipAddr >> 8)&0xff), (ipAddr&0xff),
            ((ntohs(*high)>> 8)&0x00ff), (ntohs(*high)&0x00ff),
            ((ntohl(*low)>> 24)&0x00ff), ((ntohl(*low)>> 16)&0x00ff), ((ntohl(*low)>> 8)&0x00ff), (ntohl(*low)&0x00ff));

        if ((pMacHigh != NULL) && (pMacLow != NULL))
        {
            *pMacHigh = *high;
            *pMacLow = *low;
        }
    }

The output is:
_GetMaxNetworkInterfaces 3
Interface       lo : IP 127.  0.  0.  1 : MAC = 00:00:00:00:00:00
Interface   enp4s0 : IP 192.168.128. 88 : MAC = f4:8e:38:ea:88:23
Interface   wlp5s0 : IP 192.168. 53. 63 : MAC = b8:81:98:b7:71:90

A: If you are server listening for incoming connection, you can get peer address from accept() , in the second its argument, when a new socket is accepted
From man page of accept():
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returned addr is determined by the socket's address family (see socket(2) and the respective protocol man pages). When addr is NULL, nothing is filled in; in this case, addrlen is not used, and should also be NULL.

A:
I have no idea how to get peer ip address from host ip address.

You can't. The question doesn't make sense.
To get a peer address you have to have a peer, and to have a peer you have to have a connected socket, with which you can call getpeername().
Or, if you're a server, you can get it as a side-effect of accept() via the second and third arguments.

A: I did tried to implement arp-scan to find the connected client Ip address.
First we have to define the max device connected for my case will be 32. I manage to get following information from previous code
Interface       lo : IP 127.  0.  0.  1 : MAC = 00:00:00:00:00:00
Interface   enp4s0 : IP 192.168.128. 88 : MAC = f4:8e:38:ea:88:23
Interface   wlp5s0 : IP 192.168. 53. 63 : MAC = b8:81:98:b7:71:90

The information that require by arp-scan is interface name and the device IP address. In order to get client ip address we have to remove the character after counting the third dot. The end result we will get is:
127.0.0.
192.168.128.
192.168.53.

the last step is to loop for max device
127.0.0.0~31
192.168.128.0~31
192.168.53.0~31

Then feed into arp-scan ping and we will get the response from client ip address. I am using this arp-scan reference.


text:
Q: I decided I've had enough vs I decided I'd had enough Today I heard a native English speaker teacher use We decided we have had enough while telling a story. I am somewhat familiar with the notion of Sequence of tenses and thought the correct usage was We decided we had had enough where the have had should have backshifed to had had similarly to what happens in reported speech.
Am I misinterpreting the rules?

A: Backshifting isn't mandatory in all cases, and in particular, when reporting something that you believe is still true, you often don't backshift.
Consider, yesterday, John said, "My mother lives in Wales."
Today you report what John said:

John said that his mother lives in Wales.

You don't have to backshift because you believe that today she still lives in Wales.  On the other hand if you are not sure if it is still true you would backshift.

Twenty years ago, John said that his mother lived in Wales, I'm not sure if she still does.

Similarly here.  The speaker has "had enough" and this is still true today, so she chooses not to backshift. On the other hand, if she was talking about things long ago, she may well have backshifted because her feeling of having "had enough" was no longer present.

20 years ago we bought a house because of the trouble with landlords. When our landlord doubled the rent and refused to repair the boiler we decided we'd had enough....


text:
Q: g++ -O optimizations I have the following code:
#include <iostream>
int main()
{
        int n = 100;
        long a = 0;
        int *x = new int[n];

        for(int i = 0; i < n; ++i)
                for(int j = 0; j < n; ++j)
                        for(int k = 0; k < n; ++k)
                                for(int l = 0; l < n; ++l)
                                {

                                        a += x[(j + k + l) % 100];
                                }
        std::cout << a << std::endl;
        delete[] x;
        return 0;
}

If I compile without optimizations g++ test.cc and then run time ./a.out it will display 0.7s. However when I compile it with -O, the time decreases by 2 times.
Compiler used
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2

My question
How can I rewrite the code so when compiling without -O I can obtain same time ( or close to it ) ? In other words, how to optimize nested loops manually ?
Why I ask
I have a similar code which runs about 4 times faster if I use -O optimization.
PS: I've looked in the manual of the compiler but there are way too many flags there to test which one really makes the difference.

A: This code has undefined behaviour, so actually the optimizer can do whatever it wants..
a += x[j + k + l % 100];

should be:
a += x[(j + k + l) % 100];

If you fix this I still don't get why you want to optimize something that actually doesn't do anything...
Personally I would optimize this to: :)
std::cout << 0 << std::endl;

Note: remove the loop for i and do std::cout << a * n << std::endl;

A: Most of the things the compiler optimizes with -O are things on a level below C++. For example, all variables live in memory, including your loop variables. Therefore without optimization, the compiler will most likely on each iteration of the inner loop first read the loop variable to compare it with 0, inside the loop load it again in order to use it for the index, and then at the end of the loop will read the value again, increment it, and write it back. With optimization, it will notice that the loop variable is not changed in the loop body, and therefore does not need to get re-read from memory each time. Moreover it will also note that the address of the variable is never taken, so no other code will ever access it, and therefore writing it to memory can also be omitted. That is, the loop variable will live only in memory. This optimization alone will save three hundred million memory reads and one hundred million memory writes during execution of your function. But since things like processor registers and memory reads/writes are not exposed at the language level, there's no way to optimize it at the language level.
Furthermore, it doesn't make sense to hand-optimize things which the compiler optimizes anyway. Better spend your time at optimizing things which the compiler cannot optimize.

A: You could observe that your loops form a set of coefficients coeff[i] such that a single loop summing a[i] * coeff[i] produces the same total as the nested loop.  If we assume your index was meant to be (i + j + k) % 100 then coeff[i] = n * n * n for all i, so your whole program simplifies to
long coeff = n * n * n;
for (int i = 0; i < n; ++n)
    a += x[i] * coeff;

which I'm sure runs in far less than 0.7 seconds.

A: You're using a polynomial time algorithm (n ** 4) so it stands to reason it'll be slow, especially for larger n. Perhaps an algorithm with a lower complexity would help you?
If you want your code optimized you can either ask the compiler to optimize for you, or just write it in assembly language and be done with it. Don't try to second-guess the C++ compiler.

A:
How can I rewrite the code so when compiling without -O I can obtain same time ( or close to it ) ? In other words, how to optimize nested loops manually ?

You write them in assembly. Good luck with that, BTW.
The purpose of the optimization switches in compilers is for you to say, "Compiler, I want you to try to generate fast assembly." By default, compilers do not do optimizations, because those optimizations might inhibit the debugability of the resulting code. So you have to specifically ask for them.
The things the compiler does to optimize code are, generally speaking, not something you can do manually. Some can be (like loop unrolling), but others can't be.


text:
Q: Attempting to code a c program to return a string length by dividing the code into two separate functions I've been through several examples and videos and feel like there's a basic misconception on my part somewhere that I'm not seeing.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
    char String;
    char *sendString;
    char getString[100];
    int counter;

    *sendString = String;

    printf("\nPlease enter string:\n");
    fgets(getString, 100, stdin);

    int calcLength(counter);

    printf("los1111: %d", counter);

    return 0;
}

int calcLength()
{
    char *sendString[100];
    int counter;
    for(counter = 0; *sendString[counter] != '\0'; counter++);

    printf("los: %d", counter);
    return counter;
}

there are a couple of test 'los' printf functions to see where the code is breaking but that unfortunately is bringing me up nothing.  Any help is greatly appreciated.

A: I think your over complicating it slightly.
In this block of code:
char String;
char *sendString;
char getString[100];
int counter;

*sendString = String;

You don't need most of these char declarations, if you only want to calculate the length of the string from fgets.
This can simply be reduced to:
char getstring[100];
int myStrLen;

Where you only need to give a string buffer to fgets, and an integer declaration myStrLen, used to calculate the final string length.
Additionally, there are some problems with your calcLength() function. You need to pass a char [] parameter to this function, so it knows what string it needs to calculate the length of. It really should be as simple as this:
int
calcLength(char sendstring[]) {
    int counter, len = 0;

    for (counter = 0; sendstring[counter] != '\0'; counter++) {
        len++;
    }
    return len;
}

With all of these recommendations, your code should look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFSIZE 100

int calcLength(char sendstring[]);

int
main(void) {
    char getstring[BUFFSIZE];
    int myStrLen;

    printf("\nPlease enter string:\n");
    if (fgets(getstring, BUFFSIZE, stdin) != NULL) {
        getstring[strlen(getstring)-1] = '\0'; // To remove '\n' character from fgets()
    }

    myStrLen = calcLength(getstring);

    printf("String length = %d\n", myStrLen);

    return 0;
}

int
calcLength(char sendstring[]) {
    int counter, len = 0;

    // Every valid character found, increment a counter
    for (counter = 0; sendstring[counter] != '\0'; counter++) {
        len++;
    }
    return len;
}

Note: This code can be improved, but it should help point you in the right direction. I've added some comments in the code for clarification.


text:
Q: Python: Selecting column values from multiple columns dynamically I have 2 dataframes. The first is a summary table that summarizes the accuracy (in descending order) of each industry and its source.
cols = ['industry', 'source', 'accuracy']

df = pd.DataFrame(np.array([
    ['chemical', 'source B', 0.9],
    ['chemical', 'source A', 0.7],
    ['education', 'source A', 0.9],
]), columns=cols)

In the 2nd table, Source A and B have lists of strings in them, and they can be nulls:
cols = ['company', 'industry', 'source A', 'source B']

df2 = pd.DataFrame(np.array([
    ['company1', 'chemical', np.nan, ['a123', 'b456']],
    ['company2', 'chemical', ['a555', 'd333'], np.nan],
    ['company3', 'education', np.nan, ['777', '888']],
]), columns=cols)

For each row/company, I'm supposed to select the first non-null source that has the highest accuracy, which will look something like the following table:
cols = ['company', 'industry', 'which_source', 'source_value']

df3 = pd.DataFrame(np.array([
    ['company1', 'chemical', 'source B', ['a123', 'b456']],
    ['company2', 'chemical', 'source A', ['a555', 'd333']],
    ['company3', 'education', np.nan, np.nan],
]), columns=cols)

For e.g., for company1 and 2, although they're both from the 'chemical' industry, for company2 its source is from source A because its value in source B is null.
And for company3 from 'education' industry, even though there is a value in source B, as source B for 'education' industry doesn't meet some minimum threshold (hence it didn't appear in the df1), it's 'source' and 'source_value' should just be null.
Thanks in advance!

A: You could melt, merge and filter:
df3 = (df2
 .melt(['company', 'industry'], var_name='source', value_name='source_value')
 .merge(df, how='inner')
 .sort_values(by='source_value', key=pd.isna)
 .groupby(['company', 'industry'], as_index=False).first()
 .assign(which_source=lambda d: d['source'].mask(d['source_value'].isna()))
 .drop(columns=['source', 'accuracy'])
)

output:
    company   industry  source_value which_source
0  company1   chemical  [a123, b456]     source B
1  company2   chemical  [a555, d333]     source A
2  company3  education          None          NaN


text:
Q: Flask-Celery-Redis:Memcached memory release? I'm running a flask app that is meant to receive sporadic, yet heavy-duty, jobs. I implemented a series of docker containers running the flask app, celery, redis (as the broker) and memcached (as the backend). I use celery to fork processing weight into chunks, then use get() to retrieve all results:
# Multithreading
jobs = group(processing_fn.s(c) for c in chunks)
result = jobs.apply_async()

while not result.ready() :
    time.sleep(30)

resultset = result.get()

While this does work fast and fine, I'm having troubles ordering celery to release the RAM used to store task results after I used them. Eventually, the server runs out of memory and has to be restarted, which is far from optimal.
I tried using .forget over the resultset (and even over each result in the resultset):
result = result.get()
result.forget()

...

resultset = result.get()
for r in result :
    r.forget()

However, none of these released the memory... Any ideas?
Here's how the celery app is instantiated:
from celery import Celery

def make_celery(app):
    celery = Celery(
        app.import_name,
        broker = "redis://redis:6379/",
        backend = "cache+memcached://memcached:11211"
    )
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery

...

celery = make_celery(app)

A: By default celery stores the result of any task for 1 day:
See:
You can tweak it via:  CELERY_TASK_RESULT_EXPIRES or
https://docs.celeryproject.org/en/latest/userguide/configuration.html#result-expires


text:
Q: AWS Lambda event to python dictonary I am trying to convert event json from aws lambda function to python dictionary to that I can the event type and cluster identifier but I am getting an error which i am not able to resolve
Below is my code and error
import json
st = """
{
   "Records":[
      {
         "EventSource":"aws:sns",
         "EventVersion":"1.0",
         "EventSubscriptionArn":"arn:aws:sns:us-east-2:427128480143:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e2ddc5e3c",
         "Sns":{
            "Type":"Notification",
            "MessageId":"fecb7b39-a861-5450-9179-23d0ce68f268",
            "TopicArn":"arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic",
            "Subject":"AmazonRedshiftINFO - Cluster Created",
            "Message":"{\"Event Source\":\"cluster\",\"Resource\":\"qa-redshift-cluster\",\"Event Time\":\"2021-04-08 20:12:57.466\",\"Identifier Link\":\"https://console.aws.amazon.com/redshift/home?region=us-east-2#cluster-details:cluster=qa-redshift-cluster \",\"Severity\":\"INFO\",\"Category\":[\"Management\"],\"About this Event\":\"http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html#REDSHIFT-EVENT-2000 \",\"Event Message\":\"Amazon Redshift cluster \\'qa-redshift-cluster\\' has been created at 2021-04-08 20:12 UTC and is ready for use.\"}",
            "Timestamp":"2021-04-08T20:12:57.905Z",
            "SignatureVersion":"1",
            "Signature":"jS2AK8hf/rebeXMsfFw0DJx+788w+RiDTXyAbLNZzYdE5Mlhi6GRRIns8VaAJZc5otXkkhGshvgvuE0JsUiOhXBccGEJY6Z+lhx6cLSQoEdQB0DRfwltWKOfpQ88LZXJuKCxYcsPL3y5veBdjJqwjdBZtcVYV9BYRhQvT6q/0MpDcJeOYzMkdpR2ULX5B7GasZ3AV0WbKxIjjzFSd3GNud2m85obRrB//NHQwqN6ydvg7PaN/sXuyJjmguRok27O6YNkIqzKjC4JxDbTl4BwyIbck59edbHC5kxmfpoc/RqjF/kUGaqnf0HYOUuMfDT85+9wYVz8vFFER1v3NnKRLA==",
            "SigningCertUrl":"https://sns.us-east-2.amazonaws.com/SimpleNotificationService-010a507c1833636cd94bdd98bd93083a.pem",
            "UnsubscribeUrl":"https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e7ddc5e3c",
            "MessageAttributes":{

            }
         }
      }
   ]
}
"""

data1 = json.loads(st)
print(type(data1))
print(data1)

data1 = json.loads(st)
print(type(data1))
print(data1)

{'Records': [{'EventSource': 'aws:sns', 'EventVersion': '1.0', 'EventSubscriptionArn': 'arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e1ddc5e3c', 'Sns': {'Type': 'Notification', 'MessageId': 'fecb7b39-a861-5450-9189-23d0ce68f268', 'TopicArn': 'arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic', 'Subject': '[Amazon Redshift INFO] - Cluster Created', 'Message': '{"Event Source":"cluster","Resource":"qa-redshift-cluster","Event Time":"2021-04-08 20:12:57.466","Identifier Link":"https://console.aws.amazon.com/redshift/home?region=us-east-2#cluster-details:cluster=qa-redshift-cluster ","Severity":"INFO","Category":["Management"],"About this Event":"http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html#REDSHIFT-EVENT-2000 ","Event Message":"Amazon Redshift cluster \'qa-redshift-cluster\' has been created at 2021-04-08 20:12 UTC and is ready for use."}', 'Timestamp': '2021-04-08T20:12:57.905Z', 'SignatureVersion': '1', 'Signature': 'jS2AK8hf/rebeXMsfFw0DJx+788w+RiDTXyAbLNZzYdE5Mlhi6GRRIns8VaAJZc5otXkkhGshvgvuE0JsUiOhXBccGEJY6Z+lhx6cLSQoEdQB0DRfwltWKOfpQ88LZXJuKCxYcsPL3y5veBdjJqwjdBZtcVYV9BYRhQvT6q/0MpDcJeOYzMkdpR2ULX5B7GasZ3AV0WbKxIjjzFSd3GNud2m85obRrB//NHQwqN6ydvg7SaN/sXuyJjmguRok27O6YNkIqzKjC4JxDbTl4BwyIbck59edbHC5kxmfpoc/RqjF/kUGaqnf0HYOUuMfDT85+9wYVz8vFFER1v3NnKRLA==', 'SigningCertUrl': 'https://sns.us-east-2.amazonaws.com/SimpleNotificationService-010a507c1833636cd94bdb98bd93083a.pem', 'UnsubscribeUrl': 'https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e1ddc5e3c', 'MessageAttributes': {}}}]}

Error
Traceback (most recent call last):
  File "/home/deepak/PycharmProjects/TerraformSeriousProject/boto3Examples/src/test.py", line 29, in <module>
    data1 = json.loads(st)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 26 (char 520)

I used https://jsonformatter.curiousconcept.com/# tool to format the json

A: Loading like this in Python you will need to double the backslashes on the Message line.  The slash that you have there currently will be used to create the string.
You can see this by doing a print of st
However the better way to do this would be to not have st as a string but a dictionary (i.e. remove the triple quotes), then you don't need to mess around with the json library at all here
st = {
    "Records":[
        {
            "EventSource":"aws:sns",
            "EventVersion":"1.0",
            "EventSubscriptionArn":"arn:aws:sns:us-east-2:427128480143:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e2ddc5e3c",
            "Sns":{
                "Type":"Notification",
                "MessageId":"fecb7b39-a861-5450-9179-23d0ce68f268",
                "TopicArn":"arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic",
                "Subject":"AmazonRedshiftINFO - Cluster Created",
                "Message":"{\"Event Source\":\"cluster\",\"Resource\":\"qa-redshift-cluster\",\"Event Time\":\"2021-04-08 20:12:57.466\",\"Identifier Link\":\"https://console.aws.amazon.com/redshift/home?region=us-east-2#cluster-details:cluster=qa-redshift-cluster
    \",\"Severity\":\"INFO\",\"Category\":[\"Management\"],\"About this Event\":\"http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html#REDSHIFT-EVENT-2000 \",\"Event Message\":\"Amazon Redshift cluster \\'qa-redshift-cluster\\' ha
    s been created at 2021-04-08 20:12 UTC and is ready for use.\"}",
                "Timestamp":"2021-04-08T20:12:57.905Z",
                "SignatureVersion":"1",
                "Signature":"jS2AK8hf/rebeXMsfFw0DJx+788w+RiDTXyAbLNZzYdE5Mlhi6GRRIns8VaAJZc5otXkkhGshvgvuE0JsUiOhXBccGEJY6Z+lhx6cLSQoEdQB0DRfwltWKOfpQ88LZXJuKCxYcsPL3y5veBdjJqwjdBZtcVYV9BYRhQvT6q/0MpDcJeOYzMkdpR2ULX5B7GasZ3AV0WbKxIjjzFSd3GNud2m85obRrB//NHQwqN6ydv
    g7PaN/sXuyJjmguRok27O6YNkIqzKjC4JxDbTl4BwyIbck59edbHC5kxmfpoc/RqjF/kUGaqnf0HYOUuMfDT85+9wYVz8vFFER1v3NnKRLA==",
                "SigningCertUrl":"https://sns.us-east-2.amazonaws.com/SimpleNotificationService-010a507c1833636cd94bdd98bd93083a.pem",
                "UnsubscribeUrl":"https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e7ddc5e3c",
                "MessageAttributes":{
                }
            }
        }
]
}
print(st['Records'][0]['Sns']['Message'])
{"Event Source":"cluster","Resource":"qa-redshift-cluster","Event Time":"2021-04-08 20:12:57.466","Identifier Link":"https://console.aws.amazon.com/redshift/home?region=us-east-2#cluster-details:cluster=qa-redshift-cluster ","Severity":"INFO","Category":["Management"],"About this Event":"http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html#REDSHIFT-EVENT-2000 ","Event Message":"Amazon Redshift cluster \'qa-redshift-cluster\' has been created at 2021-04-08 20:12 UTC and is ready for use."}

A: You have to escape double quotes in python with two backslashes, like this \\".
This event would work:
st = """
{"Records":[{
         "EventSource":"aws:sns",
         "EventVersion":"1.0",
         "EventSubscriptionArn":"arn:aws:sns:us-east-2:427128480143:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e2ddc5e3c",
         "Sns":{
            "Type":"Notification",
            "MessageId":"fecb7b39-a861-5450-9179-23d0ce68f268",
            "TopicArn":"arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic",
            "Subject":"AmazonRedshift INFO - Cluster Created",
            "Message":"{\\"Event Source\\":\\"cluster\\",\\"Resource\\":\\"qa-redshift-cluster\\",\\"Event Time\\":\\"2021-04-08 20:12:57.466\\",\\"Identifier Link\\":\\"https://console.aws.amazon.com/redshift/home?region=us-east-2#cluster-details:cluster=qa-redshift-cluster \\",\\"Severity\\":\\"INFO\\",\\"Category\\":[\\"Management\\"],\\"About this Event\\":\\"http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html#REDSHIFT-EVENT-2000 \\",\\"Event Message\\":\\"Amazon Redshift cluster 'qa-redshift-cluster' has been created at 2021-04-08 20:12 UTC and is ready for use.\\"}",
            "Timestamp":"2021-04-08T20:12:57.905Z",
            "SignatureVersion":"1",
            "Signature":"jS2AK8hf/rebeXMsfFw0DJx+788w+RiDTXyAbLNZzYdE5Mlhi6GRRIns8VaAJZc5otXkkhGshvgvuE0JsUiOhXBccGEJY6Z+lhx6cLSQoEdQB0DRfwltWKOfpQ88LZXJuKCxYcsPL3y5veBdjJqwjdBZtcVYV9BYRhQvT6q/0MpDcJeOYzMkdpR2ULX5B7GasZ3AV0WbKxIjjzFSd3GNud2m85obRrB//NHQwqN6ydvg7PaN/sXuyJjmguRok27O6YNkIqzKjC4JxDbTl4BwyIbck59edbHC5kxmfpoc/RqjF/kUGaqnf0HYOUuMfDT85+9wYVz8vFFER1v3NnKRLA==",
            "SigningCertUrl":"https://sns.us-east-2.amazonaws.com/SimpleNotificationService-010a507c1833636cd94bdd98bd93083a.pem",
            "UnsubscribeUrl":"https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:427128480243:terraform-redshift-sns-topic:cbdfec04-7502-4509-9954-435e7ddc5e3c",
            "MessageAttributes":{

            }
         }
      }
   ]
}
"""