text:
Q: Mysql - Insert string with white space How do I insert string with white spaces in VARCHAR?
insert into users (user_id,firstname,lastname,email,group) values('admin','some','Body','admin@something.com','Site admin');

This is giving me syntax error, I am new to mysql, I went through mysql documentation that doesnt give me clear idea why this behavior is.
 mysql> insert into users (user_id,firstname,lastname,email,group) values('admin','some','Body','admin@something.com','Site admin');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group) values('admin','some','Body','admin@something.com','Site admin')' at line 1

A: group is a keyword in MySQL. Modify your query like this:
INSERT INTO users (user_id, firstname, lastname, email, `group`)
VALUES('admin', 'some', 'Body', 'admin@something.com', 'Site admin');

A: Group is a keyword, you need to use back ticks like this `group` to make it so the group will be read as a table column instead
INSERT into users (user_id,firstname,lastname,email,`group`)
VALUES ('admin','some','Body','admin@something.com','Site admin');


text:
Q: How to play notification sound using onesignal notification via REST API? I have tried a lot of things on like created channel mode, added sound in res/raw directory it works well with when we send notification directly from onesignal dashboard but I'm not able to figure out how can I send it through API. I refered onesignals official documentation and see something android_channel_id and also set it in API API Image
Please help me if anyone knows how to enable sound via API by the way the notification is working well but can't able to play sound.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a compressed hash for my url in javascript Hi i want to compress my url very similar to below shown Result

Here is above output link: https://jsbin.com/cayuhox/edit?html,css,js,output
My Problem is (i will be having most of the url as shown below, which not working with above generator):

*

*http://100.22.0.77:8888/nginx/assets?s={%22path%22:%22com://ANTARTICA%22,%22sort_by%22:0}&page=1&_=1595330210051

*http://100.22.0.77:8888/nginx/assets/folder_assets_counter?s={%22path%22:%22com%3A%2F%2FANTARTICA%22}&_=1595330210050

*

 http://100.22.0.77:8888/nginx/assets/folder_assets_counter?s={"path":"com://ANTARTICA", selectedIds:["randeaee2d0af83b5cb4f86e","94ea39dc5eba3b41945d","ca49d38872e8b3f94758","6741e5d08fd18c7a69b3"]}&_=1595330210050

*and even big url so on..

Expected Output:  i need to generate as short output as this one woPCpXJvc2VzwqNyZWTCp3Zpb2xldHPCpGJsdWXCpmZydWnEkcKSwqVhcHDEjwI  from above hash urls should not exceed 500 chars. i'm very much open to use any plugin or some of your tricky javascript code
Please help me thanks in advance!!


text:
Q: How to get the count of specific days from week between a date range in mysql? I have a table "task_table" containing columns-
Task_id, Start_date, End_date
And I have one more "configuration" table which has the records that tell which days of the week are working days.
This table has two columns -
week_day, isHoliday
and this table contains seven records as week_days are the Monday,Tuesday.....Sunday , and each record has an entry as 1 or 0. If a day is a holiday in any organization then there will be 0 against that day. Like if an organisation has holidays on Wednesday and Friday every week then there will be 0 against Wednesday and Friday only.
Now I want to make a SQL query to get the Task_id, Start_date, End_date, and the count of total days consumed on each task. (These days are the  days between task start_date and end_date excluding the holiday days as configured in "configuration" table.)

A: I don't have time to fully answer this question now, but what I would do is:
Get the date as at the start of the Start_date week, and the date as at the end of the End_date week (you can get this by date_adding an amount of days according to the day of the week.
Then you want to date diff them, divide by seven, multiply by two, and remove any that you would have added (e.g. if the start date was Thursday then you'll need to remove one from the result, as you will have counted one for the Wednesday immediately prior.
I'll write the code out tomorrow (it's late here - something like 14 hours from now or so.) if noone else has suggested a better answer.
Edit: Right, didn't properly read the question, but the tactic still applies with a little fiddling. Speaking of which, here is the fiddle of my solution.
It boils down to the following code:
set @holidaysPerWeek = (select sum(isHoliday) from configuration);

select
  Task_id,
  ((dateDiff(
    DATE_ADD(End_Date, INTERVAL 7 - DayOfWeek(End_Date) DAY),
    DATE_ADD(Start_Date, INTERVAL -DayOfWeek(Start_Date) + 1 Day)) + 1) / 7)
    * @holidaysPerWeek
    - (select sum(isHoliday) from configuration where week_day > DayOfWeek(End_Date))
    - (select sum(isHoliday) from configuration where week_day < DayOfWeek(Start_Date)),
  DayOfWeek(End_Date)
from task_table

This does exactly what I was saying before, but with a variable number of "weekends" spread throughout the week, by first selecting the number of holidays for if the full weeks were covered, then removing holidays that were before or after the start and end dates respectively.


text:
Q: Doctrine PHP associations symfony3 What should I do? I need to stablish doctrine associations between printer, Toner,tape and ink. One printer could just use One of those {toner,tape, ink}.
but i'm not sure what's the best way to do it. I want to use the best practice as possible (OOP).

A: Doctrine2 supports inheritance mapping – you can use it:

/**
 * @ORM\Table
 * @ORM\Entity
 */
class Printer
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToOne(targetEntity="Consumable")
     */
    private $consumable;
}

/**
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"toner" = "Toner", "ink" = "Ink"})
 */
abstract class Consumable
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime")
     */
    private $updatedAt;
}

/**
 * @ORM\Entity
 */
final class Toner extends Consumable
{}

/**
 * @ORM\Entity
 */
final class Ink extends Consumable
{}


text:
Q: Overloading a function by return type? One of the most viewed questions here on SO is the question that deals with overloading of various operators. There is something I don't understand about the overloading of brackets operator operator[]. My question is about the following code:
class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...
};

Here the operator is overloaded twice, one function which allows the change of members and one which does not. I read that c++ doesn't allow function overloading by return type, but this looks like it. T& is changed to const T&. Can someone explain to me what exactly is this "overloading" called and why does this work?
Thanks in advance.
PS: If this works because the second const keyword changes the "invisible" this pointer argument to const this then I understand, but still, is there a name for that practice?

A: For overloading to work the functions need to have different signatures (the return type does not count).
In methods the this pointer to the object also counts as an implicit (first) argument. Static methods of course don't have a this pointer, so they can be treated like global functions.
In your example the two methods have different arguments. idx is identical in both cases but the first method has a this pointer of type X*, which is a variable pointer. In the second method the this pointer is a constant type: const X* and is thus distinct from the first one, that's why the overloading works.
The return value is inconsequential to the overloading. If only the return values were different, overloading would not have been allowed by the compiler.
class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
                     // -----------------------^^^^^
                     // This is what makes the overloading possible.
};


text:
Q: Is there a word or an idiom for respecting someone because you are afraid of him? I am looking for a word or an idiom about showing respect to someone superior in work because you are afraid of him. I'm not talking about real respect or showing respect to him or his works, just getting scared by his ruthless actions.
Is there a word or an idiom for respecting someone because you are afraid of him?

A: Perhaps you can say that he is in awe of, intimidated by, cowed by or daunted by his superior.

A: [have] fearful respect, [be] in awe

The British Approach to Counterinsurgency: From Malaya and ... Paul
  Dixon - 2012
rather than inspire fear, but given its history of misuse and lack of
  precision in its meaning it may be best to lay the phrase to rest. ...
  The fearful respect of the local population is insufficient to
  establish a democratic state because democracy is ..

A: "reverence" is a feeling of profound awe and respect, often used in religious contexts.
Respect itself is sometimes used for a feeling that has grown out of fear - it's just that the person won't admit there's fear involved and prefers to use "respect".  For instance: "John is tall and very strong. Everyone respects him."  or "We have to respect the X (name of a people). They have the bomb."

A: You could say that such a person might

kiss the rod
  Accept punishment submissively

Oxford Dictionaries

A: You might find these words useful:
Subdue: example,

The pair managed to subdue a man who was holding his ex-partner at
  knifepoint in front of their seven-year-old son

Quieten: example,

When storms are brewing, he speaks, and quietens the waters.

and Overcome.

A: From a different angle, that of naming your behaviour towards the pointy-haired boss, you may note "to placate". The word contains the implication that if you don't kiss butt, he is all ready and waiting to do something bad to you.

A: In the US we say: 'You kowtow to the boss' or, you are kowtowing. It means showing deference - whether or not you are sincere. (Borrowed from the Chinese expression for kneeling and touching one's head to the ground, to a revered person.)

A: To be in awe of someone means to respect, fear, and admire someone.


text:
Q: how to create a clean and scalable NSIS installer implementation out of a VB6 project? I am updating my installer from using the VB6 packaging & deployment Wizard to the NSIS installer.
The list of files my project uses are diverse, using different paths and types of files. For example,
File1=@drillcycles.pre,$(AppPath),,,8/30/10 10:23:54 AM,49152,1.0.0.1
....
File5=@techno1.TTF,$(AppPath),,$(Shared),12/6/06 10:14:56 AM,12704,0.0.0.0
....
File18=@MSCOMM32.OCX,$(WinSysPath),$(DLLSelfRegister),$(Shared),6/23/98 11:00:00 PM,103744,6.0.81.69
....

Initially, I was planning to hard code every single file into the NSIS script, but it would be cumbersome for a newbie in my team to actually update my code. It is hard to reuse and scale.
Then, I was planning to create several folders for each respective path, as well as the type of process that the file should go through. For example, an app_path_selfregistered folder in which I could drop the new files and just recompile my installer. I felt that it was not really scalable and clean solution.
Finally, someone suggested me to create an external script that I would call, but I am not sure how to implement it nor what would be the advantage over my first approach.
Any ideas how to cleanly create a scalable NSIS installer in which I can easily update to new files as well as newer versions of them?
Thanks


text:
Q: How to launch method when window got focus again in WPF? My app is multi-window, here is quickly how it works:
In main window  I have a list of items, when I click on one, it opens another window where I can modify it. When I close that window, I want main window to refresh its content. I've tried many event handlers including GotFocus() but it doesn't want to launch my method to refresh the list. Any advise?

A: If you want something to happen when the other window is closed, you can subscribe to its closed event. This will fire when the windows is closed.
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var wnd = new Window1();
        wnd.Closed += wnd_Closed;
        wnd.Show();
    }

    void wnd_Closed(object sender, EventArgs e)
    {
        MessageBox.Show("Closed");
    }


text:
Q: Ajax Call not calling the Controller Action Method I'm not able to make ajax call to the controller action method which returns the json object.
Also, I want to pass the integer-CheckID to the method.
Any help is highly appreciated.
Thanks in Advance!
***View***

<script type="text/javascript">

