text:
Q: How to write formula to get this result in excel Please refer the below screenshot:

I have 4 users on this sheet (User1, User2, User3 and User4) and a User's Catalog that shows a date in front of each user. Now what I want is to display the max date for each user in row 3 under their respective Names, so that the result is something like this:

Any Idea how to write a formula to achieve this result?
P.S. I know I have to try it first, but I a complete newbie to excel and don't know much except for very basic formula. For this one, I don't even know where to start.

A: You can use MAXIFS. In cell A3, put:
=MAXIFS($B$6:$B$14, $A$6:$A$14, "="&A2)

You can then drag copy that across into B3, C3 and D3.

A: You can use this array formula.
=MAX(IF($A$6:$A$15=A$2,$B$6:$B$15,""))

Make sure you enter it as an array formula. So, you have to press CTRL+SHIFT+ENTER after putting formula in cell.


text:
Q: WPF DataGrid sorting not doing, if the source is replaced by a new collection I have a list of objects, each contains a collection. I need a possibility to select a object from the list and display the collection. The collection should be sorted by a some property.
So, I have a ComboBox to display a list of objects. And a DataGrid to display a selected object's collection. I use a CollectionViewSource to sort a DataGrid. It work... but only first time. After selecting other object from the list, DataGrid are no longer sorted.
XAML:
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <ResourceDictionary>
        <CollectionViewSource x:Key="SortedValues"
                              Source="{Binding SelectedCategory.Values}">
            <CollectionViewSource.SortDescriptions>
                <componentModel:SortDescription PropertyName="Value" Direction="Ascending" />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <StackPanel>
        <ComboBox ItemsSource="{Binding Path=Categories}"
                  DisplayMemberPath="Name"
                  SelectedItem="{Binding Path=SelectedCategory}"/>
        <DataGrid ItemsSource="{Binding Source={StaticResource SortedValues}}"
                  CanUserSortColumns="False">
        </DataGrid>
    </StackPanel>
</Grid>

Code Behind:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = this;

        Categories = new ObservableCollection<MyCategory>
        {
            new MyCategory
            {
                Name = "Cat1",
                Values = new ObservableCollection<MyValue>
                {
                    new MyValue {Value = 5},
                    new MyValue {Value = 4},
                    new MyValue {Value = 3},
                    new MyValue {Value = 2},
                    new MyValue {Value = 1},
                }
            },

            new MyCategory
            {
                Name = "Cat2",
                Values = new ObservableCollection<MyValue>
                {
                    new MyValue {Value = 15},
                    new MyValue {Value = 14},
                    new MyValue {Value = 13},
                    new MyValue {Value = 12},
                    new MyValue {Value = 11},
                }
            }
        };
    }

    public ObservableCollection<MyCategory> Categories { get; set; }

    public MyCategory SelectedCategory
    {
        get
        {
            return _selectedCategory;
        }
        set
        {
            _selectedCategory = value;
            OnPropertyChanged();
        }
    }

    private MyCategory _selectedCategory;

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

public class MyCategory
{
    public string Name { get; set; }
    public ObservableCollection<MyValue> Values { get; set; }
}

public class MyValue
{
    public double Value { get; set; }
}
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make the alarm clock only go off on Monday and Tuesday? There is a built-in alarm clock in windows phone 7.5 (mango), which can set the clock only repeat on specific time (ex. Monday,Tuesday....). I want implement the same function, but as far as i know, the properties of "alarm"/"reminder" didn't give me enough support for this. So i wonder if any one can help me on this ? appreciate your help.

A: You can set the BeginTime of Alarm to the next monday and the RecurrenceType to Weekly


text:
Q: Finding homomorphisms in normal groups to $S_n$ This question is related to my trouble in abstract algebra in general so some general advice is really appreciated!! (I'm really new to this.)
Let A be an infinite subset of G with $n = \#A$.
\begin{equation}
H = \{g∈G: gag^{-1}∈A, \forall a∈A\}\\
N = \{g∈G: ga=ag, \forall a∈A \}
\end{equation}
First I'm asked to prove that H is a subgroup of G. No problem. first I use a=g to prove that H isn't empty, then I fix a and take g and g'.
Second I'm asked to prove that N is a normal subgroup of H. Now I have to show that any left coset $hN=Nh$ with h in H. (my first complication)
And in the end I have to find a homomorphism $\,f:H \to S_n$ so that $N=Ker(f)$.
Now with this one I have no idea how to even begin.


text:
Q: logistic regression and GridSearchCV using python sklearn I am trying code from this page. I ran up to the part LR (tf-idf) and got the similar results
After that I decided to try GridSearchCV. My questions below:
1)
#lets try gridsearchcv
#https://www.kaggle.com/enespolat/grid-search-with-logistic-regression

from sklearn.model_selection import GridSearchCV

grid={"C":np.logspace(-3,3,7), "penalty":["l2"]}# l1 lasso l2 ridge
logreg=LogisticRegression(solver = 'liblinear')
logreg_cv=GridSearchCV(logreg,grid,cv=3,scoring='f1')
logreg_cv.fit(X_train_vectors_tfidf, y_train)

print("tuned hpyerparameters :(best parameters) ",logreg_cv.best_params_)
print("best score :",logreg_cv.best_score_)

#tuned hpyerparameters :(best parameters)  {'C': 10.0, 'penalty': 'l2'}
#best score : 0.7390325593588823

Then I calculated f1 score manually. why it is not matching?
logreg_cv.predict_proba(X_train_vectors_tfidf)[:,1]
final_prediction=np.where(logreg_cv.predict_proba(X_train_vectors_tfidf)[:,1]>=0.5,1,0)
#https://www.statology.org/f1-score-in-python/
from sklearn.metrics import f1_score
#calculate F1 score
f1_score(y_train, final_prediction)
0.9839388145315489

*If I try scoring='precision' why does it give below error? I am not clear mainly because I have relatively balanced dataset (55-45%) and f1 which requires precision is getting calculated without any problems

#lets try gridsearchcv #https://www.kaggle.com/enespolat/grid-search-with-logistic-regression
from sklearn.model_selection import GridSearchCV

grid={"C":np.logspace(-3,3,7), "penalty":["l2"]}# l1 lasso l2 ridge
logreg=LogisticRegression(solver = 'liblinear')
logreg_cv=GridSearchCV(logreg,grid,cv=3,scoring='precision')
logreg_cv.fit(X_train_vectors_tfidf, y_train)

print("tuned hpyerparameters :(best parameters) ",logreg_cv.best_params_)
print("best score :",logreg_cv.best_score_)

/usr/local/lib/python3.7/dist-packages/sklearn/metrics/_classification.py:1308: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))
/usr/local/lib/python3.7/dist-packages/sklearn/metrics/_classification.py:1308: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))
/usr/local/lib/python3.7/dist-packages/sklearn/metrics/_classification.py:1308: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))
/usr/local/lib/python3.7/dist-packages/sklearn/metrics/_classification.py:1308: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))
/usr/local/lib/python3.7/dist-packages/sklearn/metrics/_classification.py:1308: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))
/usr/local/lib/python3.7/dist-packages/sklearn/metrics/_classification.py:1308: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))
tuned hpyerparameters :(best parameters)  {'C': 0.1, 'penalty': 'l2'}
best score : 0.9474200393672962

*is there any easier way to get predictions on the train data back?  we already have the  logreg_cv object. I used below method to get the predictions back. Is there a better way to do the same?

logreg_cv.predict_proba(X_train_vectors_tfidf)[:,1]
############################
############update 1

*

*Please answer question 1 from above. In the comment for the question it says The best score in GridSearchCV is calculated by taking the average score from cross validation for the best estimators. That is, it is calculated from data that is held out during fitting. From what I can tell, you are calculating predicted values from the training data and calculating an F1 score on that. Since the model was trained on that data, that is why the F1 score is so much larger compared to the results in the grid search
is that the reason I get below results #tuned hpyerparameters :(best parameters)  {'C': 10.0, 'penalty': 'l2'} #best score : 0.7390325593588823
but when i do manually i get
f1_score(y_train, final_prediction) 0.9839388145315489
2)
I tried to tune using f1_micro as suggested in the answer below. No error message. I am still not clear why f1_micro is not failing when precision  fails
from sklearn.model_selection import GridSearchCV

grid={"C":np.logspace(-3,3,7), "penalty":["l2"], "solver":['liblinear','newton-cg'], 'class_weight':[{ 0:0.95, 1:0.05 }, { 0:0.55, 1:0.45 }, { 0:0.45, 1:0.55 },{ 0:0.05, 1:0.95 }]}# l1 lasso l2 ridge
#logreg=LogisticRegression(solver = 'liblinear')
logreg=LogisticRegression()
logreg_cv=GridSearchCV(logreg,grid,cv=3,scoring='f1_micro')
logreg_cv.fit(X_train_vectors_tfidf, y_train)

tuned hpyerparameters :(best parameters)  {'C': 10.0, 'class_weight': {0: 0.45, 1: 0.55}, 'penalty': 'l2', 'solver': 'newton-cg'}
best score : 0.7894909688013136

A: You end up with the error with precision because some of your penalization is too strong for this model, if you check the results, you get 0 for f1 score when C = 0.001 and C = 0.01
res = pd.DataFrame(logreg_cv.cv_results_)
res.iloc[:,res.columns.str.contains("split[0-9]_test_score|params",regex=True)]

                           params  split0_test_score  split1_test_score  split2_test_score
0   {'C': 0.001, 'penalty': 'l2'}           0.000000           0.000000           0.000000
1    {'C': 0.01, 'penalty': 'l2'}           0.000000           0.000000           0.000000
2     {'C': 0.1, 'penalty': 'l2'}           0.973568           0.952607           0.952174
3     {'C': 1.0, 'penalty': 'l2'}           0.863934           0.851064           0.836449
4    {'C': 10.0, 'penalty': 'l2'}           0.811634           0.769547           0.787838
5   {'C': 100.0, 'penalty': 'l2'}           0.789826           0.762162           0.773438
6  {'C': 1000.0, 'penalty': 'l2'}           0.781003           0.750000           0.763871

You can check this:
lr = LogisticRegression(C=0.01).fit(X_train_vectors_tfidf,y_train)
np.unique(lr.predict(X_train_vectors_tfidf))
array([0])

And that the probabilities predicted drift towards the intercept:
# expected probability
np.exp(lr.intercept_)/(1+np.exp(lr.intercept_))
array([0.41764462])

lr.predict_proba(X_train_vectors_tfidf)

array([[0.58732636, 0.41267364],
       [0.57074279, 0.42925721],
       [0.57219143, 0.42780857],
       ...,
       [0.57215605, 0.42784395],
       [0.56988186, 0.43011814],
       [0.58966184, 0.41033816]])

