text:
Q: Google Earth Plugin Crash on Click I'm currently trying to set a breakpoint in the debug window of my browser. Whenever a click event happens the breakpoint causes the Google Earth Plugin to crash.
Is there a method that I'm missing in order to avoid the crash? I just want easy access to trying out different kml properties on a breakpoint. Hoping I was missing a feature similar to the timeout on an alert box to stop the box from crashing when GE is clicked.
Tried to debug in both Chrome and IE.
It's the basic Google Earth code.
google.earth.createInstance(this, initCB, failureCB, earthArgs);

this is the map div and earthArgs holds the database location
............
Click event code:
function initCB(instance) {
  gep = instance;
  gep.getWindow().setVisibility(true);

  google.earth.addEventListener(gep.getGlobe(), 'click', function(event) {
    //set breakpoint here
  });
}

Code works and loads the GE without issue, the issue is that when clicking on GE the breakpoint freezes up.

A: This could be because you are using an anonymous delegate for the event handler. To set a break-point try creating a named function and passing that to the addEventListener method.
 // handle click events on the globe
 // e is the KmlMouseEvent object
 var globeClickHandler = function(e) {
   // set breakpoint here
 };

 // in initCB
 google.earth.addEventListener(gep.getGlobe(), 'click', globeClickHandler);

A: What if you used a different event? say "mousedown" or "mouseup"?
google.earth.addEventListener(gep.GetGlobe(), 'mouseup', function(event){
    //do something here
});


text:
Q: Fixed Position Relative to Parent Div with sliding sidebar I would like my sidebar to push the content across when opened which i have achived but my fixed navigation stays at the position of Left: 0px; relative to the veiwport rather than the relative positioned parent element. my nav's with is 100%
my sidebar works fine on firefox but breaks out of parent in chrome
link to jsfiddle
<!doctype html>

<meta charset="utf-8">
<title>Test Page</title>
<link rel="stylesheet" type="text/css" href="style.css">

MY CSS
@font-face {
    font-family: 'icomoon';
    src:url('fonts/icomoon.eot');
    src:url('fonts/icomoon.eot?#iefix') format('embedded-opentype'),
        url('fonts/icomoon.woff') format('woff'),
        url('fonts/icomoon.ttf') format('truetype'),
        url('fonts/icomoon.svg#icomoon') format('svg');
    font-weight: normal;
    font-style: normal;
}

*{
    margin: 0;
    padding: 0;
}

#sidebar{
    position: fixed;
    left: 0;
    top: 0;
    width: 250px;
    background: rgb(60,60,60);
    float:left;
    height: 600px;
    z-index: -1;
}

.content{
    position: relative;
    left: 0;
    top: 0;
    width: 100%;
    height:600px;
    background: #FFF;
    -moz-transition:all 0.4s ease-in-out;
    -webkit-transition:all 0.4s ease-in-out;
}

.slide{
    left: 250px;
}

#nav{
    position: fixed;
    top: 0;
    background: #0af;
    width: 100%;
    box-shadow: 1px 1px #ddd;
}

 #nav p:before{
    content: "\e000";
}

.button{
    font-family: 'icomoon';
    font-size: 2em;
    color: #FFF;
    cursor: pointer;
    margin: 10px;
}

VIEW HERE