function showCheckImage(e) {
    e.preventDefault();

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var CheckID = dataItem.ID;

    $.ajax({
        url: '@Url.Action("GetDeferredCheckImage", "Customer")',
        type: 'POST',
        data: {deferredCheckID: CheckID },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',

        success: function(result) {
            //var imageObj = result;
            alert('Loaded Image Object!');
        },
        error: function (result) {
            alert('Error occurred while loading the image object.');
        }
    });
}

**Controller Method**

[HttpPost]
    public JsonResult GetDeferredCheckImage(int deferredCheckID)
    {
        try
        {
            QCEventLogger.Log($"Gathering deferred check image for check ID: {deferredCheckID}", LogType.Default);
            var response = new AjaxGetDeferredCheckImageViewModel(deferredCheckID);
            QCEventLogger.Log($"Result of service call to gather deferred check image.  check ID: {deferredCheckID}. Success: {response.Success}", LogType.Default);

            var DeferredCheckImageObject = response.ImageCheckObject.DeferredCheckImages.FirstOrDefault();

            return Json(DeferredCheckImageObject, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            var failureResponse = new AjaxGetDeferredCheckImageViewModel() { Success = false };
            QCErrorLogger.Log($"Failure trying to gather deferred check image for check ID: {deferredCheckID}", ex);
            return Json(failureResponse, JsonRequestBehavior.AllowGet);
        }
    }

A: Your ajax call might be like this,
 $.ajax({
        url: '@Url.Action("GetDeferredCheckImage", "Customer")',
        type: 'POST',
        data: { deferredCheckID: CheckID },
        dataType: 'json',
        success: function (result) {
            //var imageObj = result;
            alert('Loaded Image Object!');
        },
        error: function (result) {
            alert('Error occurred while loading the image object.');
        }
    });


text:
Q: A public Github repo not found via search using the following search query...
https://github.com/search?q=repo%3AOpeningDesign%2FOpeningDesign+GET&p=1&ref=searchbar&type=Code&l=
..on this public repo: https://github.com/OpeningDesign/OpeningDesign
nothing shows up.
Am i missing something?

A: Update January 24th, 2013: source "A Whole New Code Search"
The same query repo:OpeningDesign/OpeningDesign GET now returns result!
The search index must have been updated when then new search engine has been deployed (elasticsearch.org)

Original answer (January 6th, 2013)
Considering that:

*

*any request on the ruby/ruby repo works (as mentioned in "Search code inside a Github project")

*any request on OpeningDesign/OpeningDesign doesn't work,

it seems to be an indexation issue.
After their recent fileservers issues, this could be a side-effect.
As Iven points out, GitHub support should be able to clarify this.

The support did clarify (07 January 2013):

We have stopped adding newly pushed code into our codesearch index.
The volume of code has outgrown our current search index, and we are working on moving to a more scalable search architecture.
I'm sorry for the annoyance.
We do not have an estimate for when this new search index will be up and running, but when it is ready a blog post will be published (GitHub blog)


text:
Q: Pause/Resume another thread I know mutex can be an implementation, however I'm wondering there would be a way to pause/resume another thread as in video-playback. This approach is easier to program when the other running thread is complex.

A: There's SIGTSTP, a signal for pausing processes, which you could use if you have two processes, but signals have several drawbacks so I wouldn't recommend using them. For a controlled, stable method you'd have to do it yourself using a mutex, where user pausing the playback leads to locking the mutex, and the thread doing the playback tries to lock the mutex . Like this:
static pthread_mutex_t mutex;

/* UI thread */
void g(void)
{
    while(1) {
        get_input();
        if(user_wants_to_pause)
            pthread_mutex_lock(&mutex);
        else if(user_wants_to_resume)
            pthread_mutex_unlock(&mutex);
    }
}

/* rendering thread */
void f(void)
{
    while(1) {
        pthread_mutex_lock(&mutex);
        /* if we get here, the user hasn't paused */
        pthread_mutex_unlock(&mutex);
        render_next_frame();
    }
}

If you need more communication between the two threads you could use the standard IPC mechanisms like pipes - you could then implement pausing and resuming based on that.


text:
Q: How can I use C# parameters to insert into a SQL Database? I am having trouble using parameters in C# to insert into a SQL Database. My connection is already working
I have tried the Add, AddWithValue
static void parameter_insert(SqlConnection conn, int number)
{
    try
    {
        conn.Open();
        SqlCommand command = new SqlCommand(@"INSERT INTO test1.dbo.shopping_list(NAME, QUANTITY, QUALITY, FOOD_GROUP, FOODS VALUES('Bread', @Quantity, 'Poor', 'Carbs', 'Good')", conn);
        command.Parameters["@Quantity"].Value = 3;
        command.ExecuteNonQuery();
        Console.WriteLine("Parameter insertion successful.");
    }
    catch
    {
        Console.WriteLine("Parameter insertion failed.");
    }
}

The output gives me the insertion failed

A: You are missing a closing parenthesis on your insert query statement:
"INSERT INTO test1.dbo.shopping_list(NAME, QUANTITY, QUALITY, FOOD_GROUP, FOODS)"+ //<--missing clossing parenthesis
" VALUES('Bread', @Quantity, 'Poor', 'Carbs', 'Good')";

In any case and as a general rule, you should better log the actual exception message on a catch block instead of swallowing it with a custom message.
catch (Exception ex)
{
   Log(ex.ToString());
   ....//Inform user
}


text:
Q: How does Python know which number type to use in order to Multiply arbitrary two numbers? In C, I have to set proper type, such as int, float, long for a simple arithmetic for multiplying two numbers. Otherwise, it will give me an incorrect answer.
But in Python, basically it can automatically give me the correct answer.
I have tried debug a simple 987*456 calculation to see the source code.
I set a break point at that line in PyCharm, but I cannot step into the source code, it just finished right away.
How can I see the source code? Is it possible? Or how does Python do that multiplication?
I mean, how does Python carry out the different of number type in the result of
98*76 or 987654321*123457789, does Python detect some out of range error and try another number type?

A:
I mean, how does Python carry out the different of number type in the result of  98*76 or 987654321*123457789, does Python detect some out of range error and try another number type?

Pretty much. The source code for integer multiplication can be found in intobject.c. It multiplies the integers as C longs, then casts the longs to doubles and multiplies those. If the results are close, the long multiplication didn't overflow. If the results are very different, it switches to Python longs, which use a bignum representation.

A: The type promotion for mixed arithmetic is:
integer -> long -> float

The narrower type is converted to the wider type, and the multiplication is carried out.
https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex
Some examples to see what happens:
987*456 = 450072
987*456L = 450072L
987*456.0 = 450072.0

I hope I understood your question.

A: Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.
Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.


text:
Q: getting core data object by boolean property How can I get an object by a BOOL property? For example, if I have a custom object with a BOOL property completed, how can I get only the ones where completed = true? I'm using Magical Record
[CustomObject MR_findByAttribute:@"completed" withValue:true];

A: The searchValue argument of MR_findByAttribute:withValue: must be a reference to an object, but true is not a reference to an Objective-C object.  It is a "primitive" value.  You must wrap it in an NSValue object.
Also, in Objective-C we normally use the constants YES and NO as the boolean constants.
You can get an NSValue wrapper for YES just by saying @YES, so try this:
NSArray *completedObjects = [CustomObject MR_findByAttribute:@"completed"
    withValue:@YES];


text:
Q: Roslyn load project documents failing In a Visual Studio Extension (VSIX) solution, I'm using Roslyn to load a specific project from my current solution:
Project myProject =
    this.CurrentComponentModel.GetService<VisualStudioWorkspace>()
        .CurrentSolution.Projects
             .FirstOrDefault(p => p.Name == "MyProject")

The projct myProject is definitely loaded, but on inspection I see that:
myProject.HasDocuments == false
myProject.Documents is Empty

And yet, in Visual Studio I can see loads of documents.
If I close the solution and open the same solution but from another TFS branch, then the same code returns:
myProject.HasDocuments == true
myProject.Documents is not Empty

Any ideas?

A: I got this to work by:

*

*Deleting the obj/debug folder

*Cleaning

*Transforming all T4 templates (this is ASP.NET MVC)

*Restarting Visual Studio

*Re-compiling

Simply re-compiling had no effect.  Can't explain why, but the above formula worked for me.


text:
Q: CloudFormation Custom Resource update with the same parameters Is there a way to trigger a Custom Resource lambda without updating parameters? When I update stack without changes it doesn't detect the resource as to be modified. The only solution I'm thinking of is to have a useless parameter with a random value to invoke the lambda.

A: A custom resource really should be something that only needs to be called when something changes. That's how CloudFormation works. If you really need to force it to "update" then what you are describing would work. Your code doesn't need to care or even know about the extra parameter. As long as the value changes the call to update it will be made.


text:
Q: excel ace.oledb vba connection to csv returning only first column In VBA Excel (Office 365) trhough using a connection string like "Provider=Microsoft.ACE.OLEDB.12.0;data source=..." and using the command string  SELECT * FROM [text;HDR=Yes;FMT=Delimited;Delimiter=';';database=KKS].[kks.csv]; the results are:
 when the CSV source looks like this:
rng;key;component;
"0";"A";"Grid and distribution systems";
"0";"B";"Power transmission and auxiliary power supply";

The schema.ini is:
[kks.csv]
ColNameHeader=True
Format=CSVDelimited
Decimalsymbol=(,)
Delimiter=(;)

I have tried any combination for the connection string and for schema.ini (also removing it completely) and the results are the same at best. Any suggestion? Thank you!

A: change the Schema.ini as below.
[kks.csv]
Format = Delimited(;)


text:
Q: JAX WS webservice receives null parameters when part accessor elements are qualified with namespaces I have implemented a web service using Netbeans 7.0 and JAX-WS.
When the web service is called by Soap UI it works as it should. When it is called by SAP CRM the web service implementation receives null parameters: in the example below the userId is null instead of "foo". (userId is of type String)
The SOAP message sent by SOAP UI is:
   <?xml version="1.0" encoding="UTF-8" ?>
   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:IciSystemInterface">
       <soapenv:Header>
       </soapenv:Header>
       <soapenv:Body>
          <urn:getWorkcenterCapability>
             <userId>foo</userId>
          </urn:getWorkcenterCapability>
       </soapenv:Body>
    </soapenv:Envelope>

The SOAP message sent by SAP CRM is:
    <?xml version="1.0" encoding="UTF-8" ?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SOAP-ENV:Header>
      <pre:user xmlns:pre="urn:IciSystemInterface" SOAP-ENV:mustUnderstand="0" xsi:type="xsd:string">IC_AGENT_SRV</pre:user>
      <pre:language xmlns:pre="urn:IciSystemInterface" SOAP-ENV:mustUnderstand="0" xsi:type="xsd:string">EN</pre:language>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
     <ns0:getWorkcenterCapability xmlns:ns0="urn:IciSystemInterface">
       <userId xmlns="urn:IciSystemInterface">foo</userId>
     </ns0:getWorkcenterCapability>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

If I remove the xmlns property from the userId tag it works (I made the change and tested it by calling the web service using an HTTP client):
    <ns0:getWorkcenterCapability xmlns:ns0="urn:IciSystemInterface">
       <userId>foo</userId>
    </ns0:getWorkcenterCapability>

The problem is I can't change the way SAP CRM makes its calls. Is there a way I can make JAX WS ignore part accessor elements' namespaces?
Thank you in advance.

A: I followed @Branden's advice. I used SoapHandler to trap calls to the web service and process the soap message before JAX-WS calls my web service implementation. It worked.


text:
Q: godoc http server doesn't seem to live reload changes I seem to be unable to find an answer to the question, does the godoc server support live reload changes in for my own projects?
According to this article it should be supported however whenever I change my code (update documentation) no changes appear until restart of the web server
My documentation updates/appear every time I start the the sever:
godoc -http=:6060 &

I don't want to restart the server for every change, is this expected behavior, what can I do to update my changes with the least amount of effort?
My go version:
$ go version
go version go1.8 darwin/amd64

Using browser with incognito mode:
Chrome Version 57.0.2987.133 (64-bit)

A: Godoc for a directory ("Directory /src/github.com/someuser" at the top) does not automatically update.
Godoc for a package ("Package yourthing" at the top) will automatically update, but you must reload the page to see the change.


text:
Q: CSS - Background image and RGBA in section I just trying to put a background color (rgba) with an image, but doesn't work.
My CSS is:
section{
width:100%;

height:400px;

background: url(../img/background2.jpg);
background-color: rgba(0,0,0,0.5);
}

I just trying to put with diferent positions, like background-image, or just background, but doesn't work.

A: As I pointed out in comments, background color behaves as a fallback for the background image, unless the image is transparent:
section {background: rgba(0,0,0,0.5) url(../img/background2.png) 0 0 no-repeat;}

If you want to cover the image by an overlay layer (using rgba()), you can create a pseudo-element and position that as absolute the use left, top, right and bottom properties to expand the overlay, as follows:
.box {
    background: url(http://lorempixel.com/500/500) no-repeat center center;
    position: relative;
}

.box:after {
    content: ' ';
    position: absolute;
    left: 0;  right: 0; top: 0; bottom: 0; /* Fill the entire space */
    background-color: rgba(0,0,0,.4);
}

WORKING DEMO.
Does it have any content?
If so, you can use z-index property to move the overlay beneath the content which is wrapped by a relative positioned
 element with a higher z-index value, as follows:

Content goes here...

p {
    position: relative;
    z-index: 2;
}

.box:after {
    content: ' ';
    position: absolute;
    z-index: 1;
    left: 0; right: 0; top: 0; bottom: 0;
    background-color: rgba(0,0,0,.4);
}

UPDATED DEMO.

A: Use transparent PNG as a background image and then you can see both color and image together.
section {
    width:100%;
    height:400px;
    background-image: url(http://upload.wikimedia.org/wikipedia/en/2/2d/SRU-Logo-Transparent.png);
    background-repeat: no-repeat;
    background-size: contain;
    background-color: rgba(0, 0, 0, 0.5);
}

A: You can use rgba within the same declaration
DEMO http://jsfiddle.net/b6vzN/1/
background:url(../img/background2.jpg) no-repeat rgba(0,0,0,0.5);

If you wish to assign it seperately as in your example then you need to specify background-image, not just background
background-image: url(../img/background2.jpg);
background-color: rgba(0,0,0,0.5);


text:
Q: How do I go from Labor Statistics results to generalities on the population? I'm currently looking at survey results from the US bureau of labor statistics concerning hourly wages. With the raw survey data, I get different respondents who state how many hours they work in a week, along with the average pay, and some demographic data like age and sex.
How can I go from this information to making an educated guess about the amount of hours have been worked by the entire US population at a certain wage level, for example? Is there some way to "correlate" the values considering more than just a single parameter like age?
EDIT: I'm going to try and ask a more specific question then. Please forgive my complete lack of statistics knowledge:
Let's say I'm doing a survey about how much people earn in an hour. Based off of my survey, I know that , in my survey sample, men make about \$10 an hour, and women make \$8 an hour.  I also know that in the same sample, people under 40 make \$7 an hour on average, and people over 40 make \$11 an hour.
Assuming that the population is 50/50 male/female, I can make an educated guess that the population , on average, makes \$9 an hour. Likewise, if %30 of the population is over 40, then I can guess that the population on average makes \$8.20 an hours
But how can I "combine" both of these information points? How can I consider both the sex and the age of the people to fit it to the population? Am I just supposed to do a weighted average or something?

A: To generalize the results from survey data for the population, you need sample weights. If you are using the microdata/survey data from BLS, you can find the weights in the data. Of course, you have to look into codebook or data dictionary if you can't locate. See this introduction slides.
For analysis purpose you need to use survey analysis tool which is this in R and this is Stata


text:
Q: Error while loading DSTNEE i sagemaker terminal I got this error can someone help?
This error I got while building docker image in the sagemaker terminal , i tried to resolve by changing ubuntu and the cuda version ut still error is persistent can someone tell the reason of error?
In file included from NcExcptionWrap.h:2:0,
                 from NNNetwork.cpp:14:
/usr/include/ncException.h:26:7: note: candidate: netCDF::exceptions::NcException::NcException(const string&, const string&, const char*, int)
       NcException(const std::string& exceptionName,const std::string& complaint,const char* fileName,int lineNumber);
       ^
/usr/include/ncException.h:26:7: note:   candidate expects 4 arguments, 3 provided
/usr/include/ncException.h:24:11: note: candidate: netCDF::exceptions::NcException::NcException(const netCDF::exceptions::NcException&)
     class NcException : public std::exception {
           ^
/usr/include/ncException.h:24:11: note:   candidate expects 1 argument, 3 provided
make[1]: *** [/opt/amazon/dsstne/build/tmp/engine/cpp/NNNetwork.o] Error 1


text:
Q: How to receive a file after drag and drop I'm trying to build a web application that allows users to drag and drop a file from their desktop (like justbeamit.com) to an "icon" that represents another user, and so that the different user could receive it on the other side. I see that this is possible using the dropzone.js feature, but I want to know is how it's possible to link this with the receiving function so that the other user could download it simply after receiving a notification. I know it sounds complicated, but wish you guys could do good on me by providing knowledge on how to link the drag and drop functionality with a function that allows the other user to receive and download the file. Thanks!

A: If you are using MVC framework you can get the file from controller as body.request.body.dataParts.get


text:
Q: LDAP application account authentication using Java Would like to know if we can authenticate an applicationName & password against LDAP. In our LDAP system, I can see 'Applications' branch apart from 'Groups', 'People' etc..Need to do this check to do some action.
I'm looking for documentation or sample code to do it in Java.
Thank you,

A: You can do this with JNDI. See the Oracle JNDI tutorial. It is very extensive and it has a large section on LDAP.


text:
Q: Connect a Pervasive DB using OLE DB We have a existing closed source third party application using a Pervasive PSQL database. For Example the PSQL are located in the directory c:\test and have names like holiday.dat, offers.dat and so on. I want to read and if possible write to these files without having installed the Pervasive Workstation Engine. With the Workstation Engine and an ODBC connection it runs without any problems. But we won't install the Workstation Engine on any client and the third party application doesn't it, too.
On connectionsstrings.com i found the connection string:
"Provider=PervasiveOLEDB;Data Source=C:\datafilesDirectory;"

using directives:

using Pervasive.Data.SqlClient;
using System.Data.OleDb;
using System.Xml.Serialization;

test connection snippet:

string strAccessConn = "Provider=PervasiveOLEDB;Data Source=C:\datafilesDirectory;"

string strAccessSelect = "SELECT * FROM holidays";

// Create the dataset and add the Categories table to it:
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = null;

try
{
    myAccessConn = new OleDbConnection(strAccessConn);
}
catch(Exception ex)
{
    Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);
    return;
}

try
{
    OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect,myAccessConn);
    OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);

    myAccessConn.Open();
    myDataAdapter.Fill(myDataSet,"Categories");
}
catch (Exception ex)
{
    Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
    return;
}
finally
{
    myAccessConn.Close();
}

The application can't open the database connection.

A: In the connectionstring, you should replace C:\datafilesDirectory; with C:\test;.


text:
Q: Why aren't there any "ultra high energy density" batteries on the consumer market? I have heard of ultra high energy density lithium cells that boast incredible figures from oxis, sion, and solid energy that blow current li-ion cells out of the water. There are probably even more comapnies out there that I don't know. But when I try to do digging on them, all I get are generic news articles about the product. And the official websites for these companies say nothing about price. (No listed price = very expensive) I'm surprised that they haven't creeped out into the consumer market at all. I would suspect that old cells would be down cycled and resold onto the consumer market like many commercial battery packs/modules. I am also surprised that these are not sold to consumers even at a steep premium.
Why are these supposedly ground-breaking cells so seemingly nonexistent and mysterious?

A: When I carefully look at the three manufacturers (oxis, sion, solid energy) that you mention, I notice some commonalities:

*

*in development

*production testing

*building a factory

*etc

So my conclusion is that they're not producing and selling these batteries yet. Even if they would have a (in their view) finished product, it will take some time (think at least a year) before any well-known manufacturer (Samsung, Apple etc) will use their batteries. This is because manufacturers want to do their own tests on the batteries to be absolutely sure that they are good enough to use and safe to use in their products.
Think about the Samsung Note 7 battery issue, no manufacturer wants to repeat that as it harms customer confidence.
So sure, some new battery technologies will come but it just takes time.

A: There are a large number of technologies in development that could boost energy density to 3x current Li battery levels, or more. Some have got as far as producing laboratory examples that will survive several hundred cycles. The problem is that typically getting something out of the lab and into large scale production takes between 5 to 10 years. Just because some PhDs can hand build one by no means guarantees that they can be machine made in the millions by semi-skilled labour.


text:
Q: Rails jQuery UI Draggable Not Working I can't seem to figure out why draggable isn't working in my rails app. I'm using the jquery-ui-rails gem.
In my javascript file I'm including these:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require bootstrap
    //  Angular Stuff
//= require angular
//= require ng-rails-csrf
//= require angular-ui-router
//= require angular-cookies
//= require angular-sanitize
//= require restangular
//= require angular-bootstrap
//= require lodash/lodash.js
//= require angular-rails-templates

//= require spin.js/spin.js
//= require angular-spinner
//= require angular-toastr
//= require moment
//= require moment-timezone
//= require angular-moment
//= require ngstorage

// Core App Files
// = require survey_builder_config
//= require_tree ../survey_builder_app

In my scss:
@import "jqvmap";
@import "jquery-ui";

@import "bootstrap-switch";

In my coffeescript file I'm calling:
$scope.refreshOffers = ->
    console.log "refreshOffers"

    $("#drag-me").draggable()
    $("ui-draggable-handle").draggable()
    $(".ui-draggable").draggable()

refreshOffers does get logged to the console so I know I'm hitting this function. But none of those individually or together seem to make the button draggable.
Here's the HTML (really it's the first button that I'm trying to make draggable though they all should be draggable):

                            <button id="drag-me" type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="single_select" ng-click="questionClicked">Single Selection</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="single_select_matrix">Single Select Grid</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="rating">Rating</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="short_text_input">Short Text</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="dropdown">Drop Down</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="rank_order">Ranking</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="numeric_input">Numeric</button>

                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="multiple_select">Multiple Selection</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="multiple_select_matrix">Multiple Select Grid</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="descriptive">Message</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="long_text_input">Long Text</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="slider">Slider</button>
                            <button type="button" class="btn btn-default btn-block question-type ui-draggable ui-draggable-handle" data-type="sum_select">Sum</button>

Any idea what I'm missing?

A: It seems the answer is that buttons need cancel: false set:
$(".ui-draggable").draggable({
    cancel: false
})


text:
Q: Redraw customized google maps javascript map I'm really new to JS..
My website theme came with integrated custom google maps.
So i want that when i press on one of four buttons buttons, it reloads coordinates to different predefined ones.
So far I only managed to change the coordinates but it doesn't redraw the map to the new location with the marker.
So for example this is JS code to switch maps cordinates
function jumptomap4() {
var element = document.getElementById("kordinates");
element.setAttribute("data-coordinates", "[[55.873744, 26.513021]]");
}

Map container:

And this is the button that should change coordinates and redraw map..

<button class="small bkg-red bkg-hover-red color-white">Skatīt kartē</button>

Could someone please help me figure this out!? :)