For the question on "get predictions on the train data back", i think that's the only way. The model is refitted on the whole training set using the best parameters, but the predictions or predicted probabilities are not stored. If you are looking for the values obtained during train / test, you can check cross_val_predict


text:
Q: http.NewRequest allow only one redirect I came from this question and the answer works if I want no redirect at all:
client := &http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    },
}

But how can I allow exactly one redirect here?

A: As the documentation states:

The arguments req and via are the upcoming request and the requests made already, oldest first.

So at the first redirect, len(via) will be 1. If you return error if len(via)>1, it should fail for additional requests.


text:
Q: Python: Automatic form filling using Selenium gives Error I am trying to acces a website using selenium whenever i try to do the following error appears:
ElementNotVisibleException: Message: element not visible

the code is as follows:
from urllib import parse
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys

class ICAIScraper(object):
    def __init__(self):
        self.url = "https://www.icaionlineregistration.org/Admin_Module/Login.aspx"
        self.driver = webdriver.Chrome('C:\\chromedriver.exe')

    def scrape(self):
        self.driver.get(self.url)
        wait = WebDriverWait(self.driver, 10)
        wait.until(lambda driver: driver.find_element_by_id('txt_username').is_displayed() == False)
        print('Yay! on the first page')
        username = self.driver.find_element_by_id('txt_username')
        username.click()
        username.send_keys('username')
        password = self.driver.find_element_by_id('txt_password')
        password.send_keys('password')
        password.send_keys(Keys.ENTER)
        self.driver.quit()

if __name__ == '__main__':
   scraper = ICAIScraper()
   scraper.scrape()

A: Write a simple function that scrolls to any UI element by id (or you can customize it by using By class). Invoking the method by supplying a element's id attribute will bring the element to driver's focus.
def scroll_to_element_by_id(driver, element_id):
    driver.execute_script("return arguments[0].scrollIntoView();", driver.find_element_by_id(element_id))

Sample invocation:
scroll_to_element_by_id(self.driver, 'txt_password')

A: The error says it all :
ElementNotVisibleException: Message: element not visible

As you have tried to locate the Username and Password field through the id attribute, the fields were not uniquely identified. So we have to adopt a Locator Strategy which uniquely identifies the Username and Password field as follows :
# populate the Username field
self.driver.find_element_by_xpath("//td/img[@src='../images/login_userName.png']//following::input[2]").send_keys("username")
# populate the Password field
self.driver.find_element_by_xpath("//td/img[@src='../images/login_password.png']//following::input[2]").send_keys("password")


text:
Q: Multiple Url for same app in tomcat to test multi tenancy I have developed a multi tenant application with Java on tomcat 8. I want to test it now. Is there a way where I can replicate/create different urls pointing to same application in tomcat? i.e. like following manner.
https://abc.localhost:8080/myapp
and
https://xyz.localhost:8080/myapp
The reason for abc and xyz, is they would be the sub domain for the application. Using which I will be able to identify the tenants.
P.S I don't want to use cookie based approach and don't want to keep passing or ask the user to enter the tenant name or tenant id.

A: You can use your hosts file to test this. Change your Tomcat HTTP port to 80 and edit your host file :

127.0.0.1 abc.localhost
  127.0.0.1 xyz.localhost

on Linux : /etc/hosts
On Windows : C:\Windows\System32\Drivers\etc
I use this to test my multi-tenant application, that also use subdomain for each tenant. (I use WildFly as Application Server)

A: ok, I found a solution to this without the need to point my application to port 80.
I used fiddler for this. In fiddler you can change rules. From the menu Rules -> Customize Rules.
Selecting customizing Rules will open a script, in which there are number of methods predefined, OnBeforeRequest ,OnBeforeResponse etc. I modified OnBeforeRequest and added following lines of code.
if (oSession.host=="www.mysubdomain1.maindomain.com:8443") {
    oSession.host="localhost:8443";
}

if (oSession.host=="www.mysubdomain2.maindomain.com:8443") {
    oSession.host="localhost:8443";
}

and that is it. You can map it to your app as per your wish.
The fiddler documentation link is: Fiddler Script documentation


text:
Q: How to configure VMware in Windows 7 Home Basic? How can I configure VMWare in Windows 7, Home Basic?  Where can I download VMware? Is there a guide that shows me how to configure VMware?

A: You can download a demo at their website, www.vmware.com
There are also manuals, FAQs and whatnot on the site.  The documentation is quite thorough.

A: VMWare Player is also available for free from the website.
http://www.vmware.com/products/player/


text:
Q: How to pass parameters to a function within an Angular directive? Within an AngularJS directive, I trigger a callback function that needs access to a directive-level object that has been injected.
I am using a KendoUI template function for this, however I think this is more an issue about scope than the function.
Directive:
app.directive('projectEditorGrid', function (dataSourceFactory) {

    var dataSourceFactory = new dataSourceFactory("/odata/ProjectEditor");

    return {
        link: function ($scope, $element, $attrs) {
            $element.kendoGrid({
                dataSource: dataSourceFactory.projects(),
                pageable: true,
                height: 400,
                toolbar: ["create"],
                columns: [
                            { field: "WebsiteName", editable: true, width: 190, title: "Project Name", validation: { required: { message: "Project name is required" } } },
                            { field: "WebsiteNotes", title: "Project Notes" },
                            { field: "WebsiteGUID", title: "Project API ID", editable: false },
                            { field: "DefaultContentType", title: "Default Content Type", width: "160px", editor: defaultContentTypeDropDownEditor, template: "#=ContentTypes.Descriptions#" },
                            { command: ["edit", "destroy"] }
                ],
                editable: "inline"
            });

            function defaultContentTypeDropDownEditor(container, options) {
                console.log(container + " : " + options);
                var dataSourcFactory = dataSourceFactory("/odata/ContentType");
                var dsContentTypes = dataSourceFactory.contentTypes();  // returns a kendo.data.DataSource() object

                $('<input required data-text-field="Description" data-value-field="ContentTypeId" data-bind="value:' + options.field + '"/>')
                    .appendTo(container)
                    .kendoDropDownList({
                        autoBind: false,
                        dataSource: dataSourceFactory.contentTypes()
                    }); // kendoDropDownList
            }
        }
    }
});

dataSourceFactory is injected into the directive and successfully used to display the data.
When a row edit is triggered, defaultContentTypeDropDownEditor is called with its default parameters, container, options.   If I could pass the dataSourceFactory to this function I'd be set, but not clear on how to accomplish this from the activating call.
options:
Object {field: "DefaultContentType", editor: function, model: n.extend.o}
editor: function defaultContentTypeDropDownEditor(container, options) {
field: "DefaultContentType"
model: n.extend.o
__proto__: Object

container:
[	]

As you can see, dataSourceFactory is visible at the function level (injected into the directive), however is not accessible from within the defaultContentTypeDropDownEditor.  Can someone please explain how to accomplish this?

A: The injected object is dataSourceFactory.  By renaming the initial initialization to dataSourceFactory1 and the function callback's use of it to dataSourceFactory2, I was able to get this  working.
Thanks to Nikos for pointing me in the right direction.


text:
Q: How to prove coefficients of a power series is bounded? Let $f(z)=\sqrt{1-z}$. Let
$$\sum_{k=0}^\infty c_kz^k$$
be the power series converges to $f(z)$ in the ball $|z|<1$. How can I prove that $|c_k|$ is bounded.

A: $$|c_k|=\left|\binom{\frac{1}{2}}{k}\right|=\frac{1\times 1\times 3\times\cdots\times (2k-3)}{2^kk!}=\frac{(2k-2)!}{2^{2k-1}k!(k-1)!}=\frac{1}{2^{2k-1}(2k-1)}\binom{2k-1}{k}<\frac{1}{2k-1}$$


text:
Q: select all comments of specific posts mongoid 2 rails 3.1 Lets say an author has many posts, and a post has many comments.
How could you select all of the comments of a specific authors specific few posts?
Use case: I want every recent comment of an author's posts with the tag 'rails'
@author = Author.find(params[:author_id])
@posts = @author.posts.where(:tag => 'rails')

now
@comments = @posts.?????.where(:created_at.gte = 1.month.ago)

A: There is no way to do this via @posts.?????
You should grab post ids and select comments
post_ids = @author.posts.where(:tag => 'rails').map(&:id)
# In rails >= 3.2.1 you can use pluck(:id) instead of map(&:id)

@comments = Comment.where(:post_id => post_ids, :created_at.gte = 1.month.ago)

upd: or
@posts = @author.posts.where(:tag => 'rails')
@comments = Comment.where(:post_id => @posts.map(&:id), :created_at.gte = 1.month.ago)


text:
Q: Recall method until return true I've a condition where I want to call a method until it return true, if return true then go to next statement otherwise recall itself
     var username= GetUniqueUserName();
     if(UtilityRepository.CheckUserName(username))
     {
                   // next statement
     }
     else
     {
      // recall CheckUser

     }

A: you can
while(UtilityRepository.CheckUserName(username))
{
   //code inside, if you need some, if not just leave this blank
}

//something after `CheckUserName` returned false.

A: Use a while instead of an if.  (And NOT the condition.)

A: var username= GetUniqueUserName();
while ( UtilityRepository.CheckUserName(username) )
{
    //recall user
}
// next statement

OR more charged, but with the same functionality way:
var username= GetUniqueUserName();
bool flag = true;
while ( flag )
{
     if(UtilityRepository.CheckUserName(username))
     {
          // next statement
          flag = false;
     }
     else
     {
          // recall CheckUser
     }
}

But it looks horrible, I think you should divide your .CheckUserName method into two or more separated methods, so u do not need to left blank space on // recall Chechuser .

A: With a recursive implementation :
public void MyMethod()
{
    var username= GetUniqueUserName();
    MyImplementation(username);
}

private void MyImplementation(string userName)
{
    if (!UtilityRepository.CheckUserName(username))
    {
        MyImplementation(userName);
        return;
    }

    //actual stuff here
}

With an iterative implementation, your application might fall into an infinite loop, having a thread permanently asking the same question to UtilityRepository, as @asawyer pointed out. With a recursive implementation, you'll presumably run into a StackOverflowException. Both cases are rather unsatisfying. Could you upgrade UtilityRepository to get a notification when "the status of username has changed" ?


text:
Q: React VictoryBar style difficulties So I'm trying to make a chart show some build data using Victory charts. However I'm getting some pretty annoying issues. The documentaion is pretty bad IMO... they're  trying to cover to much ground as generically as possible.
 Screenshot located here
Look at the above screenshot, the blue box is because I've got it highlighted in Chrome's dev tools.

*

*The areas in boxed red. I can't see why they're there. Going further down, nothing is padding it out or using that space, how do I get rid of it?

*How do I get the font size down to a readable level?

The below is where I'm at right now
    <VictoryChart
      theme={VictoryTheme.material}
      height={200}
      domainPadding={{ x: 20 }}
    >
      <VictoryBar
        barWidth={30}
        style={{
          data: { fill: f => f.fill }
        }}
        height={10}
        data={this.state.dataParsed}
      />
    </VictoryChart>

I've tried editing the material theme directly to adjust the font size, to no avail.
I've also tried creating my own theme but I can't get my head around that...

A: My final result as below. Could do with more work at some point but this is doing for now. Text is more sanely sized and the padding has been sorted

        <VictoryChart
          padding={{ top: 20, bottom: 30, left: 40, right: 20 }}
          theme={VictoryTheme.material}
          height={120}
          domainPadding={{ x: 20 }}
        >
          <VictoryAxis
            style={{
              tickLabels: {
                fontSize: 7
              }
            }}
          />
          <VictoryAxis
            dependentAxis
            orientation="left"
            style={{ tickLabels: { fontSize: 10 } }}
          />
          <VictoryBar
            barWidth={30}
            style={{
              data: { fill: f => f.fill }
            }}
            data={this.state.dataParsed}
          />
        </VictoryChart>


text:
Q: Inheritance from an AbstractUser based Model in django 2.7 I have a Custom User Model extending the AbstractUser and it works fine. But now i want to create another Model that is extending my Custom User Model like this in models.py:
class CustomUser(AbstractUser):
    phone = models.CharField(max_length=10, null=False, unique=True)
    town = models.CharField(max_length=25, null=False)

class DeleveryPerson(CustomUser):
    code = models.CharField(max_length=10, null=False, unique=True)

The problem is that the table DeleveryPerson is created with just the field "code"
when I expected it to also have fields coming from the CustomUser model.
So how can i achieve that kind of inheretane between CustomUser and DeleveryPerson. Thk!


text:
Q: Cross-thread operation not valid in background worker c# I want a code running in background worker but encountered this error :

'Cross-thread operation not valid: Control 'metroComboBox1' accessed from a thread other than the thread it was created on.'

private void metroRename_Click(object sender, EventArgs e)
    {
        if (backgroundWorker1.IsBusy)
            backgroundWorker1.CancelAsync();
        backgroundWorker1.RunWorkerAsync(metroComboBox1.Text);
    }

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        this.Invoke((MethodInvoker)delegate ()
        {
            string text = metroComboBox1.Text;
        });

        if (metroComboBox1.SelectedItem == "TITLE") //error here
        {
           //some code here
        }
    }

