text:
Q: How do I plot boundary decisions of multiple classifiers in one figure? I want to plot the decision boundary conditions for multiple decision grain boundary in the same figure
The code is as follows:
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis,QuadraticDiscriminantAnalysis
from sklearn.ensemble import AdaBoostClassifier,BaggingClassifier,RandomForestClassifier,HistGradientBoostingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import VotingClassifier,ExtraTreesClassifier

iris = load_iris()
X = iris.data[:, :2]
classifiers = [LogisticRegression(solver='sag',penalty='l2',multi_class='ovr',
            max_iter=25000,random_state=None,fit_intercept=True),
            LinearDiscriminantAnalysis(),
            QuadraticDiscriminantAnalysis(),
            DecisionTreeClassifier(min_samples_leaf=1),
            BaggingClassifier(),
            RandomForestClassifier(),
            AdaBoostClassifier(),
            HistGradientBoostingClassifier(),
            VotingClassifier(estimators=[('rfc',RandomForestClassifier()),
                                         ('dtc',DecisionTreeClassifier())],voting ='soft'),
            ExtraTreesClassifier()]

for classifier in classifiers:
    classifier.fit(X,iris.target)
    disp = DecisionBoundaryDisplay.from_estimator(classifier, X, response_method="predict", xlabel=iris.feature_names[0], ylabel=iris.feature_names[1], alpha=0.5)
    disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor="k")

plt.show()

I did not get the result that I want, I need those plots in the same figure.
Can someone help me in this case?

A: To get the decision boundaries of different classifiers in one figure, make sure to pass the argument ax in DecisionBoundaryDisplay.from_estimator:
# Assuming there are 10 classifiers
fig, ax = plt.subplots(nrows=5, ncols=2)
ax = ax.T.flatten()
i = 0

for classifier in classifiers:

    classifier.fit(X,iris.target)
    disp = DecisionBoundaryDisplay.from_estimator(classifier,
    X, response_method="predict",
    xlabel=iris.feature_names[0], ylabel=iris.feature_names[1],
    alpha=0.5, ax=ax[i])

    disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor="k")

    # Refer to next Axes in a 5 * 2 grid created by plt.subplots
    i += 1

    # To get labels for contour plots
    labels = np.unique(iris.target)
    proxy = [plt.Rectangle((0,0),1,1,fc = pc.get_facecolor()[0]) for pc in disp.surface_.collections]
    disp.ax_.legend(proxy, labels)

plt.show()

This gives:

This answer was motivated by this answer and this answer.


text:
Q: Returning data from the factory to the controller I'm new to AngularJS and this is my first question in stackoverflow. I've been reading a lot of possible answers for this problem but I didn't find a solution. I have this in my factory (I think the important part is between the dots):
;(() => {
app.factory('Users', users)
users.inject = ['$state', 'UserServices']

function users($state, UserServices) {
  users.users = [];
.....
  users.activeDeactive = (userId, activate) => {
     UserServices.activeDeactive(userId, activate).then(
        response => {
           console.log(response); //it shows "{status: 0}", which is the desired value
           return response;
        }
     )
  }

.....
  return users;
}
})()

And this in my controller:
;(() => {
app.controller('UsersCtrl', usersCtrl);

function usersCtrl($scope, $state, Users, users, vendors, profiles, clients) {
   Users.users = users;
.....
   $scope.activeDeactive = function(userId, activate) {
      var response = Users.activeDeactive(userId, activate);
      console.log(response); //it shows undefined
   }
.....
   };
})();

How can I also get "{status: 0}" in the controller? I'm stuck on this for a long time... I've read about waiting for a service to resolve the data, to wait for the promise, etc... but I think this problem is much more simpler, because I've already managed to send the service info to this factory... The problem now is to send the data from the factory to the controller... Thank you very much!