A: Have you tried re-sizing the map using 'google.maps.event.trigger(map, 'resize');' you can also use 'panTo(latLng:LatLng|LatLngLiteral)'. Based on the docs, changes the center of the map to the given 'LatLng'. If the changes is less than both the width and height of the map, the transition will be smoothly animated.


text:
Q: How does "break;" work in async function? I was using pbkdf2-password module in my login process, and some of those code seems been stuck while running. I used async hashing function to verify users, and problem happens when user inputs wrong passwd. Just loading doesnt stop.
I tried redirecting and return when user inputs wrong passwd and it worked.
but I want to know why the break didnt work.
app.post('/login', (req, res) => {
  console.log(req.body);
  let userid = req.body.id;
  let password = req.body.password;
  console.log('userid = ', userid);
  console.log('password = ', password);
  console.log('userlist = ', sampleUserList);
  let bFound = false;

  for (let i = 0; i < sampleUserList.length; i++) {
    let user = sampleUserList[i];
    console.log(sampleUserList[i]);
    if (userid === user.userid) {
      console.log('[found] userid = ', userid);
      bFound = true;
      /* here's where I verify users. */
      return hasher({
        password: password,
        salt: user.salt
      }, function(err, pass, salt, hash) {
        if (err) {
          console.log('ERR : ', err);

        }

        if (hash === user.password) {
          console.log('INFO : ', userid, ' logged in successfully')

          req.session.user = sampleUserList[i];
          req.session.save(function() {
            res.redirect('/carlist');
          })
          return;
          /* here's the code for when users input wrong passwd but still have ID */
        } else {
          console.log('Wrong passwd.');
        }
      });
    }
    if (bFound) break;
  }

  if (!bFound) {
    console.log('Theres no such ID.');
  }
  res.redirect('/login_form');
});