How can I use combobox inside the background worker?

A: You should place your condition under Invoke call as well, e.g.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    this.Invoke((MethodInvoker)delegate()
    {
        string text = metroComboBox1.Text;
        if (metroComboBox1.SelectedItem == "TITLE")
        {
           //some code here
        }
    });
}

Here is an existing thread about this problem


text:
Q: How to bind Height to parent's height minus another item's height I have a ListBox that is showing an Image and a Text above it. I have bound the DataTemplate to a custom MyImage class that has a String Str and an Image Image. The next Image would appear right of the first one since the surrounding StackPanel is Horizontal.
I have problems getting the Height of the Image to a value where it would fill the entire ListBox's Height minus the Text's Height and Margin.
In the code below I have bound it to the ActualHeight of the ListBox listboxMyImages.
I would like to be able to substract now the Height of the TextBlock from that value. What's the best way to do that?

<ListBox x:Name="listboxMyImages"  Margin="10,10,10,10">
                                        <ListBox.ItemsPanel>
                                            <ItemsPanelTemplate>
                                                <StackPanel Orientation="Horizontal"/>
                                            </ItemsPanelTemplate>
                                        </ListBox.ItemsPanel>
                                        <ListBox.ItemTemplate>
                                            <DataTemplate DataType="{x:Type local:MyImage}">
                                                <StackPanel>
                                                    <TextBlock x:Name="lblMyImage" Margin="3" Text="{Binding Str}" />
                                                    <Image Margin="3" Source="{Binding Image}"  Height="{Binding ElementName=listboxMyImages, Path=ActualHeight }"/>
                                                </StackPanel>
                                            </DataTemplate>
                                        </ListBox.ItemTemplate>
                                    </ListBox>

A: use another Panel - Grid with 2 rows
<Grid>

<Grid.RowDefinitions>
   <RowDefinition Height="Auto"/>
   <RowDefinition Height="*"/>
</Grid.RowDefinitions>

<TextBlock x:Name="lblMyImage" Margin="3" Text="{Binding Str}" />
<Image Grid.Row="1" Margin="3" Source="{Binding Image}"/>

</Grid>

image will stretch and take all available Height

A: Instead of using a StackPanel you could try to use a Grid like this:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*">
        <RowDefinition Height="Auto">
    </Grid.RowDefinitions>
</Grid>

Not sure if it works as I cannot try it right now.


text:
Q: No such file to load -- 'gem name' using require I am using gem differ https://github.com/pvande/differ
I have a helper
require 'differ'
module AnswersHelper
    def self.getDiff (text1, text2)
        Differ.format = :html
        diff = Differ.diff_by_word(@current, @original)
    end
end

But I get an error No such file to load -- differ
If I remove require line
I get an error at that line
Differ.format = :html

uninitialized constant QuestionsController::Differ

When I tried following commands in rails console it worked
require 'differ'

diff = Differ.diff_by_word("text1","text2)

I  have  gem differ in my gemfile
and also I tried
require_relative 'differ'

and
require './differ'

UPD: seems restarting server helps, I'll check it right now

A: Restarting server helped........


text:
Q: Euler-Lagrange for constrained system Suppose we have Euler-Lagrange system with generalized coordinate $r_1$ and $r_2$, and input $u_1$ and $u_2$. I know how to prove this system is indeed Euler-Lagrange system.
Suppose now if we have a constraint equation so $r_1=f_1(q)$ and $r_2=f_2(q)$. How would I approach in proving that this constrained system is also Euler-Lagrange?

A: Try doing direct substitution, if you have $L=L(r_1,r_2,\dot{r}_1,\dot{r}_2;t)$, do the substitution $r_i \rightarrow f_i(q)$ so you have:
$$
L'= L(f_1(q),f_2(q),\dot{f}_1(q),\dot{f}_2(q);t)
$$
and $\frac{df_i}{dt} =\frac{\partial f_i}{\partial q} \frac{dq}{dt} = \frac{\partial f_i}{\partial q} \dot{q}$ assuming $f_i$ doesn't depend explicitly on $t$ and it's continuous derivative, then if you apply the Euler-Lagrange equations, with dependence only in $q$.
So you have then:
$$
\frac{\partial L'}{\partial q} =\frac{\partial L}{\partial r_1}\frac{\partial f_1}{\partial q} + \frac{\partial L}{\partial r_2}\frac{\partial f_1}{\partial q}
$$
The dependence on $\dot{q}$ is only on the time derivative of $f_i$ and considering $f_i$ has no explicit time dependence:
$$
\frac{d}{dt}\frac{\partial L'}{\partial \dot{q}} = \frac{d}{dt}\left(\frac{\partial L}{\partial \dot{r_1}}\frac{\partial f_1}{\partial q} + \frac{\partial L}{\partial \dot{r_2}}\frac{\partial f_2}{\partial q}\right)  =
\frac{d}{dt}\left(\frac{\partial L}{\partial \dot{r_1}}\right)\frac{\partial f_1}{\partial q} + \frac{d}{dt}\left(\frac{\partial L}{\partial \dot{r_2}}\right)\frac{\partial f_2}{\partial q}$$
If we unite everything, and factoring:
$$
\frac{\partial L'}{\partial q}-\frac{d}{dt}\frac{\partial L'}{\partial \dot{q}} = \left(\frac{\partial L}{\partial r_1}-\frac{d}{dt}\frac{\partial L}{\partial \dot{r_1}}  \right)\frac{\partial f_1}{\partial q} + \left(\frac{\partial L}{\partial r_2}   -\frac{d}{dt}\frac{\partial L}{\partial \dot{r_2}}\right)\frac{\partial f_2}{\partial q} = 0
$$
As $L$ is a good lagrangian for $r_1$ and $r_2$.


text:
Q: How to validates with proc in rails item.rb
I have enum :
enum type: { only_rental: 0, rental_buy: 1, only_one: 2 }
Now I want that if in case of type = "only_one","rental_by", then price would be> 0 and vice versa if it was "only_rental then = 0
validates :price, allow_nil: true, numericality: {
    only_integer: true,
    greater_than: 0,
    less_than: 1000000,
  }
  validates :price, if: proc { !only_rental? }

I tried it as follows but but i don't seem to work

A: Try
validates :price, allow_nil: true, numericality: {
    only_integer: true,
    greater_than: 0,
    less_than: 1000000,
  }, unless: Proc.new { only_rental? }

you can use lambda syntax for Proc.new { only_rental? } as -> { only_rental? }

A: I prefer to validate format with validates and put such logic as your into validate methods:
validates :price, allow_nil: true, numericality: { only_integer: true, less_than: 1000000 }
validate :price_amount

def price_amount
  if only_rental?
    price.zero?
  else
    price.positive?
  end
end

also you could use Rails' with_options:
with_options allow_nil: true, numericality: { only_integer: true, less_than: 1000000 } do
  validates :price, numericality: { greater_than: 0 }, unless: :only_rental?
  validates :price, numericality: { in: [0] },         if:     :only_rental?
end


text:
Q: onClick event not working on Android Blank Activity I have a blank activity in Android Studio, and I have performed the following instructions but it is not working when I run the program.

*

*Select the button and look for properties/attributes panel on the right.

*Assign the name onClick to the android:onClick property of your Button.

*Implement the following method in the Main_Activity file:
public void onClick (View view) {
    Toast.makeText(this, "Button 1 pressed", Toast.LENGTH_LONG).show();
}

When I try to run this I get errors like:

*

*expecting a member declaration

*function declaration must have a name

A: 1)in Xml file of you Activity set onClick property of button with specified function name
android:onClick:"onClick"
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:onClick="onButtonClick"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

2)after this put same function inside your activity but with parameter like this
public void onClick (View view)
public void onButtonClick(View view){
   Toast.makeText(this, "Button 1 pressed", Toast.LENGTH_LONG).show();
}

3) when you click on button provided method gets called
Note: function name can be anything but access specifier, return type and parameter has to be same.