A: Use below syntax in controller. The reason your code not working is you have written a service called Users.activeDeactive, you are calling it from the controller but not waiting for the response. Its very important to wait for the response. If the service call is successful, it will execute then part. Here you need to catch the response like in given syntax only.
In case of errors, it will go to the error part.
    ;(() => {
    app.controller('UsersCtrl', usersCtrl);

    function usersCtrl($scope, $state, Users, users, vendors, profiles, clients) {
       Users.users = users;
    .....
       $scope.activeDeactive = function(userId, activate) {
          Users.activeDeactive(userId, activate).then(function(data){
      response = data;
console.log(response);
   },
   function(error){
       console.log(error);
   });

    .....

   };
})();

A: in users factory method return promise.
users.activeDeactive = (userId, activate) => {
 return UserServices.activeDeactive(userId, activate).then(
     response => {
        console.log(response);
       return response;
    }
 )
}

and in controller method change to accept resolve object.
 $scope.activeDeactive = function(userId, activate) {
   Users.activeDeactive(userId, activate).then(response =>{
  console.log(response);
 });
}

Reason behind doing is .. UserService looks aync method as you have then in user factory. so controller method will call user factory method and will not wait until userservice returns data as that goes in to event loop. to make it work return promise from user factory method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gearman: Sending data from a background worker to the client Is it possible to send back data from a gearman worker that runs in the background (with PHP)?
I know that I can pass a status (numerator/denominator) to the client but I need to "return" data.
The background is that I need to call workers on different servers and if they don't respond, the main script should continue. So I think I have to run the workers in the background. But I need some data from them.
UPDATE:
It seems not to be possible. I think I have either to store the data in a shared database or to write it from the remote server to the local server or to read it from the remote server or to make something like this:
shell_exec('gearman -f getdata-192-168-200-1 > /my/path/ 2>&1 & echo $!');

A: I think you can pass the data from the worker to client using the following function
GearmanJob::sendData($result);

By giving your data in $result variable and also you can handle this data in the client by using the function
GearmanClient::setDataCallback("task_data");

function task_data($task)
{
    echo "DATA: " . $task->data() . "\n";
}

You can get bit more information
http://www.php.net/manual/en/gearmanclient.setdatacallback.php


text:
Q: How to override a method in the instantion of an object in C# I am a Java programmer trying to transition to C# and I'm hoping there's a way to do something in C# that I'm accustomed to in Java: overriding a method in the declaration of an abstract object like so:
//This is the way I do it in Java and want to do in C#
Keyword k = new Keyword("quit"){
    public abstract void do(String context){
        //TODO Do stuff
    }
};

This is for some text game stuff I've been doing for a while in Java. I've looked into abstract and virtual and anonymous classes but none of them do exactly this. Abstract and virtual want me to create a whole new subclass, but this would be time consuming and unfeasible on a large scale. Anonymous classes don't (as far as I can tell) enable me to override methods, just fields and don't provide any stabilization for me to rely on.
If there is a way to do this or something similar please explain. Thanks for your time.

A: That doesn't work in C#. You'll have to create a new class that inherits from Keyword.
public class MyKeyword : Keyword
{
    public MyKeyword(string s) : base(s)
    { }

    public override void do(string context)
    {
        // TODO: Do stuff.
    }
}

Anonymous Types in C# aren't classes that you can provide any public methods for. They only have properties, and are intended to be a quick, intra-method way of pasing complex data from one line to the next.
To be honest, I didn't know you could do what you show in Java. That is, if I'm understanding it as kind of an in-line class derivation.
Brian Rasmussen mentions using a delegate.  That would look something like this:
public delegate void DoSomething(string context);
public class Keyword
{
    public DoSomething Do;

    private void CallsDo()
    {
        if (Do != null)  Do("some string");
    }
}

Then you can assign to it:
Keyword k = new Keyword();
k.Do = (ctx) => { /* Do something with ctx string */ };

A: Delegates are probably what you are after.

A: You can utilize a delegate for this approach: Note the example
public class Keyword
{
     public delegate void Do();
}

//Area of Execution
{
   //...
   Keyword k = new Keyword();
   k.Do = delegate()
   {
       Console.Writeln("Anonymous Inner function assigned to a callback function i.e a Delegate!");
   };
}

These are much like function pointers in C/C++ but that may mean nothing to you depending on your background.
A delegate is, in the simplest terms, a type-safe object that encapsulates a method/function. What this means is that it maintains a reference to the method or methods and can invoke them later through the delegate object rather than explicitly on the method(s) themselves. You can assign an anonymous function to the right hand side much the same as you can to a method in Java as you described.
hope this helps. Read more here for delegates in-depth
Delegates


text:
Q: Is there any connection between the hypothetical planet Vulcan and the fictional planet Vulcan? For some time in the 19th century, it was believed that certain observed anomalies in the orbit of Mercury could be explained by the presence of a planet even closer to the sun, which was dubbed "Vulcan." Nobody ever found Vulcan, and eventually Einstein showed that these anomalies could be explained by general relativity instead.
Given the mythological names used for all the other planets in the Solar system, "Vulcan" is a pretty obvious name to use (especially for a hot planet). But it's still kind of funny that it's the name of both a very well-known fictional planet and a very well-known theorized-but-nonexistent planet.
Is there any evidence that Roddenberry was thinking of the hypothetical 19th-century planet when he named Spock's homeworld? Or did he get the name straight from Roman mythology?

A: Probably not.
According to Memory Alpha

Spock's homeworld was originally to have been Mars. At a time when Vulcans were known as Vulcanians, their home planet was to have been named Vulcanis. (Star Trek: The Magazine Volume 1, Issue 2, p. 82) This name was in fact used in an NBC promotional booklet announcing the first season of Star Trek: The Original Series, the 1966/1967 season.
The name was also used during early production of that first season but was changed to "Vulcan" soon thereafter. ("Amok Time" text commentary, TOS Season 1 DVD) The planet was referred to with that name in the final draft script of "Mudd's Women" (dated 26 May 1966), in which Kirk admitted to having been on Vulcan (though he didn't go into any further detail about the planet).

It seems more likely that the reference was to the mythological Vulcan rather than the putative astral object.
The look of Star Trek's Vulcan wasn't even decided upon until TOS Season 2 when Amok Time aired so any relation to a hot planet (such as the proposed missing planet) seems unlikely.

In the first scripted [for Amok Time] description of an orbital view of the planet, Vulcan is characterized as "a 'hot' planet... yellow, orange... no cool colors about it."


text:
Q: Visualforce page resets wrapper fields during rerender I have a wrapper class to that include opportunity line items and a selectlist value set.  When the page is rerendered, the oli fields are maintained, but the selectlist values are reset.  I can't see why.
<apex:page standardController="Opportunity" extensions="OpportunityProductEntry" >
        <apex:sectionHeader Title="Manage Products" subtitle="{!Opportunity.Name}"/>
        <apex:messages style="color:red"/>

        <apex:form id="frm">
            <apex:outputPanel id="mainBody">
                <apex:pageBlock title="Selected Products" id="sp">
                    <apex:variable var="rowNum" value="{!-1}" />
                    <apex:pageblockTable value="{!tableRows}" var="s" id="pgbt">
                        <apex:column >
                            <apex:commandLink value="Remove" action="{!RemoveFromTable}" reRender="sp" immediate="true" onComplete="ReRenderTable();">
                                <!-- this param is how we send an argument to the controller, so it knows which row we clicked 'remove' on -->
                                <apex:param value="{!s.oli.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                            </apex:commandLink>
                            <apex:variable var="rowNum" value="{!rowNum + 1}" />
                        </apex:column>
                        <apex:column headerValue="Product Name" value="{!s.oli.PriceBookEntry.Product2.Name}"/>
                        <apex:column >
                          <apex:selectList value="{!s.pb}" size="1">
                            <apex:selectOptions value="{!s.pb}"/>
                          </apex:selectList>
                        </apex:column>
                        <apex:column >
                            <apex:inputText value="{!s.str}"/>
                        </apex:column>
                        <apex:column headerValue="Unit Price">
                            <apex:inputField value="{!s.oli.UnitPrice}" required="true" id="price_level"/>
                        </apex:column>
                        <apex:column headerValue="Quantity">
                            <apex:inputField value="{!s.oli.Quantity}" required="true"/>
                        </apex:column>
                        <apex:column headerValue="Discount Item">
                            <apex:inputField value="{!s.oli.netsuite_conn__Discount_Item__c}"/>
                        </apex:column>
                    </apex:pageblockTable>
                    <apex:pageBlockButtons >
                        <apex:commandButton action="{!OnCancel}" value="Cancel" immediate="true"/>
                    </apex:pageBlockButtons>
                </apex:pageBlock>
            </apex:outputPanel>
        </apex:form>
    </apex:page>

public with sharing class OpportunityProductEntry {
    public Opportunity opp;
    public opportunityLineItem[] shoppingCart {get;set;}
    public String toUnselect {get; set;}
    public List<aTableRow> tableRows { get; set; }
    public List<selectoption> PriceBooks { get; set; }

    public class aTableRow {
        public OpportunityLineItem oli { get; set; }
        public List<selectoption> pb { get; set; }
        public String str { get; set; }

        public aTableRow(OpportunityLineItem c, List<selectoption> a, String b) {
            oli = c;
            pb = a;
            str = b;
        }
    }

    public List<selectoption> getPriceBooks() {
        List<selectoption> options = new List<selectoption>();
        Schema.DescribeFieldResult fr = Product2.Family.getDescribe();
        List<Schema.PicklistEntry> plelist = fr.getpicklistvalues();
        for(Schema.Picklistentry ple: plelist){
            options.add(new selectoption(ple.getvalue(),ple.getlabel()));
        }
        return options;
    }

    public OpportunityProductEntry(ApexPages.StandardController controller) {
        opp = [SELECT Id FROM Opportunity WHERE Id = :controller.getRecord().Id];

        shoppingCart = [
            SELECT  Id, netsuite_conn__Discount_Item__c, Quantity, UnitPrice, PriceBookEntryId, PriceBookEntry.Product2.Name
            FROM OpportunityLineItem
            WHERE OpportunityId = :opp.Id
        ];

        PriceBooks = getPriceBooks();

        tableRows = new List<aTableRow>();
        for (OpportunityLineItem sc : shoppingCart)     {
            tableRows.add(new aTableRow(sc, PriceBooks, 'test'));
        }
    }

    public PageReference RemoveFromTable() {
        // This function runs when a user clicks "Remove" on an item in the "Selected Products" section.
        Integer count = 0;

        for (OpportunityLineItem d : shoppingCart) {
            if ((String)d.PriceBookEntryId == toUnselect) {
                tableRows.remove(count);
                break;
            }
            count++;
        }

        return null;
    }

    public PageReference OnCancel() {
        // If user hits cancel we commit no changes and return them to the Opportunity.
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
}

A: <apex:selectList value="{!s.pb}" size="1">

This isn't bound to the correct attribute. You need to have a String to bind to in order to save the value. I'm not sure what field you meant to bind this to, but you'll need to fix this line in order to get it to work.

A: Sample Page:
<apex:page controller="testPageController">
    <apex:form id="renderTarget">
        <apex:pageBlock>
            <apex:pageBlockButtons>
                <apex:commandButton action="{!test}" value="Test" rerender="renderTarget" />
            </apex:PageBlockButtons>
            <apex:pageBlockTable value="{!contacts}" var="key">
                <apex:column value="{!contacts[key].key}"/>
                <apex:column>
                    <apex:outputLink value="javascript:;" onmouseup="remove('{!contacts[key].obj.Id}')">
                        Remove
                    </apex:outputLink>
                </apex:column>
                <apex:column value="{!contacts[key].obj.FirstName}"/>
                <apex:column>
                    <apex:selectList value="{!contacts[key].picklistVar}">
                        <apex:selectOptions value"{!options}" />
                    </apex:selectList>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <apex:actionFunction action="{!remove}" rerender="renderTarget">
            <apex:param name="toUnSelect" value=""/>
        </apex:actionFunction>
    </apex:form>
</apex:page>

Sample Controller
public class testPageController {
    public Map<Id, ContactWrapper> contacts {get; set;}
    public List<SelectOption> options {get; set;}

    public testPageController  () {
        contacts = new List<ContactWrapper>();
        options = new List<SelectOption>();

        options.add(new SelectOption('0','none'));
        options.add(new SelectOption('1', 'Test Option'));

        for (Contact con : [
            SELECT FirstName, Custom_Field__c FROM Contact LIMIT 10
        ]) {
            contacts.out(con.Id, new ContactWrapper(con));
        }
    }

    public void test() {
        for (contactWrapper cw : contacts) {
            system.debug(cw.picklistVar);
        }
    }

    public void remove() {
        Id toUnSelect = ApexPages.CurrentPage.getParameters().get('toUnSelect');
        contacts.remove(toUnSelect);
    }

    public class ContactWrapper {
        public static Integer count {get; set;}
        public Contact obj {get; set;}
        public String picklistVar {get; set;}
        public Integer key {get; set;}

        static {
            count = 0;
        }

        public contactWrapper (Contact con) {
            this.obj = con;
            this.picklistVar = '';
            this.key = ++contactWrapper.count;
        }
    }
}

Additional Notes
Row Count
The way you're tracking the row number is "technically" not supported.

Note:  does not support reassignment inside of an
  iteration component, such as <apex:dataTable> or <apex:repeat>. The
  result of doing so, e.g., incrementing the <apex:variable> as a
  counter, is unsupported and undefined.

I updated my answer to show 1 way you can do this without the apex:variable component.
Removing items from maps is easier than lists
Also, the way you remove an item from your "shopping cart" can be made more efficient by using a map (update in answer). This approach saves you a for loop and a counter variable.
You'll have to pay special attention to the syntax I used in the VF page when switching to a map.
Single Purpose Parameters
I also reconfigured the remove link so that instead of storing the Id of the record to remove at the page level, I store it in the method. This ensures that the variable can only be used for this one purpose and is cleaned up once it's done. This can prevent issues that occur when accessing the variable outside of this context.
Disclaimer
This code is intentionally not copy-pasta.


text:
Q: Search in a rotated array class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n=nums.size();
        int i=0, low, high;
        int pos=-1;
        while(nums[i]<nums[i+1])
            i++;
        //i stores the index of max element of the array
        if(target<nums[0]) {
            low = i+1;
            high = n-1;
        }
        else {
            low = 0;
            high = i;
        }
        while(low<=high) {
            int mid = (low+high)/2;
            // cout<<low<<high<<mid<<target;
            // cout<<(nums[mid]==target);
            if(nums[mid] == target){
                pos = mid;
                // flag=1;
                break;
            }
            else if(nums[mid]<target) {
                low = mid+1;
            }
            else {
                high = mid-1;
            }
        }
        // if (flag==0)
        //     return -1;
        return pos;
    }
};

I have attached the code above
    =================================================================
==31==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000194 at pc 0x000000345587 bp 0x7fff5346e5a0 sp 0x7fff5346e598
READ of size 4 at 0x602000000194 thread T0
    #2 0x7f210b53a0b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x602000000194 is located 0 bytes to the right of 4-byte region [0x602000000190,0x602000000194)
allocated by thread T0 here:
    #6 0x7f210b53a0b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Shadow bytes around the buggy address:
  0x0c047fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff8000: fa fa fd fa fa fa fd fa fa fa fd fa fa fa fd fa
  0x0c047fff8010: fa fa fd fd fa fa fd fa fa fa fd fa fa fa fd fa
  0x0c047fff8020: fa fa fd fa fa fa fd fd fa fa fd fa fa fa fd fa
=>0x0c047fff8030: fa fa[04]fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8070: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8080: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
  Shadow gap:              cc
==31==ABORTING

This is the error message that I am getting on LeetCode. Could somebody look into this.
The question was to search is a rotated array that was initially sorted in an ascending order.
When I run this code, it works perfectly fine but when I try to submit, it gives the heap error.


text:
Q: Visual Studio - Add default Project dependency to new projects I have a solution having quite a few projects and all of them need to have a specific project added as a dependency. This can be done manually, but leaves a window of error where someone might forget to do so while adding a new project to the solution (even though the newly added project may not be using a direct code reference of this common project, so compiler won't be of much help here) or, maybe have some kind of a pre-build verification script at solution level which verifies this (doesn't sound elegant to me). So I thought it would be better to let Visual Studio add a dependency to this common project by default, every time a new project is added to the solution.
Is there a way to do this?

A: In Solution Explorer, select a project.
On the Project menu, choose Project Dependencies. ...
On the Dependencies tab, select a project from the Project drop-down menu.
In the Depends on field, select the check box of any other project that must build before this project does.
And the dependencies automatically gets added to a project when you create a venv(a virtual environment) to that certain project. Update Venv Path Settings in VSCode. Open VSCode preferences ( Ctrl + , ) and search for "venv". Add ~/.virtualenvs to the "Venv Path" settings, like so: ...
Add the Virtual Environment Folder to VSCode. Add the folder that contains the virtual environment to VSCode, in our case, it is the ~/. virtualenv folder.
I hope i helped you and if i did not, then add a comment!


text:
Q: List of figure in table format As normal way we do, we insert \listoffigures for List of figure. But right now I want list of figure display like this picture below. How can I do it?

Here is MWE, you can choose 1 picture from your PC for testing.
\documentclass[13pt, a4paper, reqno, oneside]{book}
\usepackage{float}
\usepackage{graphicx}
\begin{document}

\thispagestyle{empty}

\listoffigures

\newpage
\begin{figure}
  \includegraphics[width=\linewidth]{xxx.PNG}
  \caption{xxx}
  \label{fig:x}
\end{figure}
Lorem ipsum dolor sit amet, consectetuer adipiscing
elit.  Etiam lobortisfacilisis...
\end{document}


text:
Q: VSIX Open a Comparison/Difference View Window I am writing a Visual Studio Extension for Visual Studio 2022 where I just want to Open a Comparison Window just like when you click on a file in the Git Changes view.
I see various classes IWpfDifferenceViewerFactoryService sounds promising but have found zero examples on how to use this class, especially when called from a Command Extension.
Same goes for IDifferenceViewer & 2, & 3.
I also see that the VS.Document.OpenAsync class of the Community Toolkit uses the VsShellUtilities class which is another can of worms and doesn't seem to have any Differencing capabilities.
If anyone has any idea how to do this, please let me know.  Sorry for the lack of code in my question, but I've googled the heck out of this to no avail.

A: not sure if this is exactly what you had in mind, but Mads Kristensen (PM on the Visual Studio team @ Microsoft) has a sample "FileDiffer" extension for VS 2022:
https://github.com/madskristensen/FileDiffer/tree/master/src
The VS Command that does the diffing is here: https://github.com/madskristensen/FileDiffer/blob/master/src/Commands/DiffFilesCommand.cs


text:
Q: Build Spark SQL query dynamically How we can pass a column name and operator name dynamically to the SQL query with Spark in Scala?
I tried (unsuccessfully) the following:
spark.sql("set key_tbl=mytable")
spark.sql("select count(1) from ${key_tbl}").collect()

A: You can pass it as parameter as shown below
val param = "tableName"
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
sqlContext.sql(s"""SELECT * FROM param=$param""")

can check this link for more details
https://forums.databricks.com/questions/115/how-do-i-pass-parameters-to-my-sql-statements.html

A: Quite more simply, you should be able to do something like the following:
val key_tbl = "mytable"
spark.sql(s"select count(1) from ${key_tbl}").collect()

Notice the s before the query string: this uses Scala's string interpolation to build the query with another variable (key_tbl).
You can read more on String interpolation in Scala here.

A: i done  with this ,as following:

val tablename="yourtablename"
val columnname="name"
val value=""
val operator="=="
spark.sql("select * from"+ tablename+"where"+name+operator+value)

A: I tried and answer is :
You make query as :
s"""(SELECT * FROM param='$param')foo"""


text:
Q: ActionMailer can I have an html and plain text partial with same name but different extensions? For each ActionMailer email view I have an html and text file, like so:
new_user_welcome.html.haml
new_user_welcome.txt.haml

Using this convention, ActionMailer automatically handles sending html and plain text emails for me.
Can I do this with email partials too, to get a html and txt version of the same partial? For example, can I name my email footer partials like this, and will ActionMailer automatically use the right one used in the html and text emails?
_email_footer.html.haml
_email_footer.txt.haml

A: You can have partials for your mails too:

_email_header.html.erb
_email_footer.html.erb

Then you can refer to them inside each of your emails:
<%= render :partial => 'email_header' %>
... Email body here...
<%= render :partial => 'email_footer' %>

Repeat the process for txt emails partials.


text:
Q: Can I improve my duplicate-detection queries? I have a DB table with US domestic flight data which I am in the process of sorta-kinda-de-duplicating. The schema appears here, but it is probably not very important. There are no perfectly-duplicate records; rather, I have a several fields which almost form a unique key: year_, month_, dayofmonth, uniquecarrier, flightnum, origin; and under 0.1% of the records share the same values on these fields with other records.
What I want to do is isolate these "pseudo-duplicates" or key-violators, i.e. pairs of records which have the same values on these columns.
Here's what I'm currently doing:
CREATE TEMPORARY TABLE dupe_keys AS (
    SELECT year_, month_, dayofmonth, uniquecarrier, flightnum, origin
    FROM (
        SELECT count(*) AS cnt, year_, month_, dayofmonth, uniquecarrier, flightnum, origin
        FROM ontime
        GROUP BY year_, month_, dayofmonth, uniquecarrier, flightnum, origin
    ) AS t WHERE cnt > 1
) ON COMMIT PRESERVE ROWS;

This query takes quite a lot of time (relative to an ideal possible implementation outside of a DBMS based on sorting the key columns). I then run:
CREATE TABLE dupes AS (
    SELECT  o.year_,o.quarter,o.month_,o.dayofmonth,o.dayofweek,o.flightdate,o.uniquecarrier,o.airlineid,o.carrier,o.tailnum,bunch_of,other_fields,go_here
    FROM ontime AS o, dupe_keys AS dk
    WHERE
            o.year_         = dk.year_
        AND o.month_        = dk.month_
        AND o.dayofmonth    = dk.dayofmonth
        AND o.uniquecarrier = dk.uniquecarrier
        AND o.flightnum     = dk.flightnum
        AND o.origin        = dk.origin
    ORDER BY o.year_ ASC, o.month_ ASC, o.dayofmonth ASC, o.uniquecarrier ASC, o.flightnum ASC, o.origin ASC
);

which obviously takes less time.
I would like to achieve the same, faster, with better queries. Alternatively, I wouldn't mind something like a pair of tables of the same size, each with one of the two dupes out of a dupe set.
Notes:

*

*You may assume that no combination of key-column values appears more than twice. It's either once or twice.

*I'm using MonetDB, a columnar in-memory DBMS. hence the syntax specifics.

*I hope my question is not DBMS-specific, but in case it is - answers based on the behavior of other DBMSes are still relevant, just please state which DBMS you're assuming.

*This query is run when the data set is loaded, rather than repeatedly, So pre-computation which takes even more time is not relevant.

A: This will either require a hash or a sort to group records having the same key. Hash can only be done in memory, but sorting can use external storage. If you have a lot of data, it will probably use a merge disk sort.
So the first thing to do would be to look what it is using, and if it is a sort, then look into memory configuration options to allocate more working memory to reduce the number of passes (this would be work_mem in postgres).
Second would be to partition the table by some key, like year or year,month. Then run the duplicate search on each partition instead of the whole table. Ideally you'd want the partitions to be small enough that the slow disk merge sort can be replaced by an in-memory hash or quicksort.
EDIT: I tried it on clickhouse. With compression enabled, the database is about the same size as the zipped csv files.
SELECT count(*) AS cnt, Year, Month, DayofMonth, UniqueCarrier, FlightNum, Origin
FROM ontimec
WHERE Year=2001
GROUP BY Year, Month, DayofMonth, UniqueCarrier, FlightNum, Origin
HAVING cnt>1;

This takes about 0.5 seconds and returns 1349948 rows, out of the 5967780 rows that have Year=2001. Are you sure about "only 0.1% of rows are duplicates?"...
Window functions have to be enabled, then:
SELECT * FROM (
    SELECT *, count(*) over (partition by Year, Month, DayofMonth, UniqueCarrier, FlightNum, Origin) cnt
    FROM ontimec
    WHERE Year=2001) foo
WHERE cnt > 1;

This also works, it takes 1.5s, much longer of course if you let it display the million rows in the console.

A: In your query to create the temporary table, it's possible to do that in standard SQL without a sub-query, using a HAVING clause, e.g.:
CREATE TEMPORARY TABLE dupe_keys AS (
    SELECT count(*) AS cnt, year_, month_, dayofmonth, uniquecarrier, flightnum, origin
    FROM ontime
    GROUP BY year_, month_, dayofmonth, uniquecarrier, flightnum, origin
    HAVING cnt > 1
);

I don't know if that will speed up the temporary table creation, but it might be worth a try.

A: You can do this quite neatly with a window function:
SELECT *
FROM (
    SELECT *,
        COUNT() OVER (PARTITION BY year_, month_, dayofmonth, uniquecarrier, flightnum, origin) cnt
    FROM ontime
) AS t
WHERE cnt > 1;

This returns all rows which are duplicates. If you wanted instead to return only the extraneous rows, and not the first row from each group, use row-numbering:
SELECT *
FROM (
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY year_, month_, dayofmonth, uniquecarrier, flightnum, origin ORDER BY some_Other_Column) rn
    FROM ontime
) AS t
WHERE rn > 1;

Insert a column into the ORDER BY clause to decide which row orders first


text:
Q: Realm database integration with Eclipse Android project I need to integrate Realm database in my eclipse JUNO(Android Development Tool). I used realm 0.81.1 version. I had include all library files in my android project lib folder and configured realm-0.81.1.jar in buildpath.when "java.lang.IlleagaArgumentException:User is not part of the schema for this realmrun my project it throws error ".
Here User is an class that extends RealmObject.
The User class code is given below:
public class User extends RealmObject {
    @PrimaryKey
    private String          name;
    private int             age;
    @Ignore
    private int             sessionId;
    // Standard getters & setters generated by your IDE…
    public String getName() { return name; }
    public void   setName(String name) { this.name = name; }
    public int    getAge() { return age; }
    public void   setAge(int age) { this.age = age; }
    public int    getSessionId() { return sessionId; }
    public void   setSessionId(int dontPersist) { this.sessionId = sessionId; }
}

The error is produced when executing the following code:
Realm realm = Realm.getInstance(this);

realm.beginTransaction();
User user = realm.createObject(User.class);
user.setName("Jhon");
user.setAge(10);

realm.commitTransaction();

Please give me suggestion to work with Realm Database
Thanks in advance.

A: As you are using Eclipse you need to add the @RealmClass annotation manually as it doesn't support inherited annotations. So you model class must look like this:
@RealmClass
public class User extends RealmObject
{
  // ...
}

Try this and let me know if it works. Thanks.


text:
Q: Debugging help - PHP include causes page refresh I'm having a very odd problem that I can't seem to track down. Any help with regards to debugging would be greatly appreciated!
Let me describe this using scenarios.
Scenario 1 (incorrect)

*

*PHP calls out to a CAS server (using curl_exec) and gets the user info back

*PHP checks the database to ensure that the user returned from CAS exists and fails (which is correct, I'm testing a non-existent user) and sets the error message to "User not found" (this is the correct error message)

*PHP includes the top.php file

*The page randomly refreshes or redirects to itself and starts the process over...this is what I can't figure out.

*PHP calls out to the CAS server (using curl_exec) and receives an error since the CAS ticket has already been used, setting a new error message of "CAS rejected your credentials" (which is not correct)

*PHP includes the top.php file and doesn't refresh/redirect a second time

*PHP prints out "CAS rejected your credentials" (which is not correct)
Scenario 2 (semi-correct)

*

*PHP calls out to a CAS server (using curl_exec) and gets the user info back

*PHP checks the database to ensure that the user returned from CAS exists and fails (again, this is correct, I'm still testing a non-existent user) and sets the error message to "User not found" (this is the correct error message)

*I skip top.php since it was commented out, and print out "User not found" (this is the correct error message)
Debugging
So, I have checked, double-checked and triple-checked that top.php doesn't use include, require, redirect (a function we wrote that prints a <meta> redirect tag and then calls exit;), or any other thing that actually refreshes the page.
In fact, I've put in a die statement that prints out the error message. On one line in top.php, it prints out correctly. When I move that statement down one line (below an HTML </div> tag), it refreshes the page and prints the incorrect error message. There aren't even any PHP tags anywhere close.
As far as I can tell, this means the problem is not actually in the top.php file, since printing out </div> should never cause a page to refresh/redirect.
Any ideas on how to debug from here would be enormously helpful. Clearing caches/buffers? How to better track what PHP is doing?
Note: No PHP errors are being output.
UPDATE: Yay, I found the culprit! Instead of calling include 'top.php'; I simply copied/pasted the code inside login.php and it presented the same problem. So I began deleting lines until I found the one causing the problem:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

So, switching the question entirely since I didn't have much of a question in the first place: Can someone explain why this causes a page refresh, and why is it only sometimes (i.e. it doesn't continually refresh the page)?

A: If you have firefox grab yourself a copy of livehttpheaders. Turn it on and go through scenario 1. Trace through the http request and response headers to see what is happening there. It should provide you with more information on just what is happening between the browser and the server.


text:
Q: Как реализовать смену url после ajax запроса? Допустим мы находимся на странице www.site/feed на этой странице есть

 в котором находится контент. На странице так же есть кнопка которая выполняет ajax запрос на страницу user.php и результат выводит в .main. Мы по прежнему находимся на странице www.site/feed но с помощью js window.history.pushState, меняем ссылку на user. Собственно проблема в том, что если после смены url нажать стрелку "назад" в браузере то контент не меняется.
Например в .main было content content....
И после ajax ссылка сменилась на user и контент в .main стал например res res...
Теперь если в браузере мы вернемся на пред ссылку то ссылка измениться на feed но контент останется.
Как сделать так, что бы и контент тоже обновился ?

A: Надо подписаться на событие popstate и в обработчике вывести желаемый контент. Оно вызовется при нажатии back.


text:
Q: Many-to-Many relationship with GraphQL Before I start I have already checked that link
Until now I was using plain SDL to define my schema in Graphql but recently I wanted to try with prototypes. I want to represent a many-to-many relationship between two nodes User and Product such that:
type User {
    id: ID!
    username: String!
    email: String!
    products: [Product]!
}

type Product {
    id: ID!
    name: String!
    price: Float!
    users: [User]!
}

However, when I try to implement it with prototypes I get Expected undefined to be a GraphQL type error because one of the two object types has not been evaluated at the time of execution. At a moment in time, either User or Product will be undefined and I am not sure how to avoid that error. Can anyone help me?
const User = new GraphQLObjectType({
    name: 'User',
    fields: {
        id: {type: GraphQLNonNull(GraphQLID)},
        username: {type: GraphQLNonNull(GraphQLString)},
        email: {type: GraphQLNonNull(GraphQLString)},
        products: {type: GraphQLNonNull(GraphQLList(Product))} // product has not been defined
    }
})

const Product = new GraphQLObjectType({
    name: 'Product',
    fields: {
        id: {type: GraphQLNonNull(GraphQLID)},
        name: {type: GraphQLNonNull(GraphQLString)},
        price: {type: GraphQLNonNull(GraphQLFloat)},
        users: {type: GraphQLNonNull(GraphQLList(User))}
    }
})

A: You can lazy-initialize the fields passing functions instead of objects:
const User = new GraphQLObjectType({
    name: 'User',
    fields: () => ({
        id: {type: GraphQLNonNull(GraphQLID)},
        username: {type: GraphQLNonNull(GraphQLString)},
        email: {type: GraphQLNonNull(GraphQLString)},
        products: {type: GraphQLNonNull(GraphQLList(Product))}
    })
})

const Product = new GraphQLObjectType({
    name: 'Product',
    fields: () => ({
        id: {type: GraphQLNonNull(GraphQLID)},
        name: {type: GraphQLNonNull(GraphQLString)},
        price: {type: GraphQLNonNull(GraphQLFloat)},
        users: {type: GraphQLNonNull(GraphQLList(User))}
    })
})

I hope it helps.


text:
Q: Is WebBrowser.Document.Forms[0].InvokeMember() paramater always "submit"? Every code example for submitting a form inside a WebBrowser control I have seen so far, hardcodes the WebBrowser.Document.Forms[0].InvokeMember() parameter as "submit".
Must this parameter always be "submit"?
If so, then why is it a parameter?
If not, what are the rules for specifying which string to put there? Is it dependent on the HTML of the page being accessed?
Update 1: The documentation for InvokeMember() clearly shows an example of using a value other than "submit". So, at least I got the answer: No.
But I still don't understand when should I use "submit" and when should I use "moveRow": In the web page I am handling via "submit" there is no mention of that string, yet it works perfectly. Where is that implied "submit" hiding in the web page?
Update 2: Ah! I think I am beginning to get it: It's a Javascript built-in method. And thus implied for any DOM Form element.
An authoritative answer is most appreciated.

A: No, it doesn't have to be "submit".  But that's certainly the most popular method you'd ever use with a form.  The Winforms HtmlDocument and HtmlElement classes are wrappers for the DOM interfaces.  Core ones in this case are IHtmlDocument2 (matching HtmlDocument) and IHtmlElement2 (matching HtmlElement).  With a raft of specific interface types, like IHtmlFormElement to represent a form object in the DOM.  But without a matching class for those in Winforms, HtmlElement wraps them all.  Which is why you need to use InvokeMember(), same idea as reflection's Type.InvokeMember().  It makes up for methods that are not wrapped by HtmlElement.  Like IHtmlFormElement::submit().
The one advantage of HtmlElement is that it helps you avoid the morass of versions of these DOM interfaces.  There are seven versions of IHtmlDocument for example.  Every time Microsoft improves IE, they tend to have to create another version of the interface with the additional members added.
You certainly can use them early bound.  Add a reference to c:\windows\system32\mshtml.tlb.  Cast the WebBrowser.ActiveXInstance to mshtml.IHtmlDocument to use it.

A: InvokeMember calls the form element's methods/properties via IDispatch::Invoke. You can find the list of methods and properties that you can invoke from IE's documentation of the form element.
Easier binding via IE's type library ensures type safety but you need to find the correct interface for the method/property, which means for the form element, you need to look under IHTMLElementX if the method/property cannot be found under IHTMLFormElementX.


text:
Q: Extract text from image with pytesseract I tried extract numbers from original image https://imgur.com/a/adMaKGy , but with no luck.
Output from pytesseract is: "[a ]:[4] G2):Go] [7 ):Ce J"
Thank you for advice,
My code:
import pytesseract
import cv2
pytesseract.pytesseract.tesseract_cmd = 'folder /tesseract.exe'
img = cv2.imread("folder /test_image.png")
text = pytesseract.image_to_string(img)
print(text)

A: The README says that OpenCV images are in BGR format and pytesseract assumes RGB format, so you need to convert it
import cv2

img_cv = cv2.imread(r'/<path_to_image>/digits.png')

# By default OpenCV stores images in BGR format and since pytesseract assumes RGB format,
# we need to convert from BGR to RGB format/mode:
img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
print(pytesseract.image_to_string(img_rgb))
# OR
img_rgb = Image.frombytes('RGB', img_cv.shape[:2], img_cv, 'raw', 'BGR', 0, 0)
print(pytesseract.image_to_string(img_rgb))


text:
Q: Show that a Quotient Map pasting a polygonal region is closed
Given a polygonal region $P$, a labeling equivalence relation and a pasting quotient map $\pi: P \to X$, show that $\pi$ is closed.

For any set $C$ closed in $P$, show that $\pi(C)$ is closed.
I'm struggling with how to approach this one.

A: We know that $P$ is comopact. To show the image $\pi(C)$ is closed directly may not be easy, but we can show $\pi^{-1}(\pi(C))$ is closed. claim:

*

*$\pi^{-1}(\pi(C))$ is the set of all points that are identified with $C$.

*There must exist a set of edges $\{e_i|i\in I\}$ (if this set is empty then we're done because all points but edges are equivalent to only themselves) for some index set $I$ that are mapped to $C$ by a family of homeomorphisms $h_i:e_i\to e$, where $e$ is an edge.

So, we have $\pi^{-1}(\pi(C))=\bigcup_{i\in I}h_i(e_i)\cup (C\cap e)\cup C$ which is compact and, therefore, closed in $P$. And because of the surjectivity, we have $\pi(\pi^{-1}(\pi(C)))=\pi(C)$ (surjections are right invertible), which is also compact (by continuity) and hence closed as desired.


text:
Q: Which class should be responsible for certain actions? I am making a Storage System Application. Each storage system contains up to 10 Warehouses capable of storing Stock Items.
I want to create a method for updating a Warehouse properties (Name, Description etc). There is a business rule that each Warehouse within a storage system must have a unique name, and im unsure which class should be responsible for this. Im trying to stick to the principle that each class should only be responsible for itself.
Here is a simple mock up of the code (C#)
 public class StorageSystem
{
    public List<Warehouse> Warehouses{Get;}
}

public class Warehouse
{
    public string Name{Get; private Set;}

    public int StorageSystemId{Get; Set;}
    public StorageSystem Sotrage System{Get; Set;}
}

I think i should do the following,
Step1. Create a method in StorageSystem class.
public bool WarehouseNameAvailable(string name)
{
   //Check List of Warehouses for the name
   //if found return false
   //else return true
}

Step2. Create a method in the Warehouse
public void UpdateWarehouseName(string name)
{
   if(StorageSystem.WarehouseNameAvailable(name))
    {
        this.name = name;
    }
    else
    {
        //Throw Exception
    {
}

Is this the "proper and correct" way to do this?

A: Make T_WAREHOUSE.NAME unique (just assumed that your table/columns would have names like this) - database wise and handle the exception if a second entry gets written with the same name.
You could rise that error/exception up to user level too, to show users what went wrong: enter a different name please, "Super Dooper Warehouse" is already taken

Your questions text suggests that this will be a bigger project with many classes that interact with each other.
If you are not using a ORM, think about using one! It does a lot what you are trying to achive via custom methods loke your WarehouseNameAvailable workaround.
If you are using Entity Framework you can do this on your class properties via [Unique] attribute.

A:
Is this the "proper and correct" way to do this?

This highly depends on your overall application architecture, imho. Ask 5 developers whether your solution is "proper and correct" and you will get 6 opinions.
To get to the point: When purely relating on DDD concepts, your solution seems at least possible. But to be honest, i've never come across an enterprise application of notable size that was able to project its business logic entirely in the domain model in a structured (!) and maintainable (!) way and did not need some kind of service layer upon it. I personally like this approach and would recommend pojecting this requirements in separate classes, that represent business/use cases:
public class RenameAction {
    //Some Kind of DbSet, Database Connection, external service,...
    //I'll go with an EF - DbSet<Warehouse> in this example
    private readonly DbSet<Warehouse>_warehouses;
    private readonly DbSet<StorageSystem> _storageSystem;

    public void Execute(int storageSystemId, int warehouseId, string name) {
        var storageSystem = _storageSystems.Single(system => system.Id == storageSystemId);

        if (_storageSystem.Warehouses.Any(wh => wh.Name == name))
            throw new BusinessLogicException("Warehouse names must be unique within storage systems!");
        var warehouse = storageSystem.Warehouses.Single(wh => wh.Id == warehouseId);
        warehouse.Name = name;

        //Write back the updated warehouse to whereever, this won't work with an DbSet<Warehouse>.
        _warehouses.Update(warehouse);
    }
}

But again, this is just how I would deal with that.


text:
Q: Printing ZPL command file from web application I'm calling a webService (from La Poste in France) in my WebApp that sends me batch of ZPL commands to print labels.
I would like to be able to print directly this set of commands to my Zebra printer from this web application ?
Question : is it possible and how ? Will it work by creating a generic text driver and printer the set of commands to the printer as I've read on Internet (https://www.foldermill.com/kb/install-generic-text-driver-in-windows for example)
For the moment, I do not have any printer to do a test and check it, so this question.
Thanks for your help

A: Unfortunately, using the print function of my browser with the generic text driver on a document containing only zpl commands does not work.
It seems the page is not sent only in text.
To achieve my goal (print from a web page), I have developed an agent installed on the computer that communicate with websockets with my web page.


text:
Q: Getting a value by name in javascript/razor application i have an asp application in which i have to use javascript to get the value of an element
@for(int i=0; i< Model.Count; i++) {
    <input type="text" value="@Model[i].age" name="age@(i)" />
    HtmlActionLink("new age","Change", new { age = "age" + i.ToString()
});
                                     }

I need to get the value of each tag age : new { age = "age" + i.ToString() didn't work and i have to replace it by a script javascript using document.getElementsByName method
How can i modify my code to do this task?

A: I would simply add a class to each input element that gives it some meaning (e.g. 'input-age'):
<input class="input-age" type="text" value="@Model[i].age" name="age@(i)" />

And then you could select all of the inputs by class name and not need to rely on the dynamically assigned name from the view engine:
var ages = document.querySelectorAll('input.input-age');

Or if you need to find the value for a specific age index, without adding a class name:
var ageIndex = 4;
var age = document.querySelector('input[name="age' + ageIndex + '"]').value;

FYI, for IE, it will only work in versions 8 or higher because of the querySelectorAll function, but you could use other methods.
If jQuery was on the table, you could not change anything and use the "starts with" selector to get all "age" elements:
var ages = $('input[name^="age"]');

Or, after adding a class name:
var ages = $('.input-age');

Or, hunt down the value for a specific input:
var ageIndex = 4;
var age = $('input[name="age' + ageIndex + '"]').val();

With the last example, you don't need to add the class name;


text:
Q: How can I make , a footer section, visible only in my wordpress frontpage? I have created 5 widgets sections for my template footer. Now I would like to know, how is possible to make a footer section only visible in my front page theme and the other widgets in all other pages? So footer 5 widget appears in front page and the footer4 in other pages!
Here is what I wrote, but it doesn't work!
<?php if (is_home()): if ( function_exists('dynamic_sidebar') && dynamic_sidebar(is_active_sidebar('footer5'))){?>

 <?php get_dynamic_sidebar('footer5'); ?>

<?php }?>
 <?php elseif(is_active_sidebar('footer4')) : ?>

 <?php dynamic_sidebar('footer4'); ?>

<?php endif; ?>

A: In order to print footer5 widget you need to change get_dynamic_sidebar('footer5') to dynamic_sidebar('footer5')
<?php
 if(is_home()):
    if(function_exists('dynamic_sidebar') && is_active_sidebar('footer5')){
        echo '
';
        dynamic_sidebar('footer5');
        echo '
';
    }
    elseif(function_exists('dynamic_sidebar') && is_active_sidebar('footer4')){
        echo '
';
        dynamic_sidebar('footer4');
        echo '
';
    }
 endif;
 ?>

The above code should work. It will show widget only on front page.
EDIT:
To show widgets on every page the below code should work.
<?php
    if(function_exists('dynamic_sidebar') && is_active_sidebar('footer5')){
        echo '
';
        dynamic_sidebar('footer5');
        echo '
';
    }
    elseif(function_exists('dynamic_sidebar') && is_active_sidebar('footer4')){
        echo '
';
        dynamic_sidebar('footer4');
        echo '
';
     }
?>

A: The problem is now solved by this code. Thanks a lot @danish.

if(is_front_page()&& function_exists('dynamic_sidebar') && is_active_sidebar('footer5')){
                echo '
';
                dynamic_sidebar('footer5');
                echo '
';
            }else
            if(!is_front_page() && function_exists('dynamic_sidebar') && is_active_sidebar('footer4')){
                echo '
';
                dynamic_sidebar('footer4');
                echo '
';
            }
        ?>

A: In Wordpress for showing particular code block on specific pages there are lots of conditional functions available.
For checking if the current page is Home page and Check If current page is a custom page.
After checking the conditional you can load the specific sidebar or a specific widget instance on any specific page or section.
For more functions just follow the wordpress codex.


text:
Q: Using if function in laravel I am having some trouble doing an if statement since most of the tutorial videos and other forums, I saw people only using variable, example $value, but I want to use if statement on the input name itself. Is that possible, if so could you help me out? Thanks a lot. Sorry if you are feeling confused of what I want maybe, if you see the code, you might understand, I don't really quite know how to say it in words.
test.blade.php

        Test:

        <input type="radio" name="test" value="Yes"> Yes

        <input type="radio" name="test" value="No"> No

        <input type="radio" name="test" value="Pending"> Pending

@if(<input type="radio" name = "test" value="Yes"> || <input type="radio" name = "test" value="Pending">)
//show some other kind of input types such as :

        Training Schedule:

        <input type="radio" name="training_schedule" value="Yes"> Yes

        <input type="radio" name="training_schedule" value="No"> No

@else
//make the other inputs value become NIL instead of showing
Something like:
    name = "training_schedule" value = "NIL"
    @endif

A: Here is the example using the javascript.

var test_input = $('input[name=test]');
var test_val = '';

var if_yes = '
Training Schedule:
<input type="radio" name="training_schedule" value="Yes"> Yes
<input type="radio" name="training_schedule" value="No"> No

';
var if_no = '
Training Schedule:
<input type="radio" name="training_schedule" value="NIL"> NIL

';

$(test_input).on('change', function () {
  test_val = $(this).val();
  if (test_val == 'Yes' || test_val == 'Pending') {
    //clear the div
    $('div#append_to_this').html('');

    // put your html code here
    $('div#append_to_this').append(if_yes);
  } else {
    //clear the div
    $('div#append_to_this').html('');

    // put your html code here
    $('div#append_to_this').append(if_no);
  }
});

          Test:

               <input type="radio" name="test" value="Yes"> Yes

               <input type="radio" name="test" value="No"> No

               <input type="radio" name="test" value="Pending"> Pending


text:
Q: Unable to prove this question related to isogonal mappings The following question was asked in my Complex analysis quiz and I couldn't make much progress on the question.
So, I am posting it here for help.
A map is called isogonal when it preserves only angle size but not orierentation. For example $f(z)=\bar z$.

Problem: Prove that both $f(\bar z)$ and $\overline {f(z)} $  are both isogonal at points where f(z) is analytic with non zero derivative.

I am unable to proceed in this question. I took f(z) to analytic function with $f'(z)\neq 0$ but not able to understand  on how will I show that angles are preserved.( For f(z)=$\bar z$ it is easy as positive real axis is mapped to positive  real axis and positive imaginary axis is mapped to negative imaginary axis and similar impact will happen over others).
But, I am not sure how operating by f will have impact of $\bar z$ as  nature of f can be quite varied and how it will have impact on  overline of f(z).
Can you please guide me through that!

A: This answer is an attempt to give a visual understanding. Apologies if it is too simplistic.
Imagine that $U$ is a $10\times40$ grid centered on some section of the real axis.  The figure below shows part of $f(U)$.  I'm assuming you already know that if $f$ is analytic it is also conformal, i.e. preserves angles.  The image of the real axis is shown as a thick blue line, and the rest of the grid is a mapping of the original grid.

The red and blue arrows above the line are images of two arrows.  $\bar{z}$ will flip the pre-images of the arrows across the real line, preserving angles, so the two arrows below the blue line are their image under $f(\bar{z}).$  Because $f$ preserves angles, the angles between the pairs of arrows are the same.
(actually, the image arrows will generally be curved line segments, and the angle that is preserved is measured at their intersection.)
Showing that $\overline{f(z)}$ is isogonal is easier, because it is just $f(z)$ flipped across the real axis.

A: Hint: If $f$ preserves angle size but reverses the orientation on some $U\subset\mathbb{C}$, then what does the function $g$ defined by $g(z) = f(\bar{z})$ do to angles on $U$? How do we characterise such a function complex analysis?
Conversely: if $f$ is analytic on $U$, what does it do to angles? What do the functions $g$ and $h$, defined by $g(z) = f(\bar{z})$ respectively $h(z)= \overline{f(z)}$ do to angles in this case?


text:
Q: cs50 pset4 - edge detection filter not working - sobel operator The following code i have written has the purpose of detecting the edges in a pixel using the sobel operator. However, it fails all of the tests given by check50 (tool offered by cs50). The output image is also the exact same as the input.
before you continue reading, visit the pset's link

*

*note: I'm supposed to form a 3x3 grid around the pixel I want to filter so that I can iterate over each value in the GX and GY values. I've used ints hh and ww to do this.

       // Detect edges
        void edges(int height, int width, RGBTRIPLE image[height][width])
        {
            int sqrtRedd;
            int sqrtGreenn;
            int sqrtBluee;

        //make copy of image
            RGBTRIPLE copy[height][width];

            for(int h = 0; h < height; h++)
            {
                for(int w = 0; w < width; w++)
                {
                    copy[h][w] = image[h][w];
                }
            }

        //loop through pixels
            for(int h = 0; h < height; h++)
            {
                for(int w = 0; w < width; w++)
                {
                    int GXred = 0;
                    int GYred = 0;
                    int GXgreen = 0;
                    int GYgreen = 0;
                    int GXblue = 0;
                    int GYblue = 0;

                    for(int hh = -1; hh <= 1; hh++)
                    {
                        for(int ww = -1; ww <= 1; ww++)
                        {
                            if( h + hh >= 0 && h + hh < height && w + ww >= 0 && w + ww < width)
                            {
                                //form 3x3 grid
                            GXred += ww * copy[2 - hh * hh][2 - ww * ww].rgbtRed;
                            GYred += hh * copy[2 - hh * hh][2 - ww * ww].rgbtRed;

                        GXgreen += ww * copy[2 - hh * hh][2 - ww * ww].rgbtGreen;
                        GYgreen += hh * copy[2 - hh * hh][2 - ww * ww].rgbtGreen;

                        GXblue += ww * copy[2 - hh * hh][2 - ww * ww].rgbtBlue;
                        GXblue += hh * copy[2 - hh * hh][2 - ww * ww].rgbtBlue;

                            }
                        }
                    }

                    int red = round(sqrt(GXred * GXred + GYred * GYred));
                    int green = round(sqrt(GXgreen * GXgreen + GYgreen * GXgreen));
                    int blue = round(sqrt(GXblue * GXblue + GYblue * GYblue));

                    if(red > 225)
                    {
                        red = 225;
                    }

                    else if(green > 225)
                    {
                        green = 225;
                    }

                    else if(blue > 225)
                    {
                        blue = 225
                    }

                    image[h][w].rgbtRed = red;
                    image[h][w].rgbtGreen = green;
                    image[h][w].rgbtBlue = blue;

                }
            }

            return;
        }

RGBTRIPLE:
typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

These are the error messages given by check50:
    :( edges correctly filters middle pixel
        expected "210 150 60\n", not "143 105 30\n"
    :( edges correctly filters pixel on edge
        expected "213 228 255\n", not "164 144 79\n"
    :( edges correctly filters pixel in corner
        expected "76 117 255\n", not "58 77 64\n"
    :( edges correctly filters 3x3 image
        expected "76 117 255\n21...", not "58 77 64\n164 ..."
    :( edges correctly filters 4x4 image
        expected "76 117 255\n21...", not "58 77 64\n164 ..."

As you can see, the output values are way off and not even near what they should actually be. the problem is: I don't know if these errors are caused by a) my way of trying to find the GX and GY values from the kernels or b)by the way i'm applying the sobel operator.
I've tried finding GX and GY values in other ways (didn't work) such as:
                         if(hh == -1)
                         {
                            GYred += copy[h - 1][w + ww].rgbtRed * -1;
                            GYgreen += copy[h - 1][w + ww].rgbtGreen * -1;
                            GYblue += copy[h - 1][w + ww].rgbtBlue * -1;
                         }

                         else if( hh == 0)
                         {
                             GYred += copy[h][w + ww].rgbtRed * 0;
                             GYgreen += copy[h][w + ww].rgbtGreen * 0;
                             GYblue += copy[h][w + ww].rgbtBlue * 0;
                         }

                         else if(hh == 1)
                         {
                             GYred += copy[h + 1][w + ww].rgbtRed * 1;
                             GYgreen += copy[h + 1][w + ww].rgbtGreen * 1;
                             GYblue += copy[h + 1][w + ww].rgbtBlue * 2;
                         }

                         else if(hh == 2)
                         {
                             GYred += copy[h + 2][w + ww].rgbtRed * 2;
                             GYgreen += copy[h + 2][w + ww].rgbtGreen * 2;
                             GYblue += copy[h + 2][w + ww].rgbtBlue * 2;
                         }

    //start setting GX values
                         if(ww == -2)
                         {
                             GXred += copy[h + hh][w - 2].rgbtRed * -2;
                             GXgreen += copy[h + hh][w - 2].rgbtGreen * -2;
                             GXblue += copy[h + hh][w - 2].rgbtBlue * -2;
                         }

                         else if(ww == -1)
                         {
                             GXred += copy[h + hh][w - 1].rgbtRed * -1;
                             GXgreen += copy[h + hh][w - 1].rgbtGreen * -1;
                             GXblue += copy[h + hh][w - 1].rgbtBlue * -1;
                         }

                         else if(ww == 0)
                         {
                             GXred += copy[h + hh][w].rgbtRed * 0;
                             GXgreen += copy[h + hh][w].rgbtGreen * 0;
                             GXblue += copy[h + hh][w].rgbtBlue * 0;
                         }

                         else if(ww == 1)
                         {
                             GXred += copy[h + hh][w + 1].rgbtRed * 1;
                             GXgreen += copy[h + hh][w + 1].rgbtGreen * 1;
                             GXblue += copy[h + hh][w + 1].rgbtBlue * 1;
                         }

I've been stuck on this pset for almost a week now and so at this point I don't know what else to try.

A: You have quite some parts that do not really make sense or are missing.

*

*You do not apply the sobel factors anywhere. Just taking the offset inside your 3x3 grid does not yield the correct values,

*You only limit 1 color channel in case of overflow,

*You limit to 225 instead of 255,

*You mixed GXblue and GYblue, same for GXgreen and GYgreen.

I have prepared a new version that should do the trick.
Now tested and with test data from initially failed test for 4x4 image.

#include <stdio.h>
#include <math.h>

typedef unsigned char BYTE;

typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

// Detect edges
void edges(int height, int width, RGBTRIPLE image[height][width])
{
    int sqrtRedd;
    int sqrtGreenn;
    int sqrtBluee;

    //make copy of image
    RGBTRIPLE copy[height][width];
    for(int h = 0; h < height; h++)
    {
        for(int w = 0; w < width; w++)
        {
            copy[h][w] = image[h][w];
        }
    }

    //loop through pixels
    for(int h = 0; h < height; h++)
    {
        for(int w = 0; w < width; w++)
        {
            int GXred = 0;
            int GYred = 0;
            int GXgreen = 0;
            int GYgreen = 0;
            int GXblue = 0;
            int GYblue = 0;

            int index = 0;
            int factorsX[] = {-1,  0,  1, -2, 0, 2, -1, 0, 1};
            int factorsY[] = {-1, -2, -1,  0, 0, 0,  1, 2, 1};

            //form 3x3 grid
            for(int hh = -1; hh <= 1; hh++)
            {
                for(int ww = -1; ww <= 1; ww++)
                {
                    int x = w+ww;
                    int y = h+hh;
                    if( y >= 0 && y < height && x >= 0 && x < width)
                    {
                        GXred += factorsX[index] * copy[y][x].rgbtRed;
                        GYred += factorsY[index] * copy[y][x].rgbtRed;

                        GXgreen += factorsX[index] * copy[y][x].rgbtGreen;
                        GYgreen += factorsY[index] * copy[y][x].rgbtGreen;

                        GXblue += factorsX[index] * copy[y][x].rgbtBlue;
                        GYblue += factorsY[index] * copy[y][x].rgbtBlue;
                    }
                    index++;
                }
            }

            int red = round(sqrt(GXred * GXred + GYred * GYred));
            int green = round(sqrt(GXgreen * GXgreen + GYgreen * GYgreen));
            int blue = round(sqrt(GXblue * GXblue + GYblue * GYblue));

            if(red > 255)
            {
                red = 255;
            }
            if(green > 255)
            {
                green = 255;
            }
            if(blue > 255)
            {
                blue = 255;
            }

            image[h][w].rgbtRed = red;
            image[h][w].rgbtGreen = green;
            image[h][w].rgbtBlue = blue;
        }
    }

    return;
}

int main(void)
{
    RGBTRIPLE test_4x4[4][4] = {
        {{0, 10, 25}, {0, 10, 30}, {40, 60, 80}, {50, 60, 80}},
        {{20, 30, 90}, {30, 40, 100}, {80, 70, 90}, {80, 80, 90}},
        {{20, 20, 40}, {30, 10, 30}, {50, 40, 10}, {50, 40, 100}},
        {{50, 20, 40}, {50, 20, 40}, {50, 40, 80}, {50, 40, 80}},
    };

    edges(4, 4, test_4x4);
    for(int h = 0; h < 4; h++)
    {
        for(int w = 0; w < 4; w++)
        {
            printf("%d %d %d\n", test_4x4[h][w].rgbtBlue, test_4x4[h][w].rgbtGreen, test_4x4[h][w].rgbtRed);
        }
    }

    return 0;
}


text:
Q: Knowing whether requested idp is google idp or wso2 idp I am trying to configure two identity server in wso2is, one is google idp and other one wso2is itself. My requirement is if user select wso2 IdP they will be able to access user information from wso2 idp and if they select google IdP they will be able to access user information from google account. So my question is for both idp there are different API to generate access token, then how I can identify which IdP user selected so that I can generate access token.

A: So by understanding your requirements from you description
Here's how you can achieve what you want to do,

*

*Create a google OAuth app and get it's client_credentials and client_secret. Register a callback_url such as "https://localhost/callbackGoogle"

*Register the google idp as an IDP in WSO2 Identity Server, under federated authenticaters section of the IDP fill in the Google Authenticator with the details of the OAuth app created in Google

*Create a service provider in WSO2 IS and enable OAuth inbound authentication. Register a callbackurl such "https://localhost/callbackWSO2"

*Under the Local & Outbound Authentication Configuration section of the Service provider select Advanced option

*Add the local and federated authenticater in step 1

*Now register two servlets, one for callback url of googleIDP and other for the callback registered for WSO2 IS

*Now you request for an access token from the service provider you will be redirected to a login page with two options ( Local IS or Google IDP)

*Based on the IDP chosen to authenticate by the user one of the servlets will be hit and you can identify which IDP user used to authenticate easily.

[ 1 ] https://docs.wso2.com/pages/viewpage.action?pageId=49092446


text:
Q: Change Google Finance Result from row to column in Google Sheets I am pulling data from google finance to google sheet using below formula:
=GOOGLEFINANCE("NASDAQ:AAPL","price",TODAY()-10,TODAY())

and the result is like below

what i want the result to be like is below so that when i put new stock in next row result show be like below

is there any google sheet expert who can help me as i am new to google sheet and searching on internet haven't haven't me any solution.

A: paste this in B1:
=ARRAYFORMULA(TEXT(SEQUENCE(1, 10, TODAY()-9, 1), "dd/mm/yyyy"))

and this in B2 and drag down:
=ARRAYFORMULA(IFNA(HLOOKUP(B$1:K$1, TRANSPOSE(TEXT(
 GOOGLEFINANCE("NASDAQ:"&A2, "price", TODAY()-10, TODAY()),
 {"dd/mm/yyyy", "@"})), 2, 0)))

update:
to exclude weekend you can do:
=INDEX(TRANSPOSE(QUERY(TEXT(SEQUENCE(10, 1, TODAY()-9, 1),
 {"dd/mm/yyyy", "ddd"}), "where not Col2 matches 'Sat|Sun'")), 1)

however to exclude holidays it needs to be done like this:
=INDEX(TRANSPOSE(QUERY(TEXT(SEQUENCE(10, 1, TODAY()-9, 1),
 {"dd/mm/yyyy", "ddd"}),
 "where not Col2 matches 'Sat|Sun'
    and not Col1 matches '"&TEXTJOIN("|", 1, M2:M)&"'")), 1)


text: Q: Ubuntu on macbook air keyboard and sound issues I have a macbook air 2016 model. I have installed ubuntu 22.04 lts on it. Currently, no sound comes out of the speaker (However headphones do work) and the down key does not register. Any recommendation on how to get these to work? Am new to linux so I might not understand all of what may be suggested right away.


text:
Q: Disabling default XML Schemas in Visual Studio? I have recently started using CAML.NET IntelliSense for SharePoint with Visual Studio 2008; which works great; however whenever I create a new project using STSDev 2008 (and thus generate feature.xml and WebParts.xml) the default schemas include the CAML.NET IntelliSense and the built-in (relatively incomplete) schemas:

*

*caml.xsd

*wss.xsd

*coredefinitions.xsd

*camlview.xsd

All found in web server extensions\12\TEMPLATE\XML. The existence of both of these schemas for the file causes a large number of warnings, notifying me that a specific schema entry is already declared in one of the above files. Disabling them for each file individually works great, however in a SharePoint solution whit 40 or 50 XML files this quickly becomes laborious.
Is it possible to disable these built-in Schemas, selecting "Do not use selected schemas" does not work for future XML files only the current one?

A: Well, if you really don't want them - you could remove the schemas from the xsd path (%VsInstallDir%\xml\Schemas) - and perhaps disable download (Options->TextEditor->Xml->Miscellaneous). My machine isn't in a suitable state to try it, but it should work in theory...


text:
Q: Is integer multiplication implemented using double precision floating point exact up until 2^53? I ask because I am computing matrix multiplications where all the matrix values are integers.
I'd like to use LAPACK so that I get fast code that is correct. Will two large integers (whose product is less than 2^53), stored as doubles, when multiplied, yield a double containing the exact integer result?

A: Your analysis is correct:

*

*All integers between -253 and 253 are exactly representable in double precision.

*The IEEE754 standard requires calculations to be performed exactly, and then rounded to the nearest representable number.

Hence a product of two values that equals an integer in that range will therefore be represented exactly.
Reference:  What every computer scientist should know about floating-point arithmetic. The key section is the discussion of the IEEE standard as pertaining to operations. That contains the statement of the second bullet point above. You already knew the first bullet point and it's the second point that completes the argument.

A: Yes!  A double's data is split into its sign, exponent, and fraction:
Wikipedia has an article explaining the ranges of representable numbers

All integers between -2^53 and 2^53 are representable in double precision.
Between 2^52=4,503,599,627,370,496 and 2^53=9,007,199,254,740,992 the representable numbers are exactly the integers. For the next range, from 2^53 to 2^54, everything is multiplied by 2, so the representable numbers are the even ones, etc. Conversely, for the previous range from 2^51 to 2^52, the spacing is 0.5, etc.


text:
Q: How to make communicate .Net core API, swagger and sql database via docker-compose I'm trying to deploy a .Net core API with swagger openAPI in it. It works well on my computer with visual studio. I can access it at the address : localhost:5000/swagger/index.html but when i try to deploy it with docker, I can't access the webpage
The .net application seems to communicate well with the sql database, I have no errors on the docker logs of the two containers but when I go to the IPAddress indicated by the "docker inspect" command on the web_API_container, I have a 404 not found page. The IP address is accessible (also with ping) but I can't access the web page of swagger.
here is my docker-compose
version: "3"
services:
    web:
        build: .
        ports:
            - "5000:80"
        depends_on:
            - db
    db:
        image: "mcr.microsoft.com/mssql/server"
        environment:
            SA_PASSWORD: "password"
            ACCEPT_EULA: "Y"

and here, my Dockerfile for the .net app :
FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
EXPOSE 5000

FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY ["TestAPI/TestAPI.csproj", "TestAPI/"]
COPY ["Abstract/Abstract.csproj", "Abstract/"]
COPY ["ClassLibrary1/Entities.csproj", "ClassLibrary1/"]
COPY ["DataAccessLayer/DataAccessLayer.csproj", "DataAccessLayer/"]
COPY ["Services/Services.csproj", "Services/"]

RUN dotnet restore "TestAPI/TestAPI.csproj"
COPY . .
WORKDIR "/src/TestAPI"
RUN dotnet build "TestAPI.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "TestAPI.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "TestAPI.dll"]

I have also tried to map port 80 to 80 instead of 5000 to 80 in the docker-compose because I read that .Net core app are on port 80 in production but it didn't worked better...
thanks for your help !


text:
Q: Correlation of non-stationary time series I am looking at finding correlations between house price time series and the time series of multiple indicators in an area. For example

These two trends clearly show a sort of strong negative correlation.
Other indicators in this example could be income (expected positive correlation), crime (expected weak negative correlation), number of pizzas I've eaten that month (expected zero correlation).
I've read that cross-correlation if the method used to find a correlation between stationary time series but these are clearly non-stationary.
This is where I'm getting confused. Is it correct to detrend e.g. take the residual part of this plot:

and then perform cross-correlation on this, providing that it is stationary enough?
I'm struggling to believe this as I feel that if we do this, we're ignoring the key part of the information which is the overall trend of the two-series through time.
I feel that perhaps a better option is to take the trend and then perform e.g. first order differencing on it. And then hopefully providing that both of the differenced time series are stationary enough, performing cross correlation on that.
Which of these options, if either is correct?

A: Find correlation between two time series. Theory and practice (R) is a good place to start your education. Note the discussion that points to the flaw of interpreting ( not computing ! ) correlation coefficients when you have auto-correlated data ...as you do .
This problem was recognized for time series as early as 1926 by Yule in his presidential address to the Royal Statistical Society and nearly 100 years later we have Google https://www.google.com/trends/correlate/tutorial and tons of others promoting the erroneous interpretation ( i.e. using standard significance testing !) of time series correlations.


text:
Q: Invalid character in my array of a function...Code Check I'm getting an invalid character error from the following array that I'm entering in my document. I don't see any characters that could be invalid:
\begin{equation*}
f(\textbf{x}) = \left[\begin{array}
                    f_{1}(\mathbf{x}) \\
                    \vdots \\
                    f_{n}(\mathbf{x})
                    \end{array} \right]
\end{equation*}

Perhaps a new set of eyes could see what is wrong. Thanks in advance.

A: Found it, you have to add the justification option {c} to the array environment. This works for me:
\begin{equation*}
f(\textbf{x}) = \left[\begin{array}{c}
                    f_{1}(\mathbf{x}) \\
                    \vdots \\
                    f_{n}(\mathbf{x})
                    \end{array} \right]
\end{equation*}

Hope this helps.


text:
Q: remove item from minicart in magento 1.9x i want to remove item from minicart but using custom jquery ui popup. here is the default code
template/checkout/cart/minicart/default.phtml
 <?php if (!$this->isOnCheckoutPage()): ?>
        <a href="<?php echo $this->getAjaxDeleteUrl() ?>" title="<?php echo $this->__('Remove This Item') ?>"
           data-confirm="<?php echo $this->__('Are you sure you would like to remove this item from the shopping cart?') ?>"
           class="remove">
            <?php echo $this->__('Remove Item') ?>

    <?php else: ?>
        <?php echo $this->__('Remove Item') ?>
    <?php endif; ?>
<?php endif ?>

This works fine.but i want custom popup instead of default alert. so i used jquery popup.

            Are you sure you would like to remove this item from the shopping cart?

        <a href="<?php echo $this->getAjaxDeleteUrl() ?>" title="<?php echo $this->__('Remove This Item') ?>" class="remove-this-item">
           <?php echo $this->__('Remove Item') ?>

using this popup only, i have to perform ajax delete operation. above code redirects to next page when confirmed YES.


text:
Q: Does apt-get install package from ppa first and then official repository? I want to get the most recent version of nodejs installed, so I add the ppa:chris-lea/node.js .
but does it mean when I run apt-get install nodejs, it will install the package from the ppa instead of the official repository???
How does apt-get determine from which source to install a package???

A: By default apt-get searches all available package sources and installs the package with the highest version number.
apt-cache policy nodejs

shows you all packages for nodejs with their versions from your package sources and tells you which one it would install ("Candidate").
There are some weays to change this behaviour, see for example How to prevent updating of a specific package?


text:
Q: why my multiple chart.js does not work properly? I have 3 Linechart in my page that get 3 different data ,when the page is loaded they're all fine but with scroll or click on stuffs all of them show the data of last chart(so they all look the same)
it's very confusing I'm not experimental with charts and I don't know how I can fix it.
here's my code

            async function createOrderChart (){
                var myLineChart = new Chart(ctxL, {
                    type: 'line',
                    data: {
                    labels: chartLabels,
                    datasets: [{
                    label: "Orders",
                    data: chartData,
                    backgroundColor: [
                        "rgba(140, 184, 179, .2)",
                    ],
                    borderColor: [
                        "rgba(214, 255, 250)",
                    ],
                    borderWidth: 2
                    },
                    ]
                    },
                    options: {
                        responsive: true
                    }
                });
            }

            async function createTradeChart (){
                var myLineChart1 = new Chart(ctxL1, {
                    type: 'line',
                    data: {
                    labels: chartLabels,
                    datasets: [{
                    label: "Trades",
                    data: chartData,
                    backgroundColor: [
                        "rgba(219, 255, 251, .2)",
                    ],
                    borderColor: [
                        "rgba(219, 255, 251)",
                    ],
                    borderWidth: 2
                    },
                    ]
                    },
                    options: {
                        responsive: true
                    }
                });
            }

            async function createUserChart (){
                var myLineChart2 = new Chart(ctxL2, {
                    type: 'line',
                    data: {
                    labels: chartLabels,
                    datasets: [{
                    label: "Users",
                    data: chartData,
                    backgroundColor: [
                        "rgba(224, 255, 251, .2)",
                    ],
                    borderColor: [
                        "rgba(224, 255, 251)",
                    ],
                    borderWidth: 2
                    },
                    ]
                    },
                    options: {
                        responsive: true
                    }
                });
            }

            chartAjax("/api/",'m');
            ctxL = document.getElementById("orderChart").getContext('2d');
            createOrderChart();

            chartAjax("/api/",'m');
            ctxL1 = document.getElementById("tradeChart").getContext('2d');
            createTradeChart();

            chartAjax("/api/",'m');
            ctxL2 = document.getElementById("usersChart").getContext('2d');
            createUserChart();

A: The problem is that all your charts use the same array for labels and also the same array for datasets.data. Each time, the chartAjax function is invoked, their content is overwritten.
To make this work, you could rewrite your code as follows. Providing the specific chart creation function as a parameter to the function chartAjax. When the ajax call is successful, chartAjax would then invokes the chart creation function with the correct data each.
async function chartAjax(url, interval, chartCreationFunction) {
  $.ajax({
    async: false,
    url: url,
    method: "GET",
    dataType: "json",
    data: {
      'interval': interval,
    },
    success: function(response) {
      let resChart = JSON.parse(JSON.stringify(response));
      let chartLabels = resChart.data.map(o => o['date']);
      let chartData = resChart.data.map(o => o['count']);
      chartCreationFunction(chartLabels, chartData);
    },
  });
}

function createOrderChart(chartLabels, chartData) {
  var myLineChart = new Chart(document.getElementById("orderChart"), {
    type: 'line',
    data: {
      labels: chartLabels,
      datasets: [{
        label: "Orders",
        data: chartData,
        backgroundColor: [
          "rgba(140, 184, 179, .2)",
        ],
        borderColor: [
          "rgba(214, 255, 250)",
        ],
        borderWidth: 2
      }, ]
    },
    options: {
      responsive: true
    }
  });
}

function createTradeChart(chartLabels, chartData) {
  var myLineChart1 = new Chart(document.getElementById("tradeChart"), {
    type: 'line',
    data: {
      labels: chartLabels,
      datasets: [{
        label: "Trades",
        data: chartData,
        backgroundColor: [
          "rgba(219, 255, 251, .2)",
        ],
        borderColor: [
          "rgba(219, 255, 251)",
        ],
        borderWidth: 2
      }, ]
    },
    options: {
      responsive: true
    }
  });
}

function createUserChart(chartLabels, chartData) {
  var myLineChart2 = new Chart(document.getElementById("usersChart"), {
    type: 'line',
    data: {
      labels: chartLabels,
      datasets: [{
        label: "Users",
        data: chartData,
        backgroundColor: [
          "rgba(224, 255, 251, .2)",
        ],
        borderColor: [
          "rgba(224, 255, 251)",
        ],
        borderWidth: 2
      }, ]
    },
    options: {
      responsive: true
    }
  });
}

chartAjax("/api/v1/admin/orderCahrt", 'm', createOrderChart);
chartAjax("/api/v1/admin/tradeChart", 'm', createTradeChart);
chartAjax("/api/v1/admin/userChart", 'm', createUserChart);


text:
Q: Most frequent words in a terabyte of data I came across a problem where we have to find say the most 10 frequent words in a terabyte of file or string.
One solution I could think was using a hash table (word, count) along with a max heap. But fitting all the words if the words are unique might cause a problem.
I thought of another solution using Map-Reduce by splitting the chunks on different nodes.
Another solution would be to build a Trie for all the words and update the count of each word as we scan through the file or string.
Which one of the above would be a better solution? I think the first solution is pretty naive.

A: Split your available memory into two halves.  Use one as a 4-bit counting Bloom filter and the other half as a fixed size hash table with counts.  The role of the counting Bloom filter is to filter out rarely occuring words with high memory efficiency.
Check your 1 TB of words against the initially empty Bloom filter; if a word is already in and all buckets are set to the maximum value of 15 (this may be partly or wholly a false positive), pass it through.  If it is not, add it.
Words that passed through get counted; for a majority of words, this is every time but the first 15 times you see them.  A small percentage will start to get counted even sooner, bringing a potential inaccuracy of up to 15 occurrences per word into your results.  That's a limitation of Bloom filters.
When the first pass is over, you can correct the inaccuracy with a second pass if desired.  Deallocate the Bloom filter, deallocate also all counts that are not within 15 occurrences behind the tenth most frequent word.  Go through the input again, this time accurately counting words (using a separate hash table), but ignoring words that have not been retained as approximate winners from the first pass.
Notes
The hash table used in the first pass may theoretically overflow with certain statistical distributions of the input (e.g., each word exactly 16 times) or with extremely limited RAM.  It is up to you to calculate or try out whether this can realistically happen to you or not.
Note also that the bucket width (4 bits in the above description) is just a parameter of the construction.  A non-counting Bloom filter (bucket width of 1) would filter out most unique words nicely, but do nothing to filter out other very rarely occuring words.  A wider bucket size will be more prone to cross-talk between words (because there will be fewer buckets), and it will also reduce guaranteed accuracy level after the first pass (15 occurrences in the case of 4 bits).  But these downsides will be quantitatively insignificant until some point, while I'm imagining the more aggresive filtering effect as completely crucial for keeping the hash table in sub-gigabyte sizes with non-repetitive natural language data.
As for the order of magnitude memory needs of the Bloom filter itself; these people are working way below 100 MB, and with a much more challenging application ("full" n-gram statistics, rather than threshold 1-gram statistics).

A: Sort the terabyte file alphabetically using mergesort.  In the initial pass, use quick sort using all available physical RAM to pre-sort long runs of words.
When doing so, represent a continuous sequence of identical words by just one such word and a count.  (That is, you are adding the counts during the merges.)
Then resort the file, again using mergesort with quick sort presorting, but this time by the counts rather than alphabetically.
This is slower but simpler to implement than my other answer.

A: The best I could think of:

*

*Split data to parts you can store in memory.

*For each part get N most frequent words, you will get N * partsNumber words.

*Read all data again counting words you got before.

It won't always give you correct answer, but it will work in fixed memory and linear time.

A: And why do you think a building of the Trie structure is not the best decision? Mark all of child nodes by a counter and that's it! Maximum memory complexity will be O(26 * longest_word_length), and time complexity should be O(n), that's not bad, is it?


text:
Q: Eclipse - CDT Content Assist extremely slow I just installed eclipse-cdt 3.2.2 on Linux (Mint). The content assist feature which pops up when you do a "." or "->" on a struct or struct pointer, is extremely slow and freezes the entire IDE for around 10-20 seconds.
This I feel, is because it searches through the entire include directory /usr/include that comes by default for any C project that you create.
How can this issue be solved?
Thanks..

A: You have bug 196203 which points to this page with some settings to perform.
It includes:

*

*how to make Eclipse actually use Sun's Java solving the "Eclipse is horribly slow" problem caused by bug 45347.

*raising the default heap size.


text:
Q: Request error after upgrading PHP from 5.6 to 7.3 I have a script that makes a request to an API, then returns back the response to AJAX. After updating my server from PHP 5.6 to PHP 7.3 the request is not succeding and just returns "null". This is the error I am getting:

PHP Warning: file_get_contents(https://api.ekata.com/3.3/identity_check?'.primary.address.city=Los Angeles&primary.address.postal_code=90001&primary.address.state_code=CA&primary.address.street_line_1=7519+Wadsworth+Ave&primary.name=SteveTest+SmithTest&primary.phone=9165551234.'&api_key=XXXXXXXXXX): failed to open stream: HTTP request failed!

Here is the PHP:
<?php

# An HTTP GET request example
header('Content-Type: application/json');
$url = $_POST['url'];

$json = file_get_contents('https://api.ekata.com/3.3/identity_check?'.$url.'&api_key=XXXXXXX');

$obj = json_decode($json);
echo json_encode($obj, JSON_PRETTY_PRINT);

A: Your error message clearly indicates that the file_get_contents attempt to fetch a remote url is failing. You should probably be using CURL instead. Alternatively, look at the output of phpinfo() and look for allow_url_fopen. If this is 0 or false then you can try changing your php.ini settings to allow PHP to access remote urls with functions like file_get_contents.
Note that if you change php.ini, you might need to restart apache if PHP runs as a module or restart PHP-FPM is your machine is running that.
EDIT: I would add that your PHP script should be checking the result of the file_get_contents call before just coughing it up. If the result is empty, you should probably have your PHP script cough up some kind of error object and have your javascript check for an error condition before trying to operate on the JSON results.

A: So the issue was that the city field had a space in it so the API URL was invalid. Wasn't obvious until I started really looking in the Network/Response tab
https://proapi.whitepages.com/3.3/lead_verify?primary.address.city=Los Angeles&primary.address.postal_code=90001

I added this to my php file and it sent successfully:
$url = str_replace(" ", "%20", $url);

I do however need to look into CURL, so I will be doing that on our DEV site. Thank you everyone for helping me troubleshoot this.