text:
Q: "Non-analytic interaction"...what does it mean? Reading an article about Hamiltonian chaos, I found this passage:

Importantly, the few Hamiltonian systems for which the KAM theorem
does not apply, and for which one can prove ergodicity and the
approach to thermal equilibrium, involve "hard spheres" and
consequently contain non-analytic interactions that are not realistic
from a physicist's perspective.

What does the expression non-analytic interactions mean in this context?

A: An analytic function is one that has a power series expansion that actually converges to the function in the region of interest.  A non analytic interaction is one in which the interparticle potential $V(x-x')$ does not have this property.  For example $V(r-r')= 1/|r-r'|$ is analytic in any region in which $|r-r'|>a$ for some positive number $a$ (i.e the particles do not collide). A potential such that $V(r-r')=0$ for $|r-r'|>a$ and infinity for $|r-r'|\le a$ (hard sphere) is non-analytic.


text:
Q: Can we change the visibility setting of a custom setting in managed package I have a managed package which uses a custom setting.
But this is not visible once the package was loaded into the org. Based on some google search i came to know that this would not be available if the visibilty setting is protected.
This package is released package and not Beta, its just been tested out in a demo org and not installed in any other external org. When i try to change the setting in the dev env. the option for changing visibility is disabled.
How can i change the visibility of the setting?
Thanks

A: The short answer is no. Once a component is packaged it is unable to be changed.
All the information about Packaging can be found here
It is possible for Salesforce to roll back a managed package from final to beta, but there are strict conditions, the package can not be installed in any orgs. So it sounds like you are in luck, uninstall it from the demo org and log a case with Salesforce.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does good power curve or bad power curve for some hypothesis tests look like? What does the most ideal power curve look like?
What does the worst power curve look like?
Does there exist good power curves or bad power curves?
Obviously there exists more powerful and less powerful hypothesis tests. I'm not sure whether looking at their power curves is useful for ranking their power.
Example of power curve

A: I recognize that image!
[Since that hint was apparently overly subtle, you should - in accordance with the stackexchange rules - credit the person who created it and link to where you got it from. Since it was originally posted here on stackexchange, it should not be too difficult to figure out who to credit.]
High power is better whenever the null is false, so at a fixed significance level, the steeper the curve rises toward 1 (where it would always reject), the better, and the shallower, the worse it is (the more often you fail to reject when you should).
Here's a sequence of power curves for a two tailed symmetric test, like a two-tailed t-test, say.

The  flatter curves (which are red-orange in the plot, apart from the totally flat one in grey) are relatively poor -- power is comparatively low while the steeper (bluer) ones are relatively good - power jumps up very near 1 as soon as the difference moves a little distance from the null value.
For a one tailed test you want the rejection rate to not exceed the significance level on the part where the alternative doesn't hold (rejection rate $\leq \alpha$) and then on the part where the alternative does hold, for it to rise as rapidly as possible toward 1.
Ideally, in whichever case, you reject when the null is false, so you would like power to be at 1 everywhere the null is false. This is usually not attainable in practice.

For some situations, there may be a uniformly most powerful test; in particular you might like to read about the Karlin-Rubin theorem. In such a case, for a given set of assumptions and sample size there may be a "best" power curve you can attain under those assumptions across a sequence of alternatives (though you can do better by increasing the sample size).
Even when there isn't a single "best" test, you can compare different tests under some particular sequence of alternatives.
For example, there's plots showing some comparisons of different tests in specific situations (both in question and answer) in this question How to graph Wilcoxon test power R

It is sometimes the case that a power curve dips below the significance level when the alternative is true; in particular this is the case with some omnibus-alternative tests (like goodness of fit tests). Such tests are said to be biased.


text:
Q: Chrome Extension - Message Passing to batch file I used the sample project
https://developer.chrome.com/extensions/samples
I am able to run the python native app.
Is there  any way to get the message within native-messaging-example-host.bat
I don't want to load python script
What I want to do here is
send message from chrome {text: "xyz.bat"}
and the batch file should run START xyz.bat

A: You should not approach this problem from the batch file standpoint, as in lieu of my solution, it requires the program to be run upfront, which in most applications is depreciated in favor of running it in the background. However if you still want to know how you could potentially do it in batch...
If you can pass the message to a blank html page (not currently sure how you can or want to do it this way), where the only thing on that html page is your runme.bat we can run a program that would copy the page, open a text file and paste it inside, close the text file, and run the batch with input from it. So code wise,
@if (@CodeSection == @Batch) @then
@echo off
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem below copys everything on the page, and closes it
%SendKeys% "{TAB}"
%SendKeys% "^{A}"
%SendKeys% "^{C}"
%SendKeys% "^{W}"

rem open text file,wait for it load, paste clipboard, save and exit

start newreadforme.txt
timeout /nobreak /t 5
%SendKeys% "^{V}"
%SendKeys% "^{S}"
timeout /nobreak /t 2
%SendKeys% "^{W}"
start program.bat
goto :EOF
@end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

then in your batch file
@echo off
set /p x=<newreadforme.txt
start %x%

This code will run simulated keystrokes on the opened page to copy its contents and relay to a text file to be referenced from another batchfile.  But you should only use this method as a last resort as this approach is a TERRIBLE way to solve your problem. My code requires you to keep the webpages open and upfront and make sure no one interferes with the program during its execution. So if a user is using the computer the time its running, then they may accidentally mess with the inputs.
On top of that, already you need to be modifying webpages to achieve your end result so you probably should use a language that supports html to filesystem operations. Nodejs can provide a nice interface between the file system and html pages that you may decide to pass. How you handle the webpage filled with the message i am not sure of but you should most certainly avoid using batch to do what you ask in favor of more html friendly languages


text:
Q: How do I use bind_rows in a list of table? Suppose I have three tables as below:
table1 <- structure(list(Pos = 1:6, A = c(16.8508287292818, 0, 0.552486187845304,
0, 1.10497237569061, 1.38121546961326), C = c(1.93370165745856,
0.276243093922652, 0.828729281767956, 0.276243093922652, 0, 0.552486187845304
), G = c(1.10497237569061, 2.48618784530387, 0.276243093922652,
0.828729281767956, 0.276243093922652, 0), T = c(0.828729281767956,
0, 0.828729281767956, 1.10497237569061, 0, 0)), .Names = c("Pos",
"A", "C", "G", "T"), row.names = c(NA, 6L), class = "data.frame")

table2<- structure(list(Pos = 1:6, A = c(4.15584415584416, 1.03896103896104,
0.779220779220779, 0.692640692640693, 2.25108225108225, 2.94372294372294
), C = c(1.12554112554113, 0.173160173160173, 0.173160173160173,
0.519480519480519, 0.173160173160173, 0.173160173160173), G = c(1.03896103896104,
0.346320346320346, 0.0865800865800866, 0.432900432900433, 0.519480519480519,
0.0865800865800866), T = c(2.77056277056277, 0.606060606060606,
0.25974025974026, 0.692640692640693, 0.346320346320346, 0.25974025974026
)), .Names = c("Pos", "A", "C", "G", "T"), row.names = c(NA,
6L), class = "data.frame")
table3 <- structure(list(Pos = 1:6, A = c(10.3492063492063, 0.317460317460317,
0.349206349206349, 0.920634920634921, 1.96825396825397, 1.23809523809524
), C = c(0.825396825396825, 0.126984126984127, 0.349206349206349,
0.317460317460317, 0.19047619047619, 0.253968253968254), G = c(0.761904761904762,
0.952380952380952, 0.285714285714286, 0.412698412698413, 0.126984126984127,
0.19047619047619), T = c(1.07936507936508, 0.412698412698413,
0.476190476190476, 0.253968253968254, 0.19047619047619, 0.253968253968254
)), .Names = c("Pos", "A", "C", "G", "T"), row.names = c(NA,
6L), class = "data.frame")

I have now saved the table names as files.table:
files.table <- paste0("table", seq(1:3))

My problem is that I could not run this bind_rows function to bind table1, table2 and table3 using files.table instead of listing all three tables. This is the error I get: Error in bind_rows_(x, .id) : Argument 1 must have names
This is the code I tried:
bind.table <- bind_rows(files.table, .id = "table") %>%
      gather(Base, Percent, -Pos, -table)

A: The .id argument for bind_rows sets the name of the variable containing the name of the list item each row came from, not these names themselves. You set the table names by naming the items in the list. Then, bind_rows will get those names and put them into a column with a name you specify:
table_list <- list(table1, table2, table3)
names(table_list) <- paste0("table", seq(1:3))
bind.table <- bind_rows(table_list, .id = 'id')

From ?bind_rows:

Each argument can either be a data frame, a list that could be a data
  frame, or a list of data frames

The easiest way to get the data frames into bind_rows is to assemble them into a list and then just pass the list of data frames in. As @joran suggests, the easiest way to do this is to load or generate them in a lapply function which will automatically output a list that can go into bind_rows.


text:
Q: How to install safari extension for Selenium 2.53 with Safari browser I've been following wiki to setup safari extension for Selenium 2.48.0:
This works mostly, but occasionally getting some weird errors in my tests scripts (that are written in Ruby/Capybara) like:
Selenium::WebDriver::Error::NoSuchElementError:
       Selenium::WebDriver::Error::NoSuchElementError
     # /Users/admin/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.53.0/lib/selenium/webdriver/common/search_context.rb:64:in `rescue in find_element'
     # /Users/admin/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.53.0/lib/selenium/webdriver/common/search_context.rb:55:in `find_element'
     # ./lib/about.rb:94:in `click_read_more_work'
     # ./spec/check_about_links.rb:91:in `block (3 levels) in <top (required)>'
     # ------------------
     # --- Caused by: ---
     # IO::EAGAINWaitReadable:
     #   Resource temporarily unavailable - read would block
     #   /Users/admin/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.53.0/lib/selenium/webdriver/safari/server.rb:63:in `read_nonblock'

and:
Selenium::WebDriver::Error::UnknownError:
       Session is executing: findElements; cannot set current to: findElements
     # /Users/admin/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.53.0/lib/selenium/webdriver/safari/bridge.rb:88:in `raw_execute'
     # /Users/admin/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.53.0/lib/selenium/webdriver/remote/bridge.rb:627:in `execute'
     # /Users/admin/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.53.0/lib/selenium/webdriver/remote/bridge.rb:606:in `find_elements_by'
     # /Users/admin/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.53.0/lib/selenium/webdriver/common/search_context.rb:84:in `find_elements'

Capybara is referred to the latest version of selenium webdriver gem: 2.53.0 but from my understanding of above's article, safari extension from Selenium 2.53.0 needs to exist in Safari browser as well.
This download link does not contain separate safari extension file:
in contrast to version 2.48.0 which does:
http://selenium-release.storage.googleapis.com/index.html?path=2.48/
Is there something changed in the installing safari extension and am I missing something?
Note: Safari version is 9.1.1
Thanks in advance,

A: Due to security changes in the past few years, you must manually install the Safari WebDriver extension on each target machine while logged in locally.
You cannot automate this step.
It must be a copy that has been built and code signed by a registered paid developer account since the last change in January of 2016.
Generally this means you should build it yourself.
Without this, it won't work.
It is worth noting the extension has had no official code changes in about two years.
It is also worth noting that Apple quietly announced Safari 10 to have a native SafariDriver, as part of the W3C WebDriver draft RFC requiring all browsers to provide the WebDriver portion of Selenium WebDriver.

A: Safari support in Selenium is far from being complete and working correctly. Also not every version of Selenium has changes in Safari driver that's why you should use the latest available version which is for the moment 2.48 and resides in respective directory of Selenium releases website.


text:
Q: HTML to PHP navigation bar I got this navigation bar and i dont know how to convert it from HTML to PHP. Can somone help me?
The HTML is

Home

RPG

Sports

Strategy

Android/IOS

Nice to try

I'm just beginner in PHP and im trying to learn the code, i searched it up on google but i couldnt figure out how to apply it to my code.
Thank you in advance!

A: Just use echo to print html tags:
<?php
echo '

Home

RPG

Sports

Strategy

Android/IOS

Nice to try

';
?>

For make a dynamic ul li see this links:
https://stackoverflow.com/a/5581200/4540183
https://stackoverflow.com/a/17638336/4540183

A: After pedram's straight-forward answer, now let's get introduced to looping...
<?php

/**
 * Hold Menu links and labels inside $menuLinks array
 **/
$menuLinks = [
'index.php?pg=' => 'Home',
'rpg.php?pg=' => 'RPG',
'sports.php?pg=' => 'Sports',
'strategy.php?pg=' => 'Strategy',
'android_ios.php?pg=' => 'Android/IOS',
'nice_to_try.php?pg=' => 'Nice to try'
];
/**
 * Introduce $menuLiList for storing
...
 html.
 **/
$menuLiList = null;
/**
 * Introduce $i counter
 **/
$i = 1;
/**
 * inside foreach loop, take each link and label and build html
 **/
foreach($menuLinks as $link => $label){
    /**
     * if $i is 1, add current class to the li, i.e. add current class to the first element.
     **/
    $current = $i == 1 ? 'class="current"' : '';
    /**
     * append html
     **/
    $menuLiList .= '
'.$label.'
';
    /**
     * increase counter.
     **/
    $i++;
}
/**
 * Finally, echo what you have in list, plus the outer wrapper.
 **/
echo '

        '.$menuLiList.'

';

Is it needed? Not really in your case, but this should be a good example how programming languages ease our daily-life problems.  Logic may vary greatly depending on you you need. Update your question for a better answer.

A: You don't really convert it...
At the end of the day, PHP outputs a HTML file in browser.
You can have mixed HTML, Javascript, PHP in your code. The browser can understand all of them. Just use correct tags.
Just use echo.
Echo prints out your HTML code.
Will be like
<?php
echo '

Home

RPG

Sports

Strategy

Android/IOS

Nice to try

';
?>

See your code as a quotation.


text:
Q: How can I set the font and the colour for a Button's text in Tkinter? This is my code below, The button's background is green, but I want to set the button text ("Done") to be white and 12 font.
from tkinter import *

def done(root):
  root.destroy()

def panel():
  root = Tk()
  root.title("PCS Employee Login")
  root.geometry('240x320+0+0')
  root.configure(bg='white')

  buttonDone = Button(root, text="Done", command=lambda: done(root))
  buttonDone.configure(bg='green', borderwidth=0)
  buttonDone.pack()

  root.mainloop()

if __name__ == '__main__':
  panel()

A: A Button's background is the button itself, and its foreground is the text or bitmap on top of it. Use the foreground option as described on Effbot.

A: This is an extract of code that I used for creating buttons and labels in tkinter. I create three font variables detailing small, normal and large font, then call these variables as needed. For the button and lable colours you can use bg for the background colour and fg for the foreground (text) colour.
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)