A: Button yourButton = (Button)findViewById(R.id.your_button_id)
yourButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(this, "Button 1 pressed", Toast.LENGTH_LONG).show();
        }
    });

Please try this in Java.

A: Using the XML attribute android:onClick to trigger a click event. Only need two steps:
1.assign android:onClick to button like this:
 <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me!"
    android:onClick="btnClicked" />

2 In activity define a function named btnClicked like this:
   public void btnClicked(View v) {
            Log.d("MR.bool", "Button1 was clicked ");
   }

Notice: don't mix this way with setOnClickListener,just only above two steps.


text:
Q: Proxy script manager for ajaxToolkit:ToolkitScriptManager We have proxy script manager asp:ScriptManagerProxy. with this i can use
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ToolkitScriptManager1" />
//Master Page Data

//Content Page
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
    </asp:ScriptManagerProxy>

My question is that, can i use reverse.
i.e
<asp:ScriptManager ID="ScriptManager1" runat="server"  AsyncPostBackTimeout="0"/>

in master page and some proxy of ajaxToolkit:ToolkitScriptManager in content page


text:
Q: How to get anon aysnc function lineItems out of stripe.checkout.session.listLineItems request into a lambda return response I have the following code, that I want to take the lineItems return in the async function inside stripe.checkout... to return in the body of the lambda try section. I have tried running a .then on the test and many other configuritations and can't quite figure it out. I only can console log the lineItems inside the async function which is good, but I need to return it in the body, below the statusCode.
Hopefully someone can help