else {
  console.log('Wrong passwd.');
  res.redirect('/login_form');
  return;
}

Problem solved with this code but I want to know why the break didnt work.
no error msg but infinite loading.

A: The break will never be reached. The return inside the if statement will prevent all subsequent code from executing.
It also breaks out of the loop, so you can feel free to remove break, your function already does what you intended the break to do.
app.post('/login', (req, res) => {
  let userid = req.body.id;
  let password = req.body.password;
  let bFound = false;

  for (let i = 0; i < sampleUserList.length; i++) {
    let user = sampleUserList[i];
    if (userid === user.userid) {
      bFound = true;
      return hasher(/* args */); // <-- this ends execution of the login handler
    }
    if (bFound) break;
  }

  if (!bFound) {
    console.log('Theres no such ID.');
  }
  res.redirect('/login_form');
});


text:
Q: VS Code - Flake8 Boa tarde,
No código abaixo, o from e o raio ** 2 não estão sendo reconhecidos.
Ao verificar o erro com o from, aparece a seguinte mensagem.

Alguém tem alguma ideia do que possa ser este problema?

A: O problema está em:
raio = input("Informe o raio: ")

Isso ocorre porque você não está definindo o tipo de variável (int,str,float,bool) que o input vai receber. Por padrão o input no python sempre vai receber uma String que tem seu tipo definido como str ou seja não está recebendo um valor numérico.

*

*Portanto o python está tentando elevar a 2 uma String e não um int que é um valor númerico  por isso que está dando erro.

Para resolver basta definir o tipo de input da seguinte forma:

raio = int(input("Informe o raio: "))

Ou também caso você queira utilizar um número com ponto flutuante (Números quebrados):

raio = float(input("Informe o raio: "))

Espero ter ajudado!


text:
Q: First: Converting object to an encodable object failed - then: HydratedCubit isn't hydrated the following situation: I want to make a ToDo list with a Cubit. That the ToDo list does not disappear after leaving the app, I found the package hydrated Bloc. When I created the HydratedCubit with the 2 override methods for the FromJson and ToJson, creating them Inside the ToDoState and executed it, I got an exception, "Converting object to an encodable object failed: Instance of 'Todo'". After research I found out that JSON can't convert such a model and you have to overwrite these models with working From and To functions first. I tried this with the package "json serializable". Here I had to ask myself in which class I have to add the "@JsonSerializable()", inside the Todo model or the todo state, in which the error appears? I decided to add the @ for my todostate because adding it on the Todo model didn't change anything. After this package created me the "todo_list_state.g.dart" I don't get the error anymore, BUT: It also doesn't save the list, looks like HydratedCubit is being "ignored".  Here a few code snippets:
First, I show you the Todo Model:
Uuid uuid = const Uuid();

class Todo extends Equatable {
  final String id;
  final String desc;
  final double menge;

  Todo( {
    String? id,
    required this.desc,
    required this.menge,

  }) : id = id ?? uuid.v4();

}

I left out the to string and props...
As I mentioned before, I tried to add the JsonSerializableGenerator inside this class, but this didn't change something.
Here is my TodoListState:
part of 'todo_list_cubit.dart';

@JsonSerializable()
class TodoListState extends Equatable {
  final List<Todo> todos;

  factory TodoListState.initial() {
    return TodoListState(todos: []);
  }

  Map<String, dynamic>toMap() => _$FoodListStateToMap(this, food);

  factory FoodListState.fromMap(Map<String, dynamic> map) => _$FoodListStateFromMap(map);

  }

Here are the generated functions inside 'todo_list_state.g.dart':
TodoListState _$TodoListStateFromMap(Map<String, dynamic> map) {
    return TodoListState (
        todo: map['todo'] as List<TodoModel>,
    );
}

Map<String, dynamic> _$TodoListStateToMap(TodoListState instance,  List<TodoModel> todo) {
    return {
        'todo': todo,
    };
}

At last here my Cubit functions where I override the From and To:
  @override
  TodoListState? fromJson(Map<String, dynamic> json) {
    return TodoListState.fromMap(json);
  }

  @override
  Map<String, dynamic>? toJson(TodoListStatestate) {
    return state.toMap();
  }

So does anybody know why my Hydrated Cubit doesn't save my list? Or do I have to convert the Model but just dont know how?... Appreciate your help. Thanks

A: Both model and states need to have toJson and fromJson methods. So the approach was right with using JsonSerializable. But converting objects to and from json is a very important thing to understand how to do without codegen tools. Those can be boilerplate and not always converting correctly complex objects. When doing it manually, it's also easier to debug. So in your case, additions to the model would be:
class Todo extends Equatable {
  final String id;
  final String desc;
  final double menge;

  Todo( {
    String? id,
    required this.desc,
    required this.menge,

  }) : id = id ?? uuid.v4();
  factory Todo.fromJson(Map<String, dynamic> json){
    return Todo(id: json['id'],
               desc: json['desc'],
               menge: json['menge'],);
    }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'desc': desc,
      'menge': menge,
    };
  }
}

Then, in your states (again, I am not going to use JsonSerializable):
class TodoListState extends Equatable {
  final List<Todo> todos;

  TodoListState({this.todos = const <Todo>[]});

  factory TodoListState.fromJson(Map<String, dynamic> json) {
    var todos = <Todo>[];
    for (var item in json['todos']) {
      todos.add(Todo.fromJson(item));
    }
    return TodoListState(todos: todos);
  }

  Map<String, dynamic> toJson() {
    var jsonTodoList = <Map<String, dynamic>>[];
    for (var item in todos) {
      jsonTodoList.add(item.toJson());
    }
    return {
      'todos': jsonTodoList,
    };
  }
}

Then in your Cubit nothing changes
  @override
  TodoListState? fromJson(Map<String, dynamic> json) {
    return TodoListState.fromJson(json);
  }

  @override
  Map<String, dynamic>? toJson(TodoListState state) {
    return state.toJson();
  }

Except for you may want to add all sorts of null safety checks around the conversions, because I omitted all aspects not related to the topic of the question.

A: Persisting single instance of todo
TodoCubit.dart
class TodoCubit extends HydratedBloc<TodoCubit, TodoState> {
  TodoCubit() : super(ToDoInitial());

  @override
  TodoState? fromJson(Map<String, dynamic> json) {
    return TodoState.fromJson(json);
  }

  @override
  Map<String, dynamic>? toJson(TodoState state) {
    return state.toJson();
  }

  saveTodo(String todo, String date) {
    emit(TodoState(presentTodo: Todo(todo: todo, day: date)));
  }
}

ToDoState.dart

class TodoState extends Equatable {
  final Todo presentTodo;

  const TodoState({required this.presentTodo});
  factory TodoState.fromJson(Map<String, dynamic> json) {
    return TodoState(presentTodo: Todo(todo: json['todo'], day: json['day']));
  }
  Map<String, dynamic> toJson() =>
      {'todo': presentTodo.todo, 'day': presentTodo.day};