label = tk.Label(popup, text=msg, font=NORM_FONT, bg='white', justify='left')
B1 = tk.Button(popup, text="Okay", command=popup.destroy, bg='#000000', fg='#ffffff')

This page will give you more options for button configuration.


text:
Q: PyCharm shows "PEP8: expected 2 blank lines, found 1" Consider the following code:
def add_function(a, b):
    c = str(a) + b
    print "c is %s" % c

def add_int_function(c, d):
    e = c + d
    print "the vaule of e is %d" % e

if __name__ =="__main__":
    add_function(59906, 'kugrt5')
    add_int_function(1, 2)

It always shows me: "expected 2 blank lines ,found 1" in aadd_int_function, but not in the add_function.
When I add two spaces in front of the def add_int_function(c, d):
there is a error shows unindent does not match any outer indentation level
in the end of add_function:

A: This is a pretty common question within the python community. After the release of PEP 8, new formatting styles were accepted into python. One of them states that after the definition of a class or function there must be two lines separating them. As such:
    def yadayada:
     print("two lines between the functions")

    def secondyadayada:
     print("this is the proper formatting")

So, you should never do it like:
    def yadayada:
     print("two lines between the functions")

    def secondyadayada:
     print("this is the proper formatting")

Or else PyCharm will throw that error at you.

A: Just add another line between your function definitions :
1 line :

2 lines:

A: Further clarification on @kennet-celeste & @shreyshrey 's answers,
Each function or class defined requires 2 spaces above and 2 spaces below. Unless the function is the last item in the script, in which the expected format is one blank line as an End of File marker. So:
# some code followed by 2 blank spaces

def function1():

def function2():

def function3():

A: For people who wonders why it requires two blank lines
if you were to write in other languages it would be:
fun doSth() {
    print()
}

fun doSth1() {
    print()
}

but if you were to delete all the curly braces from the code you will see:
two blank lines between methods
fun doSth()
    print()
#
#
fun doSth1()
    print()
#


text:
Q: How do I remove an input field after it's being emptied I am adding input fields on keystroke, by using an example from the answer for this question. This is my example. I was trying in various ways to remove field if user deletes content from it, so that there are always fields that have some content and one last empty field for adding more, but I just can't find a solution.
This is the code:
$(document.body).on("input", ".external-media-input:last", function () {
    var inputID = (parseInt($(this).attr('id')) + 1);
    $(".input_fields_wrap").append('
<input class="external-media-input" id="' + inputID + '" name="external_media[]" type="text"/>
');
});

A: You can use on('blur') or .on('focusout')
//...
.on('blur', ".external-media-input:not(:last)", function () {
    if(!$(this).val()) $(this).remove();
});

JSFiddle

A: You can use also on('keyup')
$(document.body).on("keyup", ".external-media-input", function(){
    if($(this).val() == '')
       $(this).remove();
});

here is your fiddle: https://jsfiddle.net/bembvptx/2/

A: In your style add one more event:
$(document.body).on("input", ".external-media-input", function () {
  if (!$(this).val())
  {
   $(this).remove();
  }
});


text:
Q: Cannot re-enter a color once a image has been chosen JS My website currently changes background colour when a user enters there desired color, although I am trying to allow my user to enter in a desired keyword that will change the background to the image designated with that word. For example, if the user inputs 'tree' the background will change to trees, I am doing this for only a few keywords and I'm using if statements to change the background.
The problem is when a user inputs one of these keywords such as 'tree' they are unable to change the background colour again and are stuck on the background of trees. I want the user to be able to re-input a colour and the background will change to the input.
Video of the bug (Streamable)
Live link (Codepen)
HTML
<input type="text" name="userinput" class="userinputclass" id="textinput" placeholder='Enter Your color/hex/rgb here...' onkeypress="process(event, this)" />
<input type="button" value="Change Color" onclick="changeColor();"/>

JS
function process(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13) { //Enter keycode
    changeColor();
  }
}
function changeColor() {
  var input = document.getElementById('textinput').value;
  document.body.style.backgroundColor = input;

  if (input == '') {
    document.body.style.backgroundColor = rand;
  }
  if (input == 'tree') {
    document.body.style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg')";
  }
}

A: you're setting 2 different properties 'backgroundColor' and 'backgroundImage'.
What I think you're missing is that a set 'backgroundImage' property will override any 'backgroundColor' property.
You should be able to set 'backgroundImage' back to '' or null and then the 'backgroundColor' should be visible again.
try adding something like:
document.body.style.backgroundImage = null;

to the top of your changeColor function to make sure that it is always reset.

A: Setting null for background for any entry that don't match with 'tree' will solve your problem. You will be able to enter value for color again.
if (input == 'tree') {
    document.body.style.backgroundImage = "url('...')";
} else {
    document.body.style.backgroundImage = null;
}

A: You are not deleting the background image once the tree image is set.
  function changeColor() {
      var input = document.getElementById('textinput').value;
        document.body.style.backgroundImage = null;
        document.body.style.backgroundColor = null;
       if (input == 'tree') {
          document.body.style.backgroundImage =
                 "url(keep ur link)";
           } else {
            document.body.style.backgroundColor = input;
        }
       }


text:
Q: How to exit after response in nodejs with express? This is my first time asking a question on stackoverflow. Sorry if I made posting mistakes.
I am trying to exit a function after sending a response to prevent continuing through the function.
node -v = v12.6.0
express = ^4.17.1
mongoose = ^5.6.6
// handle adding a new book request submission
        addNewBook: function (req, res) {
            var response = null;
            var name = req.body.name.toLowerCase();
            var url = req.body.url.toLowerCase();
            var category = req.body.category.toLowerCase();
            var tags = req.body.tags.toLowerCase();
            // checking if category already exist. if not, make a new category
            Category.find({label: category}).exec(function(err, data) {
                if(err) {
                    response = res.status(400).send({message:'Error finding category.'});
                } else if(data.length === 0) {
                    var newCategory = new Category({label: category, description: '', keywords: ''});
                    newCategory.save(function(err, data){
                        if(err) {
                            response = res.status(400).send({message:'Error saving new category.'});
                        }
                    })
                }
            });
            // checking if book name already exist
            Book.find({name: name}).exec(function(err, data){
                if(err) {
                    response = res.status(400).send({message:'Error validating Book existence'});
                } else if(data.length > 0) {
                    response = res.status(200).send({message:'book name already exist'});
                } else {
                    req.body.name = name;
                    req.body.url = url;
                    req.body.category = category;
                    req.body.tags = tags;
                    // make a new book document
                    var newBook = new Book(req.body);
                    newBook.save(function (err, data) {
                        if (err) {
                            response = res.status(400).send({message: 'Error saving new Book.'});
                        } else {
                            response = res.json(data);
                        }
                    })
                }
            });

            return response;

        },

Function continues to executes other part of the function code after a return.
I am also getting "Cannot set headers after they are sent to the client" error on node. Im guessing, preventing the function to continue after sending a response will fix this as well?
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

A: The error is as a result of your condition. Hence, both code blocks are run resulting in the response being sent twice. To fix this change your code to this below.
Category.find({label: category}).exec(function(err, data) {
    if(err) {
        res.status(400).send({message: 'Error finding category.'});
    } else if(data.length>0) {
       //there is no data with that label - Hence, create one
       var newCategory = new Category({label: category, description: '', keywords: ''});
        newCategory.save(function(err, data){
            if(err) {
                //if error
                res.status(400).send({message: 'Error saving new category.'});
            }else{
                //if item saves
                res.status(200).send({message: 'Item saved'});
            }
        })
    }else{
      //there is a data with that label availble - do something else
        res.status(200).send(data)
    }
});

A: There are two problems with the flow of your logic. First is that return only returns a function. It does not return the function that calls a function or the function that defines a function.
Basically, your code is:
Category.find({label: category}).exec(function(err, data) {
    if(err) {
        // ...
        return;
    } else if(/* ... */) {
        // ...
        newCategory.save(function(err, data){
            if(err) {
                // ...
                return;
            }
        })
    }
});

moreStuffDownHere();

// ...

Let's rewrite that to not use anonymous functions to make it clear what's really happening
function findCallback (err, data) {
    if(err) {
        // ...
        return; // it's obvious that this returns form findCallback()
                // and NOT yourFunction()
    } else if(/* ... */) {
        // ...
        newCategory.save(saveCallback);
    }
}

function saveCallback (err, data) {
    if(err) {
        // ...
        return;
    }
}

function yourFunction () {
    Category.find({label: category}).exec(findCallback);

    moreStuffDownHere();
}

So you can now see that you are not calling return anywhere in yourFunction().
The second problem is that Category.find().exec() is asynchronous. This means it returns immediately and let any code below it run before calling findCallback(). To solve the async issue just move moreStuffDownHere() inside findCallback().
Therefore, the simplest change to get your program flow working is to move moreStuffDownHere:
Category.find({label: category}).exec(function(err, data) {
if(err) {
        res.status(400).send({message: 'Error finding category.'});
        return;
    } else if(data.length === 0) {
        var newCategory = new Category({label: category, description: '', keywords: ''});
        newCategory.save(function(err, data){
            if(err) {
                res.status(400).send({message: 'Error saving new category.'});
                return;
            }

            // More stuff down here, that now will only execute if there are no errors
        })
    }
});

Improve program flow
One issue I have with the solution above is that now moreStuffDownHere is hardcoded inside the save callback. One way around it is to refactor the entire operation and make it your own internal API:
function addNewCategory (category, callback) {
    // callback will be passed status depending on success or failure

    Category.find({label: category}).exec(function(err, data) {
        if(err) {
            // ...
            callback('FIND_FAILURE');
            return;
        } else if(/* ... */) {
            // ...
            newCategory.save(function(err, data){
                if(err) {
                // ...
                    callback('SAVE_FAILURE');
                    return;
                }
                callback('OK');
            })
        }
    });
}

Now inside yourFunction() you can check the result of the entire operation and decide to return or continue:
function yourFunction() {
    // ...

    addNewCategory(category, function (status) {
        switch (status) {
            case 'FIND_FAILURE':
                res.status(400).send({message: 'Error finding category.'});
                return;
            case 'SAVE_FAILURE':
                res.status(400).send({message: 'Error saving new category.'});
                return;
        }

        // More stuff down here ...
    });
}

Improvement 2 - Promises
It's possible to make the program flow much easier to read by using Promises along with async/await. For that you need to wrap the operation in a promise. We can use the addNewCategory function we wrote above as an example:
function addNewCategory (category) {
    // returns a Promise of true/false

    return new Promise(function (resolve, reject) {
      Category.find({label: category}).exec(function(err, data) {
        if(err) {
            // ...
            resolve('FIND_FAILURE'); // you can also use reject if you want
                                     // to use a try/catch flow
            return;
        } else if(/* ... */) {
            // ...
            newCategory.save(function(err, data){
                if(err) {
                // ...
                    resolve('SAVE_FAILURE');
                    return;
                }
                resolve('OK');
            })
        }
      });
   });
}

Now the code is slightly easier to follow because it allows you to keep moreStuffDownHere where you originally have it without moving it inside another function:
async function yourFunction() {
    // ...

    var status = await addNewCategory(category);
    switch (status) {
        case 'FIND_FAILURE':
            res.status(400).send({message: 'Error finding category.'});
            return;
        case 'SAVE_FAILURE':
            res.status(400).send({message: 'Error saving new category.'});
            return;
    }

    // More stuff down here ...
}

Note: Express accepts functions marked as async as routes/middlewares. You just need to call res.send() or next() as usual

A: The error you report happens when there are code paths that can send a response more than once.  You get one and only one response per request.  So, calling res.send() more than once is one way that you get that error.
Preventing this when you have a number of asynchronous operations requires a bit more work as you have to make sure that all your code is properly sequenced and all error paths are properly terminated (so further processing doesn't happen).  In general, this code is a lot easier to write using promise-based interfaces for your asynchronous operations, but since you aren't using the promise interface on your database, I'll show how you can do it with your existing callback interface.  In generally, it involves a lot of nesting inside of asynchronous callbacks and very careful if/else and return around conditionals and errors.
Your code is subject to this error because you are running Category.find() and Book.find() in parallel.  You don't wait for the Category.find() code to finish before doing the book operations.  If the category code causes an error, you will send that error response, but still continue with the book code which will then send its response.  Instead, you need to make sure that if there's an error with the category stuff that you don't run the book code at all.  For the plain callback interface on your database, that means nesting the book code inside a callback from the category code.  To make this simpler to write, I put the category code into it's own function that has one completion callback that we can use to know when its all done.
Here's one way to do it:
    // utility function to create category if needed, requires callback
    // to communicate results
    function createCategoryIfNeeded(category, fn) {
        // checking if category already exist. if not, make a new category
        Category.find({label: category}).exec(function(err, data) {
            if(err) {
                fn({message:'Error finding category.'});
            } else if(data.length === 0) {
                let newCategory = new Category({label: category, description: '', keywords: ''});
                newCategory.save(function(err, data){
                    if (err) {
                        fn({message:'Error saving new category.'});
                    } else {
                        // category created
                        fn(null, true);
                    }
                })
            } else {
                // category already exists
                fn(null, false);
            }
        });
    }

    // handle adding a new book request submission
    addNewBook: function (req, res) {
        var name = req.body.name.toLowerCase();
        var url = req.body.url.toLowerCase();
        var category = req.body.category.toLowerCase();
        var tags = req.body.tags.toLowerCase();

        createCategoryIfNeeded(category, function(err, created) {
            if (err) {
                res.status(400).send(err);
            } else {
                // checking if book name already exist
                Book.find({name: name}).exec(function(err, data){
                    if(err) {
                        res.status(400).send({message:'Error validating Book existence'});
                    } else if(data.length > 0) {
                        res.status(200).send({message:'book name already exist'});
                    } else {
                        req.body.name = name;
                        req.body.url = url;
                        req.body.category = category;
                        req.body.tags = tags;
                        // make a new book document
                        var newBook = new Book(req.body);
                        newBook.save(function (err, data) {
                            if (err) {
                                res.status(400).send({message: 'Error saving new Book.'});
                            } else {
                                res.json(data);
                            }
                        });
                    }
                });

            }
        });
    },

A: The error meassage says that, res can be send once it has been send. So returning it along with the response.
Category.find({label: category}).exec(function(err, data) {
    if(err) {
        return res.status(400).send({message: 'Error finding category.'});

    } else if(!data) {
        var newCategory = new Category({label: category, description: '', keywords: ''});
        newCategory.save(function(err, data){
            if(err) {
                return res.status(400).send({message: 'Error saving new category.'});
            }
        })
    }
});


text:
Q: Enable and disable button when text is entered in textInput or removed in react native I want to make button enabled when something is typed in text field and it should get disabled when value in the text field is removed.
But currently when i type in the text field the the button gets activated but when i remove the text it remains enabled and doesn't update it's state.
What should i do?
My code:
import React, { Component } from 'react';
import { StyleSheet, View, Text, TouchableHighlight,TextInput,TouchableOpacity, ImageBackground,Button } from 'react-native';
import { createStackNavigator, createAppContainer } from "react-navigation";

class App extends Component {

  state={
    username:'',
    password:'',
    validity:true
  }

  static navigationOptions={
    header:null
  };
render() {
    return (

     <View style={styles.container}>

      <View style={{marginLeft:50,marginTop:30}}>
       <TextInput
         style={styles.textInputStyle}
         placeholderTextColor="#FFF"
         placeholder='Username'
         onChangeText={(value)=>this.setState({username:value,validity:false})}
         value={this.state.username}
          />
       <TextInput
         style={styles.textInputStyle}
         placeholderTextColor="#FFF"
         placeholder='Password'
         secureTextEntry={true}
         onChangeText={(value)=>this.setState({password:value,validity:false})}
         value={this.state.password}
          />
       </View>

       <View style={{alignSelf:'center'}} >

        <TouchableOpacity style={this.state.validity?
             styles.inactiveStyle:styles.activeStyle}
             disabled={this.state.validity}
             onPress={this.handleLogin}>
         <Text>Login</Text>
        </TouchableOpacity>
       </View>
        </View>
    )
  }
}

const AppNavigator = createStackNavigator(
  {
    Home: App,
  },
  {
    initialRouteName: "Home",
    defaultNavigationOptions:{
      header:null
    }
  }
);
const styles = StyleSheet.create({
  container:{
    flex:1,
  },
  textInputStyle:{
    height:50,
    width:300,
    borderBottomWidth:1,
    borderBottomColor:'#FFF',
    marginTop:20,
    color:'#FFF'
  },
  activeStyle:{
    marginTop:18,
    width:180,
    backgroundColor:'#05acfa',
    alignItems: 'center',
    padding: 10
  },
  inactiveStyle:{
    marginTop:18,
    width:180,
    backgroundColor:'grey',
    alignItems: 'center',
    padding: 10
  }
});

export default createAppContainer(AppNavigator);

A: If we talking about disable in case when one of field is empty better change disable prop logic. So you don't need additional variable, and logic will be clear
disabled={!Boolean(this.state.username && this.state.password)}

so if any of field is empty you will get true
in your case
import React, { Component } from 'react';
import { StyleSheet, View, Text, TouchableHighlight,TextInput,TouchableOpacity, ImageBackground,Button } from 'react-native';
import { createStackNavigator, createAppContainer } from "react-navigation";

class App extends Component {

  state={
    username:'',
    password:'',
    validity:true
  }

  static navigationOptions={
    header:null
  };
render() {
    return (

     <View style={styles.container}>

      <View style={{marginLeft:50,marginTop:30}}>
       <TextInput
         style={styles.textInputStyle}
         placeholderTextColor="#FFF"
         placeholder='Username'
         onChangeText={(value)=>this.setState({username:value,validity:false})}
         value={this.state.username}
          />
       <TextInput
         style={styles.textInputStyle}
         placeholderTextColor="#FFF"
         placeholder='Password'
         secureTextEntry={true}
         onChangeText={(value)=>this.setState({password:value,validity:false})}
         value={this.state.password}
          />
       </View>

       <View style={{alignSelf:'center'}} >

        <TouchableOpacity style={this.state.validity?
             styles.inactiveStyle:styles.activeStyle}
             disabled={!Boolean(this.state.username && this.state.password)}
             onPress={this.handleLogin}>
         <Text>Login</Text>
        </TouchableOpacity>
       </View>
        </View>
    )
  }
}

const AppNavigator = createStackNavigator(
  {
    Home: App,
  },
  {
    initialRouteName: "Home",
    defaultNavigationOptions:{
      header:null
    }
  }
);
const styles = StyleSheet.create({
  container:{
    flex:1,
  },
  textInputStyle:{
    height:50,
    width:300,
    borderBottomWidth:1,
    borderBottomColor:'#FFF',
    marginTop:20,
    color:'#FFF'
  },
  activeStyle:{
    marginTop:18,
    width:180,
    backgroundColor:'#05acfa',
    alignItems: 'center',
    padding: 10
  },
  inactiveStyle:{
    marginTop:18,
    width:180,
    backgroundColor:'grey',
    alignItems: 'center',
    padding: 10
  }
});

export default createAppContainer(AppNavigator);

A: I'm assuming you want the button to be disabled when the value is an empty string. In your onChangeText callback check if the value is "" and then update the state to disable the button.
onChangeText={(value) => {
if (value === "")
   this.setState({password:value, validity:true})}
else
   this.setState({password:value, validity:false})}
}

A: You should update the state of disabled in your TouchableOpacity component. See here


text:
Q: how to pass an input value in R Studio in this case? If I run my code in this case, it works, known that the input is yet not passed.
the code simply makes dataframe out of a  data.csv.
this datframe has many the following columns  code , vaccinationsTotal , peopleFirstTotal , peopleFullTotal , peopleBoosterTotal
and what I am trying to do is just select the column through the input$sel
library(shiny)
library(dplyr)
library(ggplot2)
library(magrittr)

library(readr)
dataf <- read_csv("data.csv")

server <- function(input, output, session) {
 #Summarize Data and then Plot
data <- reactive({
    req(input$sel)
     df <- dataf %>%  group_by(code) %>% summarise(vaccinationsTotal)
    print(df)
  })

  #Plot
  output$plot <- renderPlot({

    g <- ggplot(data(), aes( y = vaccinationsTotal  ,x = code) )
    g + geom_bar( stat = "sum")

  })
}

ui <- basicPage(

  selectInput(inputId = "sel",
              label = "eine möglichkeit auswählen",

               list("vaccinationsTotal","peopleFirstTotal","peopleFullTotal","peopleBoosterTotal")),

   plotOutput("plot")
)

shinyApp(ui = ui, server = server)

if I run my code after replacing  summarise(vaccinationsTotal)  with  summarise(input$sel)  it shows me the  ylim  just with one value which is vaccinationsTotal

 df <- dataf %>%  group_by(code) %>% summarise(vaccinationsTotal)
    print(df)
  })

  #Plot
  output$plot <- renderPlot({

    g <- ggplot(data(), aes( y = vaccinationsTotal  ,x = code) )
    g + geom_bar( stat = "sum")

How can I pass an input variable in this case ?
I spent days trying things.

A: You have made 3 mistakes in your code.

*

*You are passing input$sel to summarise. What you need to pass is get(input$sel).

*The other thing is when you summarise the data in R, it uses the column name of the data that you are summarising. So, in your case, while plotting the data, you need to pass the same column name to the y-axis of the ggplot.
Or you can just rename the column while summarising it. Like this:
summarise(output = get(input$sel))

*Now, you just need to change the variable name that you are passing, to the name variable name that you used while renaming in summarise function.

server <- function(input, output, session) {
  #Summarize Data and then Plot
  data <- reactive({
    req(input$sel)
    df <- dataf %>%
      group_by(code) %>%
      summarise(output = get(input$sel))
    print(df)
  })

  #Plot
  output$plot <- renderPlot({
    g <- ggplot(data(), aes(y = output, x = code) )
    g + geom_bar( stat = "sum")

  })
}

Please note that doing this will show output as your y-axis label. Although you can tweak it inside the ggplot function.


text:
Q: sed regex find and replace in file (macOS) I am having some trouble using sed to replace lines in files.
What i want is to switch out all occurrences of #include <path/to/my/file.h> with #include "file.h" using regex.
when I test it with echo it gives me the output I'm looking for:
echo "#include <path/to/my/file.h>" | sed -E 's/^(#include.*[\/<])([^\/\<]*\.h)(>)$/#include \"\2\"/g'

But when I run it with a file containing #includes, it changes nothing. I feel like I have tried everything I can find online and nothing makes any difference
Here is the line I use when I try changing lines in a file:
sed -E -i '' 's/^(#include.*[\/<])([^\/\<]*\.h)(>)$/#include \"\2\"/g' /path/to/my/file.h

edit:
Fixed by removing ^ and $ at the begining and end of the regex statement

A: Based on: In-place edits with sed on OS X
Note that MacOS does not support '-i' with NO suffix (a.k.a 'edit in place'). Per referenced question, try using a temporary suffix (.orig in this example)
sed -E -i '.orig' 's/^(#include.*[\/<])([^\/\<]*\.h)(>)$/#include \"\2\"/g' /path/to/my/file.h
rm -f /path/to/my/file.h.orig

A: Try this simple sed replacement:
echo "#include <path/to/my/file.h>" |sed -r 's|<[^>]+file.h>|"file.h"|'

output
#include "file.h"

explanation:
sed -r use sed with extended RegExp
's|source-pattern|target-pattern| substitue command use | as separator (instead of normal /)
<[^>]+file.h> RegExp matching <[any char not >](more than once)file.h>
"file.h" Target RegExp match.

A: It seems the line-beginning or line-ending anchors in OPs regex were not matching ... possibly because the source file did not follow the MacOS standard on line endings.  MacOS (prior to OS X) uses \r while Windows uses \r\n and linux and OS X uses only \n.  So, once OP removed the line-beginning or line-ending anchors in the regex, their expression matched and the replacement happened.
OPs regex without line begin/end anchors:
sed -E 's/(#include.*[\/<])([^\/\<]*\.h)(>)/#include \"\2\"/g'

The risk is that if there are other lines with #include <path/to/some/file.h> in them, those lines will also be replaced when they shouldn't.  That's not too likely though.
One way the OP could tell if that might be the problem is to send some samples of text with and without the problem lines to a hexdump or octal dump program.  We know that the output of echo '#include <path/to/my/file.h>' does not have any weird newlines in it (because sed with the line ending anchors worked on it), and we can examine what it does have for line endings with:
echo '#include <path/to/my/file.h>' | od -cx

And we can compare those line endings to the ones in:
cat afi.h | od -cx | head -30


text:
Q: ReactJS material-ui adding a style to an HTML tag element I have a reactjs file which loads an Icon from material-ui
import LocalHospital from "@material-ui/icons/LocalHospital";

Then in another part of the page, I am using the icon inside another HTML tag
    <div className={classes.features}>
      <GridContainer>
        <GridItem md={4} sm={4}>
          <InfoArea
            title="Addressing Crucial Diseases"
            description="Thermo analyser products aiming to solve severe problems whihc have real and crucial implications on human lives."
            icon={Accessible}
            iconColor="danger"
            vertical={true}
          />
        </GridItem>
        <GridItem md={4} sm={4}>
          <InfoArea
            title="Novel and Reliable Approaches"
            description="Thermo analyser employs novel and sophisticated apporches to effectively diagnose major diseases in reliable and acurate way."
            icon={<LocalHospital style={{ fill: "green" }} />}
            iconColor="transparent"
            vertical={true}
          />
        </GridItem>
        <GridItem md={4} sm={4}>
          <InfoArea
            title="Effective and Accurate Results"
            description="Our products are scientifically proven softwares which have been developed by proficient experts in the field. They have achived an accuracy of at least %98 in our test use-cases."
            icon={Healing}
            iconColor="success"
            vertical={true}
          />
        </GridItem>
      </GridContainer>

The problem is that I need to change the style of LocalHospital Icon in the JS file for example adig the below style to the Icon
style={{"fill": "green"}}

But I am not sure how to programmatically do it in the reactjs file?
per the comment, I edited my tags but that yet doesn't work..
  <InfoArea
    title="Novel and Reliable Approaches"
    description="Thermo analyser employs novel and sophisitcated apporches to effectively diagnose major diseases in reliable and acurate way."
    icon={() => <LocalHospital style={{ fill: "green" }}
    iconColor="transparent"
    vertical={true}
  />

It gave me below error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `InfoArea`.
▶ 20 stack frames were collapsed.
Module../src/index.js
C:/ThermoAnalyser/material-kit-pro-react-v1.9.0/src/index.js:46
  43 |
  44 | var hist = createBrowserHistory();
  45 |
> 46 | ReactDOM.render(
  47 |   <Router history={hist}>
  48 |     <Switch>
  49 |       <Route path="/about-us" component={AboutUsPage} />

A: To change styling of icon you don't need arrow function inside, it can be done just like that
  <InfoArea
    title="Novel and Reliable Approaches"
    description="Thermo analyser employs novel and sophisitcated apporches to effectively diagnose major diseases in reliable and acurate way."
    icon={<LocalHospital style={{ fill: "green" }} />}
    iconColor="transparent"
    vertical={true}
  />


text:
Q: How browser cache determine that request is same or not? I understand that the browser save the response, to return quickly at next same request.
But the question here is, what is same request? Does it mean that same resource uri  in the case of Get request?
What about the values of headers included in the request or the content of the body?
I've seen that the Cache-Control header is also used for Post requests.
If so, is the standard for the same Post request determined by comparing the contents of the body?

A: RFC 7234 defines the cache key:

The primary cache key consists of the request method and target URI....
If a request target is subject to content negotiation, its cache
entry might consist of multiple stored responses, each differentiated
by a secondary key for the values of the original request's selecting
header fields.

The secondary key uses the headers listed in the Vary response header. See section 4.1 for more detail.

When a cache receives a request that can be satisfied by a stored
response that has a Vary header field,
it MUST NOT use that response unless all of the selecting header
fields nominated by the Vary header field match in both the original
request (i.e., that associated with the stored response), and the
presented request.

To answer your specific questions:

But the question here is, what is the same request? Does it mean the same resource URI in the case of a GET request?

Yes.

What about the values of headers included in the request or the content of the body?

The content of the body doesn't matter, and the headers only matter if they're listed in the Vary header.

I've seen that the Cache-Control header is also used for POST requests. If so, is the standard for the same Post request determined by comparing the contents of the body?

Since the primary cache key consists of the URI and the method, two POST requests will have the same key if they have the same URI. However, as the standard notes, "since HTTP caches in common use today are typically limited
to caching responses to GET, many caches simply decline other methods
and use only the URI as the primary cache key."


text:
Q: SQLAlchemy: Avoid re-loading large objects from database after merge I have a Blob model to store large binary object in the (SQLite) database, addressable by their hash:
class Blob(Base):
    __tablename__ = 'blobs'
    hash = Column(String, primary_key=True)
    data = Column(LargeBinary)

    def __init__(self, data):
        self.hash = _hash(data) #  a function to calculate hash from the data
        self.data = data

I would like to avoid savings the objects to the database if they are already there, essentially making Blob.data a content-addressable piece of information.
With a naive approach,
b1 = Blob('This is a test')
session.add(b1)
session.commit()

b2 = Blob('This is a test')
session.add(b2)
session.commit()

I will get a UNIQUE constrained failed exception after the second commit, which is expected.
If I replace add with merge instead, I don't have this exception, as the second commit does nothing
b1 = Blob('This is a test')
session.merge(b1)
session.commit()

b2 = Blob('This is a test')
session.merge(b2)
session.commit()

however I get an expensive SELECT after session.merge(b2):
2020-11-01 22:03:51,579 INFO sqlalchemy.engine.base.Engine SELECT blobs.hash AS blobs_hash, blobs.data AS blobs_data
FROM blobs
WHERE blobs.hash = ?

Here blobs.data is requested from the database, and I would like to avoid that as I know that b2.data is the same as b1.data (they have the same hash, b1.hash == b2.hash); imagine that blobs.data is a gigabyte-size object.
I tried to make data a deferred field:
data = column_property(Column(LargeBinary), deferred=True)

and with that, session.merge(b2) generate a small select:
2020-11-01 21:53:21,774 INFO sqlalchemy.engine.base.Engine SELECT blobs.hash AS blobs_hash
FROM blobs
WHERE blobs.hash = ?
2020-11-01 21:53:21,774 INFO sqlalchemy.engine.base.Engine ('qz78diGV8TjV31akJUBfHZUopUX5iC7rnHIUhQ==',)

however, the second commit generates an UPDATE to the database:
2020-11-01 21:53:21,775 INFO sqlalchemy.engine.base.Engine UPDATE blobs SET data=? WHERE blobs.hash = ?
2020-11-01 21:53:21,775 INFO sqlalchemy.engine.base.Engine (<memory at 0x10931b640>, 'qz78diGV8TjV31akJUBfHZUopUX5iC7rnHIUhQ==')
2020-11-01 21:53:21,775 INFO sqlalchemy.engine.base.Engine COMMIT

which is sending unnecessary large data into the opposite direction.
What's the right strategy here to avoid sending large objects over the network that I know already exist in the database, and just update the state of the session object?

A: Ok, after spending a few hours poring over Using the Session section, here is the answer that seems to work:

*

*Make Blob.data a deferred property:

class Blob(Base):
    __tablename__ = 'blobs'
    hash = Column(String, primary_key=True)
    data = column_property(Column(LargeBinary), deferred=True)

    def __init__(self, data):
        self.hash = _hash(data)
        self.data = data

*Add a hook on before_flush event to remove all dirty Blob objects:

@event.listens_for(Session, 'before_flush')
def ignore_dirty_blob_objects(session, flush_context, instances):
    for obj in session.dirty:
        if isinstance(obj, Blob):
            session.expunge(obj)

*Always use Session.merge for adding objects to the session:

engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session.configure(bind=engine)

session = Session()

b1 = Blob('This is a test')
session.merge(b1)
session.commit()

b2 = Blob('This is a test')
session.merge(b2)
session.commit()

produces the following SQL statements. Notice that there is only one INSERT, and blobs.data is never selected from the DB:
2020-11-02 01:42:49,752 INFO sqlalchemy.engine.base.Engine SELECT blobs.hash AS blobs_hash
FROM blobs
WHERE blobs.hash = ?
2020-11-02 01:42:49,752 INFO sqlalchemy.engine.base.Engine ('qz78diGV8TjV31akJUBfHZUopUX5iC7rnHIUhQ==',)
2020-11-02 01:42:49,753 INFO sqlalchemy.engine.base.Engine INSERT INTO blobs (hash, data) VALUES (?, ?)
2020-11-02 01:42:49,753 INFO sqlalchemy.engine.base.Engine ('qz78diGV8TjV31akJUBfHZUopUX5iC7rnHIUhQ==', <memory at 0x108a56400>)
2020-11-02 01:42:49,753 INFO sqlalchemy.engine.base.Engine COMMIT
2020-11-02 01:42:49,754 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2020-11-02 01:42:49,754 INFO sqlalchemy.engine.base.Engine SELECT blobs.hash AS blobs_hash
FROM blobs
WHERE blobs.hash = ?
2020-11-02 01:42:49,754 INFO sqlalchemy.engine.base.Engine ('qz78diGV8TjV31akJUBfHZUopUX5iC7rnHIUhQ==',)
2020-11-02 01:42:49,754 INFO sqlalchemy.engine.base.Engine COMMIT


text:
Q: How to display digit always with two decimal places - Angularjs I want to display digit always with two decimal values.
I can display values with two decimal values.
$scope.value1 = 10000;
$scope.value2 = 12444.44443;

In controller I used
$scope.value1 = $scope.value1.toFixed(2);
$scope.value2 = $scope.value2.toFixed(2);

Then in HTML, I can display as "10000.00" "12444.44". But its changing my model value also. I don't want to change the value. I want to display value only as "1000.00" "12444.44".
Even I tried as
{{value1 | setDecimal : 2 }}
{{value2 | setDecimal : 2 }}

It displays as
10000
12444.44

This setDecimal changes only my decimal value.
I want to display like setDecimal but need to display 10000 also as 10000.00.

A: You can use the number filter as a pipe in your template to achieve this:

angular.module('app', []).controller('MyCtrl', ['$scope', function($scope) {
  $scope.value1 = 10000;
  $scope.value2 = 12444.44443;
}]);

{{ value1 | number: 2 }}

{{ value2 | number: 2 }}

A: Please see the code output. And I think this Documents is really helpful

 {{12342 | number: 2}}

A: value.toFixed(2)

should give what you need

A: use toFixed(2) method for fixing it to two
Demo
parseFloat(Math.round(num3 * 100) / 100).toFixed(2);


text:
Q: .NET Correct Task use I am new to .NET Tasks and async coding so I would just like to know what I should do in my case:
I have a .NET Core WebApi that receives a XML file, which acts as the trigger for the following process:

*

*I need the process to run in the "background", so what I mean is the API caller should get a response immediatly and the process should then run

*I need to parse the XML to an object

*With this data, I need to contact 3 APIs

*If any of this APIs do not respond or fails to retrieve the needed data, we need to stop and log this

*If all of the data is retrieved, I need to do a calculation with this data (get some data from a database and calculate with the API & database data)

*When calculation is done, I need to send an email and contact another API
7. And the most important: Am I safe with this, due to the AppRecycle ?
This was just to explain my situation, so what I have is the following:
[HttpPost]
public async Task<JsonResult> DepositAsync([FromBody] Taa message){
try
{
    Api1Response api1Response = await this.GetApiData1();
    Api1Response api2Response = await this.GetApiData2();

    // If all of this was successful, do the calculation
    CalculationResult result = await this.CalculateAsync(api1Response, api2Response);

    // Notify
    await Notify(result);
}
catch (Exception ex)
{
    Log.Error($"Something went wrong: {ex.Message}", ex);
    throw;
}

return new JsonResult(new ApiResponse<string>(requestId.ToString(), Response, StatusCodes.Status200OK) { Data = "Success" });
}

The question that I have now:

*

*When do I need to use Task.Run(() => {}); Inside of the GetApiData1(), GetApiData2() methods, to do the Http call ?

*Do I need call teh GetApi methods inside a Task.Run(() => {}); ?

*In general, when do I need to use Task.Run and when not ?

Or do I just need to do this:
[HttpPost]
public async Task<JsonResult> DepositAsync([FromBody] Taa message){
try
{
    Task.Run(() => {
        Api1Response api1Response = await this.GetApiData1();
        Api1Response api2Response = await this.GetApiData2();

        // If all of this was successful, do the calculation
        CalculationResult result = await this.CalculateAsync(api1Response, api2Response);

        // Notify
        await Notify(result);
    });
}
catch (Exception ex)
{
    Log.Error($"Something went wrong: {ex.Message}", ex);
    throw;
}

return new JsonResult(new ApiResponse<string>(requestId.ToString(), Response, StatusCodes.Status200OK) { Data = "Success" });
}

Many thanks!

A: It's correct that you can use Task.Run without await to "offload" some work to another thread from the ThreadPool. While doing that, your request's response time will not be affected by the work which is done inside of it.
However, any exception which happens inside of that function will not be thrown to the caller thread (since call is not awaited). That effectively means your try-catch block will only catch exceptions which happen when new Task is created (by Task.Run method). In other words, it will not catch any error which happens while processing lambda passed to the Task.Run method.
So, in your case the second approach would be correct (with mentioned downsides above).
In addition,  IIS will wait for running threads to finish and exit on recycling, limited by the timeout set on the thread pool. So, if execution is larger than the timeout, thread will be forcibly killed.
Lastly, in .Net Core new type of services are introduced, they are called Hosted services and implement IHostedService. They are built to support these kind of long running background tasks. You can get familiar with them via official documentation, and that would be my recommendation to use.


text:
Q: R/XML parsing: weird value For some reason sometimes the return value of xmlToList does not correspond to the input in an obvious way:
> library('XML')
> xmlToList(xmlTreeParse('<?xml version="1.0" encoding="UTF-8"?>
<a type="List of Filter(s)">
  <b topic="foo" id="1">
    <c topic="bar" id="2">
      <d topic="baz" id="3">
      </d>
    </c>
  </b>
</a>'))
[[1]]
[1] "baz"

[[2]]
[1] "3"

[[3]]
topic    id
"bar"   "2"

[[4]]
topic    id
"foo"   "1"

$.attrs
               type
"List of Filter(s)"

Where are my element names a..d?
Why does the data come in the reversed order?
Why is d treated differently from b and c?

R version 3.0.1 (2013-05-16) -- "Good Sport"
  Package: XML
  Version: 3.98-1.1


text:
Q: why application proxies examine data in the packet? in Packet Filtering as we know : every packet has header and data
and we know thats : Packet filters examine only the header of the packet , because it contains IP source and destination addresses.
my question is why application proxies examine data in the packet?
thanks alot.

A: Because it's a proxy.  A proxy makes a separate request to the server the request is intended for.  It has to know what is being requested which is in the body of the packet, not the headers.
If you want something that doesn't look inside the packets, use sNAT.  By definition a proxy has to look inside.


text:
Q: How to edit lotus notes multilingual database scripts I have a database with 2 languages in it but Designer only shows one of the 2 database scripts regardless of my client's regional settings...  I always see the same database script.
How to switch languages so the database script can be edited in the other language?
I have an English client.  The database is English and french.  I have set my client's regional settings to french as well as the default language in the DB, and restarted the client.... no luck...
Thanks


text:
Q: Azure Synapse Analytics - column load with high length I have a column which contains description and has length around 80000(contains unicode characters). I am unable to load it to Azure Synapse Analytics. Datatype defined in Synapse is nvarchar.
We are using Azure Databricks. I tried options with maxStrLength (.option('maxStrLength', 4000)), but the max value for this is 4000. So, I am getting this error.
: com.databricks.spark.sqldw.SqlDWSideException: Azure Synapse Analytics failed to execute the JDBC query produced by the connector.
Underlying SQLException(s):

*

*com.microsoft.sqlserver.jdbc.SQLServerException: HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: HadoopSqlException: String or binary data would be truncated. [ErrorCode = 107090] [SQLState = S0001]

Could you please let me know if there any way to solve this issue?
Update - The issue is resolved by removing .option('maxStrLength', 4000) while writing the dataframe into Synapse and declaring the target datatype as nvarchar(max)

A: You can store up to 1 billion 2-byte Unicode characters by using nvarchar [ ( n | max ) ].

Variable-length Unicode string data. n defines the string length and
can be a value from 1 through 4,000. max indicates that the maximum
storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is
two times the actual length of data entered + 2 bytes. The ISO
synonyms for nvarchar are national char varying and national character
varying.

You can refer the related SO threads mentioned below:
How does SQL Server store more than 4000 characters in NVARCHAR(max)?
SQL query variable nvarchar(max) can not store more than 4000 characters


text:
Q: Angular 2: How to mock ChangeDetectorRef while unit testing I have just started with Unit-Testing, and I have been able to mock my own services and some of Angular and Ionic as well, but no matter what I do ChangeDetectorRef stays the same.
I mean which kind of sorcery is this?
beforeEach(async(() =>
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [
        Form, DomController, ToastController, AlertController,
        PopoverController,

        {provide: Platform, useClass: PlatformMock},
        {
          provide: NavParams,
          useValue: new NavParams({data: new PageData().Data})
        },
        {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock}

      ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        IonicModule
      ],
    })
    .overrideComponent(MyComponent, {
      set: {
        providers: [
          {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
        ],
        viewProviders: [
          {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
        ]
      }
    })
    .compileComponents()
    .then(() => {
      let fixture = TestBed.createComponent(MyComponent);
      let cmp = fixture.debugElement.componentInstance;

      let cdRef = fixture.debugElement.injector.get(ChangeDetectorRef);

      console.log(cdRef); // logs ChangeDetectorRefMock
      console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
    })
  ));

 it('fails no matter what', async(() => {
    spyOn(cdRef, 'markForCheck');
    spyOn(cmp.cdRef, 'markForCheck');

    cmp.ngOnInit();

    expect(cdRef.markForCheck).toHaveBeenCalled();  // fail, why ??
    expect(cmp.cdRef.markForCheck).toHaveBeenCalled(); // success

    console.log(cdRef); // logs ChangeDetectorRefMock
    console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
  }));

@Component({
  ...
})
export class MyComponent {
 constructor(private cdRef: ChangeDetectorRef){}

 ngOnInit() {
   // do something
   this.cdRef.markForCheck();
 }
}

I have tried everything , async, fakeAsync, injector([ChangeDetectorRef], () => {}).
Nothing works.

A: Not sure if this a new thing or not, but changeDetectorRef can be accessed via fixture.
See docs: https://angular.io/guide/testing#componentfixture-properties
We ran into the same issue with change detector mocking and this is ended up being the solution

A: Update 2020:
I wrote this originally in May 2017, it's a solution that worked great at the time and still works.
We can't configure the injection of a changeDetectorRef mock through the test bed, so this is what I am doing these days:
 it('detects changes', () => {
      // This is a unique instance here, brand new
      const changeDetectorRef = fixture.debugElement.injector.get(ChangeDetectorRef);

      // So, I am spying directly on the prototype.
      const detectChangesSpy = spyOn(changeDetectorRef.constructor.prototype, 'detectChanges');

      component.someMethod(); // Which internally calls the detectChanges.

      expect(detectChangesSpy).toHaveBeenCalled();
    });

Then you don't care about private attributes or any.

In case anyone runs into this, this is one way that has worked well for me:
As you are injecting the ChangeDetectorRef instance in your constructor:
 constructor(private cdRef: ChangeDetectorRef) { }

You have that cdRef as one of the private attributes on the component, which means you can spy on the component, stub that attribute and have it return whatever you want. Also, you can assert its calls and parameters, as needed.
In your spec file, call your TestBed without providing the ChangeDetectorRef as it won't provide what you give it. Set the component that same beforeEach block, so it is reset between specs as it is done in the docs here:
component = fixture.componentInstance;

Then in the tests, spy directly on the attribute
describe('someMethod()', () => {
  it('calls detect changes', () => {
    const spy = spyOn((component as any).cdRef, 'detectChanges');
    component.someMethod();

    expect(spy).toHaveBeenCalled();
  });
});

With the spy you can use .and.returnValue() and have it return whatever you need.
Notice that  (component as any) is used as cdRef is a private attribute. But private doesn't exist in the actual compiled javascript so it is accessible.
It is up to you if you want to access private attributes at runtime that way for your tests.

A: Probably one point that needs to be pointed out, is that in essence here you want to test your own code, not unit test the change detector itself (which was tested by the Angular team).
In my opinion this is a good indicator that you should extract the call to the change detector to a local private method (private as it is something you don't want to unit test), e.g.
private detectChanges(): void {
    this.cdRef.detectChanges();
}

Then, in your unit test, you will want to verify that your code actually called this function, and thus called the method from the ChangeDetectorRef. For example:
it('should call the change detector',
    () => {
        const spyCDR = spyOn((cmp as any).cdRef, 'detectChanges' as any);
        cmp.ngOnInit();
        expect(spyCDR).toHaveBeenCalled();
    }
);

I had the exact same situation, and this was suggested to me as a general best practice for unit testing from a senior dev who told me that unit testing is actually forcing you by this pattern to structure your code better. With the proposed restructuring, you make sure your code is flexible to change, e.g. if Angular changes the way they provide us with change detection, then you will only have to adapt the detectChanges method.

A: For unit testing, if you are mocking ChangeDetectorRef just to satisfy dependency injection for a component to be creation, you can pass in any value.
For my case, I did this:
TestBed.configureTestingModule({
  providers: [
    FormBuilder,
    MyComponent,
    { provide: ChangeDetectorRef, useValue: {} }
  ]
}).compileComponents()
injector = getTestBed()
myComponent = injector.get(MyComponent)

It will create myComponent successfully. Just make sure test execution path does not need ChangeDetectorRef. If you do, then replace useValue: {} with a proper mock object.
In my case, I just needed to test some form creation stuff using FormBuilder.

A: // component
constructor(private changeDetectorRef: ChangeDetectorRef) {}

public someHandler() {
  this.changeDetectorRef.detectChanges();
}

// spec
const changeDetectorRef = fixture.componentRef.changeDetectorRef;
jest.spyOn(changeDetectorRef, 'detectChanges');
fixture.detectChanges(); // <--- needed!!

component.someHandler();

expect(changeDetectorRef.detectChanges).toHaveBeenCalled();


text:
Q: How to make responsive flex like Github? I make it for web is good but i need to make it responsive for phones too.

.features-container, .authentication-container {
    margin-left: auto;
    margin-right: auto;
    text-align: center !important;
    justify-content: center !important;
}

.features-container {
    max-width: 900px;
    border: 1px solid rebeccapurple;
}
.authentication-container {
    align-items: center !important;
    display: flex !important;
    color: rgba(255,255,255,0.65);
}
.authentication {
    max-width: 314px;
    border-style: none;
    text-align: right !important;
}
.authentication-title {
    0;
    0;
    color: white !important;
}
.authentication-title, .authentication-sub {
    text-align: left !important;
}
@media (min-width: 768px) {
    .item {
        width: 33.3333333333%;
        text-align: right !important;
        padding: 32px !important;
        flex: 1 1 auto !important;
    }
}

Attribute commits with collaborators easily

Quickly add co-authors to your commit. Great for pairing and excellent for sending a little love/credit to that special someone who helped fix that gnarly bug of yours. See the attribution on the history page, undo an accidental attribution, and see the co-authors on github.com

i want to make like a Github.
Original template: https://desktop.github.com
My Error: https://imgur.com/a/oCbcd50

A: Using flex-wrap: wrap is WORKING
.authentication-container {
    •••
    flex-wrap: wrap;
}


text:
Q: Phonegap - Share functionality to Email, Twitter and Facebook Is there an example how to program the functionality with the Phonegap Framework to share a URL to email, twitter and Facebook? For Example in Android this functionality is in 90% of the apps. In Iphone it is in any Apps. In the app of techcrunch for Iphone you can see it, when You open an article. Is it possible to create this with Phonegap too?

A: You can do this in Android with the following code for a plugin. I haven't published this anywhere else yet, but eventually I hope to add it as a plugin in the phonegap plugin repository for Android.
JAVASCRIPT:
var Share = function() {};

Share.prototype.show = function(content) {
    return PhoneGap.exec(
    function(args) {
        console.log("phonegap share plugin - success!")
    }, function(args) {
        console.log("phonegap share plugin - failed")
    }, 'Share', '', content);
};

PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin('share', new Share());
    PluginManager.addService("Share","com.COMPANYNAME(CHANGEME).android.plugins.Share");
});

JAVA IN ANDROID:
package com.COMPANYNAME(CHANGEME).android.plugins;

import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

public class Share extends Plugin {
    private String callback;

    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        PluginResult mPlugin = null;
        try {
            mPlugin = activateSharing(args.getString(0), args.getString(1));
        } catch (JSONException e) {
            Log.e("JSON Exception", e.toString());
        }
        mPlugin.setKeepCallback(true);
        this.callback = callbackId;
        return mPlugin;
    }

    private PluginResult activateSharing(String title, String body) {
        final Intent shareIntent = new Intent(
        android.content.Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, title);
        shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);

        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(Intent.createChooser(shareIntent, "Share"));
        return new PluginResult(PluginResult.Status.OK);
    }
}

A: Almost three years later: Here's a plugin that allows sharing on Android and iOS with the same API. https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin
It's available on PhoneGap Build as well!
Example
window.plugins.socialsharing.share('Google is awesome, WOOT!', 'Google facts', 'https://www.google.com/images/srpr/logo11w.png', 'http://www.google.com');

A: Login Facebook and post feed, login twitter and post status using plugin appInBrowser:
https://github.com/raulduran/facebook-twitter-cordova.git


text:
Q: how to set font to textview in android? I am doing like this but it get force close. I want to change textview font.
TextView mWeddingDataandTime=(TextView)findViewById(R.id.wedding_weddingtime_txt);
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/CURLZ_.otf");
mWeddingDataandTime.setTypeface(face);

I am using .otf file. It is in assets folder. Any idea?

A: Try this:
    TextView txt = (TextView) findViewById(R.id.custom_font);
    Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");
    txt.setTypeface(font);

Note that file extension is "ttf" search in google for any font for download in this extension
for example:
    http://www.creamundo.com/

A: In code you are using fonts/CURLZ_.otf as path but you say that font file is directly inside assets so your code should be
Typeface face=Typeface.createFromAsset(getAssets(),"CURLZ_.otf");

if there is no fonts folder inside assets folder.

A: I didn't test it but I think it may help you:
  TextView mWeddingDataandTime=(TextView)findViewById(R.id.wedding_weddingtime_txt);
  Typeface face=Typeface.createFromAsset(getAssets(),"fonts/CURLZ_");
  mWeddingDataandTime.setTypeface(face);

A: Better to make use of the styles and themes and inbuilt fonts for performance related and size of the app related issues Styles & Themes

A: If your font is only in asset folder not in asser/fonts forlder than use this
 Typeface face=Typeface.createFromAsset(getAssets(),"CURLZ_.otf");

A: Below is code which I used in my project & it's working... You might need to do some changes
  Typeface myTypeface = Typeface.createFromAsset(this.getAssets(),"segoeuil.ttf");
  TextView loantext = (TextView)findViewById(R.id.loantext);
  length1.setTypeface(myTypeface);

1) Put font in assets folder instead of fonts folders
2) instead of getAssests() in you code use "this.getAssets()" or "youractivity.this.getAssets()
Thank You


text:
Q: Angular theres a cleaner way of changing the DOM? my question is about if the way im doing this in my code is right or theres a better solution for this.
Here my Code:

                    {{ dataHolder.name }}

Every data it holds is from 1 Component.
First I got data with strings in it, these data i loop trough and show them off at the screen. Afterwards its getting rotated around the screen, so its getting a new position.
The Code is doing well and every step i mentioned finish before the user can see the app. But now as a newbie on Angular i want to ask you guys if theres a better/cleaner way to change code in the DOM (new Styles, adding new Elements, creating new paragraphs, etc.) like in my code example. If you need more examples i can give more.
I would really appreciate your help, because at the moment im unsure if the way im model my DOM is not clean and im going into the wrong way.

A: What you have looks very reasonable to me but I would prefer to extract those transforms into constants or functions that I could reference, reuse, and keep out of the already convoluted Angular DOM syntax, which is based on the already convoluted existing DOM syntax.
The alt is oft-repeated and could be factored into a directive.
I might go about it like this
list.component.html

                {{ dataHolder.name }}

list.component.ts
import {Component,  ChangeDetectionStrategy} from '@angular/core';

import template from './list.component.html';

@Component({
  selector: 'list',
  template,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export default class {
  numberArray: number[] = [];

  createTransform = createTransform;
}

// testability for the win!
export function createTransform(primaryAngle: number, height: number, secondaryAngle = 0) {
  return `rotate(${primaryAngle}deg) translate(0, -${height}px) rotate(-${secondaryAngle}deg)`;
}

However, be sure to look into the Angular official animation library.


text:
Q: Unsafe Image Processing in Python like LockBits in C# Is it possible to do Unsafe Image Processing in Python?
As with C# I encountered a hard wall with my pixel processing in Python as getPixel method from Image is simply running too slow.
Is it possible to get a direct access to the image in memory like LockBits in c# does? It will make my program run much faster.
Thanks,
Mark

A: There is nothing "unsafe" about this.
Once you understand how Python works, it becomes patent that calling a method to retrieve information on each pixel is going to be slow.
First of all, although you give no information on it, I assume you are using "Pillow" - the Python Image Library (PIL)  which is the most well known library for image manipulation using Python. As it is a third party package, nothing obliges you to use that. (PIL does have a getpixel method on images, but not a getPixel one)
One straightforward way to have all data in a manipulable way is to create a bytearray object of the image data - given an image in a img variable you can do:
data = bytearray(img.tobytes())

And that is it, you have linear access to all data on your image. To get to an specific Pixel in there, you need to get the image width , heigth and bytes-per-pixel. The later one is not a direct Image attribute in PIL, so you have to compute it given the Image's mode. The most common image types are RGB, RGBA and L.
So, if you want to write out a rectangle at "x, y, width, size" at an image, you can do this:
def rectangle(img, x,y, width, height):
    data = bytearray(img.tobytes())
    blank_data = (255,) * witdh * bpp
    bpp = 3 if data.mode == 'RGB' else 4 if data.mode == 'RGBA' else 1
    stride = img.width * bpp
    for i in range(y, y + height):
         data[i * stride + x * bpp: i * stride + (x + width) * bpp)] = blank_data
    return Image.frombytes(img.mode, (img.width, img.height), bytes(data))

That is not much used, but for simple manipulation. People needing to apply filters and other more complicated algorithms in images with Python usually access the image using numpy - python high-performance data manipulation package, wich is tightly coupled with a lot of other packages that have things specific for images - usually installed as scipy.
So, to have the image as an ndarray, which already does all of the above coordinate -> bytes conversion for you, you can use:
 import scipy.misc
 data = scipy.misc.imread(<filename>)

(Check the docs at https://docs.scipy.org/doc/scipy/reference/)


text:
Q: Scroll to middle when focus reaches to end of the screen in Java-Script Function: I have added text-box and links on page. Each element on page have tabIndex assigned. You can tabout from text-box then by pressing up and down arrow keys we can traverse links.
Problem: I want to scroll window to middle when i reach at the end of screen. I have calculated offset to find out bottom but it works sometimes and not sometime.
Note: Mainly in chrome it works somehow do not how!! but this does not work with any other browsers.
https://jsfiddle.net/bat8bf8h/7/
JavaScript Function:
function abc(event) {
    // Find active Element tabIndex
    var tabIndexElement = document.activeElement.tabIndex;

    // tabIndex for element is 0 then send focus back to first search link
    if (tabIndexElement == 38) {
        document.querySelector('[tabIndex="2"]').focus();
        event.preventDefault();
        return;
    }

    // Based on Up and Down Key press move focus from next or previous search links
    if (event.keyCode == 38) { // up key press
        var queryString = '[tabindex="' + (--tabIndexElement) + '"]';
        var currentElement = document.querySelector(queryString);
        currentElement.focus();
        event.preventDefault();
        // I will work on up event
    }

    if (event.keyCode == 40) { // down key press
        var queryString = '[tabindex="' + (++tabIndexElement) + '"]';
        var currentElement = document.querySelector(queryString);
        currentElement.focus();

        // This is what i think how can i approach this
        var h = window.innerHeight;
        var rect = currentElement.getBoundingClientRect();
        var offset = h - rect.top;
        currentElement.innerHTML = currentElement.innerHTML + ' offset:'+offset+' rectb:'+rect.bottom;
        if (offset < 0) {
            currentElement.innerHTML = currentElement.innerHTML + ' scroll';
            window.scrollTo(0, rect.top);
        } else {
            currentElement.innerHTML = currentElement.innerHTML + ' scroll1';
            event.preventDefault();
        }
    }

    return true;
}

Thanks in advance.


text:
Q: Blue Screen when i try Install Windows XP X86 in X64 Machine I need to install Windows XP X86 in a physical computer. How i don't have a 32bit processor computer, i try to install system in X64 machine.
(i need to test a automation software that available only windows xp X86 :/)
I try to use Ease2Boot and PowerIso Methods, but the both stops in the same place. When the windows begins the installation (before i choose the partition), the blue screen appears and show the same error:
"ERROR: 0X0000007E
ACPI.sys address F73B8D66 base at F73AD000 DATER 41107 27"
I search about this error in internet and didn't find anything that could help.
Anyone have an i idea if it's possible install Windows X86 in X64 Machine?
Ps: Sorry about my bad English
Thanks a lot!

A:
I need to install Windows XP X86 in a physical computer. How i don't
have a 32bit processor computer, i try to install system in X64
machine.

Any computer built in the last 5 to 7 years will not install XP. It is too old for new computers.
If you wish to run XP then use a virtual machine (VMware Workstation is best for this but there are other apps).
Make sure your physical box supports Hardware Virtualization (maybe needed for the APP; not needed to install 32-bit XP).
Then make an XP virtual machine. I have that running here inside VMware Workstation on a Windows 11 Pro 64-bit host.


text:
Q: calculation error in methods I have got the user input working and also my method of number of gallons working however when I try to calculate the hours of labor, what it does is it calculates it with the result of the previous calculation and not the one that I specified.
This is what I have so far. What it does is it uses the result of gallons to multiply it by 8 rather than using the square feet that the user enters. I can't seem to figure out why it does that
int result=gallonsofpaint(numberofsquarefeet,115,1);
System.out.println("the number of gallons of paint required is " + result);

int resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
System.out.println("the number of hours needed are " + resultnumberofhours);

public static int gallonsofpaint(int numberofsquarefeet, int squarefeet,int paint){
    int result = numberofsquarefeet/115*1;
    return result;
}

public static int hoursoflabor(int numberofsquarefeet, int squarefeet,int labor){
    int resultnumberofhours = numberofsquarefeet/115*8;
    return resultnumberofhours;
}

A: Well as per the formulas you have defined in your methods, for a specific numberofsquarefeet, the resultnumberofhours will always be result multiplied by 8. You can avert this by converting you field data types to floating point.

A: First thing, the return type is int.

so you 900/115 you get 7 not 7.82

Secondly, if you want the result to have decimals, switch to double or float.
import java.util.Scanner;

public class So{
    public static void main(String args[]) {
        int numberofsquarefeet = 900;
        int result=gallonsofpaint(numberofsquarefeet,115,1);
        System.out.println("the number of gallons of paint required is " + result);

        double resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
        System.out.println("the number of hours needed are " + resultnumberofhours);
    }
    public static int gallonsofpaint(int numberofsquarefeet, int squarefeet, int paint) {
        int result = numberofsquarefeet / 115 * 1;
        return result;
    }

    public static double hoursoflabor(int numberofsquarefeet, int squarefeet, int labor) {
        double resultnumberofhours = (double)(numberofsquarefeet * 8 ) / 115;
        return resultnumberofhours;
    }
}

If you don't want decimals in 62.608 and want the answer to be 62.
import java.util.Scanner;

public class MaximiseSum {
    public static void main(String args[]) {
        int numberofsquarefeet = 900;
        int result=gallonsofpaint(numberofsquarefeet,115,1);
        System.out.println("the number of gallons of paint required is " + result);

        int resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
        System.out.println("the number of hours needed are " + resultnumberofhours);
    }
    public static int gallonsofpaint(int numberofsquarefeet, int squarefeet, int paint) {
        int result = numberofsquarefeet / 115 * 1;
        return result;
    }

    public static int hoursoflabor(int numberofsquarefeet, int squarefeet, int labor) {
        int resultnumberofhours = (int) ((numberofsquarefeet * 8 ) / 115);
        return resultnumberofhours;
    }
}


text:
Q: Adding global IPv6 addresses using SLAAC Stateless Adress Autoconfiguration allows a node on the link to automatically configure global IPv6 addresses by appending its interface identifier (64 bits) to the prefix (64 bits) advertised by the router.
Lets assume I have a server with the global IPv6 Adress
2001:0db8:85a3:08d3:1319:8a2e:0370:7347

Now i want to add another global IPv6 address to the same interface by changing just the interface identifier and keeping the prefix. e.g.
2001:0db8:85a3:08d3:3315:2b5e:a320:3254
-------same--------|-----different-----

How can i do that using SLAAC, where the interface identifier is automatically appended to the network prefix? I am currently using Ubuntu.
(This is similar to what the IPv6 Privacy Extension does, but i want to control adding and removing temporary IPv6 addresses myself.)

A: Privacy Extensions are exactly what you're looking for. You just want to have some manual control over them. You can manipulate the expiration and generation by using the ip address command. The ip-address man page says:

mngtmpaddr (IPv6 only) make the kernel manage temporary addresses created from this one as template on behalf of Privacy Extensions (RFC3041). For this to become active, the use_tempaddr sysctl setting has to be set to a value greater than zero. The given address needs to have a prefix length of 64. This flag allows to use privacy extensions in a manually configured network, just like if stateless auto-configuration was active.

A: At the moment, I'm not aware of any method for manually causing the system to switch to a new temporary address.
However, you can tune the time period in which a temporary address is used and cause the system to create them more frequently.
From the kernel documentation:
temp_valid_lft - INTEGER
    valid lifetime (in seconds) for temporary addresses.
    Default: 604800 (7 days)

temp_prefered_lft - INTEGER
    Preferred lifetime (in seconds) for temporary addresses.
    Default: 86400 (1 day)

(Yes, the misspelling is intentional...)
So, let us say you want the system to start using a new temporary address every 10 minutes. You will then set:
sysctl net.ipv6.conf.all.temp_prefered_lft=600
sysctl net.ipv6.conf.default.temp_prefered_lft=600

The other sysctl, temp_valid_lft, allows some extra time for existing connections using a temporary address to finish up. You can also reduce this, especially if you don't anticipate long running connections. Here I reduce it to 1 hour:
sysctl net.ipv6.conf.all.temp_valid_lft=3600
sysctl net.ipv6.conf.default.temp_valid_lft=3600


text:
Q: Graphql "Network Error : Failed to Fetch" when upload images by taking image from direct camera using Oppo I have a problem when upload images by taking direct from OPPO camera. I tried this from other smartphone is working as expected.
This is my code
const form = new FormData();
function processImages() {
      return new Promise((resolve, reject) => {
        images.forEach(async (image, index, array) => {
          try {
            const data = await getBufferFromStreams(image);
            form.append('images', data.fileBuffer, data.filename);
            if (index === array.length - 1) {
              resolve(true);
            }
          } catch (error) {
            reject(error);
          }
        });
      });
    }
const success = await processImages();
const response = await this.post(`${url}`, form, {});

export const getBufferFromStreams = async (file) => {

    if (!file) {
        return new Error('file is undefined');
    }
    const { stream, filename } = await file;
    const chunks = [];
    return new Promise((resolve, reject) => {
        stream.on('data', (chunk) => {
            chunks.push(chunk);
        });
        stream.on('error', (error) => {
            reject(error);
        });
        stream.on('end', () => {
            resolve({ fileBuffer: Buffer.concat(chunks), filename });
        });
    });
};

I always get error "Network Error: Failed to Fetch" when uploading images when taking picture from camera only on OPPO smartphone.
Do you have encounter same issues and solved ?


text:
Q: Prove that $\sum_{k=0}^{6} \zeta_7^k= 0$. I have tried this complex analysis problem for hours on my own but am still stumped.

Suppose $\zeta_7 = e^{2\pi i/7} = \cos(2\pi/7)+i\sin(2\pi/7)$. Prove that $$\sum_{k=0}^{6} \zeta_7^k = 0.$$

I have so far obtained that $$\sum_{k=0}^{6} (\zeta_7)^k = 1 + (\zeta_7) + (\zeta_7)^2 + (\zeta_7)^3 +(\zeta_7)^4 +(\zeta_7)^5 + (\zeta_7)^6,$$ but that's as far as I get.

A: Note that $$\zeta ^7 = \cos 2\pi +i \sin 2\pi =1$$
Therefore, $$ \zeta ^7-1=0$$
That is $$ (\zeta -1 )(\zeta ^6 + \zeta ^5 +...+\zeta +1) =0$$
Since $\zeta \ne 1$ we have $\zeta -1 \ne 0$.
Thus $$\zeta ^6 + \zeta ^5 +...+\zeta +1 =0$$

A: Because $$\sum_{k=0}^6\zeta^k=\frac{\zeta^7-1}{\zeta-1}=0.$$

A: The equation $X^7-1=0$ has no repeated roots (can be checked by looking at the derivative of $X^7-1$)
and $\zeta_7$ is one of the roots,
The 7 numbers, $\zeta_7^k,k=0,1,\ldots, 6$ are also solutions of the same equation.
The have to be all the solutions, as we are dealing with the a 7th degree equation.
Your question requires finding the sum of all the roots of the equation.
For any equation of degree $n$ sum of all its (real/complex) roots  (counting multiplicity)
is the negative of the coefficient of $X^{n-1}$,  In the case we are discussing $X^6$ term is not present hence the sum is zero.


text:
Q: How to read a managed stream into a uint array directly in C#? I have some data in a stream which is actually in the format of uint. System.IO.Stream only allows me to read the content out to a byte array, but I don't want to read the bytes and then convert them into a uint array with 1/4 the length of the byte array. I want to read it directly into the memory of the uint array so that it saves time.
If it's in unmanaged C++ it's just so easy. Just send over the pointer to the uint array and it'd be done. But in C# it doesn't seem so straightforward. I'm trying to produce a byte array with the same memory address as another uint array and then send the byte array as the parameter of Stream.Read() so that when Stream.Read() writes to the byte array the content is just in the uint array as well. But I've looked at the Marshall class and have so far found no solution to this problem. Any ideas?

A: List<UInt32> array = new List<UInt32>();
System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
while(stream.Position < stream.Length)
   array.Add(reader.ReadUInt32());

Note that some stream implementations don't support Position and/or Length properties.