require("dotenv").config()
const stripe = require("stripe")(`${process.env.REACT_APP_STRIPE_API_SECRET}`)
exports.handler = async (event, context) => {
  try {
    var eventBody = JSON.parse(event.body)

    console.log(eventBody.customer_id)

    var test = await stripe.checkout.sessions.listLineItems(
      eventBody.customer_id,
      { limit: 5 },
      async function (err, lineItems) {
        return lineItems
      }
    )

   //TRIED TEST.THEN((OK)=>...

    return {
      statusCode: 200,
      body: JSON.stringify({ message: eventBody }),
      // ADD LINE ITEMS TO THE BODY
    }
  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}

A: You just need to wrap the stripe call in Promise and wait for resolve/reject.
Try this:
require("dotenv").config()
const stripe = require("stripe")(`${process.env.REACT_APP_STRIPE_API_SECRET}`)

const checkoutUser = (customerId) => {
  return new Promise((resolve, reject) => {
    stripe.checkout.sessions.listLineItems(
      customerId,
      { limit: 5 },
      (err, lineItems) => {
        if(err) {
          return reject(err);
        }
        resolve(lineItems)
      }
    )
  })
}

exports.handler = async (event, context) => {
  try {
    const eventBody = JSON.parse(event.body)

    console.log(eventBody.customer_id)

    const lineItems = await checkoutUser(eventBody.customer_id);

    // use lineItems here

    return {
      statusCode: 200,
      body: JSON.stringify({ message: eventBody }),
    }
  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}


text:
Q: SafeShell::CommandFailedException: in pdftk I am getting SafeShell::CommandFailedException: Shell command ["/opt/homebrew/bin/pdftk" error while executing  pdftk.fill_form 'public/data.pdf', pdf_name_with_path, data, :flatten => true
Earlier it was working when i was using pdftk, now i just installed java-pdftk using arch -arm64 brew install pdftk-java and it stopped working.
I already updated the pdftk path after installing it.
I am using above in RubyonRails5 and gem pdf-forms
I am using Mac M1(12.3.1)


text:
Q: Pytorch-Forecasting N-Beats model with SELU() activation function? I am working at timeseries forecasting, and I've using the PyTorch lib pytorch-forecasting lately. If you didn't know it, try it. It's great.
I am interested in SELU activation function for Self-Normalizing-Networks (SNNs, see, e.g., the docs). As I didn't find any N-Beats corrected to use SELU and its requirements (i.e. AlphaDropout, proper weights init), I made an implementation myself.
It would be great if any of you with experience with these concepts -NBeats architecture, pytorch-forecasting, or SELU()- could review whether everything is right in my implementation.
My implementation here: https://gist.github.com/pnmartinez/fef1f488497fa85a2cc1626af2a5b4bd


text:
Q: R: Webscraping data not contained in HTML I'm trying to webscrape in R from webpages such as these. But the html is only 50 lines so I'm assuming the numbers are hidden in a javascript file or on their server. I'm not sure how to find the numbers I want (e.g., the enrollment number under student population).
When I try to use rvest, as in
num <- school_webpage %>%
  html_elements(".number no-mrg-btm") %>%
  html_text()

I get an error that says "could not find function "html_elements"" even though I've installed and loaded rvest.
What's my best strategy for getting those various numbers and why am I getting that error message? Thnx.

A: That data is coming from an API request you can find in the browser network tab. It returns json. Make a request direct to that page (as you don't have a browser to do this based off landing page):
library(jsonlite)

data <- jsonlite::read_json('https://api.caschooldashboard.org/LEAs/01611766000590/6/true')
print(data$enrollment)


text:
Q: Getting the Value returned from a Loop to print() only once When trying to retrieve the decrypted password for the second choice, I can't keep the program from printing Does Not Compute no matter whether the website entered is true or not. It prints twice when it is untrue so this leads me to believe the it's printing for i in the range(len(passwords)) which is 2.
How do I get it to print just the password or Does Not Compute once and not have it iterate again? I'm trying to check if the input is equal to the website but it still prints iterates twice.
import csv
import sys

# The password list - We start with it populated for testing purposes
passwords = [["yahoo", "XqffoZeo"], ["google", "CoIushujSetu"]]
# The password file name to store the passwords to
passwordFileName = "samplePasswordFile"
# The encryption key for the caesar cypher
encryptionKey = 16
# Caesar Cypher Encryption
def passwordEncrypt(unencryptedMessage, key):
    # We will start with an empty string as our encryptedMessage
    encryptedMessage = ""
    # For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage
    for symbol in unencryptedMessage:
        if symbol.isalpha():
            num = ord(symbol)
            num += key
            if symbol.isupper():
                if num > ord("Z"):
                    num -= 26
                elif num < ord("A"):
                    num += 26
            elif symbol.islower():
                if num > ord("z"):
                    num -= 26
                elif num < ord("a"):
                    num += 26
            encryptedMessage += chr(num)
        else:
            encryptedMessage += symbol
    return encryptedMessage

def loadPasswordFile(fileName):
    with open(fileName, newline="") as csvfile:
        passwordreader = csv.reader(csvfile)
        passwordList = list(passwordreader)
    return passwordList

def savePasswordFile(passwordList, fileName):
    with open(fileName, "w+", newline="") as csvfile:
        passwordwriter = csv.writer(csvfile)
        passwordwriter.writerows(passwordList)

prompt_msg = """
What would you like to do:
 1. Open password file
 2. Lookup a password
 3. Add a password
 4. Save password file
 5. Print the encrypted password list (for testing)
 6. Quit program
Please enter a number (1-4)
"""

while True:
    print(prompt_msg)
    choice = input()

    if choice == "1":  # Load the password list from a file
        passwords = loadPasswordFile(passwordFileName)

    elif choice == "2":  # Lookup at password
        print("Which website do you want to lookup the password for?")
        for keyvalue in passwords:
            print(keyvalue[0])
        print("----")
        passwordToLookup = input()
        for i in range(len(passwords)):
            print(f"i={i}, store_info={passwords[i]}, website={passwords[i][0]}")
            if passwordToLookup == passwords[i][0]:
                password = passwordEncrypt(passwords[i][1], -(encryptionKey))
                print(f"=> The password is {password}.")
            else:
                print("=> Does not compute!")

    elif choice == "3":
        print("What website is this password for?")
        website = input()
        print("What is the password?")
        unencryptedPassword = input()
        unencryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey)
        newList = [website, unencryptedPassword]
        passwords.append(newList)
        print("Your password has been saved.")

    elif choice == "4":  # Save the passwords to a file
        savePasswordFile(passwords, passwordFileName)

    elif choice == "5":  # print out the password list
        for keyvalue in passwords:
            print(", ".join(keyvalue))

    elif choice == "6":  # quit our program
        sys.exit()

    print()
    print()
    ####### YOUR CODE HERE ######
    # You will need to find the password that matches the website
    # You will then need to decrypt the password
    #
    # 1. Create a loop that goes through each item in the password list
    #  You can consult the reading on lists in Week 5 for ways to loop through a list
    #
    # 2. Check if the name is found.  To index a list of lists you use 2 square backet sets
    #   So passwords[0][1] would mean for the first item in the list get it's 2nd item (remember, lists start at 0)
    #   So this would be 'XqffoZeo' in the password list given what is predefined at the top of the page.
    #   If you created a loop using the syntax described in step 1, then i is your 'iterator' in the list so you
    #   will want to use i in your first set of brackets.
    #
    # 3. If the name is found then decrypt it.  Decrypting is that exact reverse operation from encrypting.  Take a look at the
    # caesar cypher lecture as a reference.  You do not need to write your own decryption function, you can reuse passwordEncrypt
    #
    #  Write the above one step at a time.  By this I mean, write step 1...  but in your loop print out every item in the list
    #  for testing purposes.  Then write step 2, and print out the password but not decrypted.  Then write step 3.  This way
    #  you can test easily along the way.
    #

A: It seems like you want to print does not compute only if NONE of the stored passwords match the input; but as it is, you're printing that message for EACH password that doesn't match (even if some other password did match).
I've modified your loop to break when a match is found, and only print the message if no matches were found (by adding an else clause to the for loop, which executes only if the loop makes it all the way to the end.)
    passwordToLookup = input()
    for i in range(len(passwords)):
        if passwordToLookup == passwords[i][0]:
            webSite = passwordEncrypt(passwords[i][1],-(encryptionKey))
            print()
            print('The password is ' + webSite+'.')
            print(i)
            print(passwords[i])
            print(passwords[i][0])
            break
    else:
        # if we got to the end of the loop, no passwords matched
        print('Does not compute!')

A: First, I took the liberty to reformat and improve your code to look a bit nicer.

*

*Multi-line string for the prompt

*F-string to print variables (Python 3.4 and above)

*Formatting with the new black module

Your problem is that you loop through all the stored websites
    for i in range(len(passwords)):
        if passwordToLookup == passwords[i][0]:
            ...
        else:
            ...

Actually what you should do is

*

*Checking if the website exists in the current list

*Return decrypted password if found, and Cannot computer otherwise

The best way to do 1. is to:

*

*Transform the tuples of passwords to a dictionary: passwords = {"yahoo":"XqffoZeo", "google":"CoIushujSetu"}

*Check if website is one of the keys: if website in passwords.keys(): ...

*Update the rest of the code accordingly (as the list of passwords is not a list of tuples but a dictionary)

Or more simply: just transform the list of tuples to a dictionary when extracting the password:
elif choice == "2":  # Lookup at password
    print("Which website do you want to lookup the password for?")
    for keyvalue in passwords:
        print(keyvalue[0])
    print("----")
    passwordToLookup = input()
    dict_passwords = dict(passwords)
    if passwordToLookup in dict_passwords:
        encrypted = dict_passwords[passwordToLookup]
        password = passwordEncrypt(encrypted, -(encryptionKey))
        print(f"=> The password is {password}.")
    else:
        print("=> Does not compute!")


text:
Q: sendTimeout exceeded by the client on Timeout Exception I am trying to reduce the timeout/EndPointNotFound exception time to 10 seconds. Logs of Exception suggest that the call gets timeout in 10 seconds but if i add the code with StopWatch it takes around 21 - 22 seconds.
I have read the same on this link.
Is it really a bug ?. Is there any workaround?

A: 1 SendTimeout is used to initialize the OperationTimeout, which governs the whole interaction for sending a message
http://msdn.microsoft.com/fr-fr/librarysystem.servicemodel.configuration.standardbindingelement.sendtimeout.aspx
http://msdn.microsoft.com/fr-fr/library/ms731343.aspx

It's not a bug

2 you can adjust property sendTimeout="" in binding section


text:
Q: Inverse Kronecker product or minimize a distance norm Let $A$ be a real valued $4n \times 4n$ matrix, $B$ is a real valued $4\times4$ matrix, and $C$ is a non-negative $n\times n$ matrix. I have $A$ and $B$ and I am trying to get $C$ through this equation:
$$
A = C \otimes B
$$
The elements of $C$ have a certain structure:
Consider the following transition probability matrix $Q$ where
$$
Q_{i,j} =  \left\{
\begin{array}{cl}
      1-p-q & \text{if } j=i-1 \\
      p     & \text{if } j=i\\
      q     &  \text{if } j=i+1\\
\end{array}
\right.
$$
Then the elements of $C$ will be $(C_{k,l}) = [Q^l]_{1,k+1}$ where $Q^l$ is the $l$-step transition matrix.
I was thinking two things: (1) get $C$ by doing some sort of inverse kronecker product or (2) get $C$ by minimizing some norm $||A-C\otimes B||$ with respect to $C$. But more specifically, I want to get $p$ and $q$. Does someone have any citations I can read to help me figure it out or have any suggestions for me? Thanks.


text:
Q: Generics, Comparators, and Test Cases This assignment is part of a section on generics for my Java class. I think I'm having issues wrapping my head around generality by making it too general. For this particular class I have to implement a min (and several other) methods for whatever generic Collection I am given and use the given comparator (comp) to evaluate them.
Implemented code:
public static <T> T min(Collection<T> c, Comparator<T> comp)
            throws IllegalArgumentException, NoSuchElementException {
        if (c != null && comp != null) {
            if (!c.isEmpty()) {
                T min = (T) null;

                for (T t : c) {
                    if (min == null) {
                        min = t;
                    } else if (comp.compare(t, min) < 0) {
                        min = t;
                    }
                }

                return min;

            } else {
                throw new NoSuchElementException();
            }
        } else {
            throw new IllegalArgumentException();
        }
    }

My issue is I don't know how to test this method with my one comparators. I'll explain what I've read/how I understood it, and it'd be great if you guys could tell me where I'm missing something.
If I want to compare within a class (add my own compare/compareTo method):
public class Example<T extends Comparator<T>> {

}

If I want to write my own separate class as a comparator:
public class ExampleComp<T> implements Comparator<T> {
    @override
    public int compare(T o1, T o2) {
    //do fancy things here
    }
}

That means that the way I should write test cases would be to implement my own comparator class and pass the new ExampleComp() as a variable in my method call.
So if my understanding of that is all correct, how do I write the test case for comparing anything and everything? Collection is supposed to be as general as possible, so how do I implement methods to compare one piece to another while keeping everything typesafe?

A: Currently, all your types are invariant. Collection<T> is a collection with a component type of T. A List<T> will match this type, but a Collection won't. There are two other possible component definitions using wildcards, which are covariant (<? extends T>) and contravariant (<? super T>) component types.
In your case, we could make the Collection covariant, but that would mean that your result type would hinge on the Comparator type. Thus the preferred solution is to make the Comparator contravariant. Your method then becomes:
public static <T> T min(Collection<T> c, Comparator<? super T> comp)
        throws IllegalArgumentException, NoSuchElementException {…}

This works, because our comp will take any Comparator that compares at least a supertype of T. So if you have a class Person and a subclass VeryIncompetentPerson, a Comparator<Person> will be enough to get the minimum from a Collection of very incompetent persons.


text:
Q: How do I disable Data conection warning from other workbooks? Im having a issue trying to disable the data connection warning. This always happen when the code open two workbooks which has some data connection. Is there a way that i could disable these warnings?
Notice that these warning's appears in the follow lines:
Set wbsource2 = Workbooks.Open(filepath2)
Set wbsource3 = Workbooks.Open(filepath3)
Here's my code:
Sub Check_SS()
Dim filepath1 As String
Dim filepath2 As String
Dim filepath3 As String
Dim wbsource As Workbook
Application.DisplayAlerts = False
Application.EnableEvents = False

KKS = Application.InputBox("Digite um KKS")
If KKS = False Then
    GoTo Fim
End If

User = (Environ$("Username"))
filepath1 = "C:\Users\" & User & "\Box\UTE\O&M.xlsx"
filepath2 = "C:\Users\" & User & "\Box\UTE\Importações.xlsx"
filepath3 = "C:\Users\" & User & "\Box\UTE\RELATÓRIO (version 1).xlsx"
Set Wbtarget = ThisWorkbook.Sheets("SS")
Set wbtarget3 = ThisWorkbook.Sheets("Data")
Set wbtarget4 = ThisWorkbook.Sheets("Data2")
Set wbsource = Workbooks.Open(filepath1)

wbsource.Activate

ReDim Arrayone(1 To Sheets.Count)
ReDim Arraytwo(1 To 2)
For I = 1 To Sheets.Count
    Arrayone(I) = Sheets(I).Name

Next

n = 1
Total = -300
With wbsource.Sheets(n)
    Do Until n = wbsource.Sheets.Count + 1
        Set encontrar = wbsource.Sheets(n).Range("C:AB").Find(What:=KKS, lookAt:=xlPart)
        If encontrar Is Nothing Then
            If Total <> -300 Then
                GoTo Continuar
            End If
        Else
            encontrar.Select
            L = ActiveCell.Row
            C = ActiveCell.Column
            k = 0
            Do Until wbsource.Sheets(n).Range("O" & L) <> wbsource.Sheets(n).Range("O" & L + k)
                k = k + 1
            Loop
        Total = k - 1
        End If
    n = n + 1
    Loop

Continuar:
    n = n - 1
    k = 0
    While k <= Total
        Wbtarget.Range("D" & 8 + k) = wbsource.Sheets(n).Cells(L + k, C).Value
        Wbtarget.Range("E" & 8 + k) = wbsource.Sheets(n).Cells(L + k, C - 10).Value
        Wbtarget.Range("F" & 8 + k) = wbsource.Sheets(n).Cells(L + k, C + 8).Value
        Wbtarget.Range("G" & 8 + k) = wbsource.Sheets(n).Cells(L + k, C - 12).Value
        k = k + 1
    Wend

End With

wbsource.Close

k = 0
If Wbtarget.Range("F" & 8 + k).Value = "" Then
    GoTo Fim
Else
    Set wbsource2 = Workbooks.Open(filepath2)
    wbsource2.Sheets("Sheet1").Columns(22).Copy
    wbtarget3.Columns(1).PasteSpecial Paste:=xlPasteValues
    wbsource2.Sheets("Sheet1").Columns(11).Copy
    wbtarget3.Columns(2).PasteSpecial Paste:=xlPasteValues
    wbsource2.Close

End If

k = 0
Do Until k = Total
    Set encontrar2 = wbtarget3.Range("A:B").Find(What:=Wbtarget.Range("G" & 8 + k).Value, lookAt:=xlPart)
    If encontrar2 Is Nothing Then
        Wbtarget.Range("I" & 8 + k).Value = "Indisponível"
    Else
        encontrar2.Select
        L2 = ActiveCell.Row
        C2 = ActiveCell.Column
        Wbtarget.Range("H" & 8 + k) = wbtarget3.Cells(L2, 2).Value
        Wbtarget.Range("I" & 8 + k).Value = "Disponível"
    End If
k = k + 1
Loop

Set wbsource3 = Workbooks.Open(filepath3)
wbsource3.Sheets("PEDIDOS C DESCR E PN").Columns(23).Copy
wbtarget4.Columns(1).PasteSpecial Paste:=xlPasteValues
wbsource3.Sheets("PEDIDOS C DESCR E PN").Columns(19).Copy
wbtarget4.Columns(2).PasteSpecial Paste:=xlPasteValues
wbsource3.Close

k = 0
Do Until k = Total
    If Wbtarget.Range("H" & 8 + k).Value <> "" Then
        Set Encontrar3 = wbtarget4.Range("A:B").Find(What:=Wbtarget.Range("H" & 8 + k).Value, lookAt:=xlPart)
        If Encontrar3 Is Nothing Then
            Wbtarget.Range("J" & 8 + k).Value = "Indisponível"
        Else
            Encontrar3.Select
            L3 = ActiveCell.Row
            C3 = ActiveCell.Column
            If wbtarget4.Range("B" & L3).Value <> "" Then
                Wbtarget.Range("J" & 8 + k).Value = "Disponível"
            Else
                Wbtarget.Range("J" & 8 + k).Value = "Indisponível"
            End If
        End If
    Else
        Wbtarget.Range("J" & 8 + k).Value = "Indisponível"
    End If
k = k + 1
Loop

Fim:
Application.EnableEvents = True
Application.DisplayAlerts = True

End Sub


text:
Q: Node Express sending image files as API response I Googled this but couldn't find an answer but it must be a common problem. This is the same question as Node request (read image stream - pipe back to response), which is unanswered.
How do I send an image file as an Express .send() response? I need to map RESTful urls to images - but how do I send the binary file with the right headers? E.g.,
<img src='/report/378334e22/e33423222' />

Calls...
app.get('/report/:chart_id/:user_id', function (req, res) {
     //authenticate user_id, get chart_id obfuscated url
     //send image binary with correct headers
});

A: a proper solution with streams and error handling is below:
const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400);
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

A: There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile


text:
Q: How to make UIViewRepresentable focusable on tvOS in SwiftUI? The title says it all - I can't get focus on UIViewRepresentable in SwiftUI on tvOS. Any view that conforms to View protocol can be focused without problems but neither UIViewRepresentable nor UIViewControllerRepresentable can.
Any ideas?
This code works:
struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .focusable()
            .onExitCommand {
                print("Menu button pressed")
        }
    }
}

This one does not:
struct ContentView: View {
    var body: some View {
        ViewRepresentable()
            .focusable()
            .onExitCommand {
                print("Menu button pressed")
        }
    }
}

struct ViewRepresentable: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        view.backgroundColor = .red

        return view
    }

    func updateUIView(_ uiView: UIView, context: Context) {

    }
}