  @override
  List<Object?> get props => [presentTodo];
}

class Todo {
  String todo;
  String day;
  Todo({required this.todo, required this.day});
  @override
  String toString() {
    return "todo: " + todo + " day: " + day;
  }
}

class ToDoInitial extends TodoState {
  ToDoInitial() : super(presentTodo: Todo(todo: '', day: ''));
}

Home.dart
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const SizedBox(height: 10),
                    Text(state.presentTodo.toString()),
                    ElevatedButton(
                      style: Constants.kElevatedButtonStyle,
                      onPressed: () {
                        context
                            .read<TodoCubit>()
                            .saveTodo('Drink Water ', 'Tuesday');
                      },
                      child: const Text(
                        'Add Dummy Todo',
                        style: TextStyle(
                            fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ],
                ),
              );

main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  HydratedBloc.storage = await HydratedStorage.build(
    storageDirectory: await getTemporaryDirectory(),
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => TodoCubit(),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          appBarTheme: const AppBarTheme()
              .copyWith(backgroundColor: const Color.fromRGBO(18, 26, 28, 1)),
          primarySwatch: Colors.blue,
        ),
        home: const Home(),
      ),
    );
  }
}

Output:

To store multiple instance of todo that is list of todos refer this example
@Credit for the example : @Olga P


text:
Q: get form field name (that appears in the form), not actual name in PHP If I have a simple form, something like:

 <form name="create_account" action="create_account.php" method="post">

                <legend>Create Account</legend>

Username*:
<input type="text" name="user" />

Password*:
<input type="password" name="password" />

..........

Is there a way to see in the create_account.php form the "Username*:" value for the name field,in other words the value that appears next to each form field in the actual field. I am asking this because I want to create a field that displays a variable string next to it, and I don't know how to pass it to php script. I am not interested in include or require.
Thanks a lot.

A: No, that information is not passed through the form. You'll need to store it somewhere else if you want to use it later.


text:
Q: Private Pointer error in C++ linked list I'm trying to implement a linked list in C++, but every time I compile, I get an error that says 'Node* Node::nextPtr' is private. If I change nextPtr to have public protection, then I don't get the error and my list is fine. Can someone tell me why this is and how to fix it? My list and node classes are as follows:
//list.h
#include <string>

#include "node.h"

using namespace std;

class List
{

    public:
            List();

            bool isEmpty();
            void insertAtFront(string Word);
            void displayList();

    private:
            Node * firstPtr;
            Node * lastPtr;

};

//node.h
#ifndef NODE_H
#define NODE_H

#include <string>

using namespace std;

class Node
{

    public:
            Node(string arg);

            string getData();

    private:
            string data;
            Node * nextPtr;

};

//node.cpp
#include <iostream>
#include <string>

#include "node.h"

using namespace std;

Node::Node(string arg)
    :nextPtr(0)
{
    cout << "Node constructor is called" << endl;
    data = arg;

}

string Node::getData()
{
    return data;
}

//list.cpp
#include <iostream>

#include "list.h"
#include "node.h"

using namespace std;

List::List()
    :firstPtr(0), lastPtr(0)
{
}

bool List::isEmpty()
{
    if(firstPtr == lastPtr)
            return true;
    else
            return false;
}

void List::displayList()
{
    Node * currPtr = firstPtr;

    do
    {

            if(currPtr->nextPtr == lastPtr) // Error here
                    cout << endl << currPtr->getData() << endl;
            cout << endl << currPtr->getData() << endl;

            currPtr = currPtr->nextPtr; //Error here

    }
    while(currPtr != lastPtr);

}

void List::insertAtFront(string Word)
{

    Node * newPtr = new Node(Word);

    if(this->isEmpty() == true)
    {
            firstPtr = newPtr;
            cout << "Adding first element...." << endl;
    }
    else if(this->isEmpty() == false)
    {
            newPtr->nextPtr = firstPtr; //Error here
            firstPtr = newPtr;
            cout << "Adding another element...." << endl;
    }
}

A: Because somewhere in your code, you access Node * nextPtr by non member functions of class Node.  You can create a getter for nextPrt to avoid that.

A: You didn't show the definitions of your member functions inside the List class, but I bet it is due to those member functions try to access nextPtr from the Node class. You can,

*

*make nextPtr public from Node

*add public accessor functions to Node to access it

*declare List as a friend from Node, friend class List;


text:
Q: Hg - switch draft phase commits to a branch I've committed several changesets and am now thinking that it might have been better on a new branch. I haven't pushed changes yet so they're still in the draft phase. Is there some mercurial way (that doesn't involve re-cloning) that I can just change these over to a branch?

A: *

*Update to the parent of first improperly (to the wrong branch) committed changeset

*Create needed branch (hg branch ... + hg commit ...)

*Rebase changesets to the new parent (starting changeset of branch)


text:
Q: Mac OS X - report time on battery since last AC unplug but exclude sleep time Is there an app or existing command to report the battery time since the laptop was last unplugged from AC but exlude the time spend during sleep on battery?
This can be inferred from pmset -g log so I'm looking for a way to do this without using an app that stays resident to detect plug/unplug events.

A: Well, I'll provide an answer to my own question, tested on Yosemite but not extensively. This is bash code:
#!/bin/bash
humantime () { printf -v $1 "%dh%02dm%02ds" $(($2/3600)) $((($2/60)%60)) $(($2%60)); }
#unplugged=`pmset -g log | grep 'Summary- \[System: DeclUser.*\] Using Batt' | tail -1 | cut -f1,2 -d' '`
unplugged=`syslog -u -k Sender loginwindow | grep 'magsafeStateChanged state changed old 1 new 2' | tail -n 1 | cut -f1 -dZ`
onbatt=$((`date +%s` - `date -j -f "%Y-%m-%d %H:%M:%S" "$unplugged" +%s`))
slept=`pmset -g log | sed -n "/^$unplugged/,//p" | awk '/Entering Sleep.*[0-9]+ secs/ {n=split($0,a," ");sum+=a[n-1]} END {print sum}'`
[[ -z $slept ]] && slept=0
awake=$((onbatt-slept))
humantime hawake $awake
humantime hslept $slept
printf "Awake on battery for $hawake (%.1f%%)\n" `echo "$awake*100/$onbatt" | bc -l`
printf "Slept on battery for $hslept (%.1f%%)\n" `echo "$slept*100/$onbatt" | bc -l`

I won't vouch for its accuracy but it seems to work. Since I don't know Apple's internals (I'm new to Mac OS X) I reversed engineered it with a few trial and errors plugging and unplugging the adapter, both while asleep and also while awake, to see which log entries are reliable.
You will notice that I tried using pmset -g log to detect when the power was unplugged but it's unreliable. Upon unplugging, the log entry is Summary- [System: DeclUser kDisp] Using Batt but unfortunately the same log entry occurs during sleep while unplugged so it's unreliable. I resorted to syslog instead.
NOTE: This reports the time since the last unplugged event. This may not be when the battery was 100 %.
Potential issue: The above code takes the timestamp from syslog and matches against pmset. If pmset doesn't have an entry (any entry) at the same timestamp then it won't work. That shouldn't happen but if it does, then you could convert the timestamps to epoch seconds and detecting the closest timestamp in pmset that way.


text:
Q: jQuery: media queries for carousel Wondering if there's a solution for this, can't seem to figure it out, I'm looking for the jQuery equivalent of media queries to change the function of a carousel I've got setup.
The code is quite simple:
$(window).load(function () {
    $(function () {
        $(".events-slider").jCarouselLite({
            btnNext: ".next",
            btnPrev: ".prev",
            scroll: 3,
            speed: 800
        });
    });
});

But I have some css media queries set up, whereby at 900px the .event-slider reduces in size, thus now only showing 1 slide as apposed to 3, I therefore want to change the jQuery function to reflect this, i.e. when the browser window reduces below 900px the scroll: 3, attribute changes to scroll: 1, if this is at all possible? Any suggestions would be greatly appreciated!

A: You can use the jQuery .width() function on $(window) to find the width of the browser's viewport, similar to the solution to this thread:
jQuery: How to detect window width on the fly?
$(document).ready(function() {
var window = $(window);

function checkWindowWidth() {
    var windowsize = window.width();
    if (windowsize > 900) {
        $(function () {
            $(".events-slider").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev",
                scroll: 3,
                speed: 800
            });
        });
    } else {
        $(function () {
            $(".events-slider").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev",
                scroll: 1,
                speed: 800
            });
        });
    }
}
checkWindowWidth();
$(window).resize(checkWidth);
});


text:
Q: isset not givig desired result using && operator if(isset($_POST["submit"])){
    if (isset($_POST["name"]) && isset($_POST["roll"])){ // checking whether both text boxes are filled up
            echo "$_POST[name] $_POST[roll]";   // just displays some info
       }
       else{  //not being executed when both text boxes are empty
            header("Location:interface.php");
       }
   }

the above is a php code where im trying to check whether two text boxes are filled in or else i will navigate to another page. The problem is though if i fill up one text box the && condition doesn't work , it gets into the if part and echoes one value.

A: There is error (missing ') in:
echo "$_POST[name] $_POST[roll]";

It has to be $_POST['name'] and $_POST['roll']
UPDATE
isset() only is not enough. You should also check if it is not empty, like this:
if (!empty($_POST["name"]) && !empty($_POST["roll"])){


text:
Q: Listening to files in the pull requests on github I have a github repository of my project. Some users upload json file on my repo by pull requests. However, I only want to allow only special json files in my repo. I have one function which can tell if a given input json file is special or not. Whenever I receive a pull request, I want to make sure that the json file is special, if not, I want to notify the author of the PR that the file is not eligible for merge. I want to automate this process.
In addition, I also want to run a different script, when such open PRs are closed. I know about webhooks in github, but afaik, they provide very limited functionality. Using them, I can create a POST request to some server, with JSON payload. But, I want to access the files present in the PR, and run my special script on those files in the PR.
Can anyone suggest me a better approach for this? Thanks in advance :)


text:
Q: How do I fix 'KeyError: 'series' in BLS API sample Python code? I'm trying to replicate the "API Version 2.0 Python Sample Code" provided by the Bureau of Labor Statistics (BLS) on its website here, but receive "KeyError: 'series'" whenever I try to run it.
import requests
import json
import prettytable
headers = {'Content-type': 'application/json'}
data = json.dumps({"seriesid": ['CUUR0000SA0','SUUR0000SA0'],"startyear":"2011", "endyear":"2014"})
p = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers)
json_data = json.loads(p.text)
for series in json_data['Results']['series']:
    x=prettytable.PrettyTable(["series id","year","period","value","footnotes"])
    seriesId = series['seriesID']
    for item in series['data']:
        year = item['year']
        period = item['period']
        value = item['value']
        footnotes=""
        for footnote in item['footnotes']:
            if footnote:
                footnotes = footnotes + footnote['text'] + ','
        if 'M01' <= period <= 'M12':
            x.add_row([seriesId,year,period,value,footnotes[0:-1]])
    output = open(seriesId + '.txt','w')
    output.write (x.get_string())
    output.close()