A: Adding position: absolute; to .slide{...}css will fix the problem in Chrome, you might also have to fix the animation when .slide class is removed
Good luck
[UPDATE]
HERE IS A WORKING EXAMPLE: http://jsfiddle.net/QdVKD/1/
FIXING THE WIDTH AND UNNEEDED SCROLL OF PAGE: http://jsfiddle.net/QdVKD/2/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it safe to change the IP address and domain name of an Chef Node? I have a Chef Node that I'm initially setting up on one network that I need to (physically) move to another network.  When this happens, I want the IP address and domain name to change, and the Node name and simple hostname to stay the same.
I know I can do this by deleting the Chef Node and recreating it.  Could I also do it by editing Node attributes?   Or would that break the client keys or (worse still) the server?
(I'm using Chef 10.16.2 ...)

A: Recreating the node (and client) with the new name is one option, but you can preserve the ones you already have.  This requires client configuration - by the time the node retrieves attributes from the Chef server, it's already decided what its name is.
By default, chef-client will set the node name to the fully-qualified domain name of the host, as returned by ohai.  You can check what name will be used by invoking ohai directly:
zts@chef ~ % ohai fqdn
[
  "chef.nat0.cryptocracy.com"
]

If that changes when you move the host, you'll need to edit /etc/chef/client.rb to set the desired nodename:
node_name "mynode.example.com"

Take a look at Chef Docs - client.rb for more about this configuration file.


text:
Q: Am I not updating my React state correctly? I hope you can help, I've reduced my
code to make it more concise.
Objective: I'm trying to create a callback that removes the first item from the playOrder array every 2000 milliseconds until there are no more items left in the array.
Problem: Each time playOrderHandler runs, the playOrder duplicate assigned is always 4 items even though the useEffect callback is showing that the new playOrder array has been set as expected.
What am I doing wrong?
Any help is much appreciated
    const [chamberSpinning, setChamberSpinning] = useState(false)

    const [playOrder, setPlayOrder] = useState(
        [
            'left',
            'right',
            'left',
            'stop'
        ]
    )

    useEffect(() => {
        if (chamberSpinning) {
            console.log(playOrder, playOrder.length) // logs 3 items
        }
    }, [playOrder])

    function chamberSpinInit () {
        setChamberSpinning(true)
        playOrderHandler()
    }

    function playOrderHandler () {
        if (playOrder.length > 0) {
            const playOrderDup = [...playOrder]
            console.log(playOrderDup) // Logs 4 items every time
            playOrderDup.splice(0,1)
            setPlayOrder(playOrderDup)
            spinIt()
        } else {
            console.log('No more plays remaining')
        }
    }

    function spinIt () {
        setTimeout(() => {
            playOrderHandler()
        }, 2000)
    }

    return (
        <button onClick={() => chamberSpinInit()} >
            SPIN THE CHAMBER!
        </button>
    )

Any help is much appreciated
Thanks all,
Moe

A: A plain recursive call of spinIt is problematic because the spinIt in scope at the time of that call is the same spinIt that was defined at the time of rendering earlier - it's not the new spinIt that gets created as a result of calling setPlayOrder(playOrderDup) (and the subsequent rerender). Put the recursive call in a useEffect instead, which will close over the proper current value of state.

const { useState, useEffect } = React;
const App = () => {
    const [chamberSpinning, setChamberSpinning] = useState(false);
    const [playOrder, setPlayOrder] = useState(
        [
            'left',
            'right',
            'left',
            'stop'
        ]
    );

    useEffect(() => {
        if (chamberSpinning) {
            console.log(playOrder, playOrder.length);
            spinIt();
        }
    }, [playOrder, chamberSpinning])

    function chamberSpinInit() {
        setChamberSpinning(true)
        playOrderHandler()
    }

    function playOrderHandler() {
        if (playOrder.length > 0) {
            setPlayOrder(playOrder.slice(0, -1));
        } else {
            console.log('No more plays remaining')
            setChamberSpinning(false)
        }
    }

    function spinIt() {
        setTimeout(() => {
            playOrderHandler()
        }, 2000)
    }

    return (
        <button onClick={chamberSpinInit} >
            SPIN THE CHAMBER!
        </button>
    )
};

ReactDOM.createRoot(document.querySelector('.react')).render(<App />);


text:
Q: jQuery Datatables fnReloadAjax works but generates an alert I am using the following code to reload the data in a jQuery datatable.
$(".unread-rows").click( function(e) {
    e.preventDefault();
    message_table.fnReloadAjax("/letters/ajax/inbox/1");
    message_table.fnDraw();
    $(this).addClass("active").siblings().removeClass("active");
});

It reloads the data fine but it also causes an alert to appear saying:
DataTables warning (table id = 'DataTables_Table_0'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.
Any ideas what might be causing this?

A: Barring any bugs in the fnRelaodAjax function :

*

*Have you checked if your server returns valid json data ?

*Have you checked if it returns an object with the following structure : {aaData: [...]}, or a structure that matches your sAjaxDataProp property ? (look for "sAjaxSource" and "sAjaxDataProp" in the doc page)


text:
Q: How to use & differently than normal inside an `align` environment? I'm trying to write a macro to let me write logic formulae in a more natural syntax. I've come up with a working version which however has a problem when used inside align environments (and in tabular as well).
This is the code:
\documentclass{article}

\usepackage{amsmath}
\usepackage{amssymb}% for \Box
\usepackage{xparse}
\usepackage{xstring}
\usepackage{pgffor}

\makeatletter
\NewDocumentCommand\logic{m}{%
  \def\@formula{#1}%
  \saveexpandmode
  \expandarg
  \foreach \keyword/\operator in \@operators {%
    \StrSubstitute{\@formula}{\keyword}{\operator}[\@temp]%
    \global\let\@formula\@temp
  }%
  \restoreexpandmode
  \@formula
}

% Here the list of recognised syntax with the corresponding commands
\def\@operators{
  []/\Box,
  <>/\Diamond,
  !/\neg,
  &&/\land,
  ||/\lor,
  <->/\leftrightarrow,
  ->/\rightarrow,
  <-/\leftarrow
}
\makeatother

\begin{document}

Here is a valid modal logic formula: $\logic{[]p -> p && <>[]p}$

This is a display modal logic formula:
\begin{align}
 \logic{[]p -> p && <>[]p}
\end{align}

\end{document}

If I comment the second paragraph, the output is the following:

However, the same macro used inside the align environment gets totally mad, producing hundreds of error messages.
I was expecting problems when using & which is an active character with special meaning in align. I suppose the problem is that align splits beforehand the content of the line into two parts, \logic{[]p -> p and <>[]p}, which then cause all the troubles. Is that right?
Indeed, if I avoid using & in the formula and comment out the &&/\land line in the @operators macro, the macro works inside align as well.
Note that everything works in equation, using & as well.
Is there a way to make this code work inside align? Or is there a way to achieve the same result that works inside align?

A: I enclosed the \logic definition in an extra set of braces.
Depending on your need for letting information get into or out of the boundaries of \logic, an alternative "brace hack" may be used in lieu of the extra braces.  See Understanding Brace Hacks.  For example, \DeclareDocumentCommand\logic{m}{\iffalse{\fi...\iffalse}\fi} also works, plus gives the ability for the formula to be surrounded by math with binary/unary information being transmittable across the boundary. See more in SUPPLEMENT.
\documentclass{article}

\usepackage{amsmath}% for `align`
\usepackage{latexsym}% for \Box
\usepackage{xparse}
\usepackage{xstring}
\usepackage{pgffor}

\makeatletter
\DeclareDocumentCommand\logic{m}{{%
  \gdef\@formula{#1}%
  \saveexpandmode
  \expandarg
  \foreach \keyword/\operator in \@operators {%
    \StrSubstitute{\@formula}{\keyword}{\operator}[\@temp]%
    \global\let\@formula\@temp
  }%
  \restoreexpandmode
  \@formula
}}

% Here the list of recognised syntax with the corresponding commands
\def\@operators{
  []/\Box,
  <>/\Diamond,
  !/\neg,
  &&/\land,
  ||/\lor,
  <->/\longleftrightarrow,
  ->/\longrightarrow,
  <-/\longleftarrow
}
\makeatother

\begin{document}

Here is a valid modal logic formula: $\logic{[]p -> p && <>[]p}$

This is a display modal logic formula:
\begin{align}
 \logic{[]p -> p && <>[]p}
\end{align}

\end{document}

SUPPLEMENT: BRACE HACKS
Here is an example of how the brace hack makes a difference.  Compare the two cases, the first with extra braces, the 2nd with a brace hack.  In the 2nd case, the binary nature of the + communicates with the prior y to provide proper spacing around the +.
\documentclass{article}

\usepackage{amsmath}% for `align`
\usepackage{latexsym}% for \Box
\usepackage{xparse}
\usepackage{xstring}
\usepackage{pgffor}

\makeatletter
\DeclareDocumentCommand\logic{m}{{%
  \gdef\@formula{#1}%
  \saveexpandmode
  \expandarg
  \foreach \keyword/\operator in \@operators {%
    \StrSubstitute{\@formula}{\keyword}{\operator}[\@temp]%
    \global\let\@formula\@temp
  }%
  \restoreexpandmode
  \@formula
}}

% Here the list of recognised syntax with the corresponding commands
\def\@operators{
  []/\Box,
  <>/\Diamond,
  !/\neg,
  &&/\land,
  ||/\lor,
  <->/\longleftrightarrow,
  ->/\longrightarrow,
  <-/\longleftarrow
}
\makeatother

\begin{document}

Here is a valid modal logic formula: $\logic{[]p -> p && <>[]p}$

This is a display modal logic formula:
\begin{align}
 y \logic{+ []p -> p && <>[]p}
\end{align}
\makeatletter
\DeclareDocumentCommand\logic{m}{\iffalse{\fi%
  \gdef\@formula{#1}%
  \saveexpandmode
  \expandarg
  \foreach \keyword/\operator in \@operators {%
    \StrSubstitute{\@formula}{\keyword}{\operator}[\@temp]%
    \global\let\@formula\@temp
  }%
  \restoreexpandmode
  \@formula
\iffalse}\fi}

\begin{align}
 y\logic{+ []p -> p && <>[]p}
\end{align}
\end{document}

A: You can use the full power of expl3.
\documentclass{article}

\usepackage{amsmath}
\usepackage{amssymb}% for \Box
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand\logic{m}
 {
  \group_align_safe_begin:
  \tl_set:Nn \l_gigabytes_logic_input_tl { #1 }
  \clist_map_function:NN \c_gigabytes_logic_subs_clist \gigabytes_logic_sub:n
  \tl_use:N \l_gigabytes_logic_input_tl
  \group_align_safe_end:
 }
\tl_new:N \l_gigabytes_logic_input_tl
\clist_const:Nn \c_gigabytes_logic_subs_clist
 {
  []/\Box,
  <>/\Diamond,
  !/\neg,
  &&/\land,
  ||/\lor,
  <->/\longleftrightarrow,
  ->/\rightarrow,
  <-/\leftarrow
 }
\cs_new_protected:Nn \gigabytes_logic_sub:n
 {
  \__gigabytes_logic_sub:w #1 \q_stop
 }
\cs_new_protected:Npn \__gigabytes_logic_sub:w #1 / #2 \q_stop
 {
  \tl_replace_all:Nnn \l_gigabytes_logic_input_tl { #1 } { #2 }
 }
\ExplSyntaxOff

\begin{document}

Here is a valid modal logic formula: $\logic{[]p -> p && <>[]p}$

This is a display modal logic formula:
\begin{align}
\logic{[]p -> p && <>[]p}
\end{align}

\end{document}

Points to note:

*

*The & tokens are hidden from align by using \group_align_safe_begin: and \group_align_safe_end:

*The routine for substitution is easier and needs no juggling with expansion modes


text:
Q: c# OpenFileDialogue Initial directory using relative path How can I set the initial directory to be where my test data exists?
var relPath = System.IO.Path.Combine( Application.StartupPath, "../../" )

dlg.Title = "Open a Credit Card List";
dlg.InitialDirectory = relPath ;

The default directory it opens up to is where the .exe exists: Project2\Project2\bin\Debug
I want it to open up by default in the Project2 folder where my test data exists. But it does not allow me to move up a parent directory. How do I get around this?

A: You can use Directory.GetParent(string path)
string relPath = Directory.GetParent(Application.StartupPath).Parent.FullName;

Or using DirectoryInfo
DirectoryInfo drinfo =new DirectoryInfo(path);

DirectoryInfo twoLevelsUp =drinfo.Parent.Parent;
dlg.InitialDirectory = twoLevelsUp.FullName;;

A: To convert your relative path to an absolute path you can use Path.GetFullPath()
var relPath = System.IO.Path.Combine(Application.StartupPath, @"\..\..");
relPath = Path.GetFullPath(relPath);
dlg.InitialDirectory = relPath;

Alternatively if you wish to change the working directory to your test data:
Directory.SetCurrentDirectory(relPath);

More information:
http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx


text:
Q: Getting error while using 'ui.bootstrap' and '720kb.datepicker' module in same Angular.js application I am getting the following error while using ui.bootstrapand 720kb.datepicker module at a time in one application in Angular.js.
Error: [$compile:multidir] http://errors.angularjs.org/1.4.6/$compile/multidir?p0=datepicker&p1=&p2=da…-prev%3D%22%3Ci%20class%3D%26quot%3Bfa%20fa-arrow-circle-left%26quot%3B%3E
    at Error (native)
    at http://oditek.in/Gofasto/js/angularjs.js:6:416
    at Q (http://oditek.in/Gofasto/js/angularjs.js:69:353)
    at D (http://oditek.in/Gofasto/js/angularjs.js:62:492)
    at http://oditek.in/Gofasto/js/angularjs.js:68:182
    at http://oditek.in/Gofasto/js/angularjs.js:118:334
    at n.$eval (http://oditek.in/Gofasto/js/angularjs.js:132:452)
    at n.$digest (http://oditek.in/Gofasto/js/angularjs.js:129:463)
    at n.$apply (http://oditek.in/Gofasto/js/angularjs.js:133:236)
    at g (http://oditek.in/Gofasto/js/angularjs.js:87:376)

When i am removing ui.bootstrap module this error is not coming but i strongly need also ui.bootstrap module.I am explaining my code below.
<datepicker date-format="dd-MM-y" button-prev='' button-next=''>
                                <input type="text" name="birthdate" class="form-control" ng-model="date" placeholder="Add date" />
                                </datepicker>

Please help me to resolve this error by using the both module.

A: Update ui.bootstrap module to a version above 0.14.0. The team behind the module prefixed the name of the directives with uib- to avoid such collisions.


text:
Q: MVC Persist Model when paging I have a dropdown list with check boxes. The selected value is bound to my view model. The data is paged using PagedList.Mvc. All works fine when I select some checkboxes and then hit the search button, but when I click onto another page the check box list becomes null so the list loses what is checked. How can I get the model to persist whilst paging.
So my html looks like this

        @for (int i = 0; i < Model.Units.Count; i++)
        {
            @Html.CheckBoxFor(m => m.Units[i].Selected)
            @Html.HiddenFor(m => m.Units[i].UnitId)
            @Html.LabelFor(m => m.Units[i].Selected,
                       Model.Units[i].UnitName)

            }

 <button class="btn btn-primary" type="submit" id="btnSave" name="Command" value="Save">Search</button>

and further down the paging
 @Html.PagedListPager(Model.SearchData, page => Url.Action("Index", new HistoricDataViewModel { Page = page }))

and my model looks like this
public class HistoricDataViewModel
{
    public HistoricDataViewModel()
    {
        Page = 1;
    }

    public StaticPagedList<Data_Search_Result> SearchData { get; set; }
    public List<Units_Getall_Result> Units { get; set; }
    public int Page
    {
        get; set;
    }
}

When I hit my search button it is submitting the form. Is the problem because the paging plugin isn't doing a submit?

A: I always like to drop down to the low-level details in situations like this because I think it helps to understand why things are or aren't possible. Then, once you understand that, you can figure out how to work around limitations.
Namely, here you're dealing with the concepts of request-response and statelessness. Let's start with statelessness. The Internet (specifically the TCP/IP protocol) was designed to be stateless. The Internet is a mesh network, composed of many, many connected devices that join and drop from the network constantly. Having its origins in ARPA, the research arm of the U.S. military, its original purpose was to provide a communication system that could survive a nuclear attack on "hubs", or centralized communication choke points. By decentralizing the network, multiple hubs could be cut off and communication could still continue unabated. However, to implement this kind of network design, you can't have any sort of state, as when the client is forced to connect to a different server because the previous server is now offline that new server would have no knowledge of prior communication the client had. As a result, all the information required for the server to respond to the request must be in the request itself. Which brings us to request-response.
A client issues a request to a server and that server sends a response. This is the fundamental basis for all network communication. When you click one of your pager links, you're issuing a GET request to the server for the next page, and the server responds with the HTML document that represents that page. Since the web is stateless, the only information the server has to build that response with is what was sent in the request by the client (for instance, a query string with the name-value pair "page=2". If you want to persist the checked items, as well, you must find some way to include that in the query string or send a POST request with that data included in the POST body. However, while you can make a link click issue a POST, it requires JavaScript to change the default behavior of a link (sending GET), but it would also require JavaScript to dynamically change the href of the link to include extra data in the query string.
The best solution, really, would be to treat each (checking items and changing pages) as separate things. Upon checking an item, you could either use JavaScript to dynamically post that information to the server or provide a submit button to allow the user to manually post it. Server-side, you can store that value in the session. Then, you can simply let the paging work as it does out of the box and simply read the checked values from the session for each page.
Continuing the discussion above, the session is state, so you might wonder how that's possible when the web is stateless. The answer is that sessions are "fake" state. What's actually going on under the hood is that the server is saving the information and issuing a token that represents the "session". That token is sent to the client as a cookie. Web browsers (the most typical clients) are programmed to send all cookies received from a server back to the server with each request. The result is that the request still technically has all the information the server needs, as the session token is enough to allow the server to find the previous session data and "restore" it.


text:
Q: javascript jquery google translation in website . doesnot translate google map and marker infobox I have included google translation script in our website. The page is automatically translated. But google map and the marker , infobox title is not translated . please help me how to translate google map marker , also some images based on the language selection.
Thanks

function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'jp',includedLanguages: 'en,jp', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}


text:
Q: Docker: Tag does not exist I referred this Stackoverflow question prior to asking this but even though it looks similar that question does not contain the answer for my matter.
I developed Springboot project and created docker image called kubernatesimage in my local machine. So when I run docker images it will list down all the images which I have locally,
REPOSITORY                         TAG       IMAGE ID       CREATED         SIZE
kubernatesimage                    latest    0280b64ac863   15 hours ago    557MB
solr                               latest    e6b43a626b70   3 weeks ago     520MB
apache/zeppelin                    0.9.0     4e276fc244de   5 weeks ago     4.6GB
cassandra                          latest    8baadf8d390f   6 weeks ago     405MB
suhothayan/hadoop-spark-pig-hive   2.9.2     671a17ccce40   18 months ago   2.63GB
loliconneko/oracle-ee-11g          latest    b1ed15c38b8c   24 months ago   5GB

Then I referred this documentation to pull my docker image into dockerhub. So I tagged the image and pushed it by following commands,
docker tag 0280b64ac863 semicolon10/kubernatesimage:firsttry

docker push semicolon10/kubernatesimage

But it results an error,

The push refers to repository [docker.io/semicolon10/kubernatesimage]
tag does not exist: semicolon10/kubernatesimage:latest

Here one thing I noticed is that after docker tag it will create another docker image locally with the assigned tag,
REPOSITORY                         TAG        IMAGE ID       CREATED         SIZE
kubernatesimage                    latest     0280b64ac863   15 hours ago    557MB
semicolon10/kubernatesimage        firsttry   0280b64ac863   15 hours ago    557MB
solr                               latest     e6b43a626b70   3 weeks ago     520MB
apache/zeppelin                    0.9.0      4e276fc244de   6 weeks ago     4.6GB
cassandra                          latest     8baadf8d390f   6 weeks ago     405MB
suhothayan/hadoop-spark-pig-hive   2.9.2      671a17ccce40   18 months ago   2.63GB
loliconneko/oracle-ee-11g          latest     b1ed15c38b8c   24 months ago   5GB

Note: I have successfully logged into my dockerhub account and my dockerhub username is semicolon10. So please can someone point out the issue here?

A: you should:
docker tag 0280b64ac863 docker.io/semicolon10/kubernatesimage:firsttry

Then push:
docker push docker.io/semicolon10/kubernatesimage:firsttry

Note include the repository : docker.io


text:
Q: What's the use of the derivation of an algebra? We call the derivation of an algebra $A$ an arbitrary linear function $\delta : \: A \rightarrow A$ such that $$\forall_{a,b \in A} \: \delta (ab) = \delta (a) b + a \delta (b)$$
But for what things do we use it? Why is it useful? Especially in the context of Differential Geometry?


text:
Q: Writing multiple lists to multiple output files I am working with datasets stored in large text files. For the analysis I am carrying out, I open the files, extract parts of the dataset and compare the extracted subsets. My code works like so:
from math import ceil

with open("seqs.txt","rb") as f:
    f = f.readlines()

assert type(f) == list, "ERROR: file object not converted to list"

fives = int( ceil(0.05*len(f)) )
thirds = int( ceil(len(f)/3) )

## top/bottom 5% of dataset
low_5=f[0:fives]
top_5=f[-fives:]

## top/bottom 1/3 of dataset
low_33=f[0:thirds]
top_33=f[-thirds:]

## Write lists to file
# top-5
with open("high-5.out","w") as outfile1:
   for i in top_5:
       outfile1.write("%s" %i)
# low-5
with open("low-5.out","w") as outfile2:
    for i in low_5:
        outfile2.write("%s" %i)
# top-33
with open("high-33.out","w") as outfile3:
    for i in top_33:
        outfile3.write("%s" %i)
# low-33
with open("low-33.out","w") as outfile4:
    for i in low_33:
        outfile4.write("%s" %i)

I am trying to find a more clever way of automating the process of writing the lists out to files. In this case there are only four, but in the future cases where I may end up with as many as 15-25 lists I would some function to take care of this. I wrote the following:
def write_to_file(*args):
    for i in args:
        with open(".out", "w") as outfile:
            outfile.write("%s" %i)

but the resulting file only contains the final list when I call the function like so:
write_to_file(low_33,low_5,top_33,top_5)

I understand that I have to define an output file for each list (which I am not doing in the function above), I'm just not sure how to implement this. Any ideas?

A: You could have one output file per argument by incrementing a counter for each argument. For example:
def write_to_file(*args):
    for index, i in enumerate(args):
        with open("{}.out".format(index+1), "w") as outfile:
           outfile.write("%s" %i)

The example above will create output files "1.out", "2.out", "3.out", and "4.out".
Alternatively, if you had specific names you wanted to use (as in your original code), you could do something like the following:
def write_to_file(args):
    for name, data in args:
        with open("{}.out".format(name), "w") as outfile:
            outfile.write("%s" % data)

args = [('low-33', low_33), ('low-5', low_5), ('high-33', top_33), ('high-5', top_5)]
write_to_file(args)

which would create output files "low-33.out", "low-5.out", "high-33.out", and "high-5.out".

A: Make your variable names match your filenames and then use a dictionary to hold them instead of keeping them in the global namespace:
data = {'high_5': # data
       ,'low_5': # data
       ,'high_33': # data
       ,'low_33': # data}

for key in data:
    with open('{}.out'.format(key), 'w') as output:
        for i in data[key]:
            output.write(i)

Keeps your data in a single easy to use place, and assuming you want to apply the same actions to them you can continue using the same paradigm.
As mentioned by PM2Ring below, it would be advisable to use underscores (as you do in the variable names) instead of dashes(as you do in the filenames) as by doing so you can pass the dictionary keys as keyword arguments into a writing function:
write_to_file(**data)

This would equate to:
write_to_file(low_5=f[:fives], high_5=f[-fives:],...) # and the rest of the data

From this you could use one of the functions defined by the other answers.

A: Don't try to be clever. Instead aim to have your code readable, easy to understand. You can group repeated code into a function, for example:
from math import ceil

def save_to_file(data, filename):
    with open(filename, 'wb') as f:
        for item in data:
            f.write('{}'.format(item))

with open('data.txt') as f:
    numbers = list(f)

five_percent = int(len(numbers) * 0.05)
thirty_three_percent = int(ceil(len(numbers) / 3.0))
# Why not: thirty_three_percent = int(len(numbers) * 0.33)
save_to_file(numbers[:five_percent], 'low-5.out')
save_to_file(numbers[-five_percent:], 'high-5.out')
save_to_file(numbers[:thirty_three_percent], 'low-33.out')
save_to_file(numbers[-thirty_three_percent:], 'high-33.out')

Update
If you have quite a number of lists to write, then it makes sense to use a loop. I suggest to have two functions: save_top_n_percent and save_low_n_percent to help with the job. They contain a little duplicated code, but by separating them into two functions, it is clearer and easier to understand.
def save_to_file(data, filename):
    with open(filename, 'wb') as f:
        for item in data:
            f.write(item)

def save_top_n_percent(n, data):
    n_percent = int(len(data) * n / 100.0)
    save_to_file(data[-n_percent:], 'top-{}.out'.format(n))

def save_low_n_percent(n, data):
    n_percent = int(len(data) * n / 100.0)
    save_to_file(data[:n_percent], 'low-{}.out'.format(n))

with open('data.txt') as f:
    numbers = list(f)

for n_percent in [5, 33]:
    save_top_n_percent(n_percent, numbers)
    save_low_n_percent(n_percent, numbers)

A: On this line you are opening up a file called .out each time and writing to it.
with open(".out", "w") as outfile:

You need to make the ".out" unique for each i in args. you can achieve this by passing in a list as the args and the list will contain the file name and data.
def write_to_file(*args):
    for i in args:
        with open("%s.out" % i[0], "w") as outfile:
            outfile.write("%s" % i[1])

And pass in arguments like so...
write_to_file(["low_33",low_33],["low_5",low_5],["top_33",top_33],["top_5",top_5])

A: You are creating a file called '.out' and overwriting it each time.
def write_to_file(*args):
    for i in args:
        filename = i + ".out"
        contents = globals()[i]
        with open(".out", "w") as outfile:
            outfile.write("%s" %contents)

write_to_file("low_33", "low_5", "top_33", "top_5")

https://stackoverflow.com/a/6504497/3583980 (variable name from a string)
This will create low_33.out, low_5.out, top_33.out, top_5.out and their contents will be the lists stored in these variables.


text:
Q: Run javascript alert within PhP I've been wanting to post a javascript alert (a pop up window w/ a message) to simply say "Thanks! You've been added!". Once a user has entered in the details in the form and clicks the submit button.
I have googled how to do this, however when adding it, it never worked and have tried different ways but am getting stumped on how to do it now. If anyone knows what I am doing wrong then any help would be much appreciated.
I would also like to note this in a separate php file.
Below you will find my code;
insert.php
<?php
$con=mysqli_connect("localhost","cl51-main-3i6","password","cl51-main-3i6");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$email = mysqli_real_escape_string($con, $_POST['email']);

$sql="INSERT INTO emails ( Firstname, Lastname, Email) VALUES ( '$firstname', '$lastname', '$email')";

if (!mysqli_query($con,$sql)) {
    die('Error : ' . mysql_error($con));
}

echo '<script language="javascript">';
echo 'alert("Thank you! You've now joined the e-mail club!")';
echo '</script>';

header("Location: http://isometricstudios.co.uk/news.html");
exit;

mysqli_close($con);
?>

A: The problem is because the header() will execute the redirection immediately. use window.location in <script> instead of header(location)
<?php
$con=mysqli_connect("localhost","cl51-main-3i6","password","cl51-main-3i6");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$email = mysqli_real_escape_string($con, $_POST['email']);

$sql="INSERT INTO emails ( Firstname, Lastname, Email) VALUES ( '$firstname', '$lastname', '$email')";

if (!mysqli_query($con,$sql)) {
    die('Error : ' . mysql_error($con));
}

echo '<script language="javascript">';
echo 'alert("Thank you! You've now joined the e-mail club!")';
echo 'window.location.href="http://isometricstudios.co.uk/news.html";';
echo '</script>';

exit;

mysqli_close($con);
?>

Now the alert will be displayed and redirected only when ok button is pressed

A: Did you scaped the ' in your string?
echo 'alert("Thank you! You\'ve now joined the e-mail club!")';

A: You have to escape single quotes in your string which you echo:
echo 'alert("Thank you! You\'ve now joined the e-mail club!")';

A: Your code is fine apart from one line
 echo 'alert("Thank you! You've now joined the e-mail club!")';

You are using 's to quote the line but you have a ' in you've. Write "You have" instead. :)
echo 'alert("Thank you! You have now joined the e-mail club!")';

You could also escape it as the other answerers said but it makes the code slightly messier in my opinnion

A: If you redirect the browser with a Location Header, any javascript code on the page itself is not executed, because the page you're redirecting to is loaded instead.
Also, I don't think you can echo or otherwise output any content before calling the header function.
If you want to show an alert, do it on the page you're redirecting to, or, if that's not under your control, redirect using javascript instead of with the Location header:
document.location = 'http://isometricstudios.co.uk/news.html';

Also, it's probably easier to not use echo for writing javascript, because then you'd have to escape quotes, which you failed to do in
echo 'alert("Thank you! You've now joined the e-mail club!")';

It's easier to just keep javascript outside your php tags, so something like
<?php
(do server-side php stuff)
?>

<script>
(do client-side javascript stuff)
</script>

<?php
(do more server-side php stuff)
?>


text:
Q: How to add missing rows (URLs containing page numbers) to an array (like seq in Linux) I have an array consisting of URLS of the form:
$URLs = @("https://somesite.com/folder1/page/1/"
,"https://somesite.com/folder222/page/1/"
,"https://somesite.com/folder222/page/2/"
,"https://somesite.com/folder444/page/1/"
,"https://somesite.com/folder444/page/3/"
,"https://somesite.com/folderBBB/page/1/"
,"https://somesite.com/folderBBB/page/5/")

They always have /page/1/, I need to add (or reconstruct) all missing URLS from the highest page down to 1 so it ends up like so:
$URLs = @("https://somesite.com/folder1/page/1/"
,"https://somesite.com/folder222/page/1/"
,"https://somesite.com/folder222/page/2/"
,"https://somesite.com/folder444/page/1/"
,"https://somesite.com/folder444/page/2/"
,"https://somesite.com/folder444/page/3/"
,"https://somesite.com/folderBBB/page/1/"
,"https://somesite.com/folderBBB/page/2/"
,"https://somesite.com/folderBBB/page/3/"
,"https://somesite.com/folderBBB/page/4/"
,"https://somesite.com/folderBBB/page/5/")

I'd imagine the Pseudo-Code would be something like:

*

*For each folder, extract the highest page number:

hxxps://somesite.com/folderBBB/page/5/

*

*Expand this out from (5) to (1)
 hxxps://somesite.com/folderBBB/page/1/
  hxxps://somesite.com/folderBBB/page/2/
  hxxps://somesite.com/folderBBB/page/3/
  hxxps://somesite.com/folderBBB/page/4/
  hxxps://somesite.com/folderBBB/page/5/

*Output this into an array
Any pointers would be welcome!

A: You can use a pipeline-based solution via the Group-Object cmdlet as follows:
$URLs = @("https://somesite.com/folder1/page/1/"
  , "https://somesite.com/folder222/page/1/"
  , "https://somesite.com/folder222/page/2/"
  , "https://somesite.com/folder444/page/1/"
  , "https://somesite.com/folder444/page/3/"
  , "https://somesite.com/folderBBB/page/1/"
  , "https://somesite.com/folderBBB/page/5/")

$URLs |
  Group-Object { $_ -replace '[^/]+/$' } | # Group by shared prefix
    ForEach-Object {
      # Extract the start and end number for the group at hand.
      [int] $from, [int] $to =
        ($_.Group[0], $_.Group[-1]) -replace '^.+/([^/]+)/$', '$1'
      # Generate the output URLs.
      # You can assign the entire pipeline to a variable
      # ($generatedUrls = $URLs | ...) to capture them in an array.
      foreach ($i in $from..$to) { $_.Name + $i + '/' }
    }

Note:

*

*The assumption is that the first and last element in each group of URLs that share the same prefix always contain the start and end point of the desired enumeration, respectively.

*

*If that assumption doesn't hold, use the following instead:
$minMax = $_.Group -replace '^.+/([^/]+)/$', '$1' |
            Measure-Object -Minimum -Maximum
$from, $to = $minMax.Minimum, $minMax.Maximum

*The regex-based -replace operator is used for two things:

*

*-replace '[^/]+/$' eliminates the last component from each URL, so as to group them by their shared prefix.

*-replace '^.+/([^/]+)/$', '$1' effectively extracts the last component from each given URL, i.e. the numbers that represent the start and end point of the desired enumeration.

Procedural alternative:
# Build a map (ordered hashtable) that maps URL prefixes
# to the number suffixes that occur among the URLs sharing
# the same prefix.
$map = [ordered] @{}
foreach ($url in $URLs) {
  if ($url -match '^(.+)/([^/]+)/') {
    $prefix, [int] $num = $Matches[1], $Matches[2]
    $map[$prefix] = [array] $map[$prefix] + $num
  }
}

# Process the map to generate the URLs.
# Again, use something like
#    $generatedUrls = foreach ...
# to capture them in an array.
foreach ($prefix in $map.Keys) {
  $nums = $map[$prefix]
  $from, $to = $nums[0], $nums[-1]
  foreach ($num in $from..$to) {
    '{0}/{1}/' -f $prefix, $num  # synthesize URL and output it.
  }
}


text:
Q: How not to select values which exist in another table I have two MySQL tables table1 and table 2.
Table 1:-
batch    semester  scode
IT         6        DA
IT         6        IA
IT         6        FA

Table 2:-
batch    subject   user
IT        DA       1

I want to run a query to get this output:-
scode
IA
FA

So basically I want to retrieve values from table 1 which does not exist in table2 for a user with id 1 and where the batch is IT and the semester is 6. I am new to the concepts of fetching data from two tables so I am unable to think of a way to do this. Any help is highly appreciated.

A: You can use NOT EXISTS
SELECT
scode
FROM TABLE1 T1
WHERE NOT EXISTS (
   SELECT 1 FROM TABLE2 T2 WHERE T1.scode = T2.subject
);

SEE DEMO

You can use NOT IN
SELECT
scode
FROM TABLE1 T1
WHERE T1.scode NOT IN (
   SELECT T2.subject FROM TABLE2 T2
)

SEE DEMO


text:
Q: Move Magento 2 Admin to Subdomain Is it possible to run the Magento admin from a subdomain?
I.E.
https://d1.com - live site
admin;
https://backend.d1.com/admin
I've attempted alias/park domain and a view other things (of course setting the custom url in Config > Admin ) but it usually just gets stuck in a redirect loop going to https://backend.d1.com/admin
Any advice would be greatly appreciated.

A: Yes! There is a possiblility to run from a subdomain.
Along with Aman's answer, you need to mask and forward the subdomain (https://backend.d1.com) to main domain (https://d1.com) in your domain settings.
For reference, see this

A: I think it is possible you can set the custom admin URL from Magento backend/admin
Store -> Configuration -> Advanced -> Admin -> Admin Base URL -> Use Custom Admin URL (Yes) -> Custom Admin URL

A: Is this of any help? https://gist.github.com/tegansnyder/65ba3396ec7cbf70bec9
I think it's for Magento 1 but principle should be the same?

A: The solution for Magento 2 is pretty simple:
Just configure as the main domain name (default value): backend.domain.com. So the admin will be available at backend.domain.com/admin.
Change scope to the storeview, and enter www.domain.com as the store domain name. So the store will be available at www.domain.com.


text:
Q: How to fix strange object is disposed exceptions when calling UWP APIs on .NET 5 I'm trying to call Windows 10 UWP OCR APIs from a .NET 5 Windows Forms application. The code which i'm using was perfectly working on .NET Core 3.1 but on .NET 5 it's extremely unstable.
For some reason the code throws either ObjectDisposedException or sometimes InvalidCastException. this usually happens on the call to decoder.GetSoftwareBitmapAsync() but sometimes right on the first await.
Also, hen wrapped in a method, it usually works on the first run but on subsequent runs it fails as above.
Here's a full code sample tested on both .NET Core 3.1 and .NET 5 with the above results.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading.Tasks;

namespace govno
{
    static class Program
    {
        static async Task<int> Main()
        {
            Bitmap Screen = new Bitmap(500, 500);
            Graphics g = Graphics.FromImage(Screen);
            g.CopyFromScreen(1, 1, 00, 0, Screen.Size);
            Bitmap S = new Bitmap(Screen, new Size(500, 500));
            var engine = Windows.Media.Ocr.OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en"));
            using MemoryStream memoryStream = new();
            S.Save(memoryStream, ImageFormat.Bmp);
            var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryStream.AsRandomAccessStream());
            var softwareBitmap = await decoder.GetSoftwareBitmapAsync();
            var ocrResult = await engine.RecognizeAsync(softwareBitmap);
            Console.WriteLine(ocrResult.Text);
            Console.WriteLine("OK!");
            Console.ReadLine();
            return 0;
        }
    }
}

Update: This appears to be a regression. See https://github.com/microsoft/CsWinRT/issues/640 for progress on fixing it.


text:
Q: Cordova/PhoneGap: can the user change the URL? I have a rather dumb question whose answer I haven't found yet. Is there any actual way for the user to change the URL he/she is viewing? Of course we can change the URL by using links, JavaScript, etcetera, but what I want to know is whether the user can change the URL in a situation outside the program's control.
The reason I'm asking this is because I use GET parameters to send information to some of the pages in my Cordova app. So far I have been assuming that the user cannot change the URL and so I haven't been worrying too much about sanitizing the input, verifying that it's correct, etcetera, etcetera, since I already assure that it's all right when generating the URLs the user is going to work with. However, if the user can change the URL by himself in any way that I am not aware of, then much more effort needs to be put in sanitizing the parameters!

A: As you noted, as long as you don't provide a way for the user to change the URL (links, JS, etc.) then they are not able to do so.
This is because the initial URL of the app is set in the native code and there is no way to inject a new URL into this setting.


text:
Q: How to get a PIL.Image object from cv2.imread? "Unrecognized image mode" error I'm trying to convert an image I get from img = cv2.imread(path) to bytes. So I used this:
def get_bytes(img):
    result = PIL.Image.fromarray(img, 'BGR')
    bio = io.BytesIO()
    bio.name = 'result.jpeg'
    result.save(bio, 'JPEG')
    bio.seek(0)
    return bio

but it gives me an "Unrecognized image mode" error in function fromarray in line 2.
The image is not None or something.
img.dtype = uint8


text:
Q: Pass this.state variable through App Context When I set the array data using the function getData() then try to call it in the function updateData() I get an error saying the this.state.data is undefined. Any thoughts on how I can pass a this.state variable from one function to another function in the app context provider?
Example code is below:
Any thoughts? Thank you!
export class AppProvider extends React.Component {
         constructor(props) {
           super(props);
           (this.state = {
             data: [],
           });
         }

         getData = async () => {
            const data = "abc"
            this.setState({
                data,
            });
        }

        updateData = async () => {
          console.log(this.state.data)
}

         render() {
           return (
             <AppContext.Provider value={this.state}>
               {this.props.children}
             </AppContext.Provider>
           );
         }
       }

A: Three Things i would like to say,

*

*you want to add the state variables separately so you want to do value={{data:this.state.data}}

*if you plan on using these functions in another component you want to add these functions to the value prop as well

*remove the async from the functions since there is no Promise to be resolved
  export class AppProvider extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          data: []
        };
      }

      getData = () => {
        const data = "abc";
        this.setState({
          data
        });
      };

      updateData = () => {
        console.log(this.state.data);
      };

      render() {
        return (
          <AppContext.Provider
            value={{
              data: this.state.data,
              getData: this.getData,
              updateData: this.updateData
            }}
          >
            {this.props.children}
          </AppContext.Provider>
        );
      }
    }

checked this in a small example, CodeSandbox here


text:
Q: Error creating bean with name 'conversionServicePostProcessor' I'm trying to add spring security to my spring project, but I'm facing this issue:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'conversionServicePostProcessor' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.beans.factory.config.BeanFactoryPostProcessor]: Factory method 'conversionServicePostProcessor' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.core.convert.converter.Converter.andThen(Lorg/springframework/core/convert/converter/Converter;)Lorg/springframework/core/convert/converter/Converter;

This is my POM
<project xmlns="http://maven.apache.org/POM/4.0.0"
    ....
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.16.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.16.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.16.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
            <version>8.5.38</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.15</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-ri</artifactId>
            <version>2.3.0</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.adrianwalker</groupId>
            <artifactId>multiline-string</artifactId>
            <version>0.1.2b</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.6.6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.16.Final</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.7.7</version>
        </dependency>
    </dependencies>
</project>

I'm using annotated configuration of Spring.
I tried to create application.properties file in src folder, adding this content as suggested in some other questions:
spring.main.allow-bean-definition-overriding=true

But it did not help.

A: I had to align spring-core version of my POM with spring version of spring-boot dependency.
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.24</version>
        </dependency>


text:
Q: Passing a function in Swift 3 One of the drawbacks of a new language is that there often major changes from version to version. As a result anything you find on the Web can easily be out of date. Or maybe it isn't and I just am not reading it correctly.
I'm trying to pass a function in a function call. I can get it to work without any parameters. I just declare the parameter I pass as a class global. Bad experiences in assembler make me want to avoid the dreaded global. Here's the pertinent parts of my working code:
class ViewController: NSViewController {
    var artistData: NSArray = []

    override func viewDidLoad() {
/*1*/   getDataFromUrl(url: "http://catbox.loc/artists.json", loadFunction: loadArtistTable())
      //getDataFromUrl(url: "http://catbox.loc/artists.json", loadFunction: loadArtistTable)
    }

/*2*/func getDataFromUrl(url: String, loadFunction: ()) {
  //func getDataFromUrl(url: String, loadFunction: (NSArray)) {
  session.dataTask(with: request) { data, response, err in
      do {
          let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
          self.artistData = json!
          }
          catch {
              print(error)
          }
/*3*/     loadFunction
        //loadFunction(self.artistData)
      }.resume()
  }
/*4*/ func loadArtistTable() {
//func loadArtistTable(_ jsonData: NSArray) {
    ...
  }

The commented out code is one of my many permutations on trying to get it to compile. Ideally, I would like to pass 'json' from the JSONSerialization call. This last attempt was base on the Apple documentation for closure where they gave the example:
var reversedNames = names.sorted(by: backward)

My Answer
I've accepted @Nirav D's answer, but I didn't try it. My answer is based on his code. I decided to stick with NSArray. The numbers correspond to the ones I've added to the code above.
/*1*/ getDataFromUrl(url: "http://catbox.loc/records.json", loadFunction: loadArtistTable)
/*2*/ func getDataFromUrl(url: String, loadFunction: @escaping (NSArray) ->()) {
/*3*/ loadFunction(json)
/*4*/ func loadArtistTable(jsonData: NSArray) {

In 3, I'm using the output of the JSONSerialization directly instead of copying it to a class variable.
Update
I tried @Nirav D's method and it works as well.

A: In Swift use Swift's native Array/Dictionary instead of NSArray/NSDictionary. The way you are looking is called completionHandler and pass the function as completionHandler when you call the function.
So first make getDataFromUrl like this way.
func getDataFromUrl(url: String, loadFunction: @escaping ([[String: Any]]?) -> Void) {
    session.dataTask(with: request) { data, response, err in
        var array: [[String:Any]]? = nil
        do {
            if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String: Any]] {
                 array = json
            }
        }
        catch {
            print(error)
        }
        loadFunction(array)
    }.resume()
}

Now create the loadArtistTable function
func loadArtistTable(array: [[String: Any]]?) {
    if let jsonArray = array {
        print(array)
    }
}

Now simply call your getDataFromUrl and pass loadArtistTable function as second argument of it.
self.getDataFromUrl(url: url, loadFunction: self.loadArtistTable)

Note: Here [[String: Any]] is array of dictionary if you receive array string than create array of String like this [String].


text:
Q: GSconnect downloaded not working I have downloaded and extracted GSConnect (Shell 3.30 extension 19) to my ASUS laptop, I have downloaded the "sudo apt install chrome-gnome-shell".
I downloaded the KDE app to my Samsung J2 Pro, and it seems to work.
I have extracted the zip archive, but it is not working, my phone shows "No devices". (even after a reboot of the laptop).
I'm using MATE on Ubuntu 18.04. I cannot find GSConnect listed anywhere on my laptop other than in the  Downloads folder, it shows a folder with 11 items, some of which are also folders.
Any help would be greatly appreciated.
Hal.

A: You cannot use gsconnect with mate. You can however use the regular kde connect. Just add this ppa as described here:
sudo add-apt-repository ppa:webupd8team/indicator-kdeconnect
sudo apt-get update

then:
sudo apt install kdeconnect indicator-kdeconnect

Now start the indicator from the app menu and you should be good to go.


text:
Q: Call function for everly key,value in dictionary Let's say we have a dict and specified function which takes two parameters as input
foo = {'key1':'value1', 'key2':'value2'}

def bar(key, value):
    print key, value

Is is possible to call this function for every key value pair in one liner?
I know that I can do it in list/dict comprehension but I think this solution is not pythonic cause I dont return anyting in bar function. Is there any recommended and pythonic way to do that?

A: Use a for-loop over the .items method of the dictionary:
for item in foo.items():
    bar(*item)

The * syntax unpacks the tuples (e.g. ('key1', 'value1')) into the arguments to a function. Note that you could do the unpacking in the for-loop too:
for k, v in foo.items():
    bar(k, v)

Both of which give:
key2 value2
key1 value1

You may notice that they are in a different order to the order you defined them in. This is just an implicit feature of dictionaries - they have no (reliable) order. The reason I say "reliable" is because it is deterministic (based on each object's hash, but it is unwise to rely on this.

A: yes, you can with a tiny modification to your function
foo = {'key1':'value1', 'key2':'value2'}

def bar(pair):
    key, value = pair
    print key, value

With this function at hand, you can use map.
map(bar, foo.items())

that produces:
key2 value2
key1 value1

A: Quoting PEP-20

Simple is better than complex.

Read the Zen of Python
Keeping things simple, you could do something like -
def bar(key, value):
    print key, value

for k, v in foo.items():
    bar(k, v)

A: foo = {'key1':'value1', 'key2':'value2'}

def bar(key, value):
    print key, value

[bar(key, value) for key,value in foo.items()]


text:
Q: Qbs StaticLibrary on MacOS I try to move an existing project from qmake to qbs, everything works fine so far but i can't link to google test static library in that project on MacOS while on windows it works fine.
On MacOS i get :-1: error: symbol(s) not found for architecture x86_64
GitHub repo of the project
googletest.qbs:
import qbs

StaticLibrary {
    name: "GoogleTest"
    files: [
        "googletest/googletest/src/gtest-all.cc",
        "googletest/googlemock/src/gmock-all.cc"
    ]

    cpp.includePaths: [
        "googletest/googletest/include",
        "googletest/googlemock/include",
        "googletest/googletest",
        "googletest/googlemock"
    ]

    Depends { name: "cpp" }
    Export {
        Depends { name: "cpp" }
        cpp.includePaths: [
            "googletest/googletest/include",
            "googletest/googlemock/include"
        ]
    }
}

test.qbs:
import qbs

QtApplication {
    name: "Test"
    targetName: "Test"

    Depends { name: "Qt"; submodules: ["core","testlib"]; versionAtLeast: "5.6" }
    Depends { name: "GoogleTest"}

    cpp.cxxLanguageVersion: "c++11"
    consoleApplication: true

    files: [
        "QtTypePrinters.h",
        "main.cpp",
        "QStringTest.cpp"
    ]
}

A: You need to set the following properties in your static library product:
cpp.cxxLanguageVersion: "c++11"
cpp.cxxStandardLibrary: "libc++"
cpp.minimumMacosVersion: "10.7" // or higher

By default, Qbs simply lets the compiler infer the defaults. gtest happens to require C++11 and libc++, which in turn is only supported by Apple on macOS 10.7 and above.

A: Are you sure that's the entire error message from the linker? Surely the actual missing symbol(s) are mentioned as well?


text:
Q: Power BI Custom Visual : Colour Change when modify date slicer I created a custom visual in power BI that allowed to insert different types of chart in one plot. But when I insert the plot on the dashboard, I have some trouble with date slicer. I define a colour for ma data and I save it with:

let view = dataView[0].categorical;
let categories = view.categories[0];
let objects = categories.objects;
let value = view.values;

for (let i = 0, len = Math.max(value.length); i < len; i++) {
  viewModel.dataPoints.push({
    category: < string > value[i].source.displayName,
    colour: objects && objects[i] && DataViewObjects.getFillColor(objects[i], {
      objectName: "colorSelector",
      propertyName: "fill"
    }, null),
    selectionId: this.host.createSelectionIdBuilder()
      .withCategory(categories, i)
      .createSelectionId(),
  });
}

But when I change the date slicer, objects is null or undefined and colour is reset to default.
There is a solution to always save the color in object when slicer is modify.
Thanks for yours help.

A: enumerateObjectInstances method :

public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstanceEnumeration {
 let objectName = options.objectName;
 let objectEnumeration: VisualObjectInstance[] = [];
 let index = 0;
 switch (objectName) {
  case 'xAxis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.xAxis,
    selector: null
   });
   break;
  case 'y1Axis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.y1Axis,
    selector: null
   });
   break;
  case 'y2Axis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.y2Axis,
    selector: null
   });
   break;
  case 'margin':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.margin,
    selector: null
   });
   break;
  case 'legend':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.legend,
    selector: null
   });
   break;
  case 'colorSelector':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       fill: {
        solid: {
         color: dp.colour || this.settings.colorSelector[Object.keys(this.settings.colorSelector)[index]]
        }
       }
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
  case 'datashape':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       shape: dp.symbol || this.settings.datashape[Object.keys(this.settings.datashape)[index]]
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
  case 'datatrace':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       charttype: dp.trace || this.settings.datatrace[Object.keys(this.settings.datatrace)[index]]
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
   };
   return objectEnumeration;
}

Capabilities.json :

{
    "dataRoles": [
        {
            "displayName": "X-Axis",
            "name": "x",
            "kind": "Grouping"
        },
        {
            "displayName": "Y-Axis 1",
            "name": "y1",
            "kind": "Measure"
        },
        {
            "displayName": "Y-Axis 2",
            "name": "y2",
            "kind": "Measure"
        },
        {
            "displayName": "Split by",
            "name": "splitby1",
            "kind": "Grouping"
        }
    ],
    "dataViewMappings": [
        {
            "conditions": [
                {
                    "x": {
                        "max": 1
                    },
                    "legend": {
                        "max": 1
                    },
                    "splitby1": {
                        "max": 1
                    }
                }
            ],
            "categorical": {
                "categories": {
                    "for": {
                        "in": "x"
                    }
                },
                "values": {
                    "group": {
                        "by": "splitby1",
                        "select": [
                            {
                                "for": {
                                    "in": "y1"
                                }
                            },
                            {
                                "for": {
                                    "in": "y2"
                                }
                            }
                        ]
                    }
                }
            }
        }
    ],
    "suppressDefaultTitle": true,
    "objects": {
        "xAxis": {
            "displayName": "X-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "y1Axis": {
            "displayName": "Y1-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "y2Axis": {
            "displayName": "Y2-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "datatrace": {
            "displayName": "Trace Type",
            "properties": {
                "charttype": {
                    "displayName": "Trace",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Line Chart",
                                "value": "line"
                            },
                            {
                                "displayName": "Line Marker Chart",
                                "value": "lineMarker"
                            }
                        ]
                    }
                }
            }
        },
        "margin": {
            "displayName": "Margins",
            "properties": {
                "l": {
                    "displayName": "Left",
                    "type": {
                        "numeric": true
                    }
                },
                "r": {
                    "displayName": "Right",
                    "type": {
                        "numeric": true
                    }
                },
                "t": {
                    "displayName": "Top",
                    "type": {
                        "numeric": true
                    }
                },
                "b": {
                    "displayName": "Bottom",
                    "type": {
                        "numeric": true
                    }
                }
            }
        },
        "legend": {
            "displayName": "Legend",
            "properties": {
                "enabled": {
                    "displayName": "Enabled",
                    "type": {
                        "bool": true
                    }
                },
                "orientation": {
                    "displayName": "Orientation",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Vertical",
                                "value": "v"
                            },
                            {
                                "displayName": "Horizontal",
                                "value": "h"
                            }
                        ]
                    }
                }
            }
        },
        "colorSelector": {
            "displayName": "Data Colors",
            "properties": {
                "fill": {
                    "displayName": "Color",
                    "type": {
                        "fill": {
                            "solid": {
                                "color": true
                            }
                        }
                    }
                }
            }
        },
        "datashape": {
            "displayName": "Shape Type",
            "properties": {
                "shape": {
                    "displayName": "Shape",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Default",
                                "value": "none"
                            },
                            {
                                "displayName": "Circle",
                                "value": "circle"
                            }
                        ]
                    }
                }
            }
        }
    }
}