Thanks!

A: You need to make a UIView subclass that overrides canBecomeFocused to return true. You probably want to also override didUpdateFocus(in:with:) if you want to respond to focus.
For reference here is a utility class I made to let me have focusable UIViews, and respond to remote swipes and clicks.
import UIKit

@available (iOS, unavailable)
@available (macCatalyst, unavailable)
class UserInputView: UIView {
    weak var pressDelegate: PressableDelegate?
    weak var touchDelegate: TouchableDelegate?
    var touchStarted: CGFloat = 0
    var lastTouch: CGFloat = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        touchStarted = touches.first?.location(in: nil).x ?? 0
        lastTouch = touchStarted
        touchDelegate?.touchDown()
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let thisTouch = touches.first?.location(in: nil).x ?? 0
        touchDelegate?.touchMove(amount: Double((thisTouch - lastTouch)/(touches.first?.window?.frame.width ?? 1920)))
        lastTouch = touches.first?.location(in: nil).x ?? 0
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        touchDelegate?.touchUp()
    }

    override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
        if isClick(presses) {
            pressDelegate?.press(pressed: true)
        } else {
            superview?.pressesBegan(presses, with: event)
        }
    }

    override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
        if isClick(presses) {
            pressDelegate?.press(pressed: false)
            pressDelegate?.clicked()
        } else {
            superview?.pressesEnded(presses, with: event)
        }
    }

    private func isClick(_ presses: Set<UIPress>?) -> Bool {
        return presses?.map({ $0.type }).contains(.select) ?? false
    }

    override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
        pressDelegate?.focus(focused: isFocused)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var canBecomeFocused: Bool {
        return true
    }
}


text:
Q: VueJS: Run function in parent component when event triggered in child component This is my first proper Vue JS project...I've searched Stack O and can't find anything that specifically addresses my issue, but I apologise if this has already been asked.
The Problem
I have two components, the parent is the page layout, while the child is a module of that page. When somebody clicks on a button in the child component, I want to trigger a function in the parent component.
The $emit part of the process is firing correctly according to the VueJS Dev Tools, but the function in the parent doesn't trigger.
Where am I going wrong?
Here is my abberviated code (I've removed anything not related to the issue)...
Parent Component
<template>

            <layout-toolbar></layout-toolbar>

</template>

Child Component
<template>

            <button
                class="button-icon"
                aria-label="Open Navigation"
                @click="$emit('toggle-nav')">

                    Open Navigation
            </button>

</template>

Do I need to be making use of props?
Appreciate any help that can be offered.

A: You have to pass a function as a prop and then emit that function from your child component. So your parent template looks like this .
<template>

            <layout-toolbar @showHideNav="showHideNav"></layout-toolbar>

</template>

And your child template looks like this
<template>

            <button
                class="button-icon"
                aria-label="Open Navigation"
                @click="$emit('showHideNav',<pass-your-event-or-data>)">

                    Open Navigation
            </button>

</template>


text:
Q: How to create valid mail when running "User.create" from Rails 6 console I am following Michael Hartl's tutorial and have an issue when I am trying to create a user in my users table.
When I run User.create from the Rails console I always get:
@messages={:email=>["is invalid"]}"

from user.errors.  Also my test fails:
FAIL["test_email_validation_should_accept_valid_addresses",                                             #<Minitest::Reporters::Suite:0x00007f66146c67f0 @name="UserTest">, 0.05937384600110818]
 test_email_validation_should_accept_valid_addresses#UserTest (0.06s)
        "lala@example.com" should be valid

I guess this is the issue, but I have no idea why.
Also this fails:
test "should be valid" do
  assert @user.valid?
end

If I write it like this the test passes:
test "should be valid" do
  assert_not @user.valid?
end

This fails also:
test "email validation should accept valid addresses" do
  valid_addresses = %w[lala@example.com USER@foo.COM A_US-ER@foo.bar.org first.last@foo.jp alice+bob@baz.cn]
  valid_addresses.each do |valid_address|
    @user.email = valid_address
    assert @user.valid?, "#{valid_address.inspect} should be valid"
  end
end

If I write the test like this it passes:
test "email validation should accept valid addresses" do
  valid_addresses = %w[lala@example.com USER@foo.COM A_US-ER@foo.bar.org
                         first.last@foo.jp alice+bob@baz.cn]
  valid_addresses.each do |valid_address|
    @user.email = valid_address
    assert_not @user.valid?, "#{valid_address.inspect} should be valid"
  end
end

These are the Guard errors:
FAIL["test_email_validation_should_accept_valid_addresses", #<Minitest::Reporters::Suite:0x00007f6614891a58 @name="UserTest">, 0.05828664900036529]
 test_email_validation_should_accept_valid_addresses#UserTest (0.06s)
        "lala@example.com" should be valid
        test/models/user_test.rb:39:in `block (2 levels) in <class:UserTest>'
        test/models/user_test.rb:37:in `each'
        test/models/user_test.rb:37:in `block in <class:UserTest>'

 FAIL["test_should_be_valid", #<Minitest::Reporters::Suite:0x00007f6614859ab8 @name="UserTest">, 0.06591933299932862]
 test_should_be_valid#UserTest (0.07s)
        Expected false to be truthy.
        test/models/user_test.rb:11:in `block in <class:UserTest>'

This is my user_test.rb:
require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @user = User.create(name: "Example User", email: "user@example.com",
                     password: "foobar", password_confirmation: "foobar")
  end

  test "should be valid" do
    assert @user.valid?
  end

  test "name should be present" do
    @user.name = "     "
    assert_not @user.valid?
  end

  test "email should be present" do
    @user.email = "     "
    assert_not @user.valid?
  end

  test "name should not be too long" do
    @user.name = "a" * 51
    assert_not @user.valid?
  end

  test "email should not be too long" do
    @user.email = "a" * 244 + "@example.com"
    assert_not @user.valid?
  end

  test "email validation should accept valid addresses" do
    valid_addresses = %w[lala@example.com USER@foo.COM A_US-ER@foo.bar.org
                         first.last@foo.jp alice+bob@baz.cn]
    valid_addresses.each do |valid_address|
      @user.email = valid_address
      assert @user.valid?, "#{valid_address.inspect} should be valid"
    end
  end

  test "email validation should reject invalid addresses" do
    invalid_addresses = %w[user@example,com user_at_foo.org
                          user.name@example. foo@bar_baz.com
                          foo@bar+baz.com]
    invalid_addresses.each do |invalid_address|
      @user.email = invalid_address
      assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
    end
  end

  test "email address should be unique" do
    duplicate_user = @user.dup
    @user.save
    assert_not duplicate_user.valid?
  end

  test "password should present (nonblank)" do
    @user.password = @user.password_confirmation = " " * 5
    assert_not @user.valid?
  end

  test "password should have a minimum length" do
    @user.password = @user.password_confirmation = "a" * 5
    assert_not @user.valid?
  end

end

This is my user.rb:
class User < ApplicationRecord
  before_save { self.email = email.downcase}
  validates :name, presence: true, length: {maximum: 50}
  VALID_EMAIL_REGEX = /[\w+\-.]+@[a-z\-.]+\.[a-z]+/i
  validates :email, presence: true, length: { maximum: 255},
            format: { with: /VALID_EMAIL_REGEX/},
            uniqueness: false
  has_secure_password
  validates :password, presence:true, length: { minimum: 6}
end

A: :format validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option.
A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../
Your regexp is /VALID_EMAIL_REGEX/. It means valid email must contain these symbols.
So your code means that "VALID_EMAIL_REGEX@gmail.com" is valid, but "example@gmail.com" is invalid.
In fact you have constant with regexp VALID_EMAIL_REGEX.
So you need to change your code to:
format: { with: VALID_EMAIL_REGEX }

(constant with regexp, not regexp)
By the way you don't need to write difficult regex for email. You can use regex from standard library:
format: { with: URI::MailTo::EMAIL_REGEXP }


text:
Q: Flutter change Localization programatically I followed  the new Flutter Tutorial (https://flutter.dev/docs/development/accessibility-and-localization/internationalization) for Localizations and it works like a charm.
But I have a question:
Is it possible to change the Locale when the user taps a button?
MaterialApp(
        debugShowCheckedModeBanner: false,
        localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
        title: "MyApp",
        theme: ct.theme,
        home: MyHomePage(),
      );

A: You can pass your wished locale to the MaterialApp. If it is null, the app will take the system language. In that way you can wrap your MaterialApp in an InheritedWidget for changing the locale from anywhere in the widget tree. It's not an elegant but a simple solution. My InheritedWidget looks like this:
class MyI18n extends InheritedWidget {
  final Function(Locale) _localeChangeCallback;

  const MyI18n(
      this._localeChangeCallback,{
    Key key,
    @required Widget child,
  })  : assert(child != null),
        super(key: key, child: child);

  static MyI18n of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyI18n>();
  }

  void changeLocale(Locale locale) {
    _localeChangeCallback?.call(locale);
  }

  @override
  bool updateShouldNotify(MyI18n old) {
    return true;
  }
}

You can also save the locale in the InheritedWidget for using it in updateShouldNotify :)
Your MaterialApp will look like this:
MyI18n(
  (locale) => setState(() => this._locale = locale),
  child: MaterialApp(locale: _locale, ...),
),

For using it: MyI18n.of(context).changeLocale(locale)
There are other ways for changing the locale but in my opinion this one is really simple. (You can do it the same way but with less code by using a Provider and/or a Bloc.)


text:
Q: Firebase REST API GET request with params I've uploaded a geojson file to my firebase realtime database and setup an http get request in my angular app to retrieve the data.  Here's a small sample of my data.  All it is is an array of objects.  Each object is a zip code.  Below are two zip code objects.
[
   {
      "type":"Feature",
      "properties":{
         "STATEFP10":"44",
         "ZCTA5CE10":"02818",
         "GEOID10":"4402818",
         "CLASSFP10":"B5",
         "MTFCC10":"G6350",
         "FUNCSTAT10":"S",
         "ALAND10":56516634,
         "AWATER10":8882294,
         "INTPTLAT10":"+41.6429192",
         "INTPTLON10":"-071.4857186",
         "PARTFLG10":"N"
      },
      "geometry":{
         "type":"Polygon",
         "coordinates":[
            [
               [
                  -71.457848,
                  41.672076
               ],
               [
                  -71.457848,
                  41.672414
               ],
               [
                  -71.457848,
                  41.672932
               ],
               [
                  -71.457916,
                  41.67407
               ]
            ]
         ]
      }
   },
   {
      "type":"Feature",
      "properties":{
         "STATEFP10":"44",
         "ZCTA5CE10":"02878",
         "GEOID10":"4402878",
         "CLASSFP10":"B5",
         "MTFCC10":"G6350",
         "FUNCSTAT10":"S",
         "ALAND10":75250623,
         "AWATER10":8363563,
         "INTPTLAT10":"+41.6101375",
         "INTPTLON10":"-071.1804709",
         "PARTFLG10":"N"
      },
      "geometry":{
         "type":"Polygon",
         "coordinates":[
            [
               [
                  -71.210351,
                  41.656166
               ],
               [
                  -71.209897,
                  41.657718
               ],
               [
                  -71.208399,
                  41.660013
               ],
               [
                  -71.20787,
                  41.661323
               ]
            ]
         ]
      }
   }
]

I can retrieve all of my data no problem but I can't seem to filter specific zip codes.  I have read over the guides on firebase (https://firebase.google.com/docs/database/rest/retrieve-data) and can not get this to work with params.  What I'm trying to do is filter an object based on the "ZCTA5CE10" value in "properties".  I have tried many different combinations.  Below is one of them:
getZipData() {
  return this.http.get(this.url + '?orderBy="properties/ZCTA5CE10"&equalTo="02818"');
}

I get a 400 error when attempting to use params.  What am I doing wrong?
Also, Is it possible to filter multiple zip codes E.g. &equalTo="02818"&equalTo="02878"


text:
Q: Adding rows depending on condition I need a little help with a very simple question:
Let's say I have this data frame:
data_new <- data.frame(section = c("1", "4", "5","6"),
                       density = c("0.2", "0.7", "0.8", "0.2"))
> data_new
  section density
1       1     0.2
2       4     0.7
3       5     0.8
4       6     0.2

I need to add rows because the full table is based on 6 sections, but only have data on 4. This means that in this case I have to add 2 rows (sections 2 and 3) with density 0 so I have:
> data_desired
  section density
1       1     0.2
2       4     0.7
3       5     0.8
4       6     0.2
5       2       0
6       3       0

The point is that the combination of 0 density rows may vary. In this case sections 3 and 4 were empty, but next time it may be that no section has density 0 or that I have to add 5 sections, etc. It can vary a lot, from 1 section with data to all sections with data.
I'm sure there is an elegant way to add to my pipe to ad the rows I need and that is case specific. Thanks a lot for your help!!

A: Another option using rows_update:
library(dplyr)
#create zero density dataframe

n<-6
data_zero <- data.frame(section = as.character(c(1:n)),
                       density = as.character(rep(0,n)))

data_new <- data.frame(section = c("1", "4", "5","6"),
                       density = c("0.2", "0.7", "0.8", "0.2"))

rows_update(data_zero ,data_new)
  section density
1       1     0.2
2       2       0
3       3       0
4       4     0.7
5       5     0.8
6       6     0.2

For multiple columns:
library(dplyr)
n<-6
data_zero <- data.frame(section = as.character(c(1:n)),
                       density = as.character(rep(0,n)))

data_new <- data.frame(section = c("1", "4", "5","6"), density = c("0.2", "0.7", "0.8", "0.2"), potatoes = c("a","n","ed","3"))

rows_update(data_zero ,data_new[,c('section','density')]) %>%
  merge(data_new,all.x=T)

  section density potatoes
1       1     0.2        a
2       2       0     <NA>
3       3       0     <NA>
4       4     0.7        n
5       5     0.8       ed
6       6     0.2        3


text:
Q: CoreData N:M relationships I have many questions about how to make relationships N:M in CoreData.
If I have two entities A and B and have a relationship N:M in the entity relationship model has to generate a new table C that will contain the unique id of tables A and B.
Example for the entity relationship:

Now in the database model:

Considering the previous example as would be done by core data?

Or:

The truth is I'm really lost with that of relations in Core Data, any help will be welcome.
Sorry for my English but not very good.

A: The answer to this is that you have to use "join tables" even in Core Data if you are storing additional information. You do not have to keep track of foreign keys, as this is covered by the relationship.
Typically, standard DB "join tables" have ugly names such as "tableA_tableB". You should strive to find a suitable name to make the concept clear. For example:
Car <<--->> Person
becomes
Car <--->> Rental <<---> Person
Now in entity Rental you can add more information, such as the time. So, for example, if you want to find all persons that rented a car before a certain date (stored as NSDate in the Rental entity), your predicate would be something like this:
 [NSPredicate predicateWithFormat:@"ANY rentals.time < %@", cutoffTime]


text:
Q: JSON deserialize insight into failure I am working on a system using a Spring Web MVC server. The browser client uploads a JSON data transfer object to the server to save.
The JSON is auto-deserialized using Jackson before the controller is called. The controller method has the deserialized object in its parameter list:
@RequestBody MyDto myDto,

It was working, but has now stopped. The problem is that the error messages don't give me any insight into what is failing.
I get this exception in my server output:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

I also tried changing the parameter to be a String instead of an object (@RequestBody String myDto). Then I used Gson instead of Jackson to see if it would either work or give any insight:
        try {
            MyDto dto = (new Gson().fromJson(MyDto, MyDto.class));
            log.debug(dto.toString());
        } catch ( Exception e) {
            e.printStackTrace();
        }

This doesn't throw any exception. It just creates a new MyDto object with all fields null.
I guess I changed something in the object and it can't be deserialized from the JSON string until I make the change there. I have seen this scenario a few times before with trivial objects. When I had a closer look there was always a field mismatch. In this case, MyDto is a bigger object, and a subclass of other objects.
Is there any way to get Jackson or Gson to tell me what fields are causing the failure?


text:
Q: Custom validator with master page button click i have a custom validator in a content page
<asp:CustomValidator id="CustomValidator1" runat="server"
   OnServerValidate="RevisionValidate"
   ControlToValidate="TextBoxRevisionOrder"
   ErrorMessage="Invalid RevOrder Format">
</asp:CustomValidator>

where RevisionValidate is a serverside method
protected void RevisionValidate(object source, ServerValidateEventArgs args)
    {
               //Code goes here
             if (CurrentRevisionOrder != "-1" && ChangedRevisionOrder == "-1")
                            {
                                val = "Not Valid";

                            }
                            else
                            {
                                val = "Valid";

                            }
                            args.IsValid = (val == "Valid");
                        }

Custom validator fires perfectly on content page button click but the issue is i also have a button in the master page which the custom validator need to fire.with my current code it's not firing on master page button click.any help?

A: Try using ValidationGroup property on button in master page.
Content Page:
<asp:TextBox Id="TextBoxRevisionOrder" runat="server"/>
<asp:CustomValidator id="CustomValidator1" runat="server"
   OnServerValidate="RevisionValidate"
        ControlToValidate="TextBoxRevisionOrder"
          ErrorMessage="Invalid RevOrder Format" ValidationGroup="Revision">
</asp:CustomValidator>

Master Page:
<asp:Button Id="MasterButton" runat="server" ValidationGroup="Revision"> Click
</asp:Button>

A: Found the solution. I had to check
if(Page.IsValid)
{

}


text:
Q: Файл разметки для ListActivity и метод setContentView При использовании setContentView программа вылетает с ошибкой.
Я так понимаю, что ListActivity использует свой системный файл разметки.
Подскажите, как использовать другой файл разметки при работе с ListActivity?
Код:
  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myListView);

}

Мой xml файл:
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:android1="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/main_bg" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="65dp"
    android:alpha="0.7"

     >
</ListView>

<ImageView
    android1:id="@+id/imageViewCreate"
    android1:layout_width="match_parent"
    android1:layout_height="wrap_content"
    android1:layout_alignParentLeft="true"
    android1:layout_alignParentTop="true"
    android1:src="@drawable/create" />

 </RelativeLayout>

A:
To do this, your own view MUST contain a ListView object with the id "@android:id/list" (or list if it's in code).

Документация, тут вроде и особых знаний английского не надо, чтобы понять.
A: Привет. Чтобы работать с ListView, ListActivity не обязателен. Покажу пример, как я работаю с ListView, надеюсь поможет:
package ru.mysamples.listview;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListViewActivity extends Activity {

    public static String[] TITLES = {
            "Title 1",
            "Title 2",
            "Title 3",
            "Title 4",
            "Title 5",
            "Title 6",
            "Title 7"
    };

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView myListView = (ListView) findViewById(R.id.listView1);

        myListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, TITLES));
    }
}

Как видишь, я не использую ListActivity, а просто нахожу свой ListView в разметке и задаю ему адаптер. :)


text:
Q: Not able to install Impala in Ambari Server I have installed Ambari server on my CentOS server. I want to read real-time data from Hive so I am trying to install Impala but I am not able install it.
I have take reference from following link.
https://github.com/cas-bigdatalab/ambari-impala-service
I am not able to identify that where & which file need to put Impala Repo code.
The Repo code is as follows
[cloudera-cdh5]
# Packages for Cloudera's Distribution for Hadoop, Version 5, on RedHat or CentOS 6 x86_64
name=Cloudera's Distribution for Hadoop, Version 5
baseurl=https://archive.cloudera.com/cdh5/redhat/6/x86_64/cdh/5/
gpgkey =https://archive.cloudera.com/cdh5/redhat/6/x86_64/cdh/RPM-GPG-KEY-cloudera
gpgcheck = 1

I am a bit stuck to go ahead.

A: For CentOS, repos always go under /etc/yum.repos.d/.  Put the file there and you should be able to run:
# yum install impala


text:
Q: Looking for solution for an automatically scrolling information board Right now, my company has about 40 information boards scattered throughout the buildings with information relevant to each area.  Each unit is a small linux based device that is programmed to launch an RDP session, log in with a user name and password, and pull up the appropriate powerpoint and start playing.  The boards would go down every 4 hours for about 5 minutes, copy over a new version of a presentation (if applicable) and restart.
We now have "demands" for live data.  Unfortunately I believe powerpoint will no longer be an option as we used the Powerpoint viewer, which does not support plugins.  I wanted to use Google Slides, but also have the restriction that we cannot have a public facing service like Google Drive, so there goes that idea.
I was thinking of some kind of way to launch a web browser and have it rotate through a list of specified webpages (perhaps stored in a txt or csv file).  I found a way to launch Firefox and have it autologin to OBIEE via python:
#source: http://obitool.blogspot.com/2012/12/automatic-login-script-for-obiee-11g_12.html

import unittest
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

# Hardcoding this information is usually not a good Idea!
user       = ''   # Put your user name here
password   = ''   # Put your password here
serverName = ''   # Put Host name here

class OBIEE11G(unittest.TestCase):

    def setUp(self):

        # Create a new profile
        self.fp = webdriver.FirefoxProfile()
        self.fp.set_preference("browser.download.folderList",2)
        self.fp.set_preference("browser.download.manager.showWhenStarting",False)

        # Associate the profile with the Firefox selenium session
        self.driver   = webdriver.Firefox(firefox_profile=self.fp)
        self.driver.implicitly_wait(2)

        # Build the Analytics url and save it for the future
        self.base_url = "http://" + serverName + ":9704/analytics"

def login(self):

        # Retreive the driver variables created in setup
        driver = self.driver

        # Goto the loging page
        driver.get(self.base_url + "/")

        # The 11G login Page has following elements on it
        driver.find_element_by_id("sawlogonuser").clear()
        driver.find_element_by_id("sawlogonuser").send_keys(user)
        driver.find_element_by_id("sawlogonpwd").clear()
        driver.find_element_by_id("sawlogonpwd").send_keys(password)
        driver.find_element_by_id("idlogon").click()

    def test_OBIEE11G(self):
        self.login()

#
if __name__ == "__main__":
    unittest.main()

If I can use this, I would just need a way to rotate to a new webpage every 30 seconds.  Any ideas / recommendations?

A: You could put a simple javascript snippet on each page that waits a specified time then redirects to the new page. This has the advantage of simple implementation, however it may be annoying to maintain this over many html files.
The other option is to write your copy in a markdown file, then have a single html page that rotates through a list of files and renders and displays the markdown. You would then update the data by rewriting the markdown files. It wouldn't be exactly live, but if 30 second resolution is ok you can get away with it. Something like this for the client code:
HTML
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Message Board</title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">

And the javascript
// main.js
// the markdown files
var sites = ["http://mysites.com/site1.md", "http://mysites.com/site2.md", "http://mysites.com/site3.md", "http://mysites.com/site4.md"]

function render(sites) {
    window.scrollTo(0,0);

    //get first element and rotate list of sites
    var file = sites.shift();
    sites.push(file);

    $.ajax({
        url:file,
        success: function(data) { $("#content").html(marked(data)); },
        cache: false
    });

    setTimeout(render(sites), 30000);
}

// start the loop
render(sites);

You can then use any method you would like to write out the markdown files.


text:
Q: Flutter font awesome text below icons I am using the font awesome icons in my flutter app and I am trying to place descriptive text below the icons. I was hoping there was a property in the IconButton class for this but dont see one. Here is my code:
Container(
                margin: EdgeInsets.all(25.0),
                  child: IconButton(
                     icon: new Icon(FontAwesomeIcons.checkSquare,),
                     iconSize: 60.0,
                     color: const Color(0xFF0099a9),
                      onPressed: () { print("Pressed"); }
                  )

              ),

A: I encountered this problem few days ago and here is how I solved it:
Container(
  margin: EdgeInsets.all(25.0),
  child: Column(
    children: <Widget>[
      GestureDetector(
          child: Icon(
            FontAwesomeIcons.checkSquare,
            size: 60.0,
            color: const Color(0xFF0099a9),
          ),
          onTap: () {
            print("Pressed");
          }),
      Text("Some Text")
    ],
  ),
),

With this solution you have access to many more features.
There may be a cleaner solution but this one is perfectly suitable to make a clickable icon with a text below ;)
Have a nice day !


text:
Q: Lucene spellchecker with sitecore exception I am trying to implement Lucene search functionality in our solution. The way we opted to go about this is by overriding the database crawler functionality instead of the more orthodox indexwriter/reader approach.
It's working fine but trying to implement the spellchecker module generates the following exception.
 System.InvalidOperationException: Lock@C:\Windows\TEMP\lucene-df395a60eeb827dc92350de6e4528673-write.lock# is not locked
 Sitecore.Data.Indexing.FSLock.Release() +198
 Lucene.Net.Index.IndexReader.Unlock(Directory directory) +26
 SpellChecker.Net.Search.Spell.SpellChecker.ClearIndex() +15

I have tried running the spellchecker on a separate none-sitecore project and it works fine.
I'm referring to this article for guidance


text:
Q: Differing from lists/tuples from strings during iteration Is a common pattern to write functions that accept an argument, and if the argument is a scalar like a number or a string, you apply some operation on it, and if the argument is a iterable, you apply the same operation on each element of this iterable
The problem is that string is iterable, so I can't rely on Ask for forgiveness not for permission for achieving this, because iter('hello world') will not raise TypeError.
For example
def apply_(func, val):
    try:
        for v in iter(val):
            print(func(v), end=' ')
        print()
    except TypeError:
        print(func(val))

apply_(lambda x: x+1, 1) # 2 ...  Ok
apply_(lambda x: x*2, range(3)) # 0 2 4 ... Ok
apply_(str.upper, ['hello', 'world']) # HELLO WORLD ... Okay
apply_(str.upper, 'hello world') # H E L L O   W O R L D, ... oops

I can ask for persmission. But this will work only for subtypes of string.
def apply_safe(func, val):
    if issubclass(type(val), str):
        print(func(val))
        return

    try:
        for v in iter(val):
            print(func(v), end=' ')
        print()
    except TypeError:
        print(func(val))

Another option is to add this logic to the type, which seems to be the right way of doing this since being iterable is undesired (for this case) behavior of string. But this is error prone for the caller, soon or later it will forget to call it with NonIterableString or any other class.
class NonIterableString(str):
    def __iter__(self):
        raise TypeError()

apply(str.upper, NonIterableString('hello world')) # HELLO WORLD

The last solution I found is this which fix my problem but may not work for existing code is this
def apply_multi(func, *vals):
    for v in vals:
        print(func(v), end=' ')
    print()

This seems to be the more idiomatic one. It always works, is small and elegant, but because it doesn't face the problem, it smartly circumvent it. Here the problem is that I need to write a function like this for each case of this, which it doesn't seems to be a bad idea, but is still verbose...
Finally here is the complete example
def apply_(func, val):
    try:
        for v in iter(val):
            print(func(v), end=' ')
        print()
    except TypeError:
        print(func(val))

def apply_safe(func, val):
    if (issubclass(type(val), str)):
        print(func(val))
        return

    try:
        for v in iter(val):
            print(func(v), end=' ')
        print()
    except TypeError:
        print(func(val))

def apply_multi(func, *vals):
    for v in vals:
        print(func(v), end=' ')
    print()

class NonIterableString(str):
    def __iter__(self):
        raise TypeError()

apply_(lambda x: x+1, 1) # 2 => ok
apply_(lambda x: x*2, range(3)) # 0 2 4 => ok
apply_(str.upper, ['hello', 'world']) # HELLO WORLD => ok
apply_(str.upper, 'hello world') # H E L L O   W O R L D => oops
apply_(str.upper, NonIterableString('hello world')) # HELLO WORLD => ok
apply_safe(str.upper, 'Hello world') # HELLO WORLD =>j
apply_multi(str.upper, 'hello world') # HELLO WORLD => ok

Finally my question is, is there any AFFNFP way of dealing strings in python like a scalar type instead of an iterable one?

A: I think a good solution is would be something like this:
defaults = {
    str : False
}

def apply_(func, val, isiter: bool=None):
    if isiter is None:
        isiter = defaults[type(val)] if type(val) in defaults else True

    if isiter:
        try:
            for i in iter(val):
                print(func(i), end=' ')
            print()
        except TypeError:
            print(func(val))
    else:
        print(func(val))

This approach lets you decide (only when the value is an iterable) if you want to treat the value as iterable or not. Potentially if you want this behavior with string type maybe some day you would apply a function to a list, but only to the list it self and not apply the function to each value.
Here defaults represents if an iterable type should be treated as iterable by default, in this case str should't be treated as iterable by default.
You has also a param to override this "default" behavior if you want (But only if it makes sense). For example:
apply_(lambda x: x+1, 1) # 2 ...  Ok
apply_(lambda x: x*2, range(3)) # 0 2 4 ... Ok
apply_(str.upper, ['hello', 'world']) # HELLO WORLD ... Okay

Til here all is the same, all running as expected. Then lets see:
apply_(str.upper, 'hello world') # HELLO WORLD ... Okay
apply_(str.upper, 'hello world', isiter=True) # H E L L O   W O R L D ... okay

As you can see hello world at first is treated as a value, just as we define in defaults and if we set isiter=True then is treated as you setted.
Lets see another example:
apply_(lambda x: 2*x, ['hello', 'world']) # hellohello worldworld ... Okay
apply_(lambda x: 2*x, ['hello', 'world'],  isiter=False) # ['hello', 'world', 'hello', 'world'] ... Okay

As you can see in the first case the list is treated as an iterable and if we set isiter=False the function its applied to the list itself.
Finally lets see if we try to treat a non iterable type as iterable:
apply_(lambda x: x+1, 1, isiter=True) # 2 ...  Ok

In this case the try: except: handles the error.
The dictionary is very handy because setting defaults behaviors will safe you to have to use isiter most of the times.


text:
Q: Transpose in Pandas I imported the data from csv file with pandas. I want to split the column which includes 50 (0 to 49) values into 5 rows each having ten values. Can anyone tell me how i can do this transpose in form of pandas frame?
Let me rephrase what i said:
I attached the data that i have. I wanted to select the second column, and split it into two rows each having 10 values.
That is the code i have done so far:(I couldn't get the picture of 50 rows so i have only put 20 rowsenter image description here)
import numpy as np
import pandas as pd
df = pd.read_csv('...csv')
df.iloc[:50,:2]

A: Consider the dataframe df
np.random.seed([3,1415])
df = pd.DataFrame(dict(mycolumn=np.random.randint(10, size=50)))

using numpy and reshape'ing, ignoring indices
pd.DataFrame(df.mycolumn.values.reshape(5, -1))

   0  1  2  3  4  5  6  7  8  9
0  0  2  7  3  8  7  0  6  8  6
1  0  2  0  4  9  7  3  2  4  3
2  3  6  7  7  4  5  3  7  5  9
3  8  7  6  4  7  6  2  6  6  5
4  2  8  7  5  8  4  7  6  1  5