text:
Q: How to make prop mandatory based on another prop being passed I have some code for a form:
interface FormProps {
  regexPreset?: RegexPresets;
  customRegex?: RegExp;
  description?: string;
  inputTitle: string;
  errorMessage?: string;
}

const Form: React.FC<FormProps> = props => {
  return <div> somestuff </div>
}

If I pass in a customRegex, I want the compiler to throw an error if errorMessage is not passed (make errorMessage a mandatory property).
The closest thing that I've come to is this StackOverflow post, but I'm unsure whether I can apply this to my use case.
Any pointers would be gladly received.

A: I think it's feasible to utilize what's mentioned in that post you mentioned in your post, but before going into advanced typings I'd like to evaluate if the simplest solution possible is sufficient. So–if you were to include a customRegex, you would be forced to also include a errorMessage–then this type should cover your use-case:
interface FormProps {
  regexPreset?: RegexPresets;
  description?: string;
  inputTitle: string;
  customRegexProps?: {
    customRegex: RegExp;
    errorMessage: string;
  }
}

A: To simplify lets say we have following props
interface FormProps {
  inputTitle: string;
  description?: string;

  customRegex?: string;
  errorMessage: string;
}

Here 'inputTitle' prop is mandatory, description is optional but errorMessage prop has to be there (mandatory) only when customRegex (optional) prop is present.
Create a type for non-conditional props
interface FormMainProps {
  description?: string;
  inputTitle: string;
}

Now create a type for conditional props only when conditional prop 'customRegex' is present
interface FormErrorProps {
  customRegex: string;
  errorMessage: string;
}

Now create an additional type when conditional prop is not present  (to give idea for possible values present in object)
interface FormErrorRefProps {
  customRegex?: undefined;
  errorMessage?: never;
  // important step; so if customRegex prop is not present errorMessage should not be there and vice-versa
}

Now your FormProps will be
type FormProps =  FormMainProps & (FormErrorProps | FormNotErrorProps);

Following scenarios will give error as needed:
let a: FormProps;

a = {
  inputTitle: "Title",
  customRegex: "asdasd"
};

/*
Type '{ inputTitle: string; customRegex: string; }' is not assignable to type 'FormProps'.
Type '{ inputTitle: string; customRegex: string; }' is not assignable to type 'FormMainProps & FormErrorProps'.
    Property 'errorMessage' is missing in type '{ inputTitle: string; customRegex: string; }' but required in type 'FormErrorProps'.ts(2322)
*/

a = {
  inputTitle: "Title",
  errorMessage: "asdasd"
};

/*
Type '{ inputTitle: string; errorMessage: string; }' is not assignable to type 'FormProps'.
Type '{ inputTitle: string; errorMessage: string; }' is not assignable to type 'FormMainProps & FormNotErrorProps'.
    Property 'customRegex' is missing in type '{ inputTitle: string; errorMessage: string; }' but required in type 'FormNotErrorProps'.
*/

while below ones are fine:
a = {
  inputTitle: "Title",
  errorMessage: "asdasd",
  customRegex: "Title",
};

a = {
  inputTitle: "Title"
};


text:
Q: Android loading icon in title bar across multiple activities I am using the code from this post to put a loading icon in the title bar of my Android App:
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.your_layout);
    }

The code:
  activity.setProgressBarIndeterminateVisibility(true);

is called in an AsyncTask.  If the user navigates to a new activity, the icon is not longer present in the title bar since the icon was set for the first activity only.
Is there a way to have the icon show on all activities?  Thanks in advance.

A: You can create super activity (i.e. Base Activity), include the below line in this super activity:
 activity.setProgressBarIndeterminateVisibility(true);

And extends this activity to all the child activities.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Server data migration fail So we moved our SQL server to a new platform.  During this move the primary and foreign keys were not transferred.
Is there a way I can script the keys from the old tables and add them to the new tables?
It doesn't look like they are going to redo it and just have us all the keys manually.  Any speedy/safe way to do this is appreciated.
SQL Server 2008

A: Yup, you're going to love this.  I have to drop and re-add FK's once in a while (like when I want to change an index that SQL hijacked for FK enforcement), so I wrote a view that will give me the drop and add statements:
select *, addqry = 'ALTER TABLE '+FKtable+' WITH ' + case when is_not_trusted = 1 then 'NO' else '' end + 'CHECK'
                    + ' ADD  CONSTRAINT ['+FK+'] FOREIGN KEY ('+FKcol+') '
                    + ' REFERENCES '+PKtable+' ('+PKcol+')'+' ON UPDATE '+onUpdate+' ON DELETE '+onDelete
                    + case when is_not_for_replication = 1 then ' NOT FOR REPLICATION' else '' end + ';'
                    + case when is_disabled = 1 then '  ALTER TABLE '+FKtable+' NOCHECK CONSTRAINT ['+FK+'];' else '' end
    ,dropqry = 'ALTER TABLE '+FKtable+' DROP ['+FK+'];'
from (
    select   PKtable        = object_schema_name(f.referenced_object_id)+'.'+object_name(f.referenced_object_id)
        ,PKtbl      = object_name(f.referenced_object_id)
        ,PKcol      = pc.name
        ,FKtable        = object_schema_name(f.parent_object_id)+'.'+object_name(f.parent_object_id)
        ,FKtbl      = object_name(f.parent_object_id)
        ,colseq     = fk.constraint_column_id
        ,FKcol      = fc.name
        ,FK     = object_name(f.object_id)
        ,onUpdate   = replace(f.update_referential_action_desc collate SQL_Latin1_General_CP1_CI_AS, '_', ' ')
        ,onDelete   = replace(f.delete_referential_action_desc collate SQL_Latin1_General_CP1_CI_AS, '_', ' ')
        ,f.is_disabled
        ,f.is_not_trusted
        ,f.is_not_for_replication
    from sys.foreign_key_columns as fk
        join sys.foreign_keys f on fk.constraint_object_id = f.object_id
        join sys.columns as fc on f.parent_object_id = fc.object_id and fk.parent_column_id = fc.column_id
        join sys.columns as pc on f.referenced_object_id = pc.object_id and fk.referenced_column_id = pc.column_id
) t

A: Since you're dealing with primary key and foreign keys, I would use a (free) tool like SQL Server Database Tools (SSDT). This is a Microsoft tool that integrates with Visual Studio (if you have it - you don't need it). It will synch a target schema with a source schema. It does essentially what a tool like Red Gat Schema Compare does, except it's free. And it works very well. Using a tool like this will ensure your entire schema got moved over, not just PKs and FKs.


text:
Q: Can I give CRUD permissions to custom object in Customer community I have salesforce Org which is using an app from the app-exchange, the objects in the app cant be given acces trough a Customer community. Is it possible to create a custom object i.e. PersonAccountComm__c and give this object the Create (CRUD) rights in the customer community and use a trigger to create standard Person-accounts. I know this isn't "best practises Salesforce" but from a financial standpoint this could be a solution. Hope someone has experience with this.

A: Yes, you can give Community users create access to a custom object you create. Keep in mind there are limitations to how many objects you may expose to these users.


text:
Q: Смена фона DIV при нажатии на ссылку Есть ссылка:
ссылка

Есть DIV:

Есть код javascript:

Нужно, чтобы при нажатии на ссылку, фон дива менялся на нужный мне.

A: Вот, такой вариант должен сработать.
CSS:
#div{
      width: 300px;
      height: 300px;
      background-image: url("ford.jpg");
      background-repeat: no-repeat;
   }

HTML:

JS:
function change(arg){
    arg.style.backgroundImage = "url('img.jpg')";
}

A: Если в css прописать правило backgroundImage:img/666.png;, оно не сработает. Аналогично не работает и в js: надо писать document.getElementById("MyElement").style.backgroundImage = "url(img/666.png)";
A:

Link

Соответственно, backgroundColor можно заменить на backgroundImage и вставить нужный вам фон.


text:
Q: Why does the order in which Netbeans loads Java Libraries cause errors sometimes? and how do I avoid it? Basic background data:  Windows 7, Netbeans 8.0.2, LWJGL 2.9.3, Slick Util.
The rest of the code is my own.
So, periodically, I was having what I thought was a bug, that caused my program to run within the IDE, but would fail when I used "Clean and Build" on the project.
Today, when it happened again, I decided to get to the bottom of it.  So, taking a copy of the whole project folder, that was working and otherwise identical, and replacing 1 file at a time, and testing it, I was able to narrow it down to the /nbproject/project.properties file.
Every other file could be replaced and the problem persisted.  Replace ONLY this file, and the problem went away.  So then I loaded up both files and compared them side by side (using the Netbeans "Diff to..." feature) and narrowed it down to the following lines:
javac.classpath=\
${libs.LWJGL-2.9.3.classpath}:\
${libs.0-Slick_Util.classpath}:\
${libs.0-Loaders_v03.classpath}:\
${libs.0-Text2D_v03.classpath}:\
${libs.0-Foundation_v04.classpath}:\
${libs.0-Abstracts_v04.classpath}

Now this code, looks like it is telling the compiler the ORDER in which the libraries should be loaded (I may be wrong).
With that in mind, I decided to test it.  I copied this block from the working file, to the non-working file, and it worked just fine.  The working code btw is this:
javac.classpath=\
${libs.LWJGL-2.9.3.classpath}:\
${libs.0-Slick_Util.classpath}:\
${libs.0-Foundation_v04.classpath}:\
${libs.0-Abstracts_v04.classpath}:\
${libs.0-Loaders_v03.classpath}:\
${libs.0-Text2D_v03.classpath}

The only differences, you may notice, is the ORDER.  Continuing my test, I went into the non-working project's Library properties page, and simply re-ordered the libraries to match the working list.  PROBLEM WENT AWAY!  If I simply moved the Foundation and Abstracts libraries down in the list, the PROBLEM CAME BACK!
I must have tried a dozen different order combinations, and got about 2/3 that failed, and 1/3 that worked.  The ones that worked all involved Foundation and/or Abstracts to be near the top.
Why is this happening? How can I know what order my libraries need to be loaded to avoid the error?
The error btw is this:
F:\Dropbox\2-Documents\4-Java Programming\Library\0-LoadingScreen_v04-Copy\src\A_Library\Test_LoadingScreen.java:94: error: cannot find symbol
    Lib_Foundation                  .setConfigLocation(configLocation);
  symbol:   method setConfigLocation(String)
  location: class Lib_Foundation

Any information that can help me avoid this problem in the future will be appreciated.

A: It would appear that either "Loaders_v03" or "Text2D_v03" contains its own version of Foundation, including an incompatible Lib_Foundation class.  A classpath is searched in order, so your current solution—reordering javac.classpath—will always work, assuming NetBeans doesn't mess with it the next time you make any change to your project.
Whether that will break Loaders and Text2D depends upon how well Foundation adheres to object-oriented design: public classes and their public members are never supposed to be changed or removed in successive versions. (That is why 20-year-old code written for Java 1.1 will still compile in Java 8.)


text:
Q: Optimal strategies in a simple game when facing gambler's ruin Suppose we have the following game that's free to play. The game consists of an infinite number of stages, where in each stage you must bet your entire bankroll to quadruple it with probability $3/4$ and lose it with probability $1/4$. You may stop playing the game anytime you wish and collect your winnings, and you are given 1 unit for free to play with in the first stage.
My question is: what's the best strategy for when to stop? Each stage of the game has positive expected value when considered alone, as we win $4b$ with probability $3/4$ and lose $b$ with probability $1/4$, so that the EV is $(11/4)b$, where $b$ is our bankroll. However, in the long run we will lose almost surely, and so the "correct" strategy can't be to just play whenever playing is positive expected value.
I've considered "double or nothing" strategies, where we fix a value $n$ and stop playing only when we have earned at least $n$. This gives us a new random variable $X_n$, whose expected value will be
$$n\left(\frac{3}{4}\right)^{\log_4(n)}$$
as we reach our desired level after $\log_4(n)$ rounds of quadrupling and earn $n$. However, this goes to infinity, and so again it seems that the "optimal" strategy in terms of expected value is to keep going for double or nothing until we bust.
I'm sure this has a simple resolution (or maybe it's a special case, since this theoretical game is far from fair). Given this game, when should we stop playing? Thanks in advance!


text:
Q: Error in my HTML code The following HTML code has an error as the tabs are not changing when I click on Students' statistics for example.
I think the problem is not in the inside nav-tabs but in the head, but I do not know where...
Could you suggest of a website to check the errors as well? I have tried several ones but they give me strange errors like: that the coding is not defined...

function show(id) {
  if (document.getElementById(id).style.display == 'none') {
    document.getElementById(id).style.display = 'block';
  }
  return false;
}

function hide(id) {
  if (document.getElementById(id).style.display == 'block') {
    document.getElementById(id).style.display = 'none';
  }
  return false;
}
.borderradius {
  border-radius: 11px;
}

.content {
  width: 800px;
  margin: 0 auto;
}

.my_text {
  font-family: "Raleway";
  font-size: 30px;
  font-weight: italic;
  font-color: #303030
}

.left {
  text-align: center;
}

.bottom {
  bottom: 0;
  background-color: #07B;
}

.body {
  margin-top: 10px;
  margin-left: 20px;
  margin-right: 20px;
}

.nav-tabs.centered>li,
.nav-pills.centered>li {
  float: none;
  display: inline-block;
  *display: inline;
  /* ie7 fix */
  zoom: 1;
  /* hasLayout ie7 trigger */
}

.nav-tabs.centered,
.nav-pills.centered {
  text-align: center;
}

.c3-chart-arcs-title {
  fill: black;
  font-size: 13px;
}

.button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 6px 5px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin: 6px 1px;
  transition-duration: 0.4s;
  transition-duration: 0.4s;
  cursor: pointer;
}

/* Full height image header */

.bgimg-1 {
  background-position: center;
  background-size: cover;
  background-image: url("Images/views.jpg");
  min-height: 120%;
}

.button4 {
  background-color: white;
  color: black;
  border: 3px solid #e7e7e7;
}

.button4:hover {
  background-color: #e7e7e7;
}

.button4 {
  border-radius: 17px;
}

.button4:focus {
  background-color: #e7e7e7;
  outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

ANALYSIS OF HIGH SCHOOLS' PERFORMANCE IN THE INITIAL PHASE OF THE GETI

 About the project

 Students' statistics

 High schools' statistics

 Who am I

ABOUT THE PROJECT

This webapp has been developed as part of my Bachelor's thesis to analyze the performance of the students in the initial phase of the GETI Degree (Industrial Technologies Engineering) and how their prior high school affects their results.

       <button class="button button4" type="button" onclick="show('One');hide('Group');hide('Average');">Specific subject     </button>
        <button class="button button4" type="button" onclick="hide('One');show('Group');hide('Average');">Group of subjects     </button>
        <button class="button button4" type="button" onclick="hide('One');hide('Group');show('Average');">Average grade     </button>

Statistics about a specific subject

Statistics about a group of subjects

Average grade

HIGH SCHOOLS' STATISTICS

WHO AM I?

I am an Industrial Technologies Engineering Student from ETSEIB University. I have developed this web-app as part of my Bachelor Thesis in Data Mining.

Contact information

 &copy  ETSEIB
      reserves the rights of all the displayed data | M

    Escola Tècnica Superior d'Enginyeria Industrial de Barcelona
    Universitat Politècnica de Catalunya
    Avda. Diagonal 647, 08028 Barcelona
    Phone: +34 93 401
        66 15

A: you should add this code before the closing tag of body tag

A: Run your code in this validator:
https://validator.w3.org/
Choose "validate by direct input" if you wish to just paste in your code.
Correct whatever error you can. Update the snippet with what errors might be left.


text:
Q: How to Calc the odds of winning a lucky dip How do I calculate the odds of winning?
I am doing a lucky dip raffle - you pay $£1$ and pick out $3$ balls, there are $495$ balls and $50$ prizes. Each ball has a number on, and if the number matches one of the $50$ prizes you win. What are the odds of winning - bearing in mind each turn you take you pick out $3$ balls?

A: We will calculate the probability of winning at least one prize if we draw $3$ balls.
It is easier to first calculate the probability of winning no prize. Imagine drawing the balls one at a time, and looking at them. The probability the first ball is a loser is $\frac{445}{495}$.
Given that the first ball was a loser, the probability the second ball is a loser is $\frac{444}{494}$. So the probability the first two balls are losers is $\frac{445}{495}\cdot\frac{444}{494}$. Given that the first two balls were losers, the probability the third one is a loser is $\frac{443}{493}$. So the probability of $3$ losers in a row is
$$\frac{445}{495}\cdot\frac{444}{494}\cdot{443}{493}\approx 0.726051856.$$
The probability of at least $1$ winner is therefore approximately $1$ minus the above number. This is about $0.273948$.
If you want to put this in the language of odds, the odds of winning at least one prize are about $0.273948$ to $0.7260518$, roughly $0.377312$ to $1$.


text:
Q: How to return a class using the constructor in java? How to return this Customer class so i can use this class in another class.
If i use static instead of void then i am unable to call customer Transaction from the constructor.
I tried writing new keyword but it did not work but this is returning a class:
import java.util.ArrayList;

public class Customer  {
        private String name;
        private ArrayList<Double> customerTranscation;

    public Customer(String name) {
        this.name = name;
        this.customerTranscation = new ArrayList<Double>();
    }
    public String getName() {
        return name;
    }

    public ArrayList<Double> getCustomerTranscation() {
        return customerTranscation;
    }

    public void newCustomerTran(String name,double amount){
        this.customerTranscation.add(amount);
         this.name = name;

    }
}

How can I return Customer class so I can use this in another class?

A: In you second class, You got to create the object of the customer class first .
Like Customer c=new Customer("abc");
This is going to initialise the CustomerTransaction List.
Then call c.newCustomerTrans("name").which will invoke the newCustomeTrans method from your second class.
If you want an customer object to be returned . Do .!
public Customer newCustomerTrans(String name ,double amount){
//create a new object p of Customer using new
//set name to p
//initialise and set customer trans arraylist to p
// return p
}

This way you can use Customer class details from your second class..


text:
Q: AlarmManager not triggered properly For this part of my code, I have a schedule which has a boolean for each day of the week. If that day is true, then there is a start and end alarm for that day, and these alarms should be triggered each week on that day. It works if I set the alarm for later in the current day during testing, or a day later in the week, but for any other time, as in a day of the week that has already happened or if I set either alarm for earlier in the day than when testing, both alarms go off upon creation for some reason. Here is the code for alarm creation:
public void createNewAlarm(int i)   //int correlates to position in list
    {
        for(int j = 0; j < 7; j++)
        {
            if(tempmainfrag.mainObjectList.returnSchedule(i).returnDays()[j])   //if this day of the week has an alarm
            {
                ////beginning alarm stuff////
                int alarmid = (int)System.currentTimeMillis();  //creates unique id for the alarm attached to the object

                int adjustedday = j+2;  //makes time for DAY_OF_WEEK where sunday = 1, monday = 2, etc.
                if (adjustedday == 8)
                    adjustedday = 1;
                Calendar startcal = Calendar.getInstance();
                startcal.set(Calendar.DAY_OF_WEEK, adjustedday);
                startcal.set(Calendar.HOUR_OF_DAY, tempmainfrag.mainObjectList.returnSchedule(i).returnTimes()[0]);
                startcal.set(Calendar.MINUTE, tempmainfrag.mainObjectList.returnSchedule(i).returnTimes()[1]);
                startcal.set(Calendar.SECOND, 0);

                Intent intent = new Intent(this, SilenceHandler.class);
                intent.putExtra("alarm_message", "Start!");
                intent.putExtra("vibratemode", tempmainfrag.mainObjectList.returnSchedule(i).returnVibrate());
                intent.setData((Uri.parse(String.valueOf(alarmid))));
                PendingIntent pendintent = PendingIntent.getBroadcast(this, alarmid, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                tempmainfrag.mainObjectList.returnSchedule(i).addStartPendIntent(alarmid);

                AlarmManager alarmman = (AlarmManager)getSystemService(ALARM_SERVICE);
                alarmman.setRepeating(AlarmManager.RTC_WAKEUP, startcal.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendintent);
                //120000 means every 2 mins

                ////ending alarm stuff////
                if(tempmainfrag.mainObjectList.returnSchedule(i).nextday)   //if end alarm ends on next day instead of same day
                {
                    adjustedday++;
                    if (adjustedday == 8)
                        adjustedday = 1;
                }

                alarmid = (int)System.currentTimeMillis();  //creates unique id for the alarm attached to the object

                Calendar endcal = Calendar.getInstance();
                endcal = Calendar.getInstance();
                endcal.set(Calendar.DAY_OF_WEEK, adjustedday);
                endcal.set(Calendar.HOUR_OF_DAY, tempmainfrag.mainObjectList.returnSchedule(i).returnTimes()[2]);
                endcal.set(Calendar.MINUTE, tempmainfrag.mainObjectList.returnSchedule(i).returnTimes()[3]);
                endcal.set(Calendar.SECOND, 0);

                Intent intent2 = new Intent(this, SilenceHandler.class);
                intent2.putExtra("alarm_message", "End!");
                intent2.putExtra("vibratemode", tempmainfrag.mainObjectList.returnSchedule(i).returnVibrate());
                intent2.setData((Uri.parse(String.valueOf(alarmid))));
                PendingIntent pendintent2 = PendingIntent.getBroadcast(this, alarmid, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
                tempmainfrag.mainObjectList.returnSchedule(i).addEndPendIntent(alarmid);

                AlarmManager alarmman2 = (AlarmManager)getSystemService(ALARM_SERVICE);
                alarmman2.setRepeating(AlarmManager.RTC_WAKEUP, endcal.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendintent2);
                //120000 means every 2 mins
            }
        }

    }

And I am not sure if it is relevant or not, but here is the code for Alarm deletion, though this part seems to be working fine to my knowledge:
public void deleteAlarm(int i)
{
    AlarmManager alarmman = (AlarmManager)getSystemService(ALARM_SERVICE);

    Log.i("mydebug","Deleting alarm: The pending intent list null/not null is: " + tempmainfrag.mainObjectList.returnSchedule(i).startAlarmList);//.pendintentlist.size());

    //delete start alarms
    if (tempmainfrag.mainObjectList.returnSchedule(i).startAlarmList != null)
    {
        Log.i("mydebug","Cancelling start alarm...");
        //cancels all alarms
        for (int j = 0; j < tempmainfrag.mainObjectList.returnSchedule(i).startAlarmList.size(); j++)
        {
            Intent intent = new Intent(this, SilenceHandler.class);
            intent.putExtra("starttime",tempmainfrag.mainObjectList.returnSchedule(i));
            intent.putExtra("alarm_message", "Start!");
            intent.setData((Uri.parse(String.valueOf(tempmainfrag.mainObjectList.returnSchedule(i).startAlarmList.get(j)))));
            Log.i("mydebug","Alarm number " + (j+1) + " being cancelled.");

            PendingIntent pendintent = PendingIntent.getBroadcast(this, tempmainfrag.mainObjectList.returnSchedule(i).startAlarmList.get(j), intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmman.cancel(pendintent);
        }
    }

    //delete end alarms
    if (tempmainfrag.mainObjectList.returnSchedule(i).endAlarmList != null)
    {
        Log.i("mydebug","Cancelling end alarm...");
        //cancels all alarms
        for (int j = 0; j < tempmainfrag.mainObjectList.returnSchedule(i).endAlarmList.size(); j++)
        {
            Intent intent = new Intent(this, SilenceHandler.class);
            intent.putExtra("endtime",tempmainfrag.mainObjectList.returnSchedule(i));
            intent.putExtra("alarm_message", "End!");
            intent.setData((Uri.parse(String.valueOf(tempmainfrag.mainObjectList.returnSchedule(i).endAlarmList.get(j)))));
            Log.i("mydebug","Alarm number " + (j+1) + " being cancelled.");

            PendingIntent pendintent = PendingIntent.getBroadcast(this, tempmainfrag.mainObjectList.returnSchedule(i).endAlarmList.get(j), intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmman.cancel(pendintent);
        }
    }

    //deletes alarm intents from object
    tempmainfrag.mainObjectList.returnSchedule(i).deleteIntents();
}

A: I ended up figuring out a fix after further understanding the AlarmManager system. Adding these lines worked to correct it:
Calendar checkdate = Calendar.getInstance();    //used so that alarm set to earlier in the week doesnt go off
if (startcal.before(checkdate)) //see if alarm is for earlier in week
    {
        startcal.add(Calendar.DATE, 7); //makes alarm trigger next time it becomes that day instead of immediately
    }


text:
Q: How to Read certain values from a String in Android I'm developing an android application where I'm reading results from an online database to a string of this form:
{"success":1,"innerResult":[{"username":"raafat","password":"123"}]}

I need to be able to read only the username and password values even when I have more than one result. For example i need an array of usernames returned and another array of passwords.
I tried splitting the string but it's confusing when you have many entries.

A: Your string is in Json format, you can try something like that :
try{
    JSONObject yourObject = new JSONObject(yourString);
    int resultCode = yourObject.getInt("success");
    JSONArray innerResult = yourObject.getJSONArray("innerResult");
    //you'll need to iterate through your array then
    List<String> userNames = new ArrayList<>();
    List<String> passwords = new ArrayList<>();
    for(int i =0 ; i < innerResult.length() ; i++){
        JSONObject user = innerResult.getJSONObject(i);
        userNames.add(user.getString("username"));
        passwords.add(user.getString("password"));
    }
}catch(JSONException e){
   e.printStackTrace();
}

Or you can use library like GSon !

A: Use Gson.
Step 1: Creating bean of response data. In your case you want details of Username and Password.
public class User {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

Step 2: Parse JSON response and using Gson convert it to your desired bean.
String response = "{\"success\":1,\"innerResult\":[{\"username\":\"raafat\",\"password\":\"123\"}]}";
JSONObject jsonObject = new JSONObject(response);

if(jsonObject.has("innerResult")){
   Type type = new TypeToken<List<User>>() {}.getType();
   List<User> listUsers = new Gson().fromJson(jsonObject.getJSONArray("innerResult").toString(), type);
}


text:
Q: In Matlab, how do I create a CSV file from a subset of the lines in a text file? I need to open a text file and convert it into a CSV file in Matlab. The first 3 lines of the text file are sentences that need to be omitted. The next 28 lines are numbers that need to make up the first column of the CSV, and then the next 28 lines need to make up the second column.
The text file is called datanal.txt and the output file can be named anything. Any help would be appreciated.

A: Don't have Matlab now to test, but try this. Your input file should be in Matlab's current directory, or put the full path to the file name.
A = csvread('datanal.txt',3,0);
A = reshape(A,28,2);
csvwrite('output.csv',A)

A: well you can add #'s in front of the first 3 lines then use load and a reshape. Did you need a fully automated script or is there only one file? If you're familiar with matlab at all there are a bunch of ways to turn that large column vector into a matrix.


text:
Q: jQuery UI - Create menu on click I want to make a simple menu using jQuery UI depending on the position of the cursor. This is EXACTLY what I want: http://medialize.github.io/jQuery-contextMenu/demo/dynamic-create.html but as I said, I want to use jQuery UI. In the example http://jqueryui.com/menu/ the menu is always static on the screen, how can I make it dinamically (shows up near mouse click)?
Thanks in advance,
Lucas.

A: Here's the fiddle that I threw together.
http://jsfiddle.net/uG2EE/
It's not perfect by any means, but it does what you want (uses jQuery UI, shows up near cursor when the context menu event is fired - or right click)
Unfortunately, I had to paste jQuery UI script into the script pane, so you need to scroll to the very bottom. Here's the JS I added to get this working:
$(function() {
    // Set initial state (isVisible) then initialize menu
    $("#menu").data('isVisible', false).menu();

    // Initialize event handlers
    $(document).on({
        // Click is responsible for closing the menu, when it is visible
        'click': function(e){
            if(e.which === 1 && $('#menu').data('isVisible')){
                $("#menu").css({
                'display' : 'none'
                }).data('isVisible', false);
            }
        },
        // "onContextMenu" event is fired when user right clicks. We prevent the
        // default by calling e.preventDefault(), and then display our jQuery-UI menu
        'contextmenu': function(e){
            var x = e.clientX,
                y = e.clientY;

            e.preventDefault();

            // Check state (isVisible) to see if menu needs to be displayed
            if($('#menu').data('isVisible') === false) {
                $("#menu").css({
                'display' : 'block',
                'left' : x + 10,
                'top' : y + 10
                }).data('isVisible', true);
            }
        }
    });
});

The CSS is very straight forward: display:none, position:absolute, and the width.
Good luck!


text:
Q: C++: set method parameter to pointer I have a class with a public member int* classPointer. I want to have a function getPointer(int** externalPointer), that makes externalPointer point to the data of classPointer for me to use it outside of the class context.
I tried
void getPointer(int** externalPointer) {externalPointer = &internalPointer;}
and calling it like this: getPointer(&externalPointer). I get the warning: "parameter externalPointer set but never used".
I don't think this is the correct way of doing it. Help is appreciated.

A: Assuming you're using a double-pointer as a weird C-style way of emulating a reference to emulate a return value, then you'd want to write through the pointer to whatever it pointed at, not modify the local function argument:
void getPointer(int** externalPointer) {*externalPointer = internalPointer;}
                                        ^ add *            ^ lose &

Unless your goal is to baffle users of the function, use a reference when you want a reference:
void getPointer(int*& externalPointer) {externalPointer = internalPointer;}

and, if the purpose of the reference is to return a value, then just return a value:
int *getPointer() {return internalPointer;}

A: If you pass in an (int**) and assign it its address, the thing that it points to will be classPointer.
class Blah
{
public:
  void getPointer(int** externalPointer)
  {
    *externalPointer = classPointer; // Add the star at the beginning.
  }

  int* classPointer;
}

Call is like this:
int* k = new int;
std::cout << "k=" << *k << " at address:" << k << std::endl;
blah.getPointer(&k);
std::cout << "blah.classPointer=" << *blah.classPointer
          << " at address:" << blah.classPointer
          << std::endl;

If the classPointer is public, you also don't need a method to do this.
Blah blah;
int* ptr = blah.classPointer;


text:
Q: Kali linux is not booting up from virtual box I executed
$sudo apt-get update
$sudo apt upgrade -y

After that it took 3 hours to download some packages .After when download is complete then it was extracting those packages and installing on my system it was about 30% done then I had urgent work and had to close my virtual box. After that its not booting.When I start my virtual box and select kali-os and hit start it shows nothing just a black screen appears.

What has happened & why its not booting? How can I fix it?


text:
Q: Matrix multiplication but only between specific rows and columns I have three two matrices A and B, the matrix product I want is diagonal(A.B.A^T), where A^T is transpose of a matrix. The dimensions of the matrices are as follows
A - (2^n, n)
B - (n, n)

where is n is any natural number.
I want first row slice of matrix A to be multiplied with matrix B and their product is multiplied with first column of matrix A^T. I don't want the full product of A.B.A^T because I only want the diagonal slice.
It seems to me this can be achieved using eisum.
A related question on codereview

A: Here is how to do it with einsum
np.random.seed(1)

A = np.random.randint(0,10,(8,4))
B = np.random.randint(0,10,(4,4))

# brute force for reference
np.diag(A@B@A.T)
# array([3830,  233, 2835,  958, 3706, 1273, 5478,  934])

# more economical
np.einsum('ij,jk,ik->i',A,B,A)
# array([3830,  233, 2835,  958, 3706, 1273, 5478,  934])


text:
Q: Trying to check the current time falls inside a range of start/end time using momentJS (UTC) Trying to check if the current time is between start and end time.
Everything is in UTC, any ideas?
Works

shiftCurrentTime = moment.utc().format('hh:mm');
console.log(shiftCurrentTime);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>

Doesn't work

shiftStartTime = moment.utc('20:00').format('hh:mm'),
  shiftEndTime = moment.utc('05:00').format('hh:mm'),
  shiftCurrentTime = moment.utc().format('hh:mm');

console.log(shiftCurrentTime.isBetween(shiftStartTime, shiftEndTime));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>

A: You are confusing between moment objects and their string representation (given by format())
You have to parse your string into moment object specifying format, since HH:mm is not a known ISO 8601 format.
You can call isBetween on the moment object, while calling it on the formatted string gives you error.
Here a complete working example:

var shiftStartTime = moment.utc('20:00', 'HH:mm'),
shiftEndTime = moment.utc('05:00', 'HH:mm'),
shiftCurrentTime = moment.utc();

console.log(shiftCurrentTime.isBetween(shiftStartTime, shiftEndTime));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>


text:
Q: 500 Server Error after migration from VTiger CRM 5.4 to 6.0 I recently used the Migration system to upgrade from 5.4 to 6.0
Now when I login I cannot access the Contacts tab, the Sales Order tab, nor the Invoice tab (I received 500 Internal Server errors).
I looked at my error_log and found this:

[22-Jan-2015 23:41:51] PHP Fatal error: Call to a member function FetchRow() on a non-object in /home2/swanhang/public_html/Swan_Hangers/CRM/include/database/PearDatabase.php on line 532

Does anyone know how to fix this?

A: Answer:
Found the issue in PearDatabase.php, just had to check for if $result was object. Here is code solution starting on line 527:
 if (is_object($result)) {
     $arr = $result->FetchRow();
      if(is_array($arr))
           $arr = array_map('to_html', $arr);
      return $this->change_key_case($arr);
}

Always backup php file BEFORE you make changes.


text:
Q: Mimecast requires our SPF to include all the Public IP addresses We are a small business using ISP Bellhosting to host our domain- Our major client just added MIMECAST who now requires we establish our SPF record in our DNS - We did that but our email are still blocked by Mimecast who now requires us to include in our SPF all Public IP addresses that Bellhosting is using via Memamailservers. Our ISP maintains we have 1 email IP address- How can we can we get the Megamailservers public IP addresses used to forward our emails. and include them in our SPF record

A: Normally you would ask your email provider if there is something to use in the include mechanism, e.g. TXT "v=spf1 include:mailservers.example.com -all".
However, this Bellhosting doesn't seem like an service provider who cares about this at all:

*

*Their website is just a login form: there's nothing informative. Then, this megamailservers.com seems like a page that has been build around year 2000 and hasn't been updated ever since. Probably that's not their only service that hasn't been developed for a while...

*Bellhosting hasn't implemented SPF for their own domain. Neither has megamailservers.com.

*While it's possible to find some PDF Guides of their services from Google, there zero technical specifications of anything: they are brochures at best.

So I guess if you call their support they'd probably answer: "What's SPF?", and aren't going to implement DKIM and DMARC any time soon, either.
STEP 1: Short term. Figure correct SPF settings by yourself. It seems like megamailservers.com has three MX records. Wow, they are all on the same subnet, telling more about their quality.
megamailservers.com. IN  MX   10 mx1c1.megamailservers.com.  IN  A  69.49.103.242
megamailservers.com. IN  MX  100 mx2c1.megamailservers.com.  IN  A  69.49.103.243
megamailservers.com. IN  MX  150 mx3c1.megamailservers.com.  IN  A  69.49.103.244

Based on this + PTR records I'd say whole Megamail is probably within subnet 69.49.103.242/29. At first I would suggest adding TXT "v=spf1 ip4:69.49.103.242/29 ~all" for this subnet.
STEP 2: Long term. Find a competent service provider that knows how to implement the current minimum requirements for professional email services: SPF, DKIM and DMARC. Use their own settings + at least one known customer as a reference.


text:
Q: R: gather() to Tidy data with two column headings I would like to Tidy some data that has unfortunately been set up with two column headings, in the first two rows:

*

*First Row (the Heading): is actually the type of measure (eg.
estimate, std error, upper bound, lower bound).

*Second Row (also a Heading): is the Year of the measure.
Is there some way I can use gather() or anything else to tidy this data?
Also, when a measure is repeated (eg. Rank, Rank.1) it really should only read Rank, and is different because of the Year only. Is there some way to fix that?
  Country_Territory WBCode Estimate  StdErr NumSrc    Rank   Lower
1              Year   <NA>  1996.00 1996.00   1996 1996.00 1996.00
2           Andorra    ADO     1.32    0.48      1   87.10   72.04
3       Afghanistan    AFG    -1.29    0.34      2    4.30    0.00
4            Angola    AGO    -1.17    0.26      4    9.68    0.54
    Upper Estimate.1 StdErr.1 NumSrc.1  Rank.1 Lower.1 Upper.1
1 1996.00    1998.00  1998.00     1998 1998.00 1998.00 1998.00
2   96.77       1.38     0.46        1   89.18   74.74   96.91
3   27.42      -1.18     0.33        2    9.79    0.00   31.44
4   27.42      -1.41     0.21        6    1.55    0.00   13.40

This is the code to input a sample of my data:
df <-  data.frame(stringsAsFactors=FALSE,
       Country_Territory = c("Year", "Andorra", "Afghanistan", "Angola"),
                  WBCode = c(NA, "ADO", "AFG", "AGO"),
                Estimate = c(1996, 1.32, -1.29, -1.17),
                  StdErr = c(1996, 0.48, 0.34, 0.26),
                  NumSrc = c(1996, 1, 2, 4),
                    Rank = c(1996, 87.1, 4.3, 9.68),
                   Lower = c(1996, 72.04, 0, 0.54),
                   Upper = c(1996, 96.77, 27.42, 27.42),
                Estimate = c(1998, 1.38, -1.18, -1.41),
                  StdErr = c(1998, 0.46, 0.33, 0.21),
                  NumSrc = c(1998, 1, 2, 6),
                    Rank = c(1998, 89.18, 9.79, 1.55),
                   Lower = c(1998, 74.74, 0, 0),
                   Upper = c(1998, 96.91, 31.44, 13.4)
    )

For example, this attempt:
df %>% gather(key = measure, value = number, 3:14)

Didn't quite give me what I was looking for:
   Country_Territory WBCode    measure  number
1               Year   <NA>   Estimate 1996.00
2            Andorra    ADO   Estimate    1.32
3        Afghanistan    AFG   Estimate   -1.29
4             Angola    AGO   Estimate   -1.17
5               Year   <NA>     StdErr 1996.00
6            Andorra    ADO     StdErr    0.48

because the Year is mixed in with the Country_Territory.

A: This is one option:
library(tidyverse)

# get unique Year values and create column names (to add later)
df %>%
  filter(Country_Territory == "Year") %>%
  gather() %>%
  filter(value != "Year" & !is.na(value)) %>%
  pull(value) %>%
  unique() %>%
  paste0("Year_",.) -> col_years

# reshape data (excluding the Year row)
df %>%
  filter(Country_Territory != "Year") %>%
  gather(key,y,-Country_Territory, -WBCode) %>%
  separate(key, c("measure","v")) %>%
  group_by(v = ifelse(is.na(v), 0, v)) %>%
  nest() -> df_info

reduce(df_info$data, function(x,y) left_join(x,y,by=c("Country_Territory","WBCode","measure"))) %>%
  setNames(c("Country_Territory", "WBCode", "measure", col_years))

# # A tibble: 18 x 5
#   Country_Territory WBCode measure  Year_1996 Year_1998
#   <chr>             <chr>  <chr>        <dbl>     <dbl>
# 1 Andorra           ADO    Estimate      1.32      1.38
# 2 Afghanistan       AFG    Estimate     -1.29     -1.18
# 3 Angola            AGO    Estimate     -1.17     -1.41
# 4 Andorra           ADO    StdErr        0.48      0.46
# 5 Afghanistan       AFG    StdErr        0.34      0.33
# 6 Angola            AGO    StdErr        0.26      0.21
# 7 Andorra           ADO    NumSrc        1         1
# 8 Afghanistan       AFG    NumSrc        2         2
# 9 Angola            AGO    NumSrc        4         6
# 10 Andorra           ADO    Rank         87.1      89.2
# 11 Afghanistan       AFG    Rank          4.3       9.79
# 12 Angola            AGO    Rank          9.68      1.55
# 13 Andorra           ADO    Lower        72.0      74.7
# 14 Afghanistan       AFG    Lower         0         0
# 15 Angola            AGO    Lower         0.54      0
# 16 Andorra           ADO    Upper        96.8      96.9
# 17 Afghanistan       AFG    Upper        27.4      31.4
# 18 Angola            AGO    Upper        27.4      13.4

If you save the above output as df_upd you can reshape a bit more to get Year as one column:
df_upd %>%
  gather(Year, value, -Country_Territory, -WBCode, -measure) %>%
  separate(Year, c("y","Year"), convert = T) %>%
  select(-y)

# # A tibble: 36 x 5
#   Country_Territory WBCode measure   Year  value
#   <chr>             <chr>  <chr>    <int>  <dbl>
# 1 Andorra           ADO    Estimate  1996   1.32
# 2 Afghanistan       AFG    Estimate  1996  -1.29
# 3 Angola            AGO    Estimate  1996  -1.17
# 4 Andorra           ADO    StdErr    1996   0.48
# 5 Afghanistan       AFG    StdErr    1996   0.34
# 6 Angola            AGO    StdErr    1996   0.26
# 7 Andorra           ADO    NumSrc    1996   1
# 8 Afghanistan       AFG    NumSrc    1996   2
# 9 Angola            AGO    NumSrc    1996   4
# 10 Andorra           ADO    Rank      1996  87.1
# # ... with 26 more rows

A: Perhaps (if you have only two series of measures):
bind_rows(df %>% select(1:2,3:8) %>%
             mutate(Year=first(Estimate)),
          df %>% select(1:2,9:14) %>%
            rename_all(funs(str_replace(.,"\\.1",""))) %>%
            mutate(Year=first(Estimate))) %>%
  filter(Country_Territory!="Year")
#  Country_Territory WBCode Estimate StdErr NumSrc  Rank Lower Upper Year
#1           Andorra    ADO     1.32   0.48      1 87.10 72.04 96.77 1996
#2       Afghanistan    AFG    -1.29   0.34      2  4.30  0.00 27.42 1996
#3            Angola    AGO    -1.17   0.26      4  9.68  0.54 27.42 1996
#4           Andorra    ADO     1.38   0.46      1 89.18 74.74 96.91 1998
#5       Afghanistan    AFG    -1.18   0.33      2  9.79  0.00 31.44 1998
#6            Angola    AGO    -1.41   0.21      6  1.55  0.00 13.40 1998

A: Data.table solution.
Needs some preparation, (to set colnames and to create a table of unique names) but then is blazingly fast.
Solution also works for more than two years.
library( data.table )
dt <- as.data.table( df )  #or use setDT( df )

#extract unique years from the first row from the thirs column untill end of dt
dt.years <- as.data.table ( unique( t( (dt[1, 3:ncol(dt)]) ) ) )
dt.years[, year_id := 1:.N ]
setnames(dt.years, c("year", "year_id" ) )

#melt row 2:n of the data.table
dt.melt <- melt( dt[2:nrow(dt)],
                 id.vars = c( "Country_Territory", "WBCode"),
                 measure = patterns( "Estimate", "StdErr", "NumSrc", "Rank", "Lower", "Upper"),
                 value.name = c( "Estimate", "StdErr", "NumSrc", "Rank", "Lower", "Upper" ),
                 variable.name = "year")

#left join both datatables
result <- dt.years[dt.melt, on = c( year_id = "year")]

#cleaning and renaming
result[, year_id := NULL]

results
#    year Country_Territory WBCode Estimate StdErr NumSrc  Rank Lower Upper
# 1: 1996           Andorra    ADO     1.32   0.48      1 87.10 72.04 96.77
# 2: 1996       Afghanistan    AFG    -1.29   0.34      2  4.30  0.00 27.42
# 3: 1996            Angola    AGO    -1.17   0.26      4  9.68  0.54 27.42
# 4: 1998           Andorra    ADO     1.38   0.46      1 89.18 74.74 96.91
# 5: 1998       Afghanistan    AFG    -1.18   0.33      2  9.79  0.00 31.44
# 6: 1998            Angola    AGO    -1.41   0.21      6  1.55  0.00 13.40

A: The data.table method of melt() is able to reshape multiple measure columns simultaneously. Columns need not to be renamed by using the patterns() function.
library(data.table)
# reshape multiple measure columns simultaneously from wide to long format
cols <- c("Estimate", "StdErr", "NumSrc", "Rank", "Lower", "Upper")
long <- melt(setDT(df), measure.vars = patterns(cols), value.name = cols)
# extract years
yrs <- long[Country_Territory == "Year", .(variable, Year = as.integer(Estimate))]
# join to get a separate Year column, remove Year rows and helper column
result <- yrs[long[Country_Territory != "Year"], on = "variable"][, variable := NULL][]
result

   Year Country_Territory WBCode Estimate StdErr NumSrc  Rank Lower Upper
1: 1996           Andorra    ADO     1.32   0.48      1 87.10 72.04 96.77
2: 1996       Afghanistan    AFG    -1.29   0.34      2  4.30  0.00 27.42
3: 1996            Angola    AGO    -1.17   0.26      4  9.68  0.54 27.42
4: 1998           Andorra    ADO     1.38   0.46      1 89.18 74.74 96.91
5: 1998       Afghanistan    AFG    -1.18   0.33      2  9.79  0.00 31.44
6: 1998            Angola    AGO    -1.41   0.21      6  1.55  0.00 13.40

After reshaping, the variable column denotes rows which belong to one column subset in the wide format, i.e., which belong to one particular year.


text:
Q: Identify the frequency count behind an aggregate in r Hello and good evening overflowers, this could very well be a super simple answer and I hope so, here goes nothing (apologies in advance if I am not supplying enough info).....
Long story short, I am trying to figure out the mean time to resolve a case per group and how many cases they have resolved. To identify the "MTTR" I do this :
avgMttrFreq <- aggregate(db$CAL_MTTR_CALC2 ~ db$ASSIGNMENT_GROUP, db ,mean)
avgMttrFreq[order(-avgMttrFreq[,2]),]
avgMttrOrder <-avgMttrFreq[order(-avgMttrFreq[,2]),]
avgMttrOrderDf <- data.frame(avgMttrOrder)
avgMttrTopX <- avgMttrOrderDf[1:20,]
avgMttrTopX

The output looks like this:

Cool... now we can see the avg.mttr or mean time to resolve per group (sorted which is important), but I need to be able to add the "frequency" column..... what I mean is, how many observations are behind the 3k hrs to resolve in row one? any ideas on how we can do this?

A: The data.table way:
# example data
library(data.table)
data.table(
    group = sample(letters[1:3], 20, TRUE),
    time  = runif(20, 0, 10)
)

# or if your data are in a dataframe named 'df' convert to dt by:
dt <- as.data.table(df) #or just setDT(df)

# aggregate, creating 2 variables: avg_time and count
res <- dt[ , .(avg_time = mean(time), count = .N), by=group]

# print sorted result
res[order(avg_time, decreasing=TRUE)]

Inelegant Base R way:
# do mean and count (with length) separately
avgMttrFreq1 <- aggregate(CAL_MTTR_CALC2 ~ ASSIGNMENT_GROUP, db ,mean)
avgMttrFreq2 <- aggregate(CAL_MTTR_CALC2 ~ ASSIGNMENT_GROUP, db ,length)

# merge them together
avgMttrFreq <- merge(avgMttrFreq1, avgMttrFreq2, by="ASSIGNMENT_GROUP")

#then the rest of your code

A: Hope this one helps
library(data.table)
data <- data.table(db)
data[, list(count=length(CAL_MTTR_CALC2), mean=mean(CAL_MTTR_CALC2)), by=c("ASSIGNMENT_GROUP")]


text:
Q: Help with solving an equation Could anyone please help me find the real solution(s) to a system of equations, or could anyone please help me find an effective solver to solve it?
The function Func is as following:
Func = 30*(1 + a + b + c + d + e)*(1 + a + f + g + h + i)*(1 + b + f + j + k +
l)* (1 + c + g + j + m + n)*(1 + d + h + k + m + o)*(1 + e + i + l + n + o) - (3
+ a + b + c + d + e + f + g + h + i + j + k + l + m + n + o)^3 - (-1 + c^2 + d^2
+ e^2 + f^2 - c^2*f^2 - d^2*f^2 - e^2*f^2 + g^2 - d^2*g^2 - e^2*g^2 + 2*c*d*g*h
+ h^2 - c^2*h^2 - e^2*h^2 + 2*c*e*g*i + 2*d*e*h*i + i^2 - c^2*i^2 - d^2*i^2 -
2*f*g*j + 2*d^2*f*g*j + 2*e^2*f*g*j - 2*c*d*f*h*j - 2*c*e*f*i*j + j^2 - d^2*j^2
- e^2*j^2 - h^2*j^2 + e^2*h^2*j^2 - 2*d*e*h*i*j^2 - i^2*j^2 + d^2*i^2*j^2 -
2*c*d*f*g*k - 2*f*h*k + 2*c^2*f*h*k + 2*e^2*f*h*k - 2*d*e*f*i*k + 2*c*d*j*k +
2*g*h*j*k - 2*e^2*g*h*j*k + 2*d*e*g*i*j*k + 2*c*e*h*i*j*k - 2*c*d*i^2*j*k + k^2
- c^2*k^2 - e^2*k^2 - g^2*k^2 + e^2*g^2*k^2 - 2*c*e*g*i*k^2 - i^2*k^2 +
c^2*i^2*k^2 - 2*c*e*f*g*l - 2*d*e*f*h*l - 2*f*i*l + 2*c^2*f*i*l + 2*d^2*f*i*l +
2*c*e*j*l + 2*d*e*g*h*j*l - 2*c*e*h^2*j*l + 2*g*i*j*l - 2*d^2*g*i*j*l +
2*c*d*h*i*j*l + 2*d*e*k*l - 2*d*e*g^2*k*l + 2*c*e*g*h*k*l + 2*c*d*g*i*k*l +
2*h*i*k*l - 2*c^2*h*i*k*l + l^2 - c^2*l^2 - d^2*l^2 - g^2*l^2 + d^2*g^2*l^2 -
2*c*d*g*h*l^2 - h^2*l^2 + c^2*h^2*l^2 - 2*c*d*m + 2*c*d*f^2*m - 2*g*h*m +
2*e^2*g*h*m - 2*d*e*g*i*m - 2*c*e*h*i*m + 2*c*d*i^2*m + 2*f*h*j*m -
2*e^2*f*h*j*m + 2*d*e*f*i*j*m + 2*f*g*k*m - 2*e^2*f*g*k*m + 2*c*e*f*i*k*m -
2*j*k*m + 2*e^2*j*k*m + 2*i^2*j*k*m + 2*d*e*f*g*l*m + 2*c*e*f*h*l*m -
4*c*d*f*i*l*m - 2*d*e*j*l*m - 2*h*i*j*l*m - 2*c*e*k*l*m - 2*g*i*k*l*m +
2*c*d*l^2*m + 2*g*h*l^2*m + m^2 - e^2*m^2 - f^2*m^2 + e^2*f^2*m^2 - i^2*m^2 +
2*f*i*l*m^2 - l^2*m^2 - 2*c*e*n + 2*c*e*f^2*n - 2*d*e*g*h*n + 2*c*e*h^2*n -
2*g*i*n + 2*d^2*g*i*n - 2*c*d*h*i*n + 2*d*e*f*h*j*n + 2*f*i*j*n - 2*d^2*f*i*j*n
+ 2*d*e*f*g*k*n - 4*c*e*f*h*k*n + 2*c*d*f*i*k*n - 2*d*e*j*k*n - 2*h*i*j*k*n +
2*c*e*k^2*n + 2*g*i*k^2*n + 2*f*g*l*n - 2*d^2*f*g*l*n + 2*c*d*f*h*l*n - 2*j*l*n
+ 2*d^2*j*l*n + 2*h^2*j*l*n - 2*c*d*k*l*n - 2*g*h*k*l*n + 2*d*e*m*n -
2*d*e*f^2*m*n + 2*h*i*m*n - 2*f*i*k*m*n - 2*f*h*l*m*n + 2*k*l*m*n + n^2 -
d^2*n^2 - f^2*n^2 + d^2*f^2*n^2 - h^2*n^2 + 2*f*h*k*n^2 - k^2*n^2 - 2*d*e*o +
2*d*e*f^2*o + 2*d*e*g^2*o - 2*c*e*g*h*o - 2*c*d*g*i*o - 2*h*i*o + 2*c^2*h*i*o -
4*d*e*f*g*j*o + 2*c*e*f*h*j*o + 2*c*d*f*i*j*o + 2*d*e*j^2*o + 2*h*i*j^2*o +
2*c*e*f*g*k*o + 2*f*i*k*o - 2*c^2*f*i*k*o - 2*c*e*j*k*o - 2*g*i*j*k*o +
2*c*d*f*g*l*o + 2*f*h*l*o - 2*c^2*f*h*l*o - 2*c*d*j*l*o - 2*g*h*j*l*o - 2*k*l*o
+ 2*c^2*k*l*o + 2*g^2*k*l*o + 2*c*e*m*o - 2*c*e*f^2*m*o + 2*g*i*m*o -
2*f*i*j*m*o - 2*f*g*l*m*o + 2*j*l*m*o + 2*c*d*n*o - 2*c*d*f^2*n*o + 2*g*h*n*o -
2*f*h*j*n*o - 2*f*g*k*n*o + 2*j*k*n*o - 2*m*n*o + 2*f^2*m*n*o + o^2 - c^2*o^2 -
f^2*o^2 + c^2*f^2*o^2 - g^2*o^2 + 2*f*g*j*o^2 - j^2*o^2 + b^2*(1 - i^2 - m^2 +
i^2*m^2 - n^2 + h^2*(-1 + n^2) + 2*m*n*o - o^2 + 2*h*i*((-m)*n + o) + g^2*(-1 +
o^2) + 2*g*(i*(n - m*o) + h*(m - n*o))) + a^2*(1 - l^2 - m^2 + l^2*m^2 - n^2 +
k^2*(-1 + n^2) + 2*m*n*o - o^2 + 2*k*l*((-m)*n + o) + j^2*(-1 + o^2) + 2*j*(l*(n
- m*o) + k*(m - n*o))) + 2* a*((-d)*h - e*i + d*h*j^2 + e*i*j^2 + d*f*k -
d*g*j*k + e*i*k^2 + e*f*l - e*g*j*l - e*h*k*l - d*i*k*l + d*h*l^2 + d*g*m -
d*f*j*m - 2*e*i*j*k*m + e*h*j*l*m + d*i*j*l*m + e*g*k*l*m - d*g*l^2*m + e*i*m^2
- e*f*l*m^2 + e*g*n - e*f*j*n + e*h*j*k*n + d*i*j*k*n - e*g*k^2*n - 2*d*h*j*l*n
+ d*g*k*l*n - e*h*m*n - d*i*m*n + e*f*k*m*n + d*f*l*m*n + d*h*n^2 - d*f*k*n^2 +
e*h*o + d*i*o - e*h*j^2*o - d*i*j^2*o - e*f*k*o + e*g*j*k*o - d*f*l*o +
d*g*j*l*o - e*g*m*o + e*f*j*m*o - d*g*n*o + d*f*j*n*o + c*((-h)*j*k - i*j*l +
h*m + i*k*l*m - h*l^2*m + i*n - i*k^2*n + h*k*l*n + i*j*k*o + h*j*l*o - i*m*o -
h*n*o + g*(-1 + k^2 + l^2 - 2*k*l*o + o^2) + f*(j - k*m - l*n + l*m*o + k*n*o -
j*o^2)) + b*(h*k + i*l - h*j*m - i*l*m^2 - i*j*n + i*k*m*n + h*l*m*n - h*k*n^2 -
i*k*o - h*l*o + i*j*m*o + h*j*n*o + f*(-1 + m^2 + n^2 - 2*m*n*o + o^2) + g*(j -
k*m - l*n + l*m*o + k*n*o - j*o^2))) - 2* b*(e*(h*i*k + l - h^2*l - h*i*j*m -
l*m^2 - j*n + h^2*j*n + k*m*n - k*o + j*m*o + g*(i*j - i*k*m + 2*h*l*m - h*k*n -
h*j*o) + g^2*(-l + k*o) + f*(i*(-1 + m^2) + g*n - h*m*n + h*o - g*m*o)) + d*(k -
i^2*k + h*i*l - j*m + i^2*j*m - h*i*j*n + l*m*n - k*n^2 + g*h*(j - l*n) - l*o +
j*n*o - g*i*(l*m - 2*k*n + j*o) + g^2*(-k + l*o) + f*(g*m - i*m*n + h*(-1 + n^2)
+ i*o - g*n*o)) + c*(g*h*k + g*i*l - k*m + i^2*k*m - h*i*l*m - h*i*k*n - l*n +
h^2*l*n - g*i*k*o - g*h*l*o + l*m*o + k*n*o - j*(-1 + h^2 + i^2 - 2*h*i*o + o^2)
+ f*(h*m + i*n - i*m*o - h*n*o + g*(-1 + o^2)))))*p

Then, I try to solve it as follows:
Solve[
  Grad[Func, {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p}] == 0 &&
  a^2 <= 1 && 1 + 2 a b f >= a^2 + b^2 + f^2,
  Reals]

If the exact solution(s) can't be found, how about the real numerical solution(s)? Thanks a lot.

A: This answer is for free! ;-)
(Sorry, didn't understand the purpose of your comment "By the way, I paid nearly $2000 for Mathematica.")
Try NMinimize:
 NMinimize[{Grad[Func, Variables[Func]].Grad[Func, Variables[Func]],a^2 <= 1 && 1 + 2 a b f >= a^2 + b^2 + f^2}, Variables[Func]]
 (*{4.20993*10^-18, {a -> -0.754063, b -> -0.0172513, c -> 0.763396,
 d -> -0.647301, e -> -0.490722, f -> -0.122599, g -> -0.686903,
 h -> 0.0259991, i -> 0.537566, j -> -0.064485, k -> -0.226188,
 l -> -0.0367157, m -> -0.270598, n -> -0.96309, o -> -0.0470382,
 p -> -9.82239*10^-9}}*)


text:
Q: Edit or remove picture button disabled in skype for business Edit or remove button is disabled for me in Skype for business. I am also not able to update my profile picture in portal.office.com/Profile. It says access denied. Screenshots are attached. Thanks in advance!

A: In the Skype for Business main window, click the Options button, and then click Personal.
In Personal options, under Show pictures, clear the Show pictures of contacts check box.


text:
Q: In Backbone.js how can I get Model superclass defaults to act as defaults for subclasses? I have a class that defines some defaults, and a subclass that defines some defaults.  But when I create an instance of the subclass it only looks at the local defaults and does not merge its defaults with those of the parent.  Is there any simple way to do this without explicitly merging the local defaults with the parent defaults in the initialize function of every subclass?
var Inventory = Backbone.Model.extend({
    defaults: {
        cat: 3,
        dog: 5
    }
});

var ExtendedInventory = Inventory.extend({
    defaults: {
        rabbit: 25
    }
});

var ei = new ExtendedInventory({});
console.log(ei.attributes);

This outputs:
{rabbit: 25}

Not what I want:
{cat: 3, dog: 5, rabbit: 25}

A: You can't do it like that. You will have to do it after the subclass
_.extend(ExtendedInventory.prototype.defaults, {rabbit: 25});

Put this after your model definition.


text:
Q: Dynamic form builder in php Do we have any dynamic form builder in php? I am creating a dynamic form builder in PHP, I will store the fields in the database and they will be rendered in a form dynamically from database.
I wanted to know if there is any existing api that does so?

A: You can try use Symfony2 Forms. If I remember correctly this module should be separated from other parts of S2 or need a small piece.


text:
Q: How to Remove Header in LaTex I would like to not show the name of each chapter on the header of its each page. I also like to have nothing in the headers for abstract, acknowledgement, table of content, list of figures and list of tables. But I currently have the header on each page, for example:

Thanks and regards!

EDIT:
I just replaced \thispagestyle{botcenter} with \thispagestyle{plain}. The latter is said to clear the header (http://en.wikibooks.org/wiki/LaTeX/Page_Layout), but it does not. How shall I do?
Thanks!

EDIT:
I now just realized it could be the fancy pagestyle that shows the header.
\pagestyle{fancy}
\fancyhf{}
\setlength{\headheight}{15pt}
\lhead{\leftmark}
\cfoot{\thepage}
\renewcommand{\headrulewidth}{0pt}
\fancypagestyle{plain}{% Redefine ``plain'' style for chapter boundaries
    \fancyhf{} % clear all header and footer fields
    \fancyfoot[C]{\thepage} % except the center
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\footrulewidth}{0pt}
}

How can I remove header and keep the footer? I think footer is needed to show the page number right?
Thanks!

EDIT:
My pdf file also has no page numbering for the first page of Table of Content, List of Tables and List of Figures. Is this normal? If it is not, how to fix it? Thanks!

A: I think you should be experimenting with \pagestyle and, if that does not provide enough control, the fancyhdr package.  How they will interact with what I surmise is a custom document class I am not sure.

A: I did this by \fancyhead{}, along with \renewcommand{\headrulewidth}{0pt}.

A: EDIT:  I cleared my other ramblings.  The only thing you need to do is remove the \leftmark from your \lhead.


text:
Q: Android app firebase crashlytics debugging info: how to troubleshoot? I set up Firebase crashlytics following's Google's instructions (https://firebase.google.com/docs/crashlytics/get-started?platform=android&authuser=1#add-sdk), then I purposely crashed the app in order to see something in the firebase console, as per https://firebase.google.com/docs/crashlytics/test-implementation?authuser=1&platform=android.; this page also suggests turning on the crashlytics debug logging, which I did. The logging ends with:
D/FirebaseCrashlytics(23841): Crashlytics is handling uncaught exception "java.lang.RuntimeException: Unable to start activity ComponentInfo{com. ... .TabActivity}: java.lang.NumberFormatException: Invalid int: "abc"" from thread main
D/FirebaseCrashlytics(23841): Persisting fatal event for session 603B968F001F00015D21614184AB1DFB
D/FirebaseCrashlytics(23841): Finalizing report for session 603B968F001F00015D21614184AB1DFB
D/FirebaseCrashlytics(23841): Opening a new session with ID 603B9693009B00025D21614184AB1DFB
D/FirebaseCrashlytics(23841): Crashlytics automatic data collection ENABLED by global Firebase setting.
D/FirebaseCrashlytics(23841): Logging Crashlytics event to Firebase
D/FirebaseCrashlytics(23841): Awaiting app exception callback from FA...
D/FirebaseCrashlytics(23841): Received Analytics message: 3 Bundle[{params=Bundle[{_o=clx, _r=1, timestamp=1614517907044, fatal=1}], name=_ae, timestampInMillis=1614517907169}]
D/FirebaseCrashlytics(23841): App exception callback received from FA listener.
D/FirebaseCrashlytics(23841): Crashlytics report successfully enqueued to DataTransport: 603B968F001F00015D21614184AB1DFB
D/FirebaseCrashlytics(23841): Crashlytics completed exception processing. Invoking default exception handler.

According to this SO post, I should be expecting, after "Crashlytics report successfully enqueued to DataTransport", some lines like
TransportRuntime.CctTransportBackend: Making request to with subsequent
TransportRuntime.CctTransportBackend: Status Code: 200

But it wasn't there.
People also say it takes 24-48 hours for crash data to show up in the console, rather than "up to 5 minutes" like what Google says. But it is over 48 hours now.

A: Even though this was for Android, an important clue was found in the iOS instructions on testing with a forced crash, namely, that the app should run long enough the next time, or in a subsequent run, that it has time to send the crash logs to Firebase. If you fake an automatic crash early in the app lifecycle for testing purposes, it may not have time to send the data about earlier crashes when it starts again later, before it crashes again.


text:
Q: LEFT OUTER JOIN with an OR condition <- kills db server In a nutshell..
SELECT *
FROM tbl1
LEFT OUTER JOIN tbl2 ON tbl1.ID = tbl2.externalRefID
WHERE tbl1.varref = '12345' OR tbl2.varref = '12345';

With any volume of data in these tables this query takes forever. Yet I need the second table outer joined as it won't often match on the externalRefID. Indexes created for all columns that are referenced but makes no difference as I need an index across multiple tables (is that possible?)
this must be obvious but i can't see the wood for the trees...

A: Have you considered refactoring the query into a UNION query?
SELECT *
  FROM tbl1 INNER JOIN tbl2 ON tbl1.id = tbl2.externalRefId
 WHERE tbl2.varref = '12345'
UNION
SELECT *
  FROM tbl1 OUTER JOIN tbl2 ON tbl1.id = tbl2.externalRefId
 WHERE tab.1.varref = '12345'

You might be able to use UNION ALL on this too.


text:
Q: custom camera launch on button click in android I want to open a my custom camera when i click on a button in my app.
Please help me out.
Thanks in Advance:)
private static Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    OnClickButtonListener();
}

public void OnClickButtonListener() {
button = (Button) findViewById(R.id.camerabutton);
button.setOnClickListener(
    new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent =new Intent ("com.example.hrbl.camera");
                startActivity(intent);

        }
    });

A: If it's an activity inside the app then try this
 Intent intent =new Intent (MyAcitivty.this, CustomCameraActivity.class);
            startActivity(intent);

Just change the activity names so they fit yours


text:
Q: Error in result_fetch(res@ptr, n): nanodbc/nanodbc.cpp:2695: 24000: [Microsoft][ODBC SQL Server Driver]Invalid cursor state I have an R script that calls a stored procedure in SQL Server.  The Stored procedure in MS SQL Server inserts records from one table into another table that has an auto-increment ID column (IDENTITY(1,1)).  When the stored procedure executes, after inserting rows from one table into another, the auto-incremented ID (id) and the inserted value (file_name) are returned.  When I run procedure in SQL Server Management Studio, every executes as expected and a table is returned with id and file_name.  However, when I execute the stored procedure call in R using the DBI package, I get the following error:
Error in result_fetch(res@ptr, n) :
nanodbc/nanodbc.cpp:2695: 24000: [Microsoft][ODBC SQL Server Driver]Invalid cursor state Warning message:
In dbClearResult(rs) : Result already cleared

Does anyone know how to remedy this problem?  I looked through dozens of other posts on SO and none seem to resolve this for me.
As background, here is a toy example of my two tables and a stored proc and my call in R Studio that demonstrate the issue for reproducibility.  I'm also using R Studio Version 1.3.1073 with R-4.0.2:
    CREATE TABLE [dbo].[etl_log](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [file_name] [nvarchar](300) NULL,
        [file_description] [nvarchar](300) NULL,
    PRIMARY KEY CLUSTERED
    (
        [id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO

CREATE TABLE [dbo].[etl_log_temp](
    [File Name] [varchar](255) NULL,
    [File Description] [varchar](255) NULL) on [PRIMARY]
    GO

CREATE PROCEDURE [dbo].[insert_files_to_etl_log]
AS

INSERT INTO [dbo].[etl_log]
           ([file_name] ,[file_description])
OUTPUT inserted.id, inserted.file_name
SELECT
       [File Name], [File Description]
FROM [dbo].[etl_log_temp]

GO

In R Studio, I'm calling:
files_succesfully_downloaded <- DBI::dbGetQuery(con, "exec [dbo].[insert_files_to_etl_log]")

My expected output into files_succesfully_downloaded should be a data frame that look something like this:
id      file_name
1       filex
2       filey
3       filez

Instead, I get the error mentioned above.


text:
Q: Reducing the page's height when Safari's soft keyboard is on After testing my application on iOS, I noticed that, unlike Android devices, the soft keyboard does not push the content above. It keeps the page's original height and lets the user scroll as usual. To fix this, I have attached an event listener to the viewport and made the container that holds all the visible content match the viewport's height.
window.visualViewport.addEventListener("resize", function() {
    document.querySelector("#content").style.height = window.visualViewport.height + "px";
});

The code does solve the problem to some extent since it does push the visible content above the keyboard. However, when the keyboard is visible, the  tag appears to ignore every single stylesheet and set itself to 100% of the window's height.
html, html body {
    height: auto;
}

I assume stopping the scrolling altogether may be a solution if the browser refuses to listen to the CSS no matter what. I, unfortunately, have no idea how to do this and, so far, have been out of luck finding a solution. Setting the overflow property of the <html></html> tag to hidden does not seem to do anything. Any help is appreciated!


text:
Q: AVAudioPlayer crashes my app with EXC_BAD_ACCESS(code=1) when running multiple sounds at once Hello my sounds play but if I keep hitting multiple sounds rapidly I    get a crash EXC_BAD_ACCESS(code=1).  Been trying for a long time to figure this one out.  I tried using properties as well but no luck. Anybody ever seen this happen when playing multiple simultaneous sounds?
@interface SoundBoardScene : SKScene<AVAudioPlayerDelegate>
AVAudioPlayer  *Player1;
AVAudioPlayer *Player2;
AVAudioPlayer *Player3;
AVAudioPlayer *Player4;
AVAudioPlayer *Player5;
AVAudioPlayer *Player6;
AVAudioPlayer *Player7;
AVAudioPlayer *Player8;

-(AVAudioPlayer*) PlayAudioFile:(AVAudioPlayer*)player withAudioFileName:(NSString*)audioFileName withExtensionType:  (NSString*)audioFileExtension withLoopCount:(uint)NumberOfLoops

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                     pathForResource:audioFileName
                                     ofType:audioFileExtension]];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.numberOfLoops = NumberOfLoops;
return player;

}
-(void) initSounds

Player1 = [animalObject PlayAudioFile:Player1 withAudioFileName:@"Sound1" withExtensionType:@"mp3" withLoopCount:0];
 Player1.delegate=self;
Player2 = [animalObject PlayAudioFile:Player2 withAudioFileName:@"Sound2" withExtensionType:@"mp3" withLoopCount:0];
Player2.delegate=self;

etc
etc

}
if([node.name isEqualToString:@"Sound1"])
    {

            [Player1 play];

    }
if([node.name isEqualToString:@"Sound2"])
    {

            [Player2 play];

    }

A: there is no need to use avplayer for play sound file.
try this code
[self runAction:[SKAction repeatAction:[SKAction playSoundFileNamed:@"pew1.wav" waitForCompletion:NO] count:count]];


text:
Q: Lua - xterm 256 colors gradient scripting This has been bothering me for a bit, and I'm not sure there is an answer out there. I know there are modules such as Love2D that accomplish gradients, which I'm guessing uses RGB coloring. However, I'm needing to find something quite similar using xterm 256 colors, but I cannot seem to find a gradient map anywhere to assist with this.
My guess is that I'll have to create a "nearest to RGB color" and create a gradient from that, matching the corresponding RBG to the nearest xterm match, but to be quite honest, I don't even know where to begin with this. I know there's a "convert xterm to RGB hex" script in Python (located here), but as I don't know Python, I don't know how to convert that to Lua.
Ultimately, what I want to do is be able to turn text into a rainbow gradient, more or less. I currently have a function to return xterm colors, but it's completely random, and the output can be a bit harsh to read. Here's what I have for that code. The @x stands for "convert to xterm color", and it is followed by a three digit code (001 to 255), followed by the text.
function rainbow(text)
    local rtext = ""
    local xcolor = 1
    local sbyte = 1
    for i = 1, #text do
        math.randomseed(os.time() * xcolor * sbyte)
        sbyte = string.byte(i)
        xcolor = math.random(1, 255)
        rtext = rtext .. "@x" .. string.rep("0", 3 - string.len(xcolor)) .. xcolor .. text:sub(i,i)
    end
    return rtext
end

So, for example, print(rainbow("Test")) would result in:
@x211T@x069e@x154s@x177t
Obviously, this is not a gradient, and is not what I want to end up with. Is what I want possible, or is it a lost cause?
Edit
I know the limitiations of 256 colors, and I know there's not a whole lot of wiggle room. As was pointed out in the comment, there'd be a lot of the same color matching, so I'd get a string of the same colors. That's fine with me, really. No matter how many actual transitions it makes, I'd like for it to closely simulate a gradient.
What would be nice is if I were able to at least create color groups properly without having to poll the charts. What I may wind up having to do, I guess, is create a table of "compatible colors schemes" and work with that, unless someone has a better idea.

A: Define nearest_term256_color_index function:
local abs, min, max, floor = math.abs, math.min, math.max, math.floor
local levels = {[0] = 0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff}

local function index_0_5(value) -- value = color component 0..255
   return floor(max((value - 35) / 40, value / 58))
end

local function nearest_16_231(r, g, b)   -- r, g, b = 0..255
   -- returns color_index_from_16_to_231, appr_r, appr_g, appr_b
   r, g, b = index_0_5(r), index_0_5(g), index_0_5(b)
   return 16 + 36 * r + 6 * g + b, levels[r], levels[g], levels[b]
end

local function nearest_232_255(r, g, b)  -- r, g, b = 0..255
   local gray = (3 * r + 10 * g + b) / 14
   -- this is a rational approximation for well-known formula
   -- gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
   local index = min(23, max(0, floor((gray - 3) / 10)))
   gray = 8 + index * 10
   return 232 + index, gray, gray, gray
end

local function color_distance(r1, g1, b1, r2, g2, b2)
   return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2)
end

local function nearest_term256_color_index(r, g, b)   -- r, g, b = 0..255
   local idx1, r1, g1, b1 = nearest_16_231(r, g, b)
   local idx2, r2, g2, b2 = nearest_232_255(r, g, b)
   local dist1 = color_distance(r, g, b, r1, g1, b1)
   local dist2 = color_distance(r, g, b, r2, g2, b2)
   return dist1 < dist2 and idx1 or idx2
end

Define generate_gradient function which inserts @x... in your text:
local unpack, tonumber = table.unpack or unpack, tonumber

local function convert_color_to_table(rrggbb)
   if type(rrggbb) == "string" then
      local r, g, b = rrggbb:match"(%x%x)(%x%x)(%x%x)"
      return {tonumber(r, 16), tonumber(g, 16), tonumber(b, 16)}
   else
      return rrggbb
   end
end

local function round(x)
   return floor(x + 0.5)
end

local function generate_gradient(text, first_color, last_color)
   local r, g, b = unpack(convert_color_to_table(first_color))
   local dr, dg, db = unpack(convert_color_to_table(last_color))
   local char_pattern = "[^\128-\191][\128-\191]*"
   local n = max(1, select(2, text:gsub(char_pattern, "")) - 1)
   dr, dg, db = (dr - r)/n, (dg - g)/n, (db - b)/n
   local result = ""
   for c in text:gmatch(char_pattern) do
      result = result..("@x%03d"):format(nearest_term256_color_index(
         round(r), round(g), round(b)))..c
      r, g, b = r + dr, g + dg, b + db
   end
   return result
end

Test it inside terminal:
local function print_with_colors(str)
   print(
      str:gsub("@x(%d%d%d)",
         function(color_idx)
            return "\27[38;5;"..color_idx.."m"
         end)
      .."\27[0m"
   )
end

local str = "Gradient"
local blue, red = {0, 0, 255}, "#FF0000"
str = generate_gradient(str, blue, red)  -- gradient from blue to red
print(str)
print_with_colors(str)

rainbow() is not a gradient, it would be a chain of several gradients.

A: I am done with this. Just using ANSI 256 color escape code pattern.
-- ref ANSI 256 color = https://robotmoon.com/256-colors/
str = '\27[38;5;34mG\27[38;5;35mr\27[38;5;36ma\27[38;5;37md\27[38;5;38mi\27[38;5;39me\27[38;5;50mn\27[38;5;51mt\27'
if f then f.Destroy() end
f=createForm()
pb=createPaintBox(f)
pb.Canvas.Font.Size=52
pb.Align='alClient'

local rect={}
rect.Left=0
rect.Top=0
rect.Right=pb.Width
rect.Bottom=pb.Height

pb.Repaint()
pb.Canvas.Font.Style='fsBold'
pb.Canvas.Font.Name='Trebuchet MS'
pb.Canvas.Font.Color = 0
pb.Canvas.textRect(rect,16,54,'Gradient')
pb.Canvas.textRect(rect,12,50,str)

Thank you @Egor Skriptunoff for the inspirited.


text:
Q: $\mu_5=\{\xi \in \mathbb{C}| f(\xi)=0\}$,is $\mu_5\subset\mathbb{C}/\{0\}$ a finite subgroup? Consider $f(x)\in \mathbb{Z[x]}$ such that $f(x)=x^5-1$.
Now let $\mu_5=\{\xi \in \mathbb{C}| f(\xi)=0\}$,is $\mu_5\subset\mathbb{C}/\{0\}$ a finite subgroup?
I considered the factorization of $f(x)$ whose elements are in $\mu_5$ but i have problems in showing that $\mu_5$ is closed for inverse.

A: $\xi^5-1=0\implies\frac{1}{\xi^5}(\xi^5-1)=0\implies(1-\frac{1}{\xi^5})=0\implies\left( \frac{1}{\xi}\right)^5-1=0\implies\frac{1}{\xi}\in \mu_{5}$

A: Hint: A polynomial of degree $n$ has $n$ zeros in its splitting field. Here $\Bbb C$ is algebraically closed and the polynomial $f(x)=x^5-1\in{\Bbb Z}[x]$ has all its 5 roots in $\Bbb C$. These roots are the fifth roots of unity, which also form a cyclic group of order 5.


text:
Q: Log4j 2 root logger overrides everything? I am relatively new to Log4j 2. Currently, I have this configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <Appenders>
    <File name="DebugFile" fileName="../../logs/debug.log">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </File>
    <File name="BenchmarkFile" fileName="../../logs/benchmark.log">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </File>
  </Appenders>
  <Loggers>
    <Logger name="com.messaging.main.ConsoleMain" level="debug">
      <AppenderRef ref="DebugFile"/>
    </Logger>
    <Logger name="com.messaging.main.ClientMain" level="debug">
      <AppenderRef ref="BenchmarkFile"/>
    </Logger>
    <Root level="error">
      <AppenderRef ref="DebugFile"/>
    </Root>
  </Loggers>
</Configuration>

If I log something in these two classes ConsoleMain and ClientMain via a static Logger
    static Logger _logger = LogManager.getLogger(ClientMain.class.getName());

and
    static Logger _logger = LogManager.getLogger(ConsoleMain.class.getName());

they ALWAYS use the appender and level of the root logger. If the level of the root logger is "error" as above, it never shows any debug level logging output, even if the level of the individual loggers is debug. Also, it always appends to the log file specified in the root logger and not the one specified in the logger of the classes.
So, it seems that the root logger somehow overrides everything. How do I get log4j to actually use the appender and the level of the loggers of the classes?
I tried removing the appender of the root, but then it does not log anything.
Thank you!

A: I tried your setup but I cannot reproduce the issue. Here is the code I used:
package com.messaging.main;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClientMain {
    public static void main(String[] args) throws Exception {
        Logger logger = LogManager.getLogger(ClientMain.class);
        logger.debug("debug from ClientMain");
    }
}

package com.messaging.main;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ConsoleMain {
    public static void main(String[] args) throws Exception {
        Logger logger = LogManager.getLogger(ConsoleMain.class);
        logger.debug("debug from ConsoleMain");
    }
}

when I run these with your exact config file I get the following output:
benchmark.log:
07:59:51.070 [main] DEBUG com.messaging.main.ClientMain - debug from ClientMain

debug.log:
07:59:51.070 [main] DEBUG com.messaging.main.ClientMain - debug from ClientMain
07:59:58.306 [main] DEBUG com.messaging.main.ConsoleMain - debug from ConsoleMain
07:59:58.306 [main] DEBUG com.messaging.main.ConsoleMain - debug from ConsoleMain

This is expected behaviour. The duplicate entries are normal as by default additivity is true in log4j, so both the Root logger and the named Loggers will log the same message (see http://logging.apache.org/log4j/2.x/manual/configuration.html#Additivity).
I'm not seeing the issue you are reporting that debug-level messages never appear in the log file when the Root level is "error".
Perhaps something else is going on. What version of log4j2 are you using (most recent is now beta9)? Can you also try to reproduce the issue with the bare minimum sample code above and see if the issue still occurs?


text:
Q: now After clicking other than this ._box_color state changed to false ,i need after clicking on colorpicker this state dont change to false Thats is my code in React functional component :
import { HexAlphaColorPicker,HexColorInput} from "react-colorful";

const props = {
 title:'colorPicker'
}
export default function ColorPicker(){
  const [color, setColor] = useState("#ffffff");
  const [isOpen, setIsOpen] = useState(false);

  const handlerOpenColorPicker = (e,id) =>{
    if(e.target.id !== props.title ){
         setIsOpen(false)
        }else if(id === props.title){
         setIsOpen(!isOpen)
         }else{
         return '';
         }
       }
document.body.addEventListener('click',handlerOpenColorPicker);
const handler = (e)=>{
 setColor(e)
 setIsOpen(true)
}
return(
  <>

{props.title}

     {isOpen ?
      <HexAlphaColorPicker color={color} onChange={(e)=>handler(e)} />
       :
      ''
     }
     <HexColorInput class="_text_color" color={color} onChange={setColor} prefixed alpha />

handlerOpenColorPicker(e,props.title)} style={{backgroundColor:color}}>

 </>
)

i need it to be closed after clicking anywhere except Colorpicker, except for the same element and Colorpicker.

A: To prevent the state from changing when clicking on the color picker, you can add a condition to check the target element's id before setting the state. In your current code, you are using the handlerOpenColorPicker function to handle the click event on the color picker and other elements. You can add a condition to check the target element's id before setting the state. Here's an example:

const handlerOpenColorPicker = (e,id) =>{
    if(e.target.id !== props.title ){
         setIsOpen(false)
        }else if(id === props.title){
         setIsOpen(!isOpen)
         }else{
         return '';
         }
       }

when the user clicks on the color picker element, the event's target id will be "colorPicker", which matches the id of the color picker. So, the setIsOpen(!isOpen) condition will be triggered and the state will not change to false. But when the user clicks on other elements, the target id will not match the color picker's id and the setIsOpen(false) condition will be triggered, so the state will change to false.
It would be better if you use React's onClick event instead of adding event listener to document.body.
You can also add a ref to HexAlphaColorPicker and HexColorInput, and check if the event target is inside of the refs.
You can stop event propagation in the onClick function of HexAlphaColorPicker and HexColorInput to prevent the click event from propagating to parent elements.


text:
Q: Exact Online Authorization I have registered two apps(app target as 'Test') on Exact online,redirect url for one of these application is azure hosted site and other with locally hosted site.
App with locally hosted site authorizes properly and returns token successfully.
however,it fails to authorize app with azure hosted site.
OAuth2 ProtocolVersion is V20.
Can anybody help with this?
Do we need to do some settings on azure portal for Oauth2 authentication for third party software's like Exact online in this case,to get request authorized properly?
Thanks in advance.
Code sample:
region Authorize request
     private static readonly ExactOnlineOAuthClient OAuthClient = new ExactOnlineOAuthClient();
     private Boolean AuthorizeClient()
    {
        OAuthClient.Authorize(returnUri);
        return (OAuthClient.Authorization != null);
    }
    #endregion

    #region ExactOnlineOAuthClient Class
    public ExactOnlineOAuthClient()
        : base(CreateAuthorizationServerDescription(), ClientIdentifier(), ClientSecret())
    {
        ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ClientSecret());
    }

     private static AuthorizationServerDescription CreateAuthorizationServerDescription()
    {
        var baseUri = "https://start.exactonline.nl";
        var uri = new Uri(baseUri.EndsWith("/") ? baseUri : baseUri + "/");
        var serverDescription = new AuthorizationServerDescription
        {
            AuthorizationEndpoint = new Uri(uri, "api/oauth2/auth"),
            TokenEndpoint = new Uri(uri, "api/oauth2/token")
        };

        return serverDescription;
    }
    private static string ClientIdentifier()
    {
        return "ClientIdentifier"; //valid client id
    }

    private static string ClientSecret()
    {
        return "ClientSecret"; //valid client secret
    }

    private void Authorize(Uri returnUri)
    {
        try
        {
            if (Authorization == null)
            {
                Authorization = ProcessUserAuthorization();
                if (Authorization == null)
                {
                    // Kick off authorization request
                    RequestUserAuthorization(null, returnUri);
                }
            }
            else
            {
                if (AccessTokenHasToBeRefreshed())
                {
                    RefreshAuthorization(Authorization);
                }
            }
        }
        catch(Exception ex)
        {

        }
    }
    #endregion


text:
Q: Android: How to create a HttpClient with self signed certificate and a SSL cache I have some trouble to realize a SSL connection with Android. My program sends data in an specific time interval. To kepp down the sent data volume I want to use a SSL cache.
Does anybody know how to create a HttpClient in Android with a self signed certificate and a SSL cache?
I want to use the HttpClient class and my solution looks like the following (ending in a CastException):
private HttpClient getNewHttpClient(Context context, InputStream sslCertificate) {
        SSLSessionCache sslSessionCache = new SSLSessionCache(context);
        SSLCertificateSocketFactory socketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(15000, sslSessionCache);

        KeyStore keyStore = getSSLKeyStore(sslCertificate);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        socketFactory.setTrustManagers(tmf.getTrustManagers());

        HttpParams connectionParameters = new BasicHttpParams();
        HttpProtocolParams.setVersion(connectionParameters , HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(connectionParameters , HTTP.UTF_8);
        HttpConnectionParams.setStaleCheckingEnabled(connectionParameters , false);
        HttpConnectionParams.setConnectionTimeout(connectionParameters , 4 * 1000);
        HttpConnectionParams.setSoTimeout(connectionParameters , 5 * 1000);
        HttpConnectionParams.setSocketBufferSize(connectionParameters , 8192);
        HttpClientParams.setRedirecting(connectionParameters , false);

        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("https",  (SocketFactory) socketFactory , 443));
        ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(connectionParameters, registry);

        HttpClient httpClient = new DefaultHttpClient(connectionManager, connectionParameters);

        return httpClient;
}

That´s the CastException while register the new build Scheme to the SchemeRegistry
 W/System.err(343): java.lang.ClassCastException: org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl cannot be cast to org.apache.http.conn.scheme.SocketFactory

A:     public class SimpleSSLSocketFactory extends
    org.apache.http.conn.ssl.SSLSocketFactory {
private javax.net.ssl.SSLSocketFactory sslFactory = HttpsURLConnection
        .getDefaultSSLSocketFactory();

public SimpleSSLSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, UnrecoverableKeyException {
    super(null);
    try {
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManager[] trustAllCerts = new TrustManager[] { new

                 X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }
        } };

        // Initialize the socket factory
        context.init(null, trustAllCerts, new SecureRandom());
        sslFactory = context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public Socket createSocket(Socket socket, String host, int port,
        boolean autoClose) throws IOException, UnknownHostException {
    return sslFactory.createSocket(socket, host, port, autoClose);
}

@Override
public Socket createSocket() throws IOException {
    return sslFactory.createSocket();
}

}
   U can call like this

                  try {
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory
                .setHostnameVerifier(SSLSocketFactory.
                    ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                params, registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        HttpPost httpPost = new HttpPost(url);
        HttpHost proxy = new HttpHost("50.104.5.277", 23333);

        //httpPost.setHeader("Content-Type", "text/xml");
        httpPost.setEntity(entity);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                proxy);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        output = EntityUtils.toString(httpEntity);

        // Toast.makeText(getApplicationContext(), xml, 1000).show();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return output;
}


text:
Q: before event shutil copy2 I want to use my own copy2 function when calling shutil.copytree. I will be using a regex on the dst to create a new dst(copy and rename). I see the function header for copy2 as shutil.copy2(src, dst, *, follow_symlinks=True).
If I were to create the following:
def my_copy2(???):
    return copy2(src, newdst...)

What should my function header look like, and what will I call copy2 with? I am uncertain what happens to the empty * and the symlink argument, i.e. do I care?
This works, but not same function signature as copy2:
#!/usr/bin/python

import shutil

def copy_and_rename(src,dst) :
    return shutil.copy2(src, dst.replace("pdf","zzz"))

SRC_DIR="srcjunk"
DEST_DIR="destjunk"
shutil.copytree(SRC_DIR, DEST_DIR, copy_function=copy_and_rename)

A: You can import the module inside the function or you can do it on the script. The documentation doesn't explain what is *. I would omit it.
from shutil import copy2
def my_copy2(src, newdst, ...)
    return copy2(src, newdst, ...)

Or with the import inside (also you could just do import shutil and then import with shutil.copy2):
def my_copy2(src, newdst, ...)
    from shutil import copy2
    return copy2(src, newdst, ...)

You must give enough parameters to your function that copy2 is able to run.
Abut using regex means that before using the string you could prepare it, adding the suffix, or adding the path where do you want to store it. This can be done inside your function or outside.


text:
Q: Angular multiple flex layout with angular material cards I wanted to implement the design below with cards using flex layout with the margin but is reponsive , I have tried the stackblitz below but cant seem to figure it out , the margin and layout is either destroyed with tried on other screens or wrong use of flex. Anyone can help me here with the correct implementation of flex layout with example design below ? help is highly appreciated. Thanks.
https://stackblitz.com/edit/angular-mat-card-example-flsnue?file=src%2Fapp%2Fapp.component.css

A: Here is your working solution

        <mat-card class="card">
            Height will adjust based on content
        </mat-card>

        <mat-card class="card">
        </mat-card>
        <mat-card class="card">
        </mat-card>

/* CSS */
.row {
  display: flex;
  flex-wrap: wrap;
}

.leftPannel {
  width: 35%;
  margin-right: 20px;
}

.rightPannel {
  flex: 1;
}

.card {
  margin-bottom: 20px;
  background-color: #fff;
}

@media only screen and (max-width: 600px) {
  .row {
    flex-direction: column;
  }
  .leftPannel {
    width: 100%;
    margin-right: 0;
  }
}


text:
Q: Armazenar variável dentro de um While estou com uma dúvida simples mas que ta me quebrando a cabeça:
tenho um form onde há vários checkbox, o valor do checkbox é um número de id, gostaria de criar algo que quando o usuário selecionar um determinado número de checks o sistema fazer uma consulta no banco pra cada id que o usuário selecionou.
Por exemplo, o user selecionou 3 checkbox, e eles contem id 1, 2 e 3, com esses parâmetros o sistema busca no banco o nome relacionado á cada id.
id 1 : nome exemplo 1
id 2 : nome exemplo 2
id 3 : nome exemplo 3
tentei com while, for etc...
segue código até o momento que me mostra o id selecionado:
$ocs_imp = $_POST['check_imprime'];
$total=count($ocs_imp);

$inicio = 0;
$ultimo = $total-1;
$arranjo = range($inicio, $ultimo);

     foreach ( arranjo as $n => $v ) {
        echo " o id ".$v." é: ".$ocs_imp[$v]."<br>";
                              }

o código acima me mostra, o id0 é 1, o id1 é 2, etc...
agora como posso usar isso para fazer uma consulta ao banco com esse id, e trazer a coluna "nome" deste id, fazendo essa consulta proporcional ao número de checks selecionados? obrigado e desculpa se ficou confuso.

A: Você pode usar algo assim:
$ids = $_POST['check_imprime'];

// só pra garantir que não terão strings injetadas aqui
foreach($ids as $k => $v) {
  $ids[$k] = (int)$v;
}

$ids = implode(',', $ids);

$sql = "SELECT nome FROM tabela WHERE id IN ($ids)";

// assumindo que as constantes já estejam declaradas...
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$res = $mysqli->query($sql);

while($row = $res->fetch_assoc()) {
   echo 'ID: ' . $row['nome'] . "\n"
}

Não testei esse código mas acho que dá pra você entender a ideia.


text:
Q: How to set android backend minSdk im working on an android app with some server-side business logic. Im using android studio and im creating that kind of app for a first time.
I am trying to use server-side application to login to a different system and return me a cookie, so my android application can tell, whether the set credentials are correct.
Here's my endpoint provided method.
/** Returns user with cookie set either to null or actual cookie from AIS */
@ApiMethod(name = "login")
public User login(@Named("loginName") String name, @Named("password") String password) {
    AISCommunicator aisCommunicator = new AISCommunicator();
    String cookieVal = aisCommunicator.login(password,name);

    User user = new User();
    user.setCookie(cookieVal);
    //user.setCookie("asdasdasd");

    return user;
}

AISCommunicator is a serverside bean. At the moment it's part of a code
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);

is marked as incorrect by Android studio, which tells me, that to use it, i need to declare minSdk level 9, while currently i have 1. How can i do that? I have set minSdk in my client's app, but it seems like it does not influence the serverside bean.
Anyway, the code is still runnable for some reason and the endpoint Bean returns 404 not found error at the moment.

A: Ignore Android Studio's error. This is one of its known and unfixed bugs.


text:
Q: Show that there does not exist a polynomial $f \in \mathbb{R}[x]$ such that $f^2(x) = f(x) \cdot f(x) = 1 + x + x^3$. Show that there does not exist a polynomial $f \in \mathbb{R}[x]$ such that $f^2(x) = f(x) \cdot f(x) = 1 + x + x^3$.
I really have no idea where to begin and would appreciate all help I can get to solve this.
i tried to use the information from this link Is there a polynomial $f\in \mathbb Q[x]$ such that $f(x)^2=g(x)^2(x^2+1)$ - because it resembles my doubt. But I couldn't do it.

A: Alternative approach:
$f(x)^2$ should be non-negative for all $x\in\mathbb R$.
What about $1+x+x^3$, particularly when $x$ is a negative number with large magnitude?

A: Hint:
If the degree of $f$ is $n$, what is the degree of $f^2$?

A: Any
$f(x) \in F[x], \tag 1$
where $F$ is any field, may be written
$f(x) = \displaystyle \sum_0^n f_i x^i = f_nx^n + \sum_0^{n - 1}f_ix^i, \; f_i \in F; \tag 2$
then
$f(x) \cdot f(x) = f_n^2x^{2n} + \text{lesser degree terms}; \tag 3$
it follows that $f(x) \cdot f(x)$ is always of even degree; but
$\deg \; x^3 + x + 1 = 3, \; \text{odd}, \tag 4$
so . . .
Note that
$F = \Bbb R \tag 5$
needn't hold to attain the above result.


text:
Q: What happens if we query the MongoDB database in the reverse order of compound index? I have the following index
Origin.SN_1_timestamp.milliseconds_-1_error_1

And I am running the following query
db.getCollection("error").aggregate([
{
   "$match":{
      "$and":[
         {
            "error":{
               "$ne":"No Error"
            }
         },
         {
            "timestamp.milliseconds":{
               "$gte":1617561000000
            }
         },
         {
            "timestamp.milliseconds":{
               "$lte":1617627557579
            }
         },
         {
            "Origin.SN":{
               "$in":[
                  "4090",
                  "4080"
               ]
            }
         }
      ]
   }
},
{
   "$group":{
      "_id":"$error",
      "count":{
         "$sum":1
      }
   }
},
{
   "$project":{
      "_id":0,
      "count":"$count",
      "error":"$_id"
   }
},
{
   "$sort":{
      "count":-1
   }
},
{
   "$limit":1
}
])

You can see that the order of the composite index is reversed in the query. Even though this query uses the above index in IXSCAN. Is there any performance loss in this?
Do I need to create another compound index in reverse order for a better performance?

A: I think the performance is not affected by the order of the index but you can explain the query and check the execution time:
Return Information on Aggregation Pipeline Operation