text:
Q: SSIS Flat File Import into Oracle failing despite DT_WSTR definitions I am getting error messages about being unable to convert between unicode and non-unicode character sets when trying to import a flat file via SSIS.
My flat file is UTf-8 encoded according to Notepad++.  The file contains characters such as the "microgram" character (µg) for example.
My flat file connection manager is set up to use 65001 (UTF8) and all my columns are set up on my flat file connection manager to be DT_WSTR, and the data previews OK in the flat file connection manager.
My database is Oracle 11g, using Microsoft Oracle OLEDB driver for Oracle.
I have tried VARCHAR2 and NVARCHAR dta types in Oracle, but when I connect my DT_WSTR (65001) columns to my Oracle tables, I get the unicode conversion error.
I have tried conversion steps in my SSIS packaged, to convert to DT_WSTR and DT_STR.  Had some success with DT_STR, but I got my microgram symbol scrambled.
How hard should this be?  I set up a 65001 text file connection, with DT_WSTR column types and I cannot for the life of me connect it to Oracle using VARCHAR2, NVARCHAR.
Any advice appreciated.
Stephen


text:
Q: Python - 3D point to 2D coordinate I'm working on a 3D engine using only the standard python libraries.
I'm using Tkinter to display points.
I'd like to convert a given 3D (x, y, z) point to a 2D (x, y) coordinate to be displayed on a screen by drawing a line from one to the other.
I have tried searching online for how to do this but the answers don't seem to cover for all of my inputs.
I'd like to get a function that uses