Here is the output:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-21-b89f58b9b664> in <module>
      3 p = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers)
      4 json_data = json.loads(p.text)
----> 5 for series in json_data['Results']['series']:
      6     x=prettytable.PrettyTable(["series id","year","period","value","footnotes"])
      7     seriesId = series['seriesID']

KeyError: 'series'

I don't understand the cause of this error. Will you please help me figure it out and fix it? Many thanks!

A: the code works for me,
this is the output :
+-------------+------+--------+---------+-----------+
|  series id  | year | period |  value  | footnotes |
+-------------+------+--------+---------+-----------+
| SUUR0000SA0 | 2014 |  M12   | 134.207 |           |
| SUUR0000SA0 | 2014 |  M11   | 135.107 |           |
| SUUR0000SA0 | 2014 |  M10   | 135.891 |           |
| SUUR0000SA0 | 2014 |  M09   | 136.211 |           |
| SUUR0000SA0 | 2014 |  M08   | 136.127 |           |
| SUUR0000SA0 | 2014 |  M07   | 136.392 |           |
| SUUR0000SA0 | 2014 |  M06   | 136.433 |           |
| SUUR0000SA0 | 2014 |  M05   | 136.216 |           |
| SUUR0000SA0 | 2014 |  M04   | 135.771 |           |
| SUUR0000SA0 | 2014 |  M03   | 135.375 |           |
| SUUR0000SA0 | 2014 |  M02   | 134.542 |           |
| SUUR0000SA0 | 2014 |  M01   | 134.017 |           |
| SUUR0000SA0 | 2013 |  M12   | 133.509 |           |
| SUUR0000SA0 | 2013 |  M11   | 133.596 |           |
| SUUR0000SA0 | 2013 |  M10   | 133.876 |           |
| SUUR0000SA0 | 2013 |  M09   | 134.255 |           |
| SUUR0000SA0 | 2013 |  M08   | 134.098 |           |
| SUUR0000SA0 | 2013 |  M07   | 133.919 |           |
| SUUR0000SA0 | 2013 |  M06   | 133.900 |           |
| SUUR0000SA0 | 2013 |  M05   | 133.626 |           |
| SUUR0000SA0 | 2013 |  M04   | 133.421 |           |
| SUUR0000SA0 | 2013 |  M03   | 133.558 |           |
| SUUR0000SA0 | 2013 |  M02   | 133.204 |           |
| SUUR0000SA0 | 2013 |  M01   | 132.137 |           |
| SUUR0000SA0 | 2012 |  M12   | 131.770 |           |
| SUUR0000SA0 | 2012 |  M11   | 132.208 |           |
| SUUR0000SA0 | 2012 |  M10   | 132.892 |           |
| SUUR0000SA0 | 2012 |  M09   | 132.988 |           |
| SUUR0000SA0 | 2012 |  M08   | 132.430 |           |
| SUUR0000SA0 | 2012 |  M07   | 131.731 |           |
| SUUR0000SA0 | 2012 |  M06   | 131.956 |           |
| SUUR0000SA0 | 2012 |  M05   | 132.154 |           |
| SUUR0000SA0 | 2012 |  M04   | 132.284 |           |
| SUUR0000SA0 | 2012 |  M03   | 131.905 |           |
| SUUR0000SA0 | 2012 |  M02   | 130.953 |           |
| SUUR0000SA0 | 2012 |  M01   | 130.438 |           |
| SUUR0000SA0 | 2011 |  M12   | 129.844 |           |
| SUUR0000SA0 | 2011 |  M11   | 130.196 |           |
| SUUR0000SA0 | 2011 |  M10   | 130.373 |           |
| SUUR0000SA0 | 2011 |  M09   | 130.635 |           |
| SUUR0000SA0 | 2011 |  M08   | 130.351 |           |
| SUUR0000SA0 | 2011 |  M07   | 129.983 |           |
| SUUR0000SA0 | 2011 |  M06   | 129.846 |           |
| SUUR0000SA0 | 2011 |  M05   | 129.999 |           |
| SUUR0000SA0 | 2011 |  M04   | 129.483 |           |
| SUUR0000SA0 | 2011 |  M03   | 128.585 |           |
| SUUR0000SA0 | 2011 |  M02   | 127.363 |           |
| SUUR0000SA0 | 2011 |  M01   | 126.778 |           |
+-------------+------+--------+---------+-----------+

can you try to run the code inside your terminal insead of using ipython ?


text:
Q: Python flask get request in Ajax I'm executin this code in Flask python to request. an API with those parameters :
payload = {'key':'pass', 'schema':'sch', 'table':'tab','where_clause':'0', 'liste_fields':'*}
r = requests.get('https://api.com/', params=payload, verify=False)

How can I execute the same get url in Ajax ?
        $.ajax({
            url: "https://api.com/",
            type: "POST",
            data: ?,
            dataType: "json",
            success: function (result) {
                alert(result);
            },
            error: function (xhr, textStatus, errorThrown) {

            }


text:
Q: R: MclustICL function error when rounding When running mclustICL (R package mclust 5.3) on data  an error occurs:
data <- c(-0.485152666666667, -0.457841666666667, -0.457841666666667,
-0.457841666666667, -0.457841666666667, -0.457841666666667, -0.457841666666667,
-0.457841666666667)
> mclustICL(data, modelNames = "V")
fitting ...
  |=======================================================================================================| 100%
Error in if (sum((out$parameters$pro - colMeans(out$z))^2) > sqrt(.Machine$double.eps)) { :
  missing value where TRUE/FALSE needed

Rounding solves it:
> mclustICL(round(data,5), modelNames = "V") # no error

But I need to use function mclustICL on other data examples, and then rounding not only doesnt help, but the function works only when I do not use round and throws the  same error when i do:
data <- c(-0.241992333333333, -0.287035333333333, -0.33378, -0.272269333333333,
-0.241992333333333, -0.287035333333333, -0.241992333333333, -0.241992333333333,
-0.241992333333333, -0.287311, -0.287311, -0.287035333333333)

> mclustICL(data, modelNames = "V")# no error

> mclustICL(round(data,5), modelNames = "V")fitting ...
  |=======================================================================================================| 100%
Error in if (sum((out$parameters$pro - colMeans(out$z))^2) > sqrt(.Machine$double.eps)) { :
  missing value where TRUE/FALSE needed

What should I do to use the function on both data and why this behaviour happens? Thanks in advance!

A: I don't have your problems, as you can see in the code below.
Do you have the latest version of the package?
Have you look at your data?
Can you guess why only the single mixture component can be fitted?
> library(mclust)
    __  ___________    __  _____________
   /  |/  / ____/ /   / / / / ___/_  __/
  / /|_/ / /   / /   / / / /\__ \ / /
 / /  / / /___/ /___/ /_/ /___/ // /
/_/  /_/\____/_____/\____//____//_/    version 5.3
Type 'citation("mclust")' for citing this R package in publications.

> data <- c(-0.485152666666667, -0.457841666666667, -0.457841666666667,
+ -0.457841666666667, -0.457841666666667, -0.457841666666667, -0.457841666666667,
+ -0.457841666666667)
> summary(data)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-0.4852 -0.4578 -0.4578 -0.4613 -0.4578 -0.4578
> dotchart(data)

> mclustBIC(data, modelNames = "V")

Bayesian Information Criterion (BIC):
         V
1 48.44934
2       NA
3       NA
4       NA
5       NA
6       NA
7       NA
8       NA

Top 3 models based on the BIC criterion:
     V,1
48.44934       NA       NA

> mclustICL(data, modelNames = "V")

Integrated Complete-data Likelihood (ICL) criterion:
         V
1 48.44934
2       NA
3       NA
4       NA
5       NA
6       NA
7       NA
8       NA

Top 3 models based on the ICL criterion:
     V,1
48.44934       NA       NA

> data <- c(-0.241992333333333, -0.287035333333333, -0.33378, -0.272269333333333,
+ -0.241992333333333, -0.287035333333333, -0.241992333333333, -0.241992333333333,
+ -0.241992333333333, -0.287311, -0.287311, -0.287035333333333)
> summary(data)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-0.3338 -0.2871 -0.2797 -0.2710 -0.2420 -0.2420
> dotchart(data)

> mclustBIC(data, modelNames = "V")

Bayesian Information Criterion (BIC):
         V
1 46.73079
2       NA
3       NA
4       NA
5       NA
6       NA
7       NA
8       NA
9       NA

Top 3 models based on the BIC criterion:
     V,1
46.73079       NA       NA

> mclustICL(data, modelNames = "V")

Integrated Complete-data Likelihood (ICL) criterion:
         V
1 46.73079
2       NA
3       NA
4       NA
5       NA
6       NA
7       NA
8       NA
9       NA

Top 3 models based on the ICL criterion:
     V,1
46.73079       NA       NA

> mclustICL(round(data,5), modelNames = "V")
Integrated Complete-data Likelihood (ICL) criterion:
         V
1 46.72944
2       NA
3       NA
4       NA
5       NA
6       NA
7       NA
8       NA
9       NA

Top 3 models based on the ICL criterion:
     V,1
46.72944       NA       NA

A: Upgrading to R 3.4.1. solved the issue. Thanks a lot to Luca Scrucca!


text:
Q: Sscanf() Function What is the difference between using '&' with year and day as an arguments and doesn't use it with month and weekday in sscanf() function ?
#include <stdio.h>
#include <stdlib.h>

int main()
{
int day, year;
char weekday[20], month[20], dtm[100];

strcpy( dtm, "Saturday March 25 1989" );
sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

printf("%s %d, %d = %s\n", month, day, year, weekday );

return(0);
}

A: The & operator gets the address of a variable. So you're actually passing a pointer to day and year into sscanf.
Since they are arrays, weekday and month are already pointers to their first elements.
So rather than passing in different things to sscanf you're actually passing in the same things.
2 char*s and 2 int*s.


text:
Q: Finding the formula for the sequence: 7, 10, 16, 25, etc, in terms of $n$, given...
In terms of $n$, find the formula for the sequence $a_n$: 7, 10, 16, 25; given that the difference between each adjacent element in the sequence creates an arithmetic sequence of its own.

I got the incorrect solution and I cannot trace my mistake:
We create a new sequence $b_n$ based on the given information:
$b_1 = 10 - 7 = 3$
$b_2 = 16 - 10 = 6$
$b_3 = 25-16 = 9$
$d_{b_n} = 3$
We know that:
$$a_n - a_{n-1} = b_{n-1}$$
If we were to add all possible elements:
$$A_n - A_{n-1} = B_{n-1}$$
We also know that $A_n - A_{n-1} = a_n$, so therefore $a_n = B_{n-1}$:
$$a_n = \frac{[2b_1 + d(n-2)](n-1)}{2} = \boxed{\frac{3n(n-1)}{2}}$$
However, this is incorrect as it gives values inconsistent with the definition of the sequence.
The correct answer is $\frac{3n^2-3n+14}{2}$.
Where have I gone wrong?

A: You have an error when adding the sequences up to $n$.
You have the following:
$$
a_2 - a_1 = b_1 \\
a_3 - a_2 = b_2 \\
\dots \\
a_n - a_{n - 1} = b_{n - 1}
$$
So, when you add these equalities, you get:
$$\sum_2^n a_i + \sum_1^{n-1}a_i = \sum_1^{n-1}b_i$$
The second term here is indeed $A_{n-1}$, and the right hand side is $B_{n=1}$, but the first is $A_n - a_1$. Therefore you have $A_n - a_1 - A_{n-1} = B_{n-1}$. Now, using $A_n - A_{n-1} = a_n$, we have
$$a_n = B_{n-1} + a_1 = \frac{3n(n-1)}{2} + 7$$


text:
Q: How can I send a string to an external text editor? I want to display a string to the user using an external text editor (notepad++) so that they can search, edit etc. and save to file if they so choose.  The string is about 100MB-1GB in size.  I want to avoid writing to a temporary file and then opening it in the text editor as this involves writing the whole string to disk and then reading it from disk.  I would like to minimise the delay.  Can I somehow load it straight from memory into the text editor?
In linux I could write/read to tmpfs to keep it in memory but there doesn't seem to be any equivalent in Windows.  Even with tmpfs, there is an uneccesary comsumption of memory.
Ultimately something like this:
import os
with open('myfile.bin', 'rb') as f:
    whole_file: bytes = f.read()
my_str: str = process_bytes(whole_file)
os.startfile(my_str)


text:
Q: Interactive function for getting number of packages ready to upgrade? Goal: Get number of packages ready to upgrade from minibuffer or console.
Remarks:
Package.el is hard to grasp for elisp beginner - many contexts, implicit state, etc...
emacsclient -e "(list-packages)" gives: "X packages can be upgraded: type "U" to mark them for upgrading", but it also creates a new explicit buffer.
Maybe it is possible to adjust list-packages from package.el to do this in hidden buffer?
Refreshing packages archive is handled by package-refresh-contents and it is beyond this issue.
Any help is appreciated.

A: epl-find-upgrades gives you a list of upgradable packages.  Just wrap your own command around this function, to print the name of each package returned.


text:
Q: The maximum hard drive capacity for Intel 80286 based PC I got myself an Intel 80286 based PC. It has 40Mb hard drive installed. What is the maximum hard drive capacity that this PC can handle?

A: Hard to say exactly because the limit is partly BIOS based, but 504MB is a likely candidate.
Good article about the limits here:
http://web.inter.nl.net/hcc/J.Steunebrink/bioslim.htm


text:
Q: Transaction doesn't rollback when one of the statements fail in MySQL I've simple transaction here;
START TRANSACTION;
INSERT INTO user_photos(id, user_id, meta, upload_timestamp) VALUES (1211, 1, '{"a"}',
from_unixtime(unix_timestamp()));
UPDATE user_photos set user_id = '{"test"}' WHERE user_id = 1;
COMMIT;

The INSERT statement will work but the second statement, the UPDATE statement, will fail as the user_id column has type of INTEGER.
I would like to have a transaction which will rollback if any statement(inside transaction) fails. This transaction doesn't behave like that.
I use INNODB engine. Why is this transaction not working?

A: MYSQL has no "autorollback" features at transaction level.
If some statement has failed, this statement is rolled back but the transaction is not rolled back. If you run COMMIT, MySQL commits all non rolled back statements of the current transaction: that is what happened.
if you run ROLLBACK, all statements are rolled back whether they failed or succeeded.
If you want  a different behaviour you need to code it in your application code.
This can be done with a stored procedure: see mysql transaction - roll back on any exception.


text:
Q: MSAL fails with iOS simulator 13 Scheme msauthv2 for broker not present I've downloaded same code from MSAL sample iOS code
This seems to be working with iOS11 simulator but when i change target to iOS13, it doesn't open authentication just keep asking to open authentication view in loop.
App is configured with all the settings required to support iOS13 and below are the logs i see when app runs
Requiring default broker type due to app being built with iOS 13 SDK(Even if i reset simulator, this won't works)
Scheme msauthv2 for broker not present
I cannot understand above log, what broker app is searching for?


text:
Q: RxJava 2 - how to cancel infinite stream upon error and handle it? I've got the following infinite stream which does something every second.
What I want is to stop the stream upon error and handle it.
How can I achieve that?
void doSomething() {
        Disposable disposable = execute(doSomethingInner(), 0L, TimeUnit.SECONDS, schedulerProvider.io(), someClass -> 1L).doOnError
                (throwable -> {
            Timber.e(throwable, "error happened");// Never triggered
        })
                .doOnNext(someClass -> Timber.i("doing the infinite stuff"))
                .subscribe(Functions.emptyConsumer(), throwable -> {
                    Timber.e(throwable, "stop doing the infinite stuff");// Never triggered
                });
    }

    Observable<SomeClass> doSomethingInner() {
        return Observable.error(new Exception("something went wrong"));
    }

    Observable<SomeClass> execute(Observable<SomeClass> source,
                                  long delayInterval,
                                  TimeUnit timeUnit,
                                  Scheduler scheduler,
                                  Function<SomeClass, Long> interval) {
        return Observable.defer(new Callable<ObservableSource<SomeClass>>() {
            long currentInterval = delayInterval;

            @Override
            public ObservableSource<SomeClass> call() {
                return Single.timer(currentInterval, timeUnit, scheduler)
                        .flatMapObservable(o -> source)
                        .doOnNext(t -> currentInterval = interval.apply(t));
            }
        })
                .repeat()
                .retry();
    }

A: I think retry() is consuming your error.
Try to either:

*

*Remove this retry() completely

*or change it to retry(Predicate<Throwable>) to decide whether to repeat.

It is default behavior of subscriber to cancel stream on error if you don't consume it earlier, and you should receive callback to onError() inside subscribe().


text:
Q: Refresh a main window from a popup window Here is my problem. In my web application which has developed using JSP/servelt there is a page with an link. When some one click that link a popup window by calling a javascript function as follows.

function addlist() {
   winArray[7] =
  window.open("Changelist.jsp","changeList","status=1,resizable=0,width=290,height=370");
}

That popup window allow user to add things to the main window. What I want to do is when user add a new thing main window should get updated. There is already a update ajax function in the main window. What I need to do is when user add new thing to list I need to call the update method in the main window. how can I do this. Thanks in advance.

A: In your popup window, your JavaScript code may have a reference to the main window thanks to the window.opener property. You could thus call window.opener.update() when the new thing has been added.


text:
Q: Examples of special non-projective varieties If $X$ is a smooth complete non-projective variety of dimension at least three, let $U$ be a maximal (with respect to inclusion) open quasi-projective subset of $X$.  Letting $Z=X-U$, it follows that the codimension of $Z$ in $X$ is at least 2.  You can see this by first using Nagata's theorem and normalizing to get a dominant birational map $f: X' \rightarrow X$ where $X'$ is a projective normal variety and $f$ is an isomorphism on $U$.  Then $f^{-1}$ defines an open embedding into $X'$ off of the exceptional locus $Z$, which by normality and Zariski's Main Theorem must be of codimension at least 2.  It is also known (by using maximality and Seshadri's criterion) that $Z$ cannot contain an isolated point.  See http://www.ams.org/journals/proc/2005-133-09/S0002-9939-05-07859-7/home.html for a reference.
In Hironaka's example of a non-projective 3-fold (the one where he blows up two curves in different orders and glues), there are two maximal quasi-projective opens, the compliment of each being a smooth rational curve and hence of codimension exactly 2.  Here are 3 questions.
1) Does anyone know of an example of a smooth complete non-projective variety where the compliment of a maximal quasi-projective open $Z$ is of codimension greater than 2?
2) An example where $Z$ is reducible?
3) An example where $Z$ is singular?
I am not sure how difficult these questions are, but I know very few examples of smooth complete non-projective varieties in general.  Any interesting examples are welcomed.


text:
Q: finite element interpolation formulae Is there a place where I can found formalas used for interpolation in the Finite Element Method?
I'm look for recipes, where formulas are given for basic 2D and 3D elements, that can just be applied, without any theory.
In other words, there are a lot of ressoures about Finite Element Method theory available on the web, but I'm looking for a site/document that just give the algorithm for interpolation for the most common case, that I can code directly.
I'm especially looking for interpolation formula for P1 Prism (interpolating from the 6 vertices).

A: I guess you're talking about interpolation functions and I guess the formula is the only thing missing in your code, so you can check for them on this link  for 1D and 2D.
Now, I don't understand what you mean by "P1 prism". Maybe you should try it with lagrange polynomial. Check Hughes's book "The Finite Element Method" (2000 year edition), page 129, example 4. It might be what you need: an interpolation function for an almost arbitrary dimension  and quantity of nodes.


text:
Q: How to push and pull separate projects in a single repository? I want to know how to work with multiple projects in a single GitHub repository.
Suppose, I want to put my all office projects in a single repository with the name of Office. All of my future projects will be placed here separately with separate project name.
How can I achieve these. Thank you


text:
Q: How to handle routing of anchor clicks in Aurelia I have a nav bar with below code. but when i click on the anchor element the relative path doesn't get appended to the application url and eventually router not working. How do i make it work?

        Test1
        Test2
        Register
        Login

One option i got is to have a router configured in my app.ts/js and then use the router object to get the menu items like this. as per this post

            ${row.title}

and the other way is to use click.delegate on each anchor element and in the model  return this.router.navigate("specific path like \login or \register") from the on Click function

A: For random usage of anchor tags that you want to use routes from the aurelia router, you can use the following format:
Click Me!


text:
Q: parameters of glGenTexture? It sounds simple, but I looked on various sites and it gives me only two parameters :
void glGenTextures(GLsizei n, GLuint * textures)

.. with explaination.
However when using OpenGL ES with android, that method doesn't exist, and I also saw multiple websites, source codes and tutorials using this method with three parameters, which for me doesn't give me a compiler error :
gl.glGenTextures(amountOfTexturesToMake, pointerToArray, 0);

.. what's that zero for? What is that third parameter ? Even tough I saw various people using it, I couldn't find a explaination of it .

A: The offset parameter specifies the starting index in the int array. It's a way to 'emulate' pointer arithemic.
the following
glGenTextures(n, (texture + offset))

could be "translated" to
gl.glGenTextures(n, textureArray, offset)

A: I'm pretty sure it's the array offset, i.e., the index where the first texture name (ID) is stored.


text:
Q: How to create a LaTeX class with default parameters? I've learnt how to use LaTeX at the user level, but wanted to package the recurring code (resulting mostly from the styling of the cover) in a class file.
Therefore, I tried the following simple example class file:
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{test}[2018/10/12 v0.1 Test class]
\PassOptionsToClass{12pt}{report}
\ProcessOptions
\LoadClassWithOptions{report}

Although this works if I pass the size I want, if I omit it, it defaults to 10pt, instead of 12pt that I want. Do you know how to make the default become the 12pt, and still work if I decide to give it another size option?

A: Based on https://tex.stackexchange.com/a/123623/36296 you could so something like
\RequirePackage{filecontents}

\begin{filecontents}{test.cls}
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{test}[2018/10/12 v0.1 Test class]

\DeclareOption{10pt}{\def\test@ptsize{10pt}}
\DeclareOption{11pt}{\def\test@ptsize{11pt}}
\DeclareOption{12pt}{\def\test@ptsize{12pt}}

\ExecuteOptions{12pt}
\ProcessOptions
\PassOptionsToClass{\test@ptsize}{report}

\LoadClass{report}

\end{filecontents}

\documentclass{test}

\begin{document}

test

\end{document}


text:
Q: Motion of fluid inside the aircraft drop tank I have been working on motion of fluid inside the aircraft drop tank. For my initial case, fluid is moving to and fro. For this case I used the following code but is yielding the error.
zone_motion.c ..\..\src\zone_motion.c(7) : error C2100: illegal indirection
..\..\src\zone_motion.c(11) : error C2100: illegal indirection
..\..\src\zone_motion.c(14) : error C2109: subscript requires array or pointer type
..\..\src\zone_motion.c(14) : error C2100: illegal indirection
..\..\src\zone_motion.c(14) : error C2109: subscript requires array or pointer type
..\..\src\zone_motion.c(14) : error C2109: subscript requires array or pointer type

How can I modify this code?
#include "udf.h"
DEFIINE_ZONE_MOTION(fmotion, omega, axis, origin, velocity, time, dtime)
{
if(time<10)
{
    *omega=10;
}
else
{
    *omega=0;
}
N3V_D(velocity,=,0.01*sin(*omega*time), 0.0, 0.0);
}

A: I might not help you, but maybe someone else will find this usefull. I have a working code similar to your problem. The code spins up liniarly the domain and after reaching max omega it holds. Enjoy:
#include "udf.h"

DEFINE_ZONE_MOTION(fmotion2,omega,axis,origin,velocity,time,dtime)
{
float omega_max, t_end, ramp, rpm;

omega_max=314.0;
t_end=10.0;
ramp=omega_max / t_end;
velocity[0]=0.0;
velocity[1]=0.0;
velocity[2]=0.0;

origin[0]=-0.1;
origin[1]=-0.1;
origin[2]=0.0;

axis[0]=0.0;
axis[1]=0.0;
axis[2]=1.0;

    if (CURRENT_TIME < t_end)
    {
    *omega = ramp * CURRENT_TIME;
    //print("Current omega value %fn",*omega);
    }
    else
    {
    *omega = omega_max;
    }
  return;
}


text:
Q: How can I put "AdaptiveActionSet" in "AdaptiveColumn"? I would like to put "AdaptiveOpenUrlAction" in "AdaptiveColumnSet" for a better layout of adaptivecards.
However, my bot emulator does not display the OpenUrl button.
How do I add an action button? Perhaps this is a problem with the version of adaptivecards? The version of my adaptivecards is 1.1 (1.0 is also available).
I would like to ask for a solution.
Below is the code I wrote and the json log I created in the emulator. The Json Log in the ActionSet is written to the emulator, but the buttons in the ActionSet are not displayed on the card.
C# Code
new AdaptiveColumn()
{
    Items =
    {
        new AdaptiveActionSet()
        {
            Actions =
            {
                new AdaptiveOpenUrlAction()
                {
                    Url = new Uri("https://www.someurl.com"),
                    Title = "Reserve",
                    Style = "positive",
                }
            }
        }
    },
    Width = "auto",
}

JsonLog
"items": [
  {
    "actions": [
      {
        "style": "positive",
        "title": "Reserve",
        "type": "Action.OpenUrl",
        "url": "https://www.someurl.com"
      }
    ],
    "type": "ActionSet"
  }
],
"type": "Column",
"width": "auto"

Below is the layout of the adaptivecards I created from 'https://adaptivecards.io/designer/' I want.
{
    "type": "ColumnSet",
    "columns": [
        {
            "type": "Column",
            "width": "stretch",
            "items": [
                {
                    "type": "TextBlock",
                    "text": "2019-09-10",
                    "spacing": "None",
                    "horizontalAlignment": "Center",
                    "color": "Good",
                    "size": "Medium",
                    "weight": "Bolder"
                }
            ],
            "verticalContentAlignment": "Center",
            "horizontalAlignment": "Center",
            "spacing": "None",
            "style": "emphasis",
            "bleed": true
        },
        {
            "type": "Column",
            "width": "stretch",
            "items": [
                {
                    "type": "TextBlock",
                    "text": "USD 100.00",
                    "spacing": "None",
                    "horizontalAlignment": "Center",
                    "size": "Large",
                    "color": "Warning",
                    "weight": "Bolder"
                }
            ],
            "verticalContentAlignment": "Center",
            "bleed": true,
            "style": "emphasis",
            "spacing": "None"
        },
        {
            "type": "Column",
            "width": "auto",
            "items": [
                {
                    "type": "ActionSet",
                    "actions": [
                        {
                            "type": "Action.OpenUrl",
                            "title": "Reserve",
                            "style": "positive",
                            "url": "https://www.someurl.com"
                        }
                    ],
                    "spacing": "None"
                }
            ],
            "horizontalAlignment": "Center",
            "spacing": "None",
            "bleed": true,
            "style": "emphasis"
        }
    ],
    "spacing": "None",
    "separator": true
}

A: You can see in the schema that action sets were introduced in Adaptive Cards 1.2: https://adaptivecards.io/explorer/ActionSet.html

The only official chat client that currently supports Adaptive Cards 1.2 is Web Chat, but Web Chat uses the Direct Line channel and Direct Line strips out elements it doesn't recognize: https://github.com/microsoft/BotFramework-Services/issues/87
In that GitHub issue, you will find a workaround where you use a custom content type instead of application/vnd.microsoft.card.adaptive. If you set the content type to application/vnd.microsoft.card.custom for example, you can convert the attachment back into an Adaptive Card in Web Chat's attachment middleware:
const attachmentMiddleware = () => next => card => {
  if (card.attachment.contentType === 'application/vnd.microsoft.card.custom'){
    card.attachment.contentType = 'application/vnd.microsoft.card.adaptive'
  }
  return next(card)
};

window.WebChat.renderWebChat({
  directLine,
  attachmentMiddleware
}, document.getElementById('webchat'));

Using the workaround described in that issue, I was able to render your column set successfully:


text:
Q: Como incluir arquivo JSON dentro de um .JS Já procurei aqui no fórum, peguei exemplos prontos em outros sites, mas nenhum adiantou para mim.
Como diz no título, eu não estou conseguindo fazer essa ligação de um arquivo .json pra dentro do arquivo .js.
Esse é o meu arquivo script.js
function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'dados.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);
 }

meu arquivo dados.json:
{
  "rgV":"50.000.000-0",
  "veiculoV":"Carro",
  "dataV":"20/08/2018",
  "blocoV":"A","aptoV":"12",
  "placaV":"DWK - 3818",
  "horaV":"13:18h",
  "nomeV":"Nome Sobrenome",
  "empresaV":"Alguma Empresa"
}

E no meu HTML, eu chamo a página script.js assim:
<script src="script.js"></script>

Enfim, eu abro o console e o navegador não me retorna nenhum erro... Desculpe se não fui muito claro. Resumindo tudo, não estou conseguindo incluir o arquivo JSON dentro do meu javascript

A: Resolvi, se alguém precisar, segue o código:
function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

//usage:
readTextFile("dados.json", function(text){
    var dados = JSON.parse(text);

    var foto = document.getElementById('foto');
    foto.innerHTML = dados.fotoV;

    var nome = document.getElementById('nome');
    nome.innerHTML = dados.nomeV;

    var bloco = document.getElementById('bloco');
    bloco.innerHTML = dados.blocoV + " - " + dados.aptoV;

    var rg = document.getElementById('rg');
    rg.innerHTML = dados.rgV;

    var veiculo = document.getElementById('veiculo');
    veiculo.innerHTML = dados.veiculoV + ", " + dados.placaV;

    var empresa = document.getElementById('empresa');
    empresa.innerHTML = dados.empresaV;

    var datahora = document.getElementById('datahora');
    datahora.innerHTML = dados.dataV + " - " + dados.horaV;

    console.log(dados);
});


text:
Q: Why do they prefer dynamic scheduling in this code snippet I solved an exercise, where I had to implement SGD (stochastic gradient descent) with momentum. The exercise was to parallelize it afterwards.
My suggestion was as follow:
#pragma omp for schedule(static) nowait
for (int i = 0; i < size; i++)
    {
         const double nablaE_w = (1.0/double(B)) * (grad[i] + lambda * param[i]);
         mom_w[i] = beta * mom_w[i] - eta * nablaE_w;
         param[i] = param[i] + mom_w[i];
    }

I use nowait because after the for-loop the calculation is finished.
But on the solution they uses:
#pragma omp for schedule (dynamic, 64/sizeof(double)) nowait

Also after reading several stackoverflow-answers, I still cannot see the advantage of scheduling(dynamic) and why they uses the chunksize=8
I am careful when using schedule(dynamic) - actually I never use it, because I have no idea how to do it correctly.

A: The solution likely did it for one of two reasons: there is another nowait loop nearby that is imbalanced and might create a case in which threads reach this loop out of order, or they were worried about running on a system with a great deal of interference that is variable by core.  Using schedule(dynamic) is materially more expensive, for now until runtimes actually implement nonmonotonic properly, so static is the clear choice as long as the workload is balanced, which this snippet is.  The only reason to use dynamic here would be if imbalance between threads were expected to come from somewhere else, either in the code or from interfering workloads.