text:
Q: Understanding how read the `const`ness of c++ code In my attempt to teach myself C++, I was hoping to get some help in how to read the const-ness of a expression/function etc. For example, the code below:
const screen &display(std::ostream &output) const {
    do_display(output); return *this;
}

In the above code. there are two const declarations in the function display. In "English" how is that properly read? example: the first const is a const to reference or const to type screen? etc. and what exactly does the const-ness mean/imply when a reference is const etc. I have tried reading up on it but is still a bit muddy at this point.
Feel free to point to a youtube video or other reference material. Hopefully the material that is very clear.

A: I've always found that the simplest way to remember it is:

const applies to whatever is to the left of it, unless there isn't anything to the left of it, in which case it applies to whatever is to the right of it.

So, you have a const method that returns a const reference to a screen.
A const reference means you can't modify the referenced object. The const method means that the method won't modify the object it's being called on (the this pointer inside that method will be to a const object).

A: You read it right to left.
You have a constant method that returns a reference to a screen that is constant.
Returning a constant reference means you cannot modify what is returned.
If you call the method and assign it to some variable, the variable must use the const keyword.  The only exception to this is if you cast the returned reference from the method to something that is not constant.
Here's a helpful link for more detail on the right to left rule:
http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html
That's actually written by a professor at UCSD (and he's pretty good).
The const on the right side of the method just means you can't modify any instance variables inside the function (for the most part).  There's a bit more to it, but for more detail, refer to:
Meaning of "const" last in a C++ method declaration?

A: Read it right to left.
int const & foo() const
const method which returns a...
int const & foo() const
Reference to a...
int const & foo() const
const int.
The const can go on either side of int. You can read it as a "constant integer" or a "integer which is constant".

A: In English it means:
display() is a constant method of its class (this is the 2nd const keyword) that takes a reference to a std::ostream class instance as its parameter, and returns a reference to a constant (this is the 1st const keyword) instance of the screen class.
A const reference means that this reference cannot be used to modify the object being referenced. You can use the reference only to access, but not change, the members of the class, or to invoke the class's const methods (like display() is a const method of its own class).


text:
Q: Why didn't George Lucas direct the entire original trilogy? Why didn't George Lucas direct and screenwrite The Empire Strikes Back and Return of the Jedi?  This seems to be in conflict with how protective George Lucas is about his "baby".  Is there a reason why he gave up a lot of his Sith artistic powers for those movies?

A: Lucas revealed in several interviews at the time that he was fed up with directing.
In 1977, on the set of Star Wars, he told American Film:

"I come from the filmmaker's school of doing movies, which means I do everything myself...If I left anything for a day, it would fall apart...Whenever there is a leak in the dam, I have to stick my finger in it. I should learn to say, 'Somebody else go plug it up.'"
George Lucas: Interviews Edited by Sally Fine

In 1983, he said:

"I dislike directing. I hate the constant dealing with volatile personalities. Directing is emotional frustration, anger, and tremendously hard work - seven days a week, twelve to sixteen hours a day. For years my wife would ask why we couldn't go out to dinner like other people. But I couldn't turn it off. Eventually, I realized that directing simply wasn't healthy for me."
George Lucas: Interviews Edited by Sally Fine

Apparently he got nostalgic for it, though, after a long absence; in a 1990 intervew he said that he wanted to get back into directing:

"It's not that I prefer producing, that's just where I find myself these days. It wasn't something I did by choice. I was just more effective in the producing area, which is where the opportunities have presented themselves in the last few years...Ultimately, I'm a director. I've done many things, but that's where my heart is...I just want to get back to what I started doing.
George Lucas: Interviews Edited by Sally Fine

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery parse xml from single and multiple tags Got a problem returning the text from an xml node. It all needs to be dynamic. Here is the xml:
<instructions>Some ins text.</instructions>
<options>
    <option>1.png</option>
    <option>2.png</option>
    <option>3.png</option>
    <option>4.png</option>
</options>
<noOfOptions>4</noOfOptions>

Here is the jquery parse code:
currentPageData.push({
    title:$(xml).find("page").attr("name"),
    noOfOptions:$(xml).find("noOfOptions").text(),
    text:$(xml).find("text").text(),
    instructions:$(xml).find("instructions").text(),
    option:$(xml).find("option").each(function() {
        $(this).text();
    }),

The problem is the option section. This just returns one object. I think this is because of the .each function. But I need all of them, that are present to be returned and i need it to return the text in a for loop like this:
for(i=0;i<noOfOptions;i++) {
    currentPageData[0].option[0];
}

The above is not working. How can I fix it?
Thanks!

A: To get the text content of your option nodes try this....
Firstly, your xml isn't valid. I've added a root node
var xml = "<root>
               <instructions>Some ins text.</instructions>
               <options>
                   <option>1.png</option>
                   <option>2.png</option>
                   <option>3.png</option>
                   <option>4.png</option>
               </options>
               <noOfOptions>4</noOfOptions>
           </root>",
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $options = $xml.find("option"); // get all option nodes

Then to get each option value using jquery .each
$.each($options, function() {
    console.log($(this).text());
});

Hope that helps
Fiddle:
http://jsfiddle.net/JohnMcNulty/vRf9Z/


text:
Q: Rename part of the directory names? The following command found the following directories.
$ find tmp/ -name "date=*" -type d
tmp/year=2022/month=05/date=27
tmp/year=2022/month=05/date=21
tmp/year=2022/month=05/date=29
tmp/year=2022/month=05/date=24
tmp/year=2022/month=05/date=31
tmp/year=2022/month=06/date=01
tmp/year=2022/month=06/date=02

I need to rename the directories by replacing date= to day=.
find tmp/ -name "date=*" -type d -exec rename s/date=/day=/g "{}" +;

However, the command doesn't rename the directories?
I will need to implement it in Python.

A: rename utility is not part of standard Unix tool/utilities and comes in different flavors.
I may suggest sticking with bash and mv using this find command:
find tmp -name "date=*" -type d -exec bash -c '
   for f;do echo mv "$f" "${f/date=/day=}"; done' _ {} +

I have kept echo before mv for your testing purpose. Once satisfied with the output just remove echo from above command.

A: If you want to do this from Python anyway, a subprocess is just unnecessary.
import os

for curdir, dirs, files in os.walk("/tmp"):
    for dirname in dirs:
        if dirname.startswith("date="):
            new = dirname.replace("date=", "day=")
            os.rename(os.path.join(curdir, dirname), os.path.join(curdir, new))

A: If you are on Python 3.4+, you can use pathlib:
from pathlib import Path

tmp = Path('tmp')

for o in tmp.rglob('date=*'):
    if o.is_dir():
        o.rename(o.with_name(o.name.replace('date', 'day')))

To address the problem you mentioned in your post comment, you can check if the target directory already exists and then workaround it the way you want. Something like this:
from pathlib import Path

tmp = Path('tmp')

for o in tmp.rglob('date=*'):
    new_name = o.with_name(o.name.replace('date', 'day'))
    if o.is_dir():
        if new_name.exists():
            # Your logic to work around a directory
            # that already exists goes here
        else:
            o.rename(new_name)

The code above is just an initial idea. It needs a lot of improvement to be made more reliable.


text:
Q: How to draw threshold on original frame I am very new to opencv and with some tutorials I am able todo a Motion Detection,
I can draw contors but I want to draw the threshold between frames on my orignial frame as on the image below, how can I do this?
When I try to use the function addWeighted I get an error because the shape of the arrays are not equal.
Orig: (1080, 1920, 3) Thrash:(180, 320)

thanks

A: I've seen a video before. The codes are below. Choose the one you need.
I think you are talking about:
while True:
_, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
bodies = face_cascade.detectMultiScale(gray, 1.3, 5)

if len(faces) + len(bodies) > 0:
    if detection:
        timer_started = False
    else:
        detection = True
        current_time = datetime.datetime.now().strftime("%d-%m-%Y-%H-%M-%S")
        out = cv2.VideoWriter(
            f"{current_time}.mp4", fourcc, 20, frame_size)
        print("Started recording!")
elif detection:
    if timer_started:
        if time.time() - detection_stopped_time >= SECONDS_TO_RECORD_AFTER_DETECTION:
            detection = False
            timer_started = False
            out.release()
            print('Stop Recording!')
    else:
        timer_started = True
        detection_stopped_time = time.time()

if detection:
    out.write(frame)

for (x, y, width, height) in faces:
    cv2.rectangle(frame, (x, y), (x + width, y + height), (255, 0, 0), 2)


text:
Q: Quick beginner CSS, how to "scope" styles? Excuse the poor phrasing, I know it's possible but I can't figure out what to google so I'll just explain it like so..
I have this html:

Home

About

Speakers

Exhibitors

Agenda

Location

and then later on I might have another list..
All I want to do is style just the
 /
 items for the class navbar_links. Not for any occurrence of an unordered list in the html, just an unordered list found within
 Could someone explain to me how to do that? And for future reference, let me know what it's "called" so I don't have to waste SO's time with something I know I should have been able to google, sorry :P

A: Use .navbar_links ul or .navbar_links li depending on what you actually want to style. This will restrict the styling to only those items that fall inside the navbar_links class.

A: You're looking for CSS selectors: www.w3.org/TR/CSS2/selector.html
In this case, you can write the following:
.navbar_links ul {
  /* put styles for ul here */
}

A: Like so:
.navbar_links ul

Here's a sample fiddle: http://jsfiddle.net/AWWmc/1

A: You can just use:
.navbar_links ul

to do what you want.

A: What you're looking for are called CSS Selectors or more specifically, the class selector. e.g.
.navbar_links ul, /* Select all ul within elements of class='navbar_links' */
.navbar_links ul > li /* Select all li that are *children* of a ul within els of class='navbar_links' */

(The second example would not select the inner li of

…)


text:
Q: How to get row number of clicked button when Application.Caller just returns an Error? There are many questions like mine and I just tried out the solution mentioned in many places, for example here. But for me it just returns the error "Run-time error '1004': Unable to get the Buttons property of the worksheet class" when I enter the following code:
Sub Mainscoresheet()
     ' Mainlineup Macro
    Dim b As Object, RowNumber As Integer
    Set b = ActiveSheet.Buttons(Application.Caller) 'here I get the error
    With b.TopLeftCell
        RowNumber = .Row
    End With
    MsgBox "Row Number " & RowNumber
End Sub

Does anyone know another solution which would fix my problem?
If you need any further information, please feel free to ask.
Thanks in advance!
Kind regards,
Julia

A: I tested your code. It works fine with a formsbutton, but not with an ActiveXbutton. Could that be the problem?


text:
Q: CreatedDate = LAST_N_MONTHS:3 vs CreatedDate >= LAST_N_MONTHS:3 This might be a silly question... but I'm trying to get the records created within the last 3 months. I have a custom object and I have the following two queries below. I see that the results are very different when I run >= or = and I couldn't put my finger on it. What is the correct usage of the LAST_N_MONTHS against the CreatedDate field in order to get the correct data?
SELECT Id
    FROM MyCustomObject__c
    WHERE CreatedDate >= LAST_N_MONTHS:3

or
SELECT Id
    FROM MyCustomObject__c
    WHERE CreatedDate = LAST_N_MONTHS:3

I have a data set like below...
Id                  |     CreatedDate
a4b7X0000009h91QAA  |   Dec 17, 2022

I am getting the result with CreatedDate >= LAST_N_MONTHS:3, but if I change to CreatedDate = LAST_N_MONTHS:3 then the query doesn't return it.

A: This is explained in the documentation:

To filter for results within a range, use the = comparison operator. To filter for results on either side of a range, use the > or < comparison operators.

Using ">" checks after the end of the range, while "<" checks before the start of the range.
If you include "=" in the comparison with ">" or "<", the range is included too.
For what you want, just check within the range with "=".
However, as noted in the comments, below, you need to make sure you use a range definition that meets your expectations (last 3 months does not include the current month). The same documentation (link above) explains how each possible range is constructed.


text:
Q: Can't implement sweet alert 2 with laravel 5.6. What's the issue with this code? I want to perform the delete operation with sweetalert2. But after clicking the confirm button nothing is happening. Form is not submitted. What's the error i'm getting?

function deleteTag(id) {
  swal({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes, delete it!',
    cancelButtonText: 'No, cancel!',
    confirmButtonClass: 'btn btn-success',
    cancelButtonClass: 'btn btn-danger',
    buttonsStyling: false,
    reverseButtons: true
  }).then((result) => {
    if (result.value) {
      event.preventDefault();
      document.getElementById('delete-form-' + id).submit();
    } else if (
      // Read more about handling dismissals
      result.dismiss === swal.DismissReason.cancel
    ) {
      swal(
        'Cancelled',
        'Your data is safe :)',
        'error'
      )
    }
  })
}
<button class="btn btn-simple btn-danger btn-fab btn-icon" type="button" onclick="deleteTag({{ $tag->id }})"><i class="material-icons">delete</i>
</button>

<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
  @csrf @method('DELETE')
</form>

I got this console error after selecting confirm delete button.
enter image description here


text:
Q: UWP: how to optimize synchronization between WCF WebServices and SQLite through async calls I must synchronize data coming from WCF WebServices in a SQLite database.
This synchronization represents a dozen of WebServices, that can be "grouped" in 4 categories:

*

*"User's" Rights

*"Forms" data, which can be updated from the two sides (user/server)

*"Server" data, which are only updated from the server

*"Views" data, wich copy locally the views of the server

Each call to the WebService is done through HttpClient:
response = await client.PostAsync(webServiceName, content);

Each WebService has its own async method where the WebService response is deserialized:
public static async Task<string> PushForm(List<KeyValuePair<string, string>> parameters)
{
    var response = await JsonParser.GetJsonFromUrl(WebServiceName.PushForm.Value, parameters);
    Forms forms = new Forms();
    try
    {
        forms = JsonConvert.DeserializeObject<Forms>(response);
        return response;
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }
}

Then I have a SynchronizationService class, where I regroup the calls to WebServices by categories:
public async Task<bool> SynchronizeServerData()
{
    bool result = false;
    try
     {
        result = true;
        List<Table1> tables1 = await WebServices.GetListTable1(null);
        if (tables1 != null)
        {
            ServiceLocator.Current.GetInstance<IRepository>().DeleteAll<Table1>(true);
            ServiceLocator.Current.GetInstance<IRepository>().AddAll<Table1>(tables1);
        }
        List<Table2> tables2 = await WebServices.GetListTable2(null);
        if (tables2 != null)
        {
            ServiceLocator.Current.GetInstance<IRepository>().DeleteAll<Table2>(true);
            ServiceLocator.Current.GetInstance<IRepository>().AddAll<Table2>(tables2);
        }
        List<Table3> tables3 = await WebServices.GetListTable3(null);
        if (tables3 != null)
        {
            ServiceLocator.Current.GetInstance<IRepository>().DeleteAll<Table3>(true);
            ServiceLocator.Current.GetInstance<IRepository>().AddAll<Table3>(tables3);
        }
        ...
    }
    catch (Exception e)
    {
        result = false;
    }
    return result;
}

And finally, in the main ViewModel, I call each of these methods:
public async void SynchronizeData(bool firstSync)
{
    IsBusy = true;
    var resUsers = await _synchronisation.SynchronizeUsersRights();
    var resServer = await  _synchronisation.SynchronizeServerData();
    var resForm = await _synchronisation.SynchronizeForms();
    var resViews = await _synchronisation.SynchronizeViews();
    IsBusy = false;
}

But due to the use of "await" the performance is not good.
=> I would like to know if there is an easy way to "parallelize" the calls to optimize performance? Or is it possible to separate the data recovery from the SQLite update for this?

A: On the face of it there appear to be opportunities to run a few things concurrently, for instance in SynchronizeData you could do this instead:
{
    IsBusy = true;
    Task resUsersTask = _synchronisation.SynchronizeUsersRights();
    Task resServerTask = _synchronisation.SynchronizeServerData();
    Task resFormTask = _synchronisation.SynchronizeForms();
    Task resViewsTask = _synchronisation.SynchronizeViews();
    await Task.WhenAll(resUsersTask, resServerTask, resFormTask, resViewsTask);
    var resUsers = resUsersTask.Result;
    var resServer = resServerTask.Result;
    var resForm = resFormsTask.Result;
    var resViews = resViewsTask.Result;
    IsBusy = false;
}

...which would allow those 4 tasks to run concurrently.
You could do the same in SynchronizeServerData; e.g.:
result = true;
Task tables1Task = WebServices.GetListTable1(null);
Task tables2Task = WebServices.GetListTable2(null);
Task tables3Task = WebServices.GetListTable3(null);

List<Table1> tables1 = await tables1Task;
// ...

List<Table2> tables2 = await tables2Task;
// ...

List<Table3> tables3 = await tables3Task;
// ...

This would allow the 3 tasks to run concurrently as well.
How much you actually gain from this might depend on things like does SQLite allow you to do multiple concurrent requests - I don't know the answer to that offhand.
Some other comments:
public async void SynchronizeData(bool firstSync)

async void is almost always incorrect, except for event handlers and rare fire-and-forget methods, and usually async Task is what you want.  Search SO for any number of good answers on why.
Then lastly, what you really should do is profile the code to see where your real bottlenecks are.


text:
Q: background-image in HTML, CSS and JavaScript game not displaying In a simple HTML,CSS and JavaScript game, I replaced (in the CSS)
background-color:green;

with
background-image: url(flappybird.png);

and I also tried: (and with single quotations)
background-image: url("flappybird.png");

but the image is not being displayed on the page. I have tried adding the semi colon and also speech marks.
I also tried adding z-index=10000000 to character, but that didn't help.
Can anyone tell me what I am doing wrong. I can confirm that the image is named correctly flappybird.png and is in the root folder.

var character = document.getElementById("character");
var enemy = document.getElementById("enemy");

function jump(){
    if(character.classlist!="animate"){
    character.classList.add("animate");
    }
    setTimeout(function(){
        character.classList.remove("animate");
    },500);

}

//right movement

function right() {

  var leftVal =  parseInt(window.getComputedStyle(character).getPropertyValue("left"))
  character.style.left = (leftVal + 30) + "px";

}

//left movement

function left() {

  var leftVal =  parseInt(window.getComputedStyle(character).getPropertyValue("left"))
  character.style.left = (leftVal - 30) + "px";

}

var checkDead =setInterval(function(){
    var characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
    var enemyLeft = parseInt(window.getComputedStyle(enemy).getPropertyValue("left"));
    //ADD VARIABLE TO FIND CHARACTER RIGHT -if it collides with enemy left, you are out
    //remove the condition that the enemy has to be in the first 30 pixels of the game (left side)
    var characterRight =parseInt(window.getComputedStyle(character).getPropertyValue("right"));

    if(
        characterTop==enemyLeft //have tried characterRight==enemyLeft didn't work
    )
    {
        enemy.style.animation="none"; //remove the animation
        enemy.style.display="none";
        alert("Game Over");

    }
},10);

//left
addEventListener("keydown", function(e) {
    if(e.keyCode == 37) left()
})

//jump (up)
addEventListener("keydown", function(e) {
  if (e.keyCode === 38) {
    jump()
  }
})

//right
addEventListener("keydown", function(e) {
  if (e.keyCode === 39) {
    right()
  }
})
*{
        padding:0;
        margin:22;
    }

    #game{
        width:500px;
        height:500px;
        border:4px solid #171918;
    }

    #character{
        width:30px;
        height:120px;
        /*background-color:green;*/
        background-image: url(flappybird.png);
        position:relative;
        top:320px;
        border-radius:20px;
        /*animation: jump 300ms */

    }

    /* new class called animate */
    .animate{
        animation: jump 500ms;
    }

    #enemy{
        width:60px;
        height:60px;
        background-color:red;
        border-radius:14px;
        position:relative;
        top:320px;
        le

ft:440px;
    animation: moveenemy 1s infinite linear;

}

@keyframes moveenemy{
    0%{left:440px;}
    50%{top:58px;}
    100%{left:0px; top:320x;}
}

@keyframes jump{
    0%{top:380px;}
    30%{top:50px;}
    50%{top:40px;}
    100%{top:380px;}
}

/* adding sky*/
#sky{
    width:500px;
    height:340px;
    background-color:skyblue;
    position:absolute;
    top:118px;
}

/* adding ground */
#ground{
    width:500px;
    height:170px;
    background-color:bisque;
    position:absolute;
    top:450px;
}

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

Game

A comment below suggests the option to resize and add background-size: cover;
This works to some extent but does not solve the problem of getting the image to fit the specifications we want. Resizing the width and height here, doesn't resize - it just uncovers or covers the image.
If I was to use an image, it should also resize, and I note the width and height don't work as expected in this situation. Could that also be addressed in any answers.
The below code thus uncovers the image if I adjust the width and height, but does not resize correctly, which I cannot figure out.
#character{
    width:60px;
    height:50px;
    /*background-color:green;*/

    background-image: url(flappybird.png);
    position:relative;
    top:320px;
    background-size: cover;
    /*animation: jump 300ms */

A: Is this what you want to achieve? I added a little border to show the width problem solved.
#character {
  width: 50px;
  border: 1px solid black;
  height: 50px;
  background-color: green;
  background: url("https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fatomix.vg%2Fwp-content%2Fuploads%2F2014%2F05%2FFlappy-Bird.png&f=1&nofb=1")
    center no-repeat;
  background-size: contain;
  position: relative;
  top: 50%;
  border-radius: 20px;
  /*animation: jump 300ms */
}

Update:
The background-size: contain;rule tells the background to adjust its size to the container, without stretching it, your can read more info about the values of this rule here. If the container is bigger than the img, it might repeat, so it's wise to control it with background-repeat: no-repeat;, or use the shorthand version of background: <url> <position> <repeat>; more on that here.
About the change of the top from px to % it was purely experimental while trying to resolve your question. You can add your original value.


text:
Q: React rendering test with role, testid and classname I'm trying to test react rendering. As I known, There is several method to find elements that I defined.

*

*role

*test id

*class name

*query selector

When should I define 'role' or 'test id' instance of class name, and What is differnce between role and test id?

A: What is difference between role and test id?
A role is a html attribute used in accessibility and semantic html structures.
WAI-ARIA Roles
test-id are special id's used to hook onto a specific DOM node for testing. They are typically a data-X attribute, i.e. data-testid="test", but could also be plain id attributes for some testing libraries.
You should primarily use roles as part of your applications accessibility strategy, not for testing.
When should I define 'role' or 'test id' instance of class name?
react-testing-library query cheatsheet
What Query Should I Use?

Based on the Guiding Principles, your test should resemble how users interact with your code (component, page, etc.) as much as possible. With this in mind, we recommend this order of priority:

*

*Queries accessible to everyone (label/placeholder text, aria role, text, and display values)

*Semantic Queries (HTML5 and ARIA compliant selectors)

*Test IDs
  Manual queries on the container (container.querySelector)


text:
Q: using Rstudio, how to import xlsx file larger than 100MB? How to work with excel file larger than 100 MB, I already imported but it doesn't running the shiny app?

A: if the excel is format ,you can save as csv .then you can usedata.table::fread() to read. it's more effective and easily , csv  is ligthter than xlsx


text:
Q: Customize Reminder or Alarm Class in Windows phone 8 is that possible to derive reminder or alarm in windows phone 8 programmatically?
can I customize the reminder sound or alarm sound?

A: You cannot, you are stuck with the default sound.


text:
Q: keystore file exists but its empty in android key store I'm trying to get keyhash for facebook application.For this i've installed openssl.and now trying to get hash key from command line.I've also generated .apk file and keystore for an app.
But when i try i' getting java.lang.Exception: Keystore file exists, but is empty: E:\key
where E:\key is folder where i've generated my keystore.
E:\apk is folder where my apk file is kept.
Please help me...This is first time i'm doing this and not getting it
Thanks in advance...


text:
Q: how to unset single date from bootstrap datepicker? I have following bootstrap datepicker:

Now, when I am deleting the 24th date from my another table, as a result, it should remove the 24th date from the date picker after the ajax call.
I have written the following code for it. However, it's not working:
$.ajax({
            type: "POST",
            url: "<?php echo VIEW_HOST_PATH;?>remove_data.php",
            data: {ch: ch, dh: dh, sp_rec: sp_rec, cartDate: 1},
            success: function(data) {
                console.log(data);

                var obj = $.parseJSON(data);
                //console.log(obj.length);
                var selectedDates = '';
                for(var i=0;i<obj.length;i++) {
                    //selectedDates = selectedDates+"'"+obj[i]+"',";
                    //$('#disc_single_datepicker_1').datepicker('setDates',[obj[i]]);
                }
                console.log(selectedDates);
                //alert(selectedDates);
                //$('#disc_single_datepicker_1').datepicker('setDates',[data]);
                //$('#disc_single_datepicker_1').datepicker('update',selectedDates);
                display_toastr(datainfo+" record has been removed!","Remove Record",true,"right","info");
                $("#row_"+dh).fadeOut('slow');

            }, error: function() {
                alert("Something went wrong. Please contact admin!");
            }
        });

so what should I write to unset that particular date. thanks


text:
Q: Calculate the Norton Resistance and Current and the Thevenin Voltage of the following circuit
U=10 V, R=10 ohm
I calculated the resistance as such:
1/Rt = 1/R + 1/R <=> Rt = R/2 = 5 ohm
To calculate the voltage I did KVL as such:
U - 2Ur = 0 <=> Ur = 5V, where Ur is the voltage in the resistors
And then by applying KVL to the closed network that goes from a to b passing through the resistor, I got Ut=5V
Then I calculated the current using U=RI, and I got I=1A.
Is this correct? Because in my solutions I=0,5A

A: I answered your last question here.
Once again, you have the right answer and your "solution" answer is wrong.
You have done the correct method; found the open-circuit terminal voltage, which is the Thevenin voltage. You have then found the Thevenin resistance - also correct. You have then used the transform \$ I_n = V_{th}/R_{th}\$ to find the Norton current, correct again.
Good job - wherever you keep getting your solution answers from, stop using it!!!


text:
Q: Hide button "Edit list" on other user profile page for moderators For example, https://ru.stackoverflow.com/users/2/stanislav?tab=profile.

Moderators can see link "Edit list", which opens https://ru.stackoverflow.com/users/hidecommunities/2 page. But we can't edit this list.
So, I guess, better to hide this link for moderators.


text:
Q: Why is the Android onCreate() method not called when the AVD is rotated? My AndroidManifest.xml does not include anything that would cause this (that I know of).
I.e. it does not include:
android:configChanges="orientation"
Android Version: Chipmunk 2021.2.1 Patch 1
class MainActivity : AppCompatActivity() {
    internal lateinit var tapMeButton: Button
    internal lateinit var gameScoreTextView: TextView
    internal lateinit var timeLeftTextView: TextView
    internal var score: Int = 0
    internal var gameStarted = false
    internal lateinit var countDownTimer: CountDownTimer
    internal val initialCountDown: Long = 5000
    internal val countDownInterval: Long = 1000

    companion object {
        private val TAG = MainActivity::class.java.simpleName
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d(TAG, "onCreate called. Score is $score")

        tapMeButton = findViewById(R.id.tapMeButton)
        gameScoreTextView = findViewById(R.id.gameScoreTextView)
        timeLeftTextView = findViewById(R.id.timeLeftTextView)

        tapMeButton.setOnClickListener { view ->
            if (!gameStarted) {
                startGame()
            }
            incrementScore()
        }

        resetGame()
    }

A: It's hard to help you without seeing your code. But check that is this line available in your code.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

A: Maybe be you don't activate rotation in the top panel of your simulator.


text:
Q: GDB test script So I am relatively new to coding so please forgive improper vocab. What I am basically trying to do is create a script for, or perhaps enter commands into, GDB so that it can run my code with the input file of a test case over and over. Basically, I am working on a project right now that makes heavy usage of semaphores and mutexes, and somewhere, every once in a blue moon, my code breaks due to race conditions. If I could have gdb run my test case continuously until my code reached a seg fault, this would be ideal.
PS- Please be specific as to what I must do, I am not great at dissecting answers that have heavy technical answers.
Thank You!

A: The simplest solution is expect script. Expect is a program to automate interactions with programs that expose a text terminal interface.
Examples are available at http://en.wikipedia.org/wiki/Expect
The script should be like
#!/usr/bin/expect

# start gdb
spawn gdb yourprogram

while {1} {

# wait for gdb to start, expect the (gdb) to appear
expect "(gdb)"

# send command to run your program
send "run your_args\n"

expect {
    "Program exited normally."    {continue}  # just run again
    "(Some error message)"        {interact}  # start to debug
}

}

A: You can use GDB scripts in order to automate your GDB sessions.The GDB macro coding language consists of gdb commands along with basic looping statements and conditional statements.
You can find information about it here
http://www.adacore.com/adaanswers/gems/gem-119-gdb-scripting-part-1/
What are the best ways to automate a GDB debugging session?


text:
Q: Show that any connected open subset of $E^n$ is arcwise connected. So I know that the definition of arcwise connected is that there is a continuous function $f:[0,1] -> S$ s.t. $f(0) = p$ and $f(1) = q$ when $p,q \in S$, $S$ = any connected open subset of $E^n$... can anyone push me in the right direction?

A: Pick $p \in S$. Let $C_p \subset S$ be given by
$C_p = \{ q \in S | \text{there is a path from }p\text{ to }q\text{ in }S \}$.
Since $S$ is open, $C_p$ is open.
Suppose $q \in S \setminus C_p$. Since $S$ is open, we have some
$B(q,\epsilon) \subset S$ (with $\epsilon>0$), hence
$B(q,\epsilon) \cap C_p = \emptyset$ (otherwise we get a quick contradiction). Hence $S\setminus C_p$ is open, which
contradicts the connectedness of $S$. Hence $C_p =S$.

The following construction shows that we can choose the connecting path to
be polygonal.
Choose $p,q \in S$, then there exists a path from $p$ to $q$, call it $\gamma$.
The set $\Gamma=\gamma([0,1])$ is compact. Since $S$ is open,  for each
$s \in \Gamma$, there is some $\epsilon_s>0$ such that $B(s,\epsilon_s) \subset S$, and this collection is an open cover of $\Gamma$, hence has a finite
subcover.
Call the elements of this subcover $B_1,...,B_n$, where $p \in B_1$ and $q \in B_n$, and let $x_k$ be the centre of $B_k$.
Let $i_1 = 1$ and define $t_2 = \sup \{ t \in [0,1] | \gamma(\tau) \in B_{i_1} \forall \tau \in [0,t] \}$. If $t_2 = 1$ we are finished, otherwise
$\gamma(t_2) \not\in B_{i_1}$, and there is some $i_2$ such that
$\gamma(t_2) \in B_{i_2}$.
Now suppose we have $0=t_1 < \cdots < t_k < 1$ and $B_{i_1}, ..., B_{i_k}$ such that $\gamma(t)\in B_{i_1}\cup ...\cup B_{i_k}$ for
$t \in [t_1,t_k]$.
Let $t_{k+1} = \sup \{ t \in [0,1] | \gamma(\tau) \in B_{i_1}\cup ...\cup B_{i_k} \forall \tau \in [0,t] \}$.
As above, if $t_{k+1} = 1$ we are finished, otherwise
$\gamma(t_{k+1}) \not\in B_{i_1}\cup ...\cup B_{i_k}$, and there is some $i_{k+1}$ such that
$\gamma(t_{k+1}) \in B_{i_{k+1}}$.
It is clear that this construction must terminate with some $t_{m} = 1$. Then
form the polygonal path $p \to x_{k_1} \to \cdots \to x_{k_m} \to q $.

A: For every point $p$ consider $B_p$ an open ball centered at $p$ and contained in $U$ - our open set. I claim that for every $p$, $p'$, there exist a sequence of point $p_0 = p$, $p_1$, $\ldots$, $p_n=p'$ so that $B_{p_i} \cap B_{p_{i+1}} \ne \emptyset$, for all $0 \le i \le n-1$. For otherwise we could separate the balls $B_q$ into two groups so that balls from different groups do not intersect, and that would provide a partition of our set into two nonempty open sets. Take for every $i$ a point $q_i$ in the intersection $B_{p_i} \cap B_{p_{i+1}}$. Consider now the polygonal line $p_0 q_0 p_1 q_1 \ldots p_{n-1} q_{n-1} p_n$ contained in $U$ and joining $p_0=p$ and $p_n=p'$.


text:
Q: MODX - Template variable that hides post author when checked So I am using the add-on articles to create a press release section on my site. I need to create a template variable that is a check box and if checked it will NOT show the post author:
[[*publishedby:userinfo=`username`]]

What is the best way for me to do this.

A: If your checkbox tv input option value like "Hide==1" then use output filter like this:
[[*your_tv:ne=`1`:then=`[[*publishedby:userinfo=`username`]]`]]


text:
Q: Determining camera orientation (possibly using calibration images). I need to generate a camera calibration pattern. Cameras are expected to be placed at an average height of 15 to 30 feet above ground pointing downwards at roughly 30 degrees. These cameras are deployed in open spaced monitoring different types of movement. During installation, operators often make mistakes when entering camera height and angle information into our system.
The objective is to get a sense of the ground plane and to be able to calculate how close or far objects are relative to their size.
The only automated option I could think of was to have operators use a camera calibration pattern that have been printed on a large paper. The pattern image will be a simple black and white checkerboard with a constant number of rows and columns (let's say 10). The problem is, I will not know in advance what size the printed image is.
The variables are:

*

*Height of the camera.

*Angle of the camera to the ground.

*Distance to pattern image.

*Size of the pattern image.

Question:
How can I determine the size of the pattern image while analyzing (which will allow me to scale other objects in a relative way).
Is there a better way to approach this problem?

A: I apologize for not having a picture.  Let the height of the camera be $h$, the angle of the camera to the ground be $\theta$, the distance to the pattern image be $d$, and the size of the pattern be $s$.  Consider the simple case where $\theta = 0$.  Similar triangles reveals that the image size $t(0) = s h/d$.  It should be noted that the light emanates from the camera at a half-angle $\phi = \arctan{[s/(2 d)]}$.
Now consider the tilted case.  The system may be modeled with a triangle with angles $\theta$, $\pi/2 + \phi$, and $\psi = \pi/2 - (\theta + \phi)$.  The side opposite the angle $\psi$ has length $t(0)$.  We may then use the law of sines to find the image size $t(\theta)$:
$$\frac{t(\theta)}{\cos(\phi)} = \frac{t(0)}{\cos(\theta+\phi)} $$
With a little manipulation, we find that the image size is
$$t(\theta) = \frac{2 s h}{2 d \cos(\theta) - s \sin(\theta)} $$


text:
Q: ELI5: How do I make these FFT-related lists act properly? I have been working on an FFT-assignment for the past couple of weeks. It is due thursday, and I thought it would be quite cool to pick up Python and program an FFT-calculator that transformed from time to frequency domain. Now, I have just started TODAY with learning Python, so please do bear with me.
Anyways, I have stumbled upon a problem
The frequency is given by
(k*sample rate)/N
where k is an integer ranging from 0 to N-1, and where N is the amount of samples.
What I want is to have a list, freq[n], like this:
freq[n] = k[n]*sample rate/N

I have tried the following, but with no success:
samplerate = 44100
N = 2048
k = range(0,N-1)

for n in range(0,N-1):
    freq = k[n]*samplerate/N

print freq[2]

with following error:
TypeError: 'int' object has no attribute 'getitem'
I owe you guys a thousand beers if you are willing to help me
Edit: It really warms my heart that you guys are so nice to newbies like me :) Thank you

A: The problem is in your loop.
You're assigning a new value for freq each time, overwriting the old value of freq. What you are trying to do in the last line is to access an element of a list, but it is not a list (it is an int).
If you want to be freq a list of all frequencies, change your line in the loop to:
freq.append(k[n]*samplerate/N)

Edit: Maybe I don't understand your problem correctly, though, then please tell us what the result shall look like.

A: Your problem is that freq is being re-assigned each time through your for loop. Instead, make it a list of the values for corresponding n:
freq = [(k[n] * samplerate) / N for n in range(0, N)]

or, given that k[n] == n, simply
freq = [(n * samplerate) / N for n in range(0, N)]

Note that range in Python excludes the upper bound.


text:
Q: Trying to copy text from e-mail I am having many issues with IBM Notes e-mail.  When I highlight to copy text from an e-mail I received, instead of copying the text it generates a new e-mail to myself.  What can I do to fix this?

A: To copy, highlight the text either with the mouse or holding down shift and moving the cursor keys. Press Control and C together to copy the text, and then Control and V to paste into wherever you need it.


text:
Q: How to reload fixtures in a test I'm trying to test an RSS feed by comparing a dynamically generated feed against a known output. To make this work, I need to load fixtures with the time frozen. The following works, but it seems overkill to reset the database by reloading the schema and the fixtures.
# test/integration/feed_test.rb
require 'test_helper'
load 'Rakefile'

class FeedTest < ActionDispatch::IntegrationTest
  def setup
    # Normalize time in order to match fixture file
    travel_to Time.zone.parse('2015-03-01T12:00:00') do
      silence_stream(STDOUT) do
        # anything written to STDOUT here will be silenced
        Rake::Task['db:schema:load'].reenable
        Rake::Task['db:schema:load'].invoke
      end
      Rake::Task['db:fixtures:load'].reenable
      Rake::Task['db:fixtures:load'].invoke
    end
  end

  test 'feed matches fixture file' do
    get feed_path
    assert_equal contents('feed.atom'), response.body
  end
end

# test/test_helper.rb
module ActiveSupport
  class TestCase
    fixtures :all

    def contents(file_name)
      IO.read "test/fixtures/files/#{file_name}"
    end
  end
end

I can't figure out how to reload just the projects filter inside a travel_to block. I also can't get travel_to to work in test_helper.rb.
But, the real problem with this approach is that reloading the Rakefile causes the following spurious warnings from the secure_headers gem:
$ rake test
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:1: warning: already initialized constant INLINE_SCRIPT_REGEX
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:1: warning: previous definition of INLINE_SCRIPT_REGEX was here
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:2: warning: already initialized constant INLINE_STYLE_REGEX
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:2: warning: previous definition of INLINE_STYLE_REGEX was here
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:3: warning: already initialized constant INLINE_HASH_SCRIPT_HELPER_REGEX
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:3: warning: previous definition of INLINE_HASH_SCRIPT_HELPER_REGEX was here
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:4: warning: already initialized constant INLINE_HASH_STYLE_HELPER_REGEX
/Users/dan/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/secure_headers-3.3.1/lib/tasks/tasks.rake:4: warning: previous definition of INLINE_HASH_STYLE_HELPER_REGEX was here
Run options: --seed 17868

# Running:

........................................................................................................

Finished in 17.397614s, 5.9778 runs/s, 191.3481 assertions/s.

104 runs, 3329 assertions, 0 failures, 0 errors, 0 skips
Coverage report generated for MiniTest to /Users/dan/Dropbox/Documents/dev/cii-best-practices-badge/coverage. 754 / 781 LOC (96.54%) covered.

It seems like I should be able to reload some of the fixtures without using rake at all, but I can't figure out how to do so.

A: Here's the fix that resolved my issue:
# frozen_string_literal: true
require 'test_helper'
load 'Rakefile'

class FeedTest < ActionDispatch::IntegrationTest
  # Turn off transactional fixtures for this test since we are loading
  # the fixtures database anyway. This will prevent the timestamp change
  # from spilling into other tests.
  self.use_transactional_tests = false

  setup do
    # Ensure the test db has its environment metadata set to test,
    # otherwise tasks farther down will fail.  New for Rails 5
    Rake::Task['db:environment:set'].invoke
    # Normalize time in order to match fixture file
    travel_to Time.zone.parse('2015-03-01T12:00:00') do
      ActiveRecord::Schema.verbose = false
      Rake::Task['db:schema:load'].reenable
      Rake::Task['db:schema:load'].invoke
      Rake::Task['db:fixtures:load'].reenable
      Rake::Task['db:fixtures:load'].invoke
    end
  end

  test 'feed matches fixture file' do
    get feed_path
    assert_equal contents('feed.atom'), response.body
  end
end


text:
Q: PayPal payment wall not rendered - Error "Invalid approval URL" I'm integrating the PayPal Plus environment on our site. We are using the current version of PayPal PHP SDK (1.7.4) available on Github https://github.com/paypal/PayPal-PHP-SDK. We are using PHP 7.0.7 on IIS 10.
First we create a payment as explained in the integration guide. We receive a valid approval url from the payment (format:
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=...).
I checked the url in the browser manually.
The payment is created in a controller and is given to the view.
Controller:
    function showPaymentWall() {
    $payment = $this->createPayment();
    return view("payments.paypal.paymentWall",['payment'=>$payment, 'approval_url'=> $this->approvalUrl]);
}

The approval_url is set in the method createPayment.
Here is the code from the view:
@extends('layouts.master')
@section('title')
Upgrade
@endsection
@section('content')

{{ $approval_url }}

@endsection

@section('scriptIndividualJSCode')

@endsection

As you can see the valid url is displayed before the ppplus container. So that it is clear, that the url is valid and correctly given by the controller.
But when I visit the page, I always get this error:

When I check the reason via console it says "Invalid approval url".

Anybody an idea why or what I can check to get forward?
Thanks in advance for any help!

A: I found the reason after a long search.
It comes out, that the & in the approval URL has to be replaced with &.
Then it worked. This can be done with the PHP function htmlspecialchars_decode() (see http://php.net/manual/de/function.htmlspecialchars-decode.php). Here is my code for the javascript part:


text:
Q: Why doesn't "chrome.bookmarks.getTree" work? If I try the following code:
chrome.bookmarks.getTree(function(items) {
  items.forEach(function(item) {
    document.write(item.url);
  });
});

it returns undifined. But when I write:
chrome.bookmarks.getRecent(20, function(items) {
  items.forEach(function(item) {
    document.write(item.url);
  });
});

it works.
Why does it differ?

A: Both chrome.bookmarks.getTree and chrome.bookmarks.getRecent return an array of BookmarkTreeNodes, but BookmarkTreeNodes do not necessarily have a url property. In the case of getTree, the top nodes of the tree are folders and do not have URLs:

If you use getTree, you'll have to traverse the tree recursively using each node's children array.  It helps to know that every BookmarkTreeNode either has a children attribute (if it's a folder) or a url attribute (if it's an actual bookmark).  Try something like:
chrome.bookmarks.getTree(function(itemTree){
    itemTree.forEach(function(item){
        processNode(item);
    });
});

function processNode(node) {
    // recursively process child nodes
    if(node.children) {
        node.children.forEach(function(child) { processNode(child); });
    }

    // print leaf nodes URLs to console
    if(node.url) { console.log(node.url); }
}

A: chrome.bookmarks needs permission to use. Try to use it in page
chrome://bookmarks.


text:
Q: angularjs correct row is not being deleted from table I have been struggling with a couple of issue so I thought I would reach out for help after doing much searching. I'm using AngularJS.

*

*My first problem is that checkbox is not working properly when I use ng-repeat, it will only check the first box in the table code snippet below. I'm using a custom checkbox which I coded with css is the reason for the label.

*My second issue is when I click on the check box it should delete any row I want but it deletes the row before it if I start from the bottom of the table up, but if I start from the top of the table down it works as expected except for the box being checked code snippet.  I tried many ways to set the index but it still does not work.
$scope.removeRow = function(type) {
var index = -1;
var myArr = eval( $scope.contacts );
    for( var i = 0; i < myArr.length; i++ ) {
       if( myArr[i].type === type ) {
           index = i;
           break;
             }
      {
if( index === -1 ) {
        alert( "Something gone wrong" );
      }

    $scope.contacts.splice(index, 1);
};

A: First off, don't use eval($scope.contacts).  If that variable is a string and contains javascript it will run that javascript. if myArr isn't defined using myArr = $scope.contacts you can use myArr = JSON.parse(JSON.stringify($scope.contacts) or use angular.copy method.
I don't see your html, so I can't tell you why your checkbox doesn't work.  But regarding your second problem, if it's deleting a row above when you hit splice, why not change that code to :
$scope.contacts.splice(index + 1, 1)


text:
Q: Insert a 2D graph in a 3D graph I have this question:
      Suppose I have some two dimsensional graphic element, say "flower" (i.e. a picture of a flower) in a Mathematica notebook.  I want to insert this figure, say at a specific point such as (1,1,2) in a 3-dimensional plot such as given by
Plot3D[x^2+y^2,{x,-2,2},{y,-2,2}]

I tried Epilog command with inset within the above Plot3D command, but was not succesful.  For example, I tried:
Plot3D[x^2+y^2,{x,-2,2},{y,-2,2},Epilog->{  Inset[flower,{1,1,2}]  } ].

The problem is possibly that Inset command only allows 2D coordinates.
Can someone please help me to achieve this task?
Thank you for any help in advance
Best Regards,
Tim

A: Just to make sure I understand what you want first. Do you want like this:

With the help of this post here is an example of the above. This allows you to change the z coordinate of the 2D image into the 3D image. You can do the same for the other coordinates if needed.
Manipulate[
 Module[{p2g},
  p2g = Graphics3D[
    {
     EdgeForm[],
     Texture[p2],
     Polygon[{{-1, -1, z}, {1, -1, z}, {1, 1, z}, {-1, 1, z}},
      VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}
      ]
     },

    Lighting -> "Neutral",
    BoxRatios -> {1, 1, .1},
    Axes -> True
    ];
  Show[p1, p2g, PlotRange -> {{-2, 2}, {-2, 2}, {-10, 15}}]
  ],

 {{z, 15, "z="}, -3, 15, .1, ImageSize -> Small,
  Appearance -> "Labeled"},

 SynchronousUpdating -> True,
 ControlPlacement -> Top,
 Alignment -> Center,
 ImageMargins -> 0,
 FrameMargins -> 1,

 Initialization :> {
   p1 = Plot3D[x^3 + y^3, {x, -2, 2}, {y, -2, 2},
     PerformanceGoal -> "Quality", ImagePadding -> 5,
     ImageSize -> 300];
   p2 = Import["ExampleData/lena.tif"];
   }
 ]


text:
Q: "Straightening Out the Boundary" in PDE In Chapter 3 of Evans' PDE Text, we're interested in solving nonlinear first-order PDEs of the form $$F(Du, u, x) = 0 \text{ in } U \\ u = g \text{ on } \Gamma$$
In the section where constructing local solutions via the method of characteristics is discussed, the first step is given to be "straighten out the boundary" by finding a smooth mapping $\Phi$ that straightens out $\partial U$ near some point $x^0 \in \partial U$ (some fixed point on the boundary).
My question is - why is this done? The idea is that this transformation gives you a PDE of the same form and now from the outset, given some point $x^0 \in \Gamma$ you can assume that $\Gamma$ is flat near $x^0$ (lying in the plane $x_n = 0$.
I suppose it has something to do with letting you take derivatives more easily (instead of on some general non-straightened domain) but I'm not seeing why this is helpful or how it's even used in subsequent calculations to construct solutions.

A: The flatness of boundary is used throughout the section "Local solution". It begins by setting up the problem so that the boundary is $x_n=0$. Then the equation of characteristic curves becomes $\mathbf x(s) = \mathbf x(y_1,\dots, y_{n-1}, s)$ where $(y_1,\dots, y_{n-1}, 0)$ is the initial point of the curve. This structure of $\mathbf x$ is used to find its derivative matrix and conclude it's invertible.
Without the boundary being flat, how would we write the mapping $\mathbf x$? The initial point would be $(y_1, \dots, y_n)$ subject to some nonlinear constraint on $y_1,\dots, y_n$. Hence, $\mathbf x$ depends on $(n+1)$ variablves $y_1,\dots, y_n, s$ which are not independent. Not exactly what we need to apply the Inverse Mapping Theorem to $\mathbf x$.


text:
Q: How can i download a file from another remote computer I'm trying to download a file from target computer remotely while having reverse connection. I am using Linux as my server machine and my target machine (client) is Windows 10. My code is written in python3.9.
Before modifying my code I was able to download files, however I would lose connection as soon as entered wrong file path. So now I modified the code to first confirm if the path given exists or not. So now I'm able to keep my connection with the client alive and if I enter wrong file path it does show the error message, however the problem is that now I'm not able to download the file by proving the correct path. Now when I enter correct path nothing happens, the cursor just blinks. Can I know what's wrong in either side of my code and the correction and also how to maintain the connection incase of wrong input, as at the moment I lose connection with the client side whenever I enter something wrong.
Here's my server side code:
while True:
    #BUFFER_SIZE=1024
    # get the command from prompt
    command = input("Command >> ")
    if command == "":
         continue
    # download file
    #THIS IS SERVER MACHINE - LINUX
    elif command.lower() == "download":
        client_socket.send(command.encode())
        print("")
        filepath = input(str("Please enter the file path: "))
        client_socket.send(filepath.encode())
        confirm = client_socket.recv(BUFFER_SIZE).decode()
        if confirm == "Please enter correct File Path":
            print(confirm) #just checking if I'm getting response from client side,but it seems that I dont.
            print("")
            continue
        elif confirm == "Press [y] to Confirm Download": #add hereTOMORO
            print(confirm)
            inp_confirmation = input(str("Press [y] to Confirm Download: "))
            client_socket.send(inp_confirmation.encode())
            print("Recieving file... ")
            results = client_socket.recv(1078000)
            new_file = open(filepath, "wb")
            new_file.write(results)
            new_file.close()
            print("")
            print(filepath, "Has been downloaded and saved")
            print("")
        else:
            Err = client_socket.recv(BUFFER_SIZE).decode()
            print(Err)
            print("")
            continue

And Here is my Client side code:
while True:
if command.lower() == "download":
    file_path = s.recv(1024).decode()
    if os.path.isfile(file_path):
        msg2 = "Press [y] to Confirm Download "
        s.send(msg2.encode())
        confirmation_recv = s.recv(1024).decode()
        if recv_confirmation.lower() == "y":
            with open(file_path, "rb") as file:
                print("sending file... ")
                data = file.read(1078000)
                s.send(data)
                while(data !=""):
                    data = file.read(1078000)
                    s.send(data)
                    file.close()
                    print("Done Sending!")

    else:
        msg = "Please enter correct File Path"
        s.send(msg.encode())

Thanks!


text:
Q: Characterizing uncertainty in empirical PMF of unknown discrete random distribution Suppose a discrete random distribution $X$ which takes integer values in some small (but not binary) range, e.g. $[0, 255]$ and whose true pmf is unknown (however, the null hypothesis is that it is uniform).  If I draw a large sample $\{x\}$ from this distribution, I can estimate the pmf by counting the number of $x_i$ that take each value and dividing by the total.  But if I draw another large sample, I will most likely get a different estimate.
I'd like some way of characterizing the uncertainty in each point in the pmf, ideally one that can be updated as I (that is, the computer) continually draws new samples.
"Confidence intervals for empirical CDF" looks closely related to what I'm trying to do but AFAICT only applies to continuous distributions.


text:
Q: Custom DropdownFor in ASP.NET MVC2 I'm trying to build dropdowns automatically in my project by creating my own Html helper method that takes a "dropdown group" code and automatically builds the Html. However, it needs to do this while fully supporting the model.
My end code needs to look like this.
<%: Html.CodeList(m => m.state, 121) %>

... where "121" is the code group that returns a dictionary of key/value pairs from the database.
Here's what I have for my Html helper method so far.
    public static MvcHtmlString CodeList<T, TProp>(this HtmlHelper<T> html, Expression<Func<T, TProp>> expr, int category)
    {
        Dictionary<int, string> codeList = CodeManager.GetCodeList(category); //returns dictionary of key/values for the dropdown
        return html.DropDownListFor(expr, codeList, new Object()); //this line here is the problem
    }

I can't figure how what exactly to hand to the DropDownListFor method. I assume that I do return html.DropDownListFor() but I'm missing something obvious. Any help?

A: There you go:
public static MvcHtmlString CodeList<T, TProp>(
    this HtmlHelper<T> html,
    Expression<Func<T, TProp>> expr,
    int category
)
{
    var codeList = CodeManager.GetCodeList(category);

    var selectList = new SelectList(
        codeList.Select(item => new SelectListItem {
            Value = item.Key.ToString(),
            Text = item.Value
        }),
        "Value",
        "Text"
    );
    return html.DropDownListFor(expr, selectList);
}

Remark: static methods such as CodeManager.GetCodeList are very bad in terms of unit testing your components in isolation.


text:
Q: Number of license plates formed by four digits and one letter, qualified. I need some help with this question:

If a license plate for a vehicle consist of five characters: $4$ digits (the first of
  which cannot be $0$), followed by one letter of the alphabet (which
  cannot be $I$ or $O$), how many different license plates are possible?

A: We have a license plate format:

*

*first digit from $\{1, 2, 3, 4, 5, 6, 7, 8, 9\}:\;$ 9 choices

*second, third, fourth digit from $\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9\}:\;$
10 choices, for each place.

*fifth position: one of 24 letters (26 letters of alphabet, minus the two distinct letters not allowed) gives 24 choices.

Using the rule of the product, that gives us:
$$9 \times 10 \times 10 \times 10 \times 24 = 9 \times 10^3 \times 24 = 216,000\;\text{license plates available}$$

A: The first condition means that you have to choose from the $9000$ numbers between $1000$ and $9999$. The second one, assuming that your alphabet contains $25$ characters, means that you the letter can be any of $23$ different ones. With no further restriction, the number of combinations is
$$9000 \cdot 23.$$
If you prefer, the first part you could also view as 4 separate digits, so that there are 9 combinations for the first one, and 10 for the remaining three, which nets you
$$9 \cdot 10 \cdot 10 \cdot 10 \cdot 23$$
total combinations.
Edit: Okay, after seeing the other answers and counting thrice, I now see how to arrive at $26$ letters instead of $25$ ...

A: Imagine there are $4$ slots: $A$, $B$, $C$ and $D$ for each of the four digits of the license plate.
For $A$: There are $9$ digits to choose from since $0$ is omitted. There are $26$ alphabets and omitting $I$ or $O$ leave you with $24$. So by the fundamental principle of counting you have: $(9)(24)$ ways of selecting a number or an alphabet for Slot $A$.
For Slot $B$: $10$ ways (because you can choose a number from the 10 digits)
For Slot $C$: $10$ ways
For Slot $D$: $10$ ways
So in total you have: $(9)(24)(10)(10)(10)=216,000$ possible license plates by the fundamental principle of counting.


text:
Q: Personal reference information / Note Taking As a habit, I typically use outlook to take notes. If I want to document something for myself, all I need to do is compose an email, send it to myself and then put an appropriate category onto it.
Outlook works great for this.

*

*I can search through and organize these 'notes' easily.

*I can embedded any sort of rich text with tables, images, or any other similar formatting.

However, my corporation is going to start deleting emails older than 18 months. Other than resending my emails to myself every 18 months (which I might end up doing).. How else could I keep track of this information?
Preferably a no-cost solution.
Caveats:

*

*This is property financial information notes. I can't put them on the
cloud.

*I don't have access to onenote.

A: Evernote seems to fit your requirements. You can even send email to it, which may work with your current workflow.
On the other hand, you can probably continue to keep using Outlook the way you do, just create a local archive/data file (.pst) and keep your notes in there. Most of the time when a company enacts a data retention policy like that, its for the server stored email. A local archive probably won't be touched.

A: I'm not sure if it applies to your specific situation, but your title and description immediately brought to mind a program I recently learned of which might fit the bill: Personal Historian.
It is something of a cross between a journal and a calendar and can organize events by date and supports embedding images and such because it uses HTML. It also has categories which can be used to organize the events/notes.
I don't see anything about emailing in the list of features, but you could easily request it.
It has a free version which might suffice if you don't need built-in spell-checking, text-to-speech, PDF export, etc.

A: Try CintaNotes:

*

*Has a usable free version;

*Can (and is designed to) work completely offline;

*Has instant full-text search;

*Can clip any text into a note on hotkey;

*Supports rich text (simple);

*Has powerful tagging system.

Disclaimer: I'm the author of the app, should you have any questions about it - I'll be glad to answer them!


text:
Q: AutoMapper with a complex EF Entity I have a basic table with a few  FK references. So when I retrieve an entity for an update operation; that entity contains ICollectionsof related entites. I also have a main ViewModel inside which each entity is a sub viewModel. My aim is to use Automapper like:
mapper.Map(MainViewmodel obj,MainEntity obj);

For this I have a MappingConfiguration like:
 CreateMap<MainViewModel, MainEntity>();
 CreateMap<subViewModel1, subEntity1>();
 CreateMap<subViewModel2, subEntity2>();

This gives me an Unmapped properties exception because the ICollections are not getting mapped. Could anyone please guide me on the best way to deal with this kind of situation?
thanks.

A: If I understand you correctly, you has classes like this:
class MainViewModel
{
    ICollection<SubViewModel1> SubViewModels { get;set; }
}

class SubViewModel1
{
}

and
class MainEntity
{
    ICollection<SubEntity1> SubEntities { get;set; }
}

class SubEntity1
{
}

Then you should create rules for each class, and collection of such classes automaper map automatically.
CreateMap<MainViewModel, MainEntity>();
CreateMap<SubViewModel1, SubEntity1>();

Addditions 1:

*

*Try this method: var mappedMainEntity = rmapper.Map<MainEntity>(MainViewmodel obj);

*If you map MainEntity to MainViewModel you need add .ReverseMap() to map rule, like this:
CreateMap().ReverseMap();
CreateMap().ReverseMap();
Additions 2:

*

*AutoMapper mapping public Properties only

*If the mapping Properties have different names, you need to use explicitly indicating how to map these Properties. Using ForMember method and MapFrom option. Example


text:
Q: Projecting a list of lists efficiently in F# I have to do projection of a list of lists which returns all combinations with each element from each list. For example:
projection([[1]; [2; 3]]) = [[1; 2]; [1; 3]].
projection([[1]; [2; 3]; [4; 5]]) = [[1; 2; 4]; [1; 2; 5]; [1; 3; 4]; [1; 3; 5]].

I come up with a function:
let projection lss0 =
    let rec projectionUtil lss accs =
        match lss with
        | []        ->  accs
        | ls::lss'  ->  projectionUtil lss' (List.fold (fun accs' l ->
                                                        accs' @ List.map (fun acc -> acc @ [l]) accs)
                                                        [] ls)
match lss0 with
| [] -> []
| ls::lss' ->
    projectionUtil lss' (List.map (fun l -> [l]) ls)

and a testcase:
#time "on";;
let N = 10
let fss0 = List.init N (fun i -> List.init (i+1) (fun j -> j+i*i+i));;
let fss1 = projection fss0;;

The function is quite slow now, with N = 10 it takes more than 10 seconds to complete. Moreover, I think the solution is unnatural because I have to breakdown the same list in two different ways. Any suggestion how I can improve performance and readability of the function?

A: This function is Haskell's sequence (although sequence is more generic). Translating to F#:
let sequence lss =
    let k l ls = [ for x in l do for xs in ls -> x::xs ]
    List.foldBack k lss [[]]

in interactive:
> test projection 10;;
Real: 00:00:12.240, CPU: 00:00:12.807, GC gen0: 163, gen1: 155, gen2: 4
val it : int = 3628800
> test sequence 10;;
Real: 00:00:06.038, CPU: 00:00:06.021, GC gen0: 75, gen1: 74, gen2: 0
val it : int = 3628800

General idea: avoid explicit recursion in favor to standard combinators (fold, map etc.)

A: Here's a tail-recursive version. It's not as fast as some of the other solutions (only 25% faster than your original function), but memory usage is constant, so it works for extremely large result sets.
let cartesian l =
  let rec aux f = function
    | [] -> f (Seq.singleton [])
    | h::t -> aux (fun acc -> f (Seq.collect (fun x -> (Seq.map (fun y -> y::x) h)) acc)) t
  aux id l

A: First of all, try to avoid list concatenation (@) whenever possible, since it's O(N) instead of O(1) prepend.
I'd start with a (relatively) easy to follow plan of how to compute the cartesian outer product of lists.

*

*Prepend each element of the first list to each sublist in the cartesian product of the remaining lists.

*Take care of the base case.

First version:
let rec cartesian = function
  | [] -> [[]]
  | L::Ls -> [for C in cartesian Ls do yield! [for x in L do yield x::C]]

This is the direct translation of the sentences above to code.
Now speed this up: instead of list comprehensions, use list concatenations and maps:
let rec cartesian2 = function
  | [] -> [[]]
  | L::Ls -> cartesian2 Ls |> List.collect (fun C -> L |> List.map (fun x->x::C))

This can be made faster still by computing the lists on demand via a sequence:
let rec cartesian3 = function
  | [] -> Seq.singleton []
  | L::Ls -> cartesian3 Ls |> Seq.collect (fun C -> L |> Seq.map (fun x->x::C))

This last form is what I use myself, since I most often just need to iterate over the results instead of having them all at once.
Some benchmarks on my machine:
Test code:
let test f N =
  let fss0 = List.init N (fun i -> List.init (i+1) (fun j -> j+i*i+i))
  f fss0 |> Seq.length

Results in FSI:
> test projection 10;;
Real: 00:00:18.066, CPU: 00:00:18.062, GC gen0: 168, gen1: 157, gen2: 7
val it : int = 3628800
> test cartesian 10;;
Real: 00:00:19.822, CPU: 00:00:19.828, GC gen0: 244, gen1: 121, gen2: 3
val it : int = 3628800
> test cartesian2 10;;
Real: 00:00:09.247, CPU: 00:00:09.250, GC gen0: 94, gen1: 52, gen2: 2
val it : int = 3628800
> test cartesian3 10;;
Real: 00:00:04.254, CPU: 00:00:04.250, GC gen0: 359, gen1: 1, gen2: 0
val it : int = 3628800

A: You implementation is slow because of the @ (i.e List concat) operation, which is a slow operation and it is being done many a times in recursive way. The reason for @ being slow is that List are Linked list in functional programming and to concat 2 list you have to first go till the end of the list (one by one traversing through elements) and then append another list .
Please look at the suggested references in comments. I hope those will help you out.

A: The following version is even faster than cartesian3, and uses basic features of functional programming (no fancy List.collect, Seq.collect...)
let cartesian xss =
    let rec add x yss s =
        match yss with
        | [] -> s
        | ys :: yss' -> add x yss' ((x :: ys) :: s)

    let rec mul xs yss p =
        match xs with
        | [] -> p
        | x :: xs' -> mul xs' yss (add x yss p)

    let rec cartesian xss c =
        match xss with
        | [] -> c
        | xs :: xss' -> cartesian xss' (mul xs c [])

    cartesian xss [ [] ]

Results
> test cartesian3 10;;
Real: 00:00:04.132, CPU: 00:00:04.109, GC Gen0: 482, Gen1: 2, Gen2: 1
val it: int = 3628800

> test cartesian 10;;
Real: 00:00:01.414, CPU: 00:00:01.406, GC Gen0: 27, Gen1: 16, Gen2: 2
val it: int = 3628800

> test cartesian3 11;;
Real: 00:00:45.652, CPU: 00:00:45.281, GC Gen0: 5299, Gen1: 5, Gen2: 1
val it: int = 39916800

> test cartesian 11;;
Real: 00:00:17.242, CPU: 00:00:16.812, GC Gen0: 260, Gen1: 174, Gen2: 6
val it: int = 39916800

The partition strategy used here is naive: the input list xss is separated into head and tail, I believe that a smarter strategy can give much better performance.
Edit: Another solution is of Christopher Strachey, which is explained in [1] (the observation is that the recursion on list can be expressed by folding):
let cartesianf xss =
    let f xs yss =
        let h x ys uss = (x :: ys) :: uss
        let g yss x zss = List.foldBack (h x) yss zss
        List.foldBack (g yss) xs []

    List.foldBack f xss [ [] ]

[1] Mike Spivey. Strachey's function pearl, forty years on.

A: let crossProduct listA listB listC listD listE =
  listA |> Seq.collect (fun a ->
  listB |> Seq.collect (fun b ->
  listC |> Seq.collect (fun c ->
  listD |> Seq.collect (fun d ->
  listE |> Seq.map (fun e -> a,b,c,d,e))


text:
Q: SQL DataReader in IronPython Please help me to read just one record from MS SQL table.
I tried to do that in the next way (IronPython 2.6 RC1):
cmd = SqlCommand("SELECT * FROM myTable", cn)
dr = cmd.ExecuteReader()

After that I have ALL the table in dr!
But  need only ONE record (more precise: read table records one by one)
...
Sorry!
I was wrong!
I forget about two more commands in my program:
    table=[]
    for row in dr: table.append(row)
So it turned out an equivalent to dr.Read()!...

A: Use TOP to restrict to one (random) record.
cmd = SqlCommand("SELECT TOP 1 * FROM myTable", cn)
dr=cmd.ExecuteReader()

Usually though when one is interested in a record, is interested in a specific record, like for example the one record with ID = 42.
TOP 1 will return the first record in the order the engine will choose to access the table.


text:
Q: what should be the offset width of the following so that is it should stop on the maxScroll I've tried to calculate the offset width, which i found to be bit higher for this case. Kindly calculate the offset width and let me know. And if there's any shorter and simpler way to find offset width let me know. Kindly have a glance at the cards i made.
Link is here: https://codepen.io/TA0011/pen/YzeRRrm
let currentScrollPosition = 0;
let scrollAmount = 320;

        const sCont = document.querySelector(".card-container");
        const hScroll = document.querySelector(".horizontal-scroll");

const btnScrollLeft = document.querySelector("#btn-scroll-left");
const btnScrollRight = document.querySelector("#btn-scroll-right");

btnScrollLeft.style.opacity = "0";

let maxScroll = -(sCont.offsetWidth + hScroll.offsetWidth);

function scrollHorizontally(val) {
  currentScrollPosition += val * scrollAmount;
  if(currentScrollPosition > 0){
    currentScrollPosition = 0
    btnScrollLeft.style.opacity = "0";
  }else{
    btnScrollLeft.style.opacity = "1";
  }
  if(currentScrollPosition <= maxScroll){
    currentScrollPosition = maxScroll;
    btnScrollRight.style.opacity = "0";
  }else{
    btnScrollRight.style.opacity = "1";
  }
  sCont.style.left = currentScrollPosition + "px";
}

.horizontal-scroll{
    overflow-x: hidden;
}
.card-container{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: row;
    flex-basis: 30%;
    width:calc(100% - 100px);
  position: absolute;

    gap: 10px;
  transition:  1s all ease-out;
}
.card-container .card{
    min-width: 280px;
    flex: 1;
    height: 200px;
    width: 100%;
    border: 1px solid #ccc;
    background: #fff;
  background: #00F260;  /* fallback for old browsers */
background: -webkit-linear-gradient(to bottom, #0575E6, #00F260);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to bottom, #0575E6, #00F260); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

    box-shadow: 2px 2px 6px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow:2px 2px 6px 0px rgba(0, 0, 0, 0.1);
    -moz-box-shadow:2px 2px 6px 0px rgba(0, 0, 0, 0.1);
  text-align:center;
 justify-content: space-between;
}
.card-container .card img{
    flex-wrap: wrap;
    pointer-events: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;

    width: 100%;
    float: none;
    display:block;
    object-fit: fill;
    height: 180px;
    }
/* btn */
.horizontal-scroll .btn-scroll{
    background: 0;
    border: 0;
    padding: 0 10px;
    z-index: 10;
    cursor: pointer;
    font-size: 40px;
    color: #007bff;
    transition:  all .2s linear;
    }
.horizontal-scroll .btn-scroll:hover{
    color: #ffffff;
    background-color: #007bff;
    border-radius: 10px;
}
.horizontal-scroll .btn-scroll:focus{
    outline: none;
    background-color:#007bff;
    color: rgba(255, 255, 255, 1.0);
    border-radius: 5px;
}
.horizontal-scroll #btn-scroll-left{
    position: absolute;
    left: 0;
    top: calc(200px/2);
}
.horizontal-scroll #btn-scroll-right{
    position: absolute;
    right: 0;
    top: calc(200px/2);
}

        <button class="btn-scroll" id="btn-scroll-left" onclick="scrollHorizontally(1)">
        </button>
        <button class="btn-scroll" id="btn-scroll-right" onclick="scrollHorizontally(-1)">
        </button>

                Card 1

                Card 2

                Card 3

                Card 4

                Card 5

                Card 1

                Card 2

                Card 3

                Card 4

                Card 5


text:
Q: How to extract a sub portion of a large video file I want to extract a small portion of video from a large video file on the basis of a given start and end time.
My internet search shows that many suggest using Xuggle to do this, but I am unfamiliar with this library, its use, or how one can use it to achieve my goals. Please help me with this.

A: try reading the manual!
-ss and -t    will start at ss and copy for '-t'...
ffmpeg -i test.mpg -r 25 -ss 00:00:10 -t 00:00:05 images%05d.png

starts 10 seconds in for 5 seconds


text:
Q: How can I pass struct(not a pointer to struct) to Win32API call in ruby? I am trying to pass structure to Win32API call in ruby.
How can I do this?
A structure is not a pointer. So I can't code like following:
require 'win32api'
get_std_handle = Win32API.new('kernel32.dll',"GetStdHandle",['I'],'I')
h = get_std_handle.call(-11) # STD_OUTPUT_HANDLE

# ['I','P'] is wrong. COORD is not a pointer. it's a structure.
set_console_cursor_position = Win32API.new('kernel32.dll',"SetConsoleCursorPosition",['I','P'],'I')
p = [10,10].pack('S*')
set_console_cursor_position.call(h,p)
puts "hello" # since above code is wrong, this will not printed at position 10,10

So the question is: How to pass structure (not a pointer) to Win32API call?

A: The folks at RubyDoc have listed code for the source of their Win32Console gem, which uses this, as
def SetConsoleCursorPosition( hConsoleOutput, col, row )
  @SetConsoleCursorPosition ||= Win32API.new( "kernel32", "SetConsoleCursorPosition", ['l', 'p'], 'l' )
  dwCursorPosition = (row << 16) + col
  @SetConsoleCursorPosition.call( hConsoleOutput, dwCursorPosition )
end

Reading How to pass structures as parameters to Win32API in Ruby (Array#pack and Array#unpack) may also shed some light for you.
Unfortunately I'm not sure about the answer to your follow-up comment, maybe you could ask that as another question, or someone that knows could add another answer or comment here or indeed, feel free to edit this answer to add that information.


text:
Q: What is the correct way to pass props to NavItem My code works but give an error so I just wanted to inform how I can prevent an error from showing up.
I'd like to learn how to write correct code.
This is what my code looks like now:

export const AuthenticatedNavigation = (props) => {
  const activeCity = props.activeCity;

  return (

        <LinkContainer to="beijing" >
          <NavItem eventKey={ 1 } href="">Chapter 1: Beijing</NavItem>
        </LinkContainer>
            <LinkContainer to="shanghai">
          <NavItem eventKey={ 2 } activeCity={props.activeCity} href="/shanghai">{activeCity}</NavItem>
        </LinkContainer>
            <LinkContainer to="chengdu">
          <NavItem eventKey={ 3 } href="/chengdu">Chapter 3: Chengdu</NavItem>
        </LinkContainer>

        <LinkContainer to="about">
          <NavItem eventKey={ 1 } href="/about">About</NavItem>
        </LinkContainer>
        <NavDropdown eventKey={ 2 } title={ userName() } id="basic-nav-dropdown">
          <MenuItem eventKey={ 2.1 } onClick={ handleLogout }>Logout</MenuItem>
        </NavDropdown>

)}

This is the error code I am getting:

modules.js:4689 Warning: Unknown prop `activeCity` on  tag. Remove this prop from the element. For details, see link
    in a (created by SafeAnchor)
    in SafeAnchor (created by NavItem)
    in li (created by NavItem)
    in NavItem (created by AuthenticatedNavigation)
    in LinkContainer (created by AuthenticatedNavigation)
    in ul (created by Nav)
    in Nav (created by AuthenticatedNavigation)
    in div (created by AuthenticatedNavigation)
    in AuthenticatedNavigation (created by AppNavigation)
    in div (created by NavbarCollapse)
    in Transition (created by Collapse)
    in Collapse (created by NavbarCollapse)
    in NavbarCollapse (created by AppNavigation)
    in div (created by Grid)
    in Grid (created by Navbar)
    in nav (created by Navbar)
    in Navbar (created by Uncontrolled(Navbar))
    in Uncontrolled(Navbar) (created by AppNavigation)
    in AppNavigation (created by Container(AppNavigation))
    in Container(AppNavigation) (created by App)
    in div (created by App)
    in App (created by RouterContext)
    in RouterContext (created by Router)
    in Router

As I said, it works, but I'd rather not have any errors ofcourse.
Cheers,
Dominic

A: In your NavItem component, you probably have something like:
render: function() {
    return {this.props.children};
}

In the latest versions of React, you can't pass props to DOM elements that aren't real attributes without a warning (https://facebook.github.io/react/docs/dom-elements.html#all-supported-html-attributes).
You could fix by doing the following:
render: function() {
    return {this.props.children};
}

A: To pass non-standard attributes through React, you must follow the HTML 5 convention of using the "data-" prefix and no camelCase. The following is allowed:
<NavItem eventKey={ 2 } data-active-city={activeCity} href="/shanghai">{activeCity}</NavItem>


text:
Q: Laravel 5 Failed opening required bootstrap/../vendor/autoload.php CentOs I have this painful issue in laravel with composer. Composer does not create the vendor folder. I've read every single post here in stackoverflow and other pages about this problem, and the solution always was that: I should install the composer in my project folder and update the composer or remove composer and install it again. I did all this suggestions, but nothing works.
When I want to generate php artisan key:generate it shows me this:

what can I do? what it's wrong?
Thank you.

A: It seems you had failed the installation. In my case, there was a php extension missing called php-xml. I'm using php 5.6 on centos so here is the command to install that missing package:
yum -y install php56w-xml.x86_64

After that, I can install laravel just fine.


text:
Q: Moving objects between hands Essentially, I'm trying to move an object between two "hands" that are currently fully functional. I can pick objects up and manipulate them both within the room space and rotationally.
However, the issue I'm having is transferring the object between the controllers.
I can hand over the object to the other hand, however if I let go of the trigger on the original hand, the object then becomes Non-Kinematic and drops back to the floor.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;

public class HandGrab : MonoBehaviour
{
    // Variable for Controller button register
    public string buttonName;

    // Allows objects to be transferred between hands
    public HandGrab secondaryHandRef;

    // Determines the referenced object type
    public XRNode nodeType;

    // This affects the distance of object grab from controller
    public Vector3 objectGrabOffset;

    // Default grab distance relative to the controller, (Where the collider sphere is) This can be changed to affect the visuals and where the items get manipulated from
    public float grabDistance = 0.1f;

    // Force at which an object is thrown
    public float throwingMultiplier = 1.5f;

    // To determine if object has been grabbed or cant be grabbed
    public string grabName = "Grabbing";

    // Stores the values of the currently grabbed object
    public Transform CurrentGrabObject
    {
        get { return _currentlyHeldObject; }
        set { _currentlyHeldObject = value; }
    }

    // Does as it says and stores the last frame and is used to work out velocity calculations
    private Vector3 _lastFramePosition;

    // Determines the transform values for the currently selected objects
    private Transform _currentlyHeldObject;

    // bolean to determine if an object is currently being held
    private bool _isHeld;

    // *Hopefully gets the roation of the controllers and matches that to the roation of the item*
    // *private Transform _objectRotation;*

    // Use this for initialization
    void Start()
    {
        // Clearing all variables back to zero
        _currentlyHeldObject = null;
        _lastFramePosition = transform.position;
        _isHeld = false;

        // Determining the tracking space available
        XRDevice.SetTrackingSpaceType(TrackingSpaceType.RoomScale);
    }

    // Update is called once per frame

    void Update()
    {
        // rotation and position tracking. Updates every frame, should be 90fps

        transform.localPosition = InputTracking.GetLocalPosition(nodeType);
        transform.localRotation = InputTracking.GetLocalRotation(nodeType);

        // Check the object in hand variable. If hand is empty, check to see if we can pick anything up (Object highlight posibilites)

        if (_currentlyHeldObject == null)
        {
            // Check to see if there are any colliders in the proximity of hands

            Collider[] colliders = Physics.OverlapSphere(transform.position, grabDistance);
            if (colliders.Length > 0)
            {
                // If there is a collision, then pickup the object if we press the grab button and give it the tag "Grabbing"

                if (Input.GetAxis(buttonName) >= 0.5F && colliders[0].transform.CompareTag(grabName))
                {
                    // Now we set to grabbing to true

                    if (_isHeld)
                    {
                        return;
                    }
                    _isHeld = true;

                    // Sets the current object to the object we have just picked up and binds it as a child object (this should allow all rotation to mimic the hands)

                    colliders[0].transform.SetParent(transform);

                    // If there is no RigidBody attached to the current object, then assign it a RigidBody variable

                    if (colliders[0].GetComponent<Rigidbody>() == null)
                    {
                        colliders[0].gameObject.AddComponent<Rigidbody>();
                    }

                    // Disable all physics on the grabbed object until it is released (May need to change if we want to enable objects to be swung and hit other "live objects")

                    colliders[0].GetComponent<Rigidbody>().isKinematic = true;

                    // Save the current object for a reference later

                    _currentlyHeldObject = colliders[0].transform;

                    // If other hand grabs the object, then release the object to be able to be re-parented above

                    if (secondaryHandRef.CurrentGrabObject != null)
                    {
                        secondaryHandRef.CurrentGrabObject = null;
                    }
                }
            }
        }
        else
        // We must now have an object in our hand at this point. We now update its current position to the current hand poistion + the offset definded above

        {
            //If we release the grab button, we drop the object here
            if (Input.GetAxis(buttonName) < 0.1f)
            {

                // Return the value of the object back to Non-Kinematic and re-enable physics
                Rigidbody _objectRB = _currentlyHeldObject.GetComponent<Rigidbody>();
                _objectRB.isKinematic = false;
                _objectRB.collisionDetectionMode = CollisionDetectionMode.Continuous;

                // Fun stuff starts here, we now calculate the hands current velocity
                Vector3 velocity = (transform.position - _lastFramePosition) / Time.deltaTime;

                // We now set that object velocity to the current velocity of the hand (I may adjust this to improve physics simulation)
                _objectRB.velocity = velocity * throwingMultiplier;

                // Kill the reference and revert the hands back to being empty and remove its parent
                _currentlyHeldObject.SetParent(null);
                _currentlyHeldObject = null;
            }
        }

        //Release the grab function
        if (Input.GetAxis(buttonName) < 0.5f && _isHeld)
        {
            _isHeld = false;
        }

        // Store the current position of the hand for velocity calculation in the upcoming frame
        _lastFramePosition = transform.position;

        //Tying off all loose ends here
    }
}

A: In your update function:
if (_currentlyHeldObject != null && !_currentlyHeldObject.GetComponent<Rigidbody>().isKinematic) {
    _currentlyHeldObject.GetComponent<Rigidbody>().isKinematic = true;
}


text:
Q: Replace all elements in vector with its ordinal number data frame:
#    V1    V2
1    abc   23
2    bcd   43
3    cde   54
4    def   10

How to replace V1 with its ordinal number?
#    V1    V2
1    1     23
2    2     43
3    3     54
4    4     10

A: Do you mean this?
# Original
dat <- structure(list(V1 = c("abc", "bcd", "cde", "def"), V2 = c(23L,
43L, 54L, 10L)), row.names = c(NA, -4L), class = "data.frame")
dat
  V1 V2
1 abc 23
2 bcd 43
3 cde 54
4 def 10

# Change V1 with numbers
dat$V1 <- 1:nrow(dat)
  V1 V2
1  1 23
2  2 43
3  3 54
4  4 10

A: We could use row_number() from dplyr:
library(dplyr)

df %>%
  mutate(V1 = row_number())

  V1 V2
1  1 23
2  2 43
3  3 54
4  4 10

A: Using data.table
library(data.table)
setDT(dat)[, V1 := .I]


text:
Q: ArcGIS python itertools.combinations There is following sample code combination 5C2.  I want to create all combinations 5C1 , 5C3 , 5C4 and 5C5.
list = [ 0,1,2,3,4 ]
5C1 means (0),(1),(2),(3),(4),(5)
5C2 means (0,1),(0,2),(0,3),..(1,2),(1,3),(1,4)..,(2,3),(2,4)
5C3 means (0,1,2),(0,1,3),(0,1,4),(0,1,5)..(1,2,3),(1,2,4)
5C4 means (0,1,2,3),(0,1,2,4),(0,1,2,5)..(1,2,3,4),(1,2,3,5)
5C5 means (0,1,2,3,4)

Please let me know your advice and comments.
import arcpy
import itertools

arcpy.env.workspace = r"C:\path\to\workspace"

base_shapefile = "some_shapefile.shp"

oid_field = arcpy.Describe(base_shapefile).OIDFieldName
feature_count = int(arcpy.GetCount_management(base_shapefile).getOutput(0))

for (i, j) in itertools.combinations(range(feature_count), 2):
    arcpy.Select_analysis(base_shapefile , "combination_%i_%i.shp" % (i, j), '"%s" in (%i, %i)' % (oid_field, i, j))

A: If I understand what you want to do, you want one new feature class per OID. I think that it would be more simple to take advantage of the string concatenation in Python. the first parameter of select analysis is your input, the second will be "combination5C1_0.shp, combination5C1_1.shp, ..., combination5C2_2.shp ..., the third will be, e.g., "FID" in (0,1) (with shapefile, FID is the default oid fiel name).
for i in (range(feature_count) +1):
    counter =0
    for x in itertools.combinations(range(feature_count), i):
        counter += 1
        arcpy.Select_analysis(base_shapefile , "combination5C" + str(i) + "_" + str(counter) +  ".shp",'"' + oid_field + '" in ' + str(x))

I use a counter here, because you cannot create more than one shp with the same name, and using the first value of your combination, as you did, may yield the same output name.
Note that with some geodatabase, the where clause should put the field names between [ ] and not between " "
Also, it is often not a good idea to make a large number of small shapefiles. You could use layers instead.
   arcpy.MakeFeatureLayer_management(base_shapefile , "combination5C" + str(i) + "_" + str(counter) ,'"' + oid_field + '" in ' + str(x))


text:
Q: MySQL load data infile from CSV (fields optionally enclosed by quotes, numbers have comma thousand separators) Sorry for the wordy title. I'm running the following query:
LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE tablename
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY ',\r\n'

I have a CSV with data in the following format:
1111, 2222, "32", "1,234.304", 1023.53,

All lines are terminated with an extra comma.
When attempting to load, I get an error when trying to put the "1,234.304" type field into a NUMERIC(12,4) column. I end up with 1.0000 and a warning that the data was truncated. I had expected 1234.304.
Edit: It seems that doing a regular insert for a value which has comma thousand-separators upsets MySQL. Is there a way to modify the load command for the desired behavior?

A: Break the problem down into two steps:

*

*Get the data into the database

*Get the data into the table/format you want it in

If you get all the data into a table with VARCHAR fields, you can easily manipulate it and explicitly convert the values into the types you want them in, rather than relying on whatever implicit conversion you get with LOAD DATA LOCAL INFILE.


text:
Q: Android CTS on 4.0.3 list device is showing device as unavailable I am trying to run CTS on Android 4.0.3. In the process i am facing following issue.
Cts-tf > list devices is showing my device state as unavailable. As per CTS manual, this means the device is not responding to adb commands. But the commands works just fine for me when i try to run them manually. I would like to know what all can be the possible cause of device being treated as unavailable. Also if someone can suggest me more pointer to debug the issue further.
Other information.

*

*I have verified that all the settings are done as discussed in CTS manual.

*I am connecting adb using ethernet ( adb connect IP_addr) and not usb.

*I am running cts on windows host ( in case this matters).

A: I encountered the same problem under Linux and found it is related to the environment variable ANDROID_SERIAL. If ANDROID_SERIAL is not set or is different from the serial of the device to be tested, the device will show up as "Unavailable"
This behavior doesn't make much sense, as CTS allows to distribute the tests on several devices (--shards) and also has an option to specify the serial number of the device to test


text:
Q: Prove that a set $E \subset R$ has non-measurable subsets if and only if $m∗(E)>0$
Prove that a set $E \subset R$ has non-measurable subsets  if and only if $m*(E)>0$

I dont know how to define what is a non measurable set, i read a little about vitali set, but don't understand how to use this to solve the problem.

A: Suppose that $E$ has a non-measurable subset and then suppose for a contradiction that $m^{*}(E)=0$. It follows that $m_{*}(E)=0$ where $m_{*}$ is inner measure and consequently, $E$ is measurable with $m(E)=0$. Finally, Lebesgue measure is complete so $F\subset E\implies F$ is measurable and $m(F)=0$ and, in particular, this contradicts the fact that $E$ is supposed to have a non-measurable subset.
If $m^{*}(E)>0$, then you can use Vitali set construction to build a non-measurable set.


text:
Q: Java - Spring(HSql + Rest) - date time format in the POST vs HSQL database I am trying to build a very minimalistic rest application in spring with HSQL in memory database.
I have a date column in one entity. I am able to POST messages through the rest endpoint and fill in the database. I can also GET messages. When I try to GET messages using a search findByDate I am not getting any results back.
If I do a GET localhost:8080/weather to the web server endpoint, I get the following output
{
    "_embedded": {
        "weather": [
            {
                "city": "Amsterdam",
                "date": "2019-01-30T00:00:00.000+0000",
                "unit": "celcius",
                "lowTemp": "-5",
                "highTemp": "3",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/weather/1"
                    },
                    "weather": {
                        "href": "http://localhost:8080/weather/1"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/weather{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/profile/weather"
        },
        "search": {
            "href": "http://localhost:8080/weather/search"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 1,
        "totalPages": 1,
        "number": 0
    }
}

But when I go a GET localhost:8080/weather/search/findByDate?date=2019-01-30T00:00:00.000+0000 I get unparsable date error.
I tried many different date time formats in my GET request. Nothing worked.
2019-01-30T00:00:00.000+0000
2019-01-30'T'00:00:00.000+0000

Can someone help me with the right format to use?

A: tl;dr
OffsetDateTime
.parse(
    "2019-01-30T00:00:00.000+0000".replace( "+0000" , "+00:00" )
)

…and…
OffsetDateTime.now( ZoneOffset.UTC ).toString()

See this code run live at IdeOne.com.

2019-01-27T02:11:42.754Z

The Z on the end means UTC, as a shortcut for +00:00. Commonly used in date-time work. Specified in the ISO 8601 standard. Pronounced "Zulu".
details
Your Question does not provide enough detail for a definitive solution. But this might get you headed in the right direction.
The time-of-day in your date-time happens to be 00:00. So I suspect you want a date-only value rather than a moment (without time-of-day and without time zone or offset-from-UTC). If so, use LocalDate object in Java, and use standard ISO 8601 format in text of the format YYYY-MM-DD.
ZoneID z = ZoneId.of( "Pacific/Auckland" ) ;
LocalDate ld = LocalDate.now( z ) ;
String output = ld.toString() ;

You can parse such a string. The java.time classes use the standard ISO 8601 formats by default, so no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2019-01-30" ) ;

If you want to parse a moment in the format of your example, parse as a OffsetDateTime. Unfortunately, your input omitted the optional colon character in the offset, and the OffsetDateTime class has a small bug in parsing without the colon. So do a search-and-replace to make +0000 into 00:00.
String input = 2019-01-30T00:00:00.000+0000".replace( "+0000" , "+00:00" ) ;
OffsetDateTime odt = OffsetDateTime.parse( input ) ;