*

*Camera X

*Camera Y

*Camera Z

*Camera Rotation X

*Camera Rotation Y

*Point X

*Point Y

*Point Z

to produce my 2D coordinate.
I don't really have any code to show since nothing I tried got close to doing what I want.
Thanks


text:
Q: Keyframe interpolation catmull rom I understand there are many methods to do this.  I am specifically interested in the catmull romfor animation purposes.  I am having trouble understanding it however.  All the sites I have visited have identified key poses as points.  However key poses can also contain joint angles.  Are these treated the same as points when interpolating?  And are there any good sites for learning catmull rom?

A: The Catmull-Rom spline calculation is a mathematical tool used to make a smooth curve from a set of points.  It is routinely used to plan the path of the camera so that the camera will smoothly transition, and won't sharply change view angles, while still allowing for the anchor points to be fairly sparse.  It could definitely also be used to map the transitions of animation skeletons, or the poses, including joints and other values.  The spline can be applied to any scalar value.  So you could apply the spline to the positions of the joint locations in an animation sequence.  You would calculate the X, Y and Z values separately.  But you could also apply it to joint angles, or other scalar values that change over time.  The spline will just interpolate a value along a smooth curve.
The best Catmull-Rom implementation I have found is Centripetal Implementation, where I give a detailed solution with full implementation here.
Catmull-rom curve with no cusps and no self-intersections
The principle article that helped me the most is here: http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
The main thing you need to understand is that this is a spline tool that takes a set of points and uses them as "anchor" points for curves that try to create a smooth path that goes through the points.  The path will always go through all of your points.  You have to add on two control points to either end.  If you are creating a closed curve where the first and last point are the same, the points you add to the beginning is the next to last point, and the point you add to the end is the second point.  If the line is open, you can repeat the first and end points, or in fact, I recommend extending the first and last segments in the same direction so that your line starts out with momentum moving in the direction of your lines.  Here are some of the artifacts from the various parameterizations.  Remember that the results from the "Uniform" version are the same as the unparameterized version.


text:
Q: Display data in dynamic matrix format using jquery I will get the below json from webapi and I need to display this data in matrix format on UI. How would I do this?
The json data looks like this:
[
 {"ShippingLine_Cd":"AAC","SizeType_Cd":"20BU","ERIStatus_Cd":"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"ACL","SizeType_Cd":"20BU","ERIStatus_Cd" :"Active","Shift_Nbr":"2"},
 {"ShippingLine_Cd":"AMA","SizeType_Cd":"20DR","ERIStatus_Cd" :"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"ABC","SizeType_Cd":"20DR","ERIStatus_Cd" :"Pending","Shift_Nbr":"2"},
 {"ShippingLine_Cd":"CDE","SizeType_Cd":"20DR","ERIStatus_Cd" :"Pending","Shift_Nbr":"3"},
 {"ShippingLine_Cd":"AAC","SizeType_Cd":"20DR","ERIStatus_Cd" :"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"CDE","SizeType_Cd":"20BU","ERIStatus_Cd" :"Pending","Shift_Nbr":"1"}
]

This desired UI format:

A: Because your question shows no code, I will only answer in pseudo code, its up to you to write the real code.
you could do something like this (after you first created your html table):
data.forEach(item => {
     var x = item.SizeType_Cd == ("20BU" ? 2 : 0) + item.Shift_Nbr;
     var y = 0; //some logic here to get the y coordinate
     table.children[y].chilren[x].text = item.ERIStatus_Cd; //set the status text
})


text:
Q: Laravel4 POST unexplained redirect to GET Another I-did-not-sleep-enough question, I'm sure. I'm posting it as a sacrifice to the Elder God Murphy: as soon as I expose my moronity for all to see, I'm guaranteed to find by myself that answer that otherwise will elude me for hours (by way of further penance, I will then post the answer as well).
I have a HTML form that gets rendered as
<form method="post" id="mysearch" action="/search/?uid=1701">
    <input id="searchterm" type="text" name="query" />
</form>

The form can be submitted via jQuery $.POST with url of '/search' and data of { uid: '1701', query: $('#searchterm').val() } and it works.
If I press ENTER after entering something, and thus override the jQuery submission, the following happens:

*

*a POST is issued to the server, as expected.

*the Route::post('/search', function() {... does not get invoked.

*a 301 Moved Permanently is returned

*a GET with search parameters lost is issued to the URL specified by the Redirect

*quite obviously, the search fails.

The 301 response looks like something by Laravel4, added explicitly:
HTTP/1.0 301 Moved Permanently
Date: Thu, 28 Nov 2013 14:05:29 GMT
Server: Apache
X-Powered-By: PHP/5.4.20
Cache-Control: no-cache
Location: http://development/search?uid=1701
Connection: close
Content-Type: text/html

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="refresh" content="1;url=http://development/search?uid=1701" />
    <title>Redirecting to http://development/search?uid=1701</title>

Redirecting to Redirecting to http://development/search?uid=1701

This is not the same as this question, because there the redirect is expected and it's the answer to that which is undesired. Here it's the redirect itself that is generated for no reason that I can (for now) see.
I suspect that for some reason I'm triggering the "security redirect" described in this other answer, that is not triggered by jQuery (either because it puts everything in the POST while here I've one parameter in the URL and another in the POST, or because jQuery uses XHR).
I had thought it might be a CSRF defense, but that particular route isn't shielded. As a last resource, I'll CSRF-protect the route and add the token to the form, even if it looks a bit like voodoo to me. Something vaguely similar appears to be happening in Rails.
Workarounds
I've got not one, not two, but three workarounds that neatly sidestep the question of why is the above happening:

*

*(most brutal) block the keyUp event in the form.

*redirect the submit event of the form to jQuery

*(most transparent) route the above event to $('#search-button').click()
...but I'd like to make without the button altogether (which I could do with jQuery) and without jQuery altogether. As well as understand what is happening here. I'm 99% certain I'm missing something obvious.
Debugging
I'm now going to grep -r "Redirecting to" * the whole framework source code (I expect to find something in Symfony/Components/HttpFoundation/ResponseRedirect) and doing step-by-step from there.

A: TL;DR
ensure POST URLs do not end with a slash. -- but Laravel 4.1 users check the update below, first.
=======
When it works, it's not superstition - it's science :-(

as soon as I expose my moronity for all to see, I'm guaranteed to find by myself
  that answer that would otherwise elude me for hours

I will argue that Laravel4's HTML message could have been just a bit more informative.
The grep found as expected the origin of the redirect:
grep -r "Redirecting to" *
vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/RedirectResponse.php:        <title>Redirecting to %1$s</title>
vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/RedirectResponse.php:        Redirecting to %1$s.

at that point, a simple backtrace found the origin, very early in Laravel4 spin-up:
bootstrap/start.php:

...
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/

$app = new Illuminate\Foundation\Application;

$app->redirectIfTrailingSlash();

As soon as I saw the redirectIfTrailingSlash, I realized that the two URLs sent by the form and by jQuery were not the same:
... action="/search/?uid=1701">   <--- TRAILING SLASH AFTER 'search'

... url:   '/search',             <--- NO TRAILING SLASH
    data:  {
               uid  : 1701,
               query: $('#searchterm').val()
           },
...

Why this should happen I don't quite grok, but the solution is fiendishly simple:
remove the slash from the POST action field.
(and ensure .htaccess has no rule to consider the URL a "directory" and add back the slash - but if it had, jQuery would have failed too).
UPDATE
Apparently, the matter got reviewed in Laravel 4.1. The upgrade mentions

Removing Redirect Trailing Slash
In your bootstrap/start.php file, remove the call to
  $app->redirectIfTrailingSlash(). This method is no longer needed as
  this functionality is now handled by the .htaccess file included with
  the framework.
Next, replace your Apache .htaccess file with this new one that
  handles trailing slashes.


text:
Q: Wolfram Mathematica NDSolve error I'm getting an error for the BC in this equation:
s = NDSolve[{D[h[t, x], t] + Sin[x Degree] h[t, x]^2 D[h[t, x], x] +
     2/3 Cos[x Degree] h[t, x]^3 == 0, h[0, x] == 1,
   D[h[t, 0], x] == 0}, h, {t, 0, 100}, {x, 0, 90}]

NDSolve::deqn: Equation or list of equations expected instead of True in the first argument {2/3 Cos[[Degree] x] h[t,x]^3+h[t,x]^2 Sin[[Degree] x] (h^(0,1))[t,x]+(h^(1,0))[t,x]==0,h[0,x]==1,True}. >>

Any tips?

A: The last condition:
D[h[t, 0], x] == 0

is always True as you derivate on a constant.  If what you mean is
D[ h[t,x], x]  /. x->0

that's something else.
For the time being, just remove it (and possibly find another sensible boundary condition compatible with the order of your equation).
NDSolve[{D[h[t, x], t] + Sin[x] h[t, x]^2 D[h[t, x], x] + 2/3 Cos[x] h[t, x]^3 == 0, h[0, x] == 1}, h, {t, 0, 100}, {x, 0, Pi/2}]

works with a few warnings about the underdetermined system.


text:
Q: Can I share ipa files OTA without collecting UDIDs through a 99$ publisher account I want to know can ipa files be shared through a 99$ publisher account without demanding the UDID of your testers, as in an enterprise account.

A: No. Each ipa file contains embedded.mobileprovision file. This files contains information about provisioning profile app was signed and devices on which app can be installed. If UDID not in this file then app can't be installed on this device.
Look at service https://testflightapp.com/ It can help you collect info about devices and publish builds.


text:
Q: Code to detect all words that start with an X in a array :Python import urllib.request
import csv
import http.client
import bs4
import Data
import re

from bs4 import BeautifulSoup
from Data import DA

#Extracting Html code from the URL
with urllib.request.urlopen("http://www.apecbraking.co.uk/catalogue/frictionParts/range/783854") as url:
        D = url.read()

#HTML Code *

soup = BeautifulSoup(D)
Table = (soup.table)
soup = (Table.get_text())

#Creates 'APEC.csv'

file = open("APEC.csv", "w")
file.write(soup)
file.close()
print('Written')

# Set the Data into a list so it can be refered back to later on e.g searching for only words with certain letter
# from there they can be seperated from one list into categories (Variables)

newRow = []
with open('APEC.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        print()
    #New List
    newRow.append(row)

print(re.findall('A'))

Anyone explain to me whats wrong i do not understand tbh :/

Error
Traceback (most recent call last):
  File "C:/Users/B8/Desktop/Task/TaskOriginal.py", line 49, in <module>
    print(newRow.findall('A'))
AttributeError: 'list' object has no attribute 'findall'

Ignore had to add more detail to update
  sdfdsffffffffffffffffffffddfsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss

A: try using
with open('yourfile') as f:
    new_list = [row for row in f if row.startswith('A')]

A: Your newRow has type list. That has no method associated with this type. You can get list of all available methods for this type by typing help(list) in python console.

A: You need to import the regular expression library
import re

OR just try this snippet of code
print([item for item in newRow if item[0]=='A'])


text:
Q: How to install a specific version of GLIBCXX? I need to install up to GLIBCXX_3.4.2, but not later. All the instructions I have found let you install the latest version right away. I am a beginner so please be a little detailed.

A: GLIBCXX_3.4.2 is extremely old; it's from 2004 or so.  It's unlikely that this version is your actual baseline requirement.
You need to figure out what operating system version the cluster uses, set up a chroot or virtual machine with that, and use that to build your software.


text:
Q: How to compare AT&T-assembly-like sources (e.g. CUDA PTX)? I want to compare two pieces of low-level code, each in its own file. The format is AT&T-Assembly-style: For me, it's two CUDA PTX files, but this question applies also for the output of gcc -S or clang -S. For the sake of discussion assume that they're two implementations of the same function.
Now, I can of course diff the files textually. The problem is that the register assignments are different. The programs could be completely the same, just with different register names; or a small difference in one line may change the register assignments everywhere (e.g. reduce everything by 1 since an extra register is not used).
I don't mind extra instructions or comments etc. - those are handled just fine by textual diff tools.
My question: What can I do in order to hide those register differences everywhere, for a more "structural" comparison? Should I try some "canonicalization" with a pre-diff'ing parsing script (and if so, which/how)? Can I maybe avail myself of an assembler which takes my code, or a compiler which produces my code, to help me with this?


text:
Q: Find the volume of the region by triple integral
What is triple integral? How can I sketch region $D$ as well as evaluate it's volume? I get stuck.

A: By considering the $x$, $y$, and $z$ intercepts, we see that the region is the pyramid determined by the points $(1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1)$. By slicing the pyramid at a fixed $z$ and solving for $x$ and $y$ in terms of $z$, we obtain:
$$
V = \int_0^1 \int_0^{1-z} \int_0^{1 - z} dx \, dy \, dz = \int_0^1 (1 - z)^2 \, dz = \left[ z - z^2 + \frac{z^3}{3} \right]_0^1 = \frac{1}{3}
$$
which agrees with the usual formula for finding the volume of a pyramid:
$$
V = \frac{1}{3}(\textsf{area of base})(\textsf{height}) = \frac{1}{3}(1^2)(1) = \frac{1}{3}
$$


text:
Q: jquery setInterval or animate with easing I've got a problem with setInterval and .animate(); during a project in jQuery/JavaScript.
I use the following code for start my interval:
interval=setInterval(function(){initspin()},40);
What it does with initspin():
$('.device-carousel .spincontent').css('left','-'+(currimgnum-1)*imagewidth+'px');
It moves the div container .spincontent every 40ms around 500px to the left side. It's necessary to do all the 500px steps, because the background-image of the .spincontent is a image-stripe of 22 images for a 3D spinner.
What I would like to have is, that after 50% of the .spincontent the ratio change from 40ms to 60ms for a lower/easing moving.
How can I realize this? Or is it better to switch to .animate()?

A: jQuery has clear easing functions that you can use with .animate().
It would be both cleaner, easier to understand, and smoother.
http://api.jquery.com/animate/


text:
Q: Why does icrawler pause when downloading dozens of images? I want to download image from Google using icrawler. I set the maximum number of download to 1000. But I just get 92 images when it stops. Moreover, the result is different every time I run it, which is less than 100.
from icrawler.builtin import GoogleImageCrawler

for var in ['car front bumper damage']:
    var_folder = var.replace(" ", "_")
    image_folder = '/content/drive/MyDrive/DataStor/Crawler-datasets/'
    path = image_folder + var_folder

    import os
    try:
        os.makedirs(path)
    except FileExistsError:
        print("File already exists")

    print(f'Collecting images for {var}......')
    google_Crawler = GoogleImageCrawler(downloader_threads=4, storage = {'root_dir': path})
    google_Crawler.crawl(keyword = var , max_num = 1000)
    print(google_Crawler.feeder.in_queue.qsize())

I don't know if the parameters are not set correctly.

A: this is because when you are crawling in google images only the first page is processed so you cannot get all your 1000 images. a solution is to crawl multiple times and in different periodes :
google_Crawler.crawl(keyword = var, max_num=350, date_min=date(2019, 1, 1), date_max=date(2019, 12, 31))
google_Crawler.crawl(keyword = var, max_num=350, date_min=date(2020,1,1), date_max=date(2020, 12, 31), file_idx_offset='auto')
google_Crawler.crawl(keyword = var, max_num=350, date_min=date(2021,1,1), date_max=date(2021, 12, 31), file_idx_offset='auto')

you can crawl more just you have to specifie a different periode if you don't want to have duplicate images
dont for get to :
from datetime import date


text:
Q: How to check if a model has been changed but has not been saved to the server? (Ember.js / Ember-data) With ember models as they are changed by user input, they are persisted over the application with the changed values (until a refresh of some sort to reload the data from the server). Now  these models and their changes have not been saved to the server.
So I am wondering how I can check if models have been changed but have not been saved to the server yet.
Use case: To let users know that the following changes have not been saved yet.
I am just looking for some sort of boolean variable if one is available through ember or ember-data.
If not, some help would be appreciated to roll my own (I'm very new to ember).

A: You want the isDirty attribute.


text:
Q: Is it possible to support multiple snapshots / store a snapshot / restore from a snapshot to a state with another snapshot? So, I would like to have a snapshot structure like the following:
A snapshot 1 is taken. Some code is run, then a snapshot 2 is taken.
Then some more code is run, and the database is reverted to snapshot 2. Then more code, then snapshot 2, N times.
Then, once all that is done, the database is restored to its original state, snapshot 1. Basically, I would like it to be the case that I do not need to delete existing snapshots when restoring a snapshot, but rather that snapshot 1 is "stored" in snapshot 2 somehow, and when snapshot 2 is loaded, snapshot 1 is available again for a subsequent restore.
It seems as though this should be possible, because if snapshot 1 is "frozen" immediately prior to snapshot 2 being created, then once snapshot 2 is reverted to, there should be nothing preventing snapshot 1 from working, since the database state is identical to when it was frozen and snapshot 2 was created.
Is this possible? Do I need to create a snapshot of a system table?

A: This can't be done, the snapshots are not 'tiered' such that snapshot 2 can revert back to the snapshot 1 state.
In SQL Server, database snapshots preserve the original state of each page only when it is changed in the source database. Snapshot 2 is not preserving changed pages from snapshot 1 but from the original source database.
The documentation highlights this in step 2 under "How to Revert a Database to a Database Snapshot".
Your best bet would be to copy the original database, then take a snapshot of the copied database. Run your "snapshot 2" tests against the snapshot taken of the copied database. You can then easily revert the snapshot for multiple tests and return to your pre-test state and when you're finished, simply drop the copied database. In this fashion, your original database will be unaffected by your testing.


text:
Q: What does this RegExp pattern /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/ mean in Javascript? This regex
/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/

pattern is intended to match a valid password.
I've searched the answer on regexper.com, here is the link.
I know the meaning of the contents in each parenthesis, but I don't know why here are there parentheses and how they work together..

A: The pattern  (?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,} asserts

*

*6 or more characters

*a digit

*a lower-case letter

*an upper-case letter

That's it.
Explanation of the moving parts:

*

*(?=.*\d) checks if a digit exists using a positive lookahead.

*(?=.*[a-z]) checks in the same fashing to see if a lowercase letter exists.

*(?=.*[A-Z]) .. and an uppercase letter exists as well.

*.{6,} The 6+ quantifier is obvious.

The beauty of using a lookahead here is it makes it easy to (spot and) maintain the password rules.

A: (?=.*\d) This is a positive lookahead to see if a digit exists
(?=.*[a-z]) This is a positive lookahead to see if a lowercase letter exists
(?=.*[A-Z]) This is a positive lookahead to see if an uppercase letter exists
.{6,} This matches for 6 or more of any character
So overall, it expects a string of 6 or more characters that contains at least one number, one lowercase letter, and one uppercase letter.


text:
Q: If $f(x) \lvert f(x^m) (m \gt 1)$, then every root of $f$ must be $0$ or a root of unity. If $f \in \mathbb{C}[x]$ satisfies $f(x)\ \lvert\ f(x^m)\ (m \gt 1)$, prove that every root of $f$ is either $0$ or a root of unity.
My idea: let $\alpha$ be a root of $f$, show that $\alpha^{q} = \alpha$ for some natural number $q$.
  Let $\alpha$ be a root of $f$, then so is $\alpha^{m}$, because $f(x)\ \lvert\ f(x^m)$. Apply this fact repeatedly, it follows that the sequence
$$\alpha, \alpha^{m},\alpha^{m^2},\dots$$
contains only roots of $f$, therefore must contain a loop. That is, there is some $\beta = \alpha^{m^p}$ and a natural number $q$ such that $\beta^{q} = \beta$, thus either $\beta = 0$ or $\beta^{q-1} = 1$.
But how to show that $\alpha$ is also contained in this loop?

A: Let me complete your proof: There's $p$ and $q$ such that
$$\alpha^{m^p}=\alpha^{m^q}$$
and if $\alpha\ne0$ then
$$\alpha^{m^q-m^p}=1$$
and this is the needed result.

A: You have proved that $\beta$ is either $0$ or a root of unity. But $\alpha$ is a root of $\beta$, so either $0$ or a root of unity as well.


text:
Q: Is it possible to know how a user connected to an Angular / firebase app? I have an Angular / firebase application which provides two ways for a user to connect:

*

*The classic couple email / password

*A link to sign in from an email (using the "sendSignInLinkToEmail()" method from Firebase/auth)

I would like to know (from the angular app), when the user sign in, which way they used.
Thank you for your time.
I tried both ways and looked in the "user" object return by firebase.
I found a lot of information, including a "provider" but not detailed enough to know if it was a "mail/password connection" or the link one.


text:
Q: MongoDB - distinct with multiple fields and get most recent result I am saving message communication between users in mongoDB in format below
instance = {
    'from_user' : from_user,
    'to_user' : to_user,
    'message' : msg_text,
    'date' : timezone.now(),
}

For logged-in user I need to query his communication with all others and fetch only their single most recent message text.
e.g. from following dataset
{'from_user':'user1', 'to_user':'user2', 'message':'Hello World'}
{'from_user':'user2', 'to_user':'user1', 'message':'Hello World2'} # most recent between user1 & user2
{'from_user':'user1', 'to_user':'user3', 'message':'Hello World3'}
{'from_user':'user3', 'to_user':'user4', 'message':'Hello World4'}

query result should be following
{'from_user':'user2', 'to_user':'user1', 'message':'Hello World2'}
{'from_user':'user1', 'to_user':'user3', 'message':'Hello World3'}

A: The following query finds the most recent message to or from user1:
db.msgs.find({ "$or" : [ { "from_user" : "user1" }, { "to_user" : "user1" } ] })
       .sort({ "date" : -1 })
       .limit(1)

If you want to find the most recent message to a user and the most recent message from a user, you'll need two queries:
db.msgs.find({ "from_user" : "user1" }).sort({ "date" : -1 }).limit(1)
db.msgs.find({ "to_user" : "user1" }).sort({ "date" : -1 }).limit(1)


text:
Q: zeppelin with sparkr is not displaying dataframe as table The zeppelin R interpreter documentation states:
If you return a data.frame, Zeppelin will attempt to display it using Zeppelin's built-in visualizations.

This can be seen in the documentation example:

However, when I attempt to run the same R commands from my zeppelin 0.6.0 notebook, I see the following:

Any idea why I'm not seeing the tabular output?

A: You need to register a temp table and then do a select * from temp_table, just as @Arun Gunalan suggested.