text:
Q: Prove that $4m + 1$ is a perfect square if $\{ \sqrt {n + \sqrt n}\} = \{\sqrt m\}$
Let $n,m \in \mathbb{N}-\{0\}$ so that $\{ \sqrt {n + \sqrt n}\} =
 \{\sqrt m\} \tag1$ Prove that $4m + 1$ is a perfect square.

($\{x\}$ is the fractional part of $x$)

No idea how to start. Replacing $\{x\}$ by $x-[x]$ doesn't seem to help.
Trying some values for $n, m$, it seems that (1) cannot hold unless $n$ is a perfect square.

A: So $$\tag1\sqrt{n+\sqrt n}-\sqrt m$$ is an integer $k\in\Bbb Z$.
Then
$\alpha_=\sqrt{n+\sqrt n}$ is a root of the polynomial
$$f(X)=X^4-2nX^2+n^2-n$$
but because   $\alpha=\sqrt m+k$, it is also a root of
$$g(X)=X^2-2kX+k^2-m $$
hence also a root of
$$\tag2\begin{align}&f(X)-(X^2+2kX+3k^2+m+2n)g(X)\\&=4k(k^2+m-n)X +(-3k^4+2(n+m)k^2+(n-m)^2-n)\end{align}$$
If $4k(k^2+m-n)\ne 0$, this implies that $\sqrt m$ and $\sqrt n$ are rational, so $m,n$ are perfect squares, say $n=a^2$, $m=b^2$ with $a,b>0$, and also $n+\sqrt n=a^2+a$ is a perfect square, say $a^2+a=c^2$ with $c>0$.
But then $a=c^2-a^2=(c+a)(c-a)$, contradicting $|c+a|>|a|>0$.
If $k^2+m-n=0$, the constant term in $(2)$ must be zero, i.e.,
$$\begin{align}0&=-3k^4+2(n+m)k^2+(n-m)^2-n
\\&= -3(n-m)^2+2(n+m)(n-m)+(n-m)^2-n\\
&=(4m-1)n-4m^2 \end{align}$$
i.e., $4m^2=(4m-1)n$.
As $4$ and $m$ are coprime to $4m-1$ and $4m-1\ge 3$, we arrive at a contradiction.
Therefore, we are left only with the case $k=0$.
But then $n+\sqrt n=m$, so that $\sqrt n$ is rational, hence a perfect square, say $n=a^2$, and finally
$$4m+1=4(a^2+a)+1=(2a+1)^2. $$

A: In this solution $\mathbb{N}$ denotes the set of positive integers.  For the set of nonnegative integers, $\mathbb{N}_0$ is used.
Note that $\mathbb{Q}\big[\sqrt{n+\sqrt{n}}\big]=\mathbb{Q}\big[\sqrt{m}\big]$.  If $\sqrt{m}$ is rational, then $\sqrt{n+\sqrt{n}}$ is also rational.  Thus, $n$ is a perfect square, and $$\frac{1}{2}\sqrt{(2a+1)^2-1}=\sqrt{a^2+a}=\sqrt{n+\sqrt{n}}\in\mathbb{Q}$$
if $n=a^2$ for some $a\in\mathbb{N}_0$. That is $(2a+1)^2-1$ is a perfect square, or $a=0$.  Then, $m=n=0$, which is a contradiction.  Hence, $\sqrt{m}$ is not a rational number.
We now see that $\sqrt{n+\sqrt{n}}\notin\mathbb{Q}$ lies in $\mathbb{Q}\big[\sqrt{m}\big]$.  As a minimal polynomial of $\sqrt{n+\sqrt{n}}$ in $\mathbb{Q}[X]$ divides $X^4-2n\,X^2+\left(n^2-n\right)$, the conjugate in $\mathbb{Q}\big[\sqrt{m}\big]$ of $\sqrt{n+\sqrt{n}}$ is one of the three possible values: (a) $\sqrt{n-\sqrt{n}}$, (b) $-\sqrt{n-\sqrt{n}}$, or (c) $-\sqrt{n+\sqrt{n}}$.
In the first two cases (a) and (b), a minimal polynomial of $\sqrt{n+\sqrt{n}}$ must then take the form $X^2-u\,X+v$ for some $u,v\in\mathbb{Q}$.  Note that $|v|=\sqrt{n^2-n}$, so $\sqrt{n^2-n}=\frac{\sqrt{(2n-1)^2-1}}{2}$ is rational.  This means $n=0$ or $n=1$.
In the last case (c), a minimal polynomial of $\sqrt{n+\sqrt{n}}$ must take the form $X^2-w$ for some $w\in\mathbb{Q}$.  Note that $w=n+\sqrt{n}$, so $n$ is a perfect square.  That is, $n=a^2$ for some $a\in\mathbb{N}_0$.
From the assumption that $m,n\neq 0$, the previous two paragraphs yield $n=a^2$ for some $a\in\mathbb{N}$.  Now, we use the given equality $\sqrt{n+\sqrt{n}}=\sqrt{m}+k$ for some $k\in\mathbb{Z}$.  This means $\sqrt{m}+k=\sqrt{a^2+a}$.  Thus, $$m+k^2+2k\sqrt{m}=a^2+a\in\mathbb{Q}\,.$$
Since $\sqrt{m}$ is irrational, we must have $k=0$.  Ergo, $m=a^2+a$, and $4m+1=(2a+1)^2$, as required.
P.S.: The condition $\mathbb{Q}\big[\sqrt{n+\sqrt{n}}\big]=\mathbb{Q}\big[\sqrt{m}\big]$ already implies $n=a^2$ and $m=r^2\left(a^2+a\right)$ for some $a\in\mathbb{N}$ and $r\in\mathbb{Q}_{>0}$.  The given equality only establishes $r=1$.


text:
Q: Proving a Limit I need to prove that
$$\displaystyle\lim_{n→∞} \frac{4n^5 − 1000}{2n^5 − n^3 + 2000} = 2$$
$n$ is a natural number.
I know that I need to use
$$∀ε > 0 : ∃N : n ≥ N ⇒ |(4n^5-1000/2n^5-n^3+200) − 2| <ε$$
I'm just not sure where exactly to go from here.

A: You already know what to do, so I'll give you a hint that will make it easier. Try this:
$$\dfrac{4n^5 − 1000}{2n^5 − n^3 + 2000}=\dfrac{(4n^5-2n^3 +4000)+(2n^3 -4000 -1000)}{2n^5-n^3+2000}= 2 +\dfrac{2n^3 -5000}{2n^5-n^3+2000} $$

A: For sufficiently large $n$
$\frac{4n^5 − 1000}{2n^5 − n^3 + 2000}= \frac {4n^5 -2n^3 +4000}{2n^5 − n^3 + 2000}+ \frac {2n^3 - 5000}{2n^5 − n^3 + 2000}=$
$2 + \frac{2}{2n^2 - 1 + 2000/n^3} - \frac {5000}{2n^5 - n+ 2000}$
You can use whatever method you want to show the limits of $ \frac{2}{2n^2 - 1 + 2000/n^3}$ and $\frac {5000}{2n^5 - n+ 2000}$ are zero.

A: From your question it appears that you do have some idea of $\epsilon$ based definitions. Thus for your problem at hand, for each $\epsilon > 0$ we need to find a positive integer $N$ such that $$\left|\frac{4n^{5} - 1000}{2n^{5} - n^{3} + 2000} - 2\right| < \epsilon$$ whenever $n \geq N$. Thus we have to achieve the goal $$\left|\frac{2n^{3} - 5000}{2n^{5} - n^{3} + 2000}\right| < \epsilon\tag{1}$$ and we note that if $n > 20$ then the denominator becomes positive and we can remove absolute value signs so that the goal is changed to $$\frac{2n^{3} - 5000}{2n^{5} - n^{3} + 2000} < \epsilon\tag{2}$$ Note further that $$\frac{2n^{3} - 5000}{2n^{5} - n^{3} + 2000} < \frac{2n^{3}}{2n^{5} - n^{3}} = \frac{2}{2n^{2} - 1} < \frac{1}{n}$$ So based on this inequality our goal will be achieved if we can ensure $1/n < \epsilon$ so that $n > 1/\epsilon$. It is now clear that we can choose $N = \max(20, \lfloor 1/n\rfloor + 1)$.

Note that such problems of verifying limit definition always require you to ensure that an inequality of type $(1)$ holds when the variable $n$ is constrained in a certain way. Now most beginners try to think of the problem as solving the inequality $(1)$ via algebraic manipulation because they are so used to solving equations like $ax + b = c$ or $ax^{2} + bx + c = 0$. Note that the inequality in $(1)$ is not to be solved (i.e. find all values of $n$ for which it holds), but rather it needs to be ensured to hold by constraining $n$ in a well specified manner ($n \geq N$).
We can ensure the inequality by finding a simple expression which is greater than LHS of $(1)$ (by using trivial laws of inequalities) and then instead ensure that this newer/simpler expression is less than $\epsilon$. This will ensure that our original expression (being less than the newer expression) also remains less than $\epsilon$. Proceeding in this manner gives us the constraint on $n$ very easily and our job is done.

Another point regarding formalism. Unless you are expert in mathematical logic (or real analysis, in which case you wouldn't have asked this question) it is simply useless to write statements like these $$\forall \epsilon > 0 : \exists N : n ≥ N ⇒ |(4n^5-1000/2n^5-n^3+200) − 2| <\epsilon$$ Such formalism does not help at all in gaining any understanding or in solving such problems. Analytical arguments are much more than symbol shunting and unless one grasps the meaning of such formalism very clearly it is best to avoid it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Number of Dice rolling till reaches a Stop Value I am trying to count the number of dice rolls till it reaches to a definite stop value. For example, I want the stop value as 100. I am writing the following code:
sumofsides <- function(stopvalue) {
  totalsum <- 0
  while (totalsum < stopvalue) {
    face <- sample(6, 1, replace= TRUE)
    totalsum <- totalsum + face
  }
  return(total value)
}

sumofsides(100)
[1] 103

When I am writing the following code to get the number of rolling till it reaches to the stop value. But it's always giving value of 1 which is wrong.
numofrolls <- function(stopvalue) {
  totalsum <- 0
  while (totalsum < stopvalue) {
    face <- sample(6, 1, replace= TRUE)
    totalsum <- totalsum + face
  }
  return(length(face))
}

numofrolls(100)
[1] 1

Any help is appreciated.

A: In your current loop, you are rewriting totalsum every iteration with a new value, so its length will never go beyond one. One solution would be to use a second variable to count the number of rolls:
rollUntil <- function(n) {
        nRolls   <- 0
        sumRolls <- 0
        while (sumRolls <= n) {
                sumRolls <- sumRolls + sample.int(6, 1)
                nRolls = nRolls + 1
        }
        return(nRolls)
}

# let's look at the distribution of rolls till 100:
hist(replicate(1000,rollUntil(100)))


text:
Q: QuickSight disable future dates greater than current date in Date Picker I have a requirement to disallow selecting future dates in Date picker in QuickSight. Want to know if any one came across this scenario
Eg : If today is 13th Dec 2021 I want date picker to disable all dates greater than 13th Dec 2021 from selection


text:
Q: Is there an easy wrapper to sync an array of documents between memory and MongoDB I'm trying to implement a moderation dashboard. Users post listings continuously and an Admin would delete or modify new unapproved Listings (approves a listing finally).
I found this amazing library the sync HTTP front and back magically.
As you can see, all data is backed in-memory in an array. I would like to keep the data synchronised based on ID in the MongoDB collection. Obviously, I can go through the implementation of each HTTP method, but this would be easier if any solution exists already.
Here a part of my longer code. I'm fulfilling each HTTP method: GET, POST, PUT, PATCH.
// CLONE BASE DATA LIST
let realtimeJSON
// TODO: secure, but doubleSecure (admin)
router.get('/admin', async function (req, res, next) {
  const listings = await mongoQueries.getDocumentsForApproval()
  realtimeJSON = listings.documents
  // realtimeJSON.forEach((a, idx) => a.id = idx+1)
  res.send(realtimeJSON)
})

router.get('/dashboard', function (req, res) {
  res.render('admin', {})
})

// CREATE
router.post('/admin/', function (request, response) {
  console.log('--- POST 200 ---')
  realtimeJSON.push(request.body)
  // Return list
  response.send(realtimeJSON)
})
...

The array is realtimeJSON.


text:
Q: Parsing two xml files together I have two xml files which i need to parse at the same time using NSXMl parser (not sequentially). These files have different data that will be displayed in uiLabel's in tableviewCell. I have successfully parse one xml file. I have also looked into apple docs but it says you can only parse one xml file at a time. is there any other way of doing it? Please help
That is how i am currently parsing two xm files.
- (void)viewDidLoad

{
if(!_suraDict || ![_suraDict count])
{
    _suraTitle = [NSMutableArray array];
    _suraDict =[NSMutableDictionary dictionary];
    _indexArray = [NSMutableArray array];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"simple" ofType:@"xml"];
    NSData *Mydata = [NSData dataWithContentsOfFile:filePath];

    _transTitle = [NSMutableArray array];
    _transDict =[NSMutableDictionary dictionary];
    _indexArray2 = [NSMutableArray array];
    NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"en.yusufali" ofType:@"xml"];
    NSData *Mydata2 = [NSData dataWithContentsOfFile:filePath2];
    NSXMLParser *parser = [[NSXMLParser alloc]initWithData:Mydata];
    NSXMLParser *parser2 = [[NSXMLParser alloc]initWithData:Mydata2];

    [parser2 setDelegate:self];
    [parser2 parse];
    [parser setDelegate:self];
    [parser parse];
}

else{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
       self.detailViewController.detailItem = [ _suraDict valueForKey:[_indexArray objectAtIndex:0]];
        self.detailViewController.detailItem2 = [ _transDict valueForKey:[_indexArray2 objectAtIndex:0]];
        }
    }

[super viewDidLoad];

   self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
}

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    if([elementName isEqualToString:@"sura"]){

        _sura = [NSMutableString string];

        _sura = [attributeDict objectForKey:@"name"];
    }
    else if([elementName isEqualToString:@"aya"]){
        _aya = [NSMutableString string];

        [_suraTitle addObject:[attributeDict objectForKey:@"text"]];
    }

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

    if([elementName isEqualToString:@"sura"]){
        [_suraDict setObject:_suraTitle forKey:_sura];
        [_indexArray addObject:_sura];
        _suraTitle = [NSMutableArray array];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

     //  NSLog(@"foundCharacters : %@", string);

}

- (void)parserDidEndDocument:(NSXMLParser *)parser{

    [[AppDelegate modelController]setcountArrayDict:_suraDict];
    [[AppDelegate modelController]setIndexArray:_indexArray];

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        self.detailViewController.detailItem = [ _suraDict valueForKey:[_indexArray objectAtIndex:0]];
    }
}

- (void)parser2:(NSXMLParser *)parser2 didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict2{
    if([elementName isEqualToString:@"sura"]){

        _sura2 = [NSMutableString string];

        _sura2 = [attributeDict2 objectForKey:@"name"];
    }
    else if([elementName isEqualToString:@"aya"]){
        _trans = [NSMutableString string];

        [_transTitle addObject:[attributeDict2 objectForKey:@"text"]];
    }

}

- (void)parser2:(NSXMLParser *)parser2 didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

    if([elementName isEqualToString:@"sura"]){
        [_transDict setObject:_transTitle forKey:_sura2];
        [_indexArray2 addObject:_sura2];
        _transTitle = [NSMutableArray array];
    }
}

- (void)parser2:(NSXMLParser *)parser2 foundCharacters:(NSString *)string{

        NSLog(@"foundCharacters : %@", string);

}

- (void)parser2DidEndDocument:(NSXMLParser *)parser2{

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        self.detailViewController.detailItem2 = [ _transDict valueForKey:[_indexArray2 objectAtIndex:0]];
    }
}

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender   //valueforkey means the aayahs
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

        DetailViewController *viewcontroller= [segue destinationViewController];
        viewcontroller.selectedRow=indexPath.row;
        [viewcontroller setDetailItem:[ _suraDict valueForKey:[_indexArray objectAtIndex:[indexPath row]]]];
        [viewcontroller setDetailItem2:[ _transDict valueForKey:[_indexArray objectAtIndex:[indexPath row]]]];
    }
}


text:
Q: WPF datepicker validation error appears when binding value is null I have a WPF application where I am using a date picker that is bound to an entity framework(with SQL server) entity's date field.  I bind it as follows:
<DatePicker x:Name="dtComplete" Style="{StaticResource FTC_DatePicker}" Grid.Column="2" Grid.Row="7" Grid.ColumnSpan="3"
Text="{Binding dtComplete, Mode=TwoWay, ValidatesOnDataErrors=True}"/>

The binding works fine and can be updated to the entity.
My problem is that when the underlying database field is null, I get the select a date watermark, which I want, but that watermark is being validated and coming back as not being of a date format.  I want to keep the watermark, but not have the validation trigger until the user changes the input.  Also, I want to keep ValidatesOnDataErrors=True because I use that somewhere else to evaluate business logic.
To see what I mean, here is a form that uses the datepicker with a null value for the date, you can see the validation error:

The output window when debugging gives the following validation conversion error:

System.Windows.Data Error: 7 : ConvertBack cannot convert value ''
  (type 'String'). BindingExpression:Path=dtComplete;
  DataItem='job_BF0D6052EEADCDA3C2B6D1A174D77C322D5AB16A035F214705610767131A80F0'
  (HashCode=17930557); target element is 'DatePicker'
  (Name='dtComplete'); target property is 'Text' (type 'String')
  FormatException:'System.FormatException: String was not recognized as
  a valid DateTime.    at System.DateTime.Parse(String s,
  IFormatProvider provider)    at System.Convert.ToDateTime(String
  value, IFormatProvider provider)    at
  System.Convert.ChangeType(Object value, Type conversionType,
  IFormatProvider provider)    at
  System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter
  converter, Object value, Type sourceType, Object parameter,
  CultureInfo culture)'

Can someone help me get rid of this validation error until the user changes the input?
Thanks in advance

A: Figured it out:
I was binding to the text value of hte datePicker, so it was trying to validate the watermark text as a date, but what I really should have been doing was binding to the selectedDate Property as follows:
<DatePicker x:Name="dtComplete" Style="{StaticResource FTC_DatePicker}" Grid.Column="2" Grid.Row="7" Grid.ColumnSpan="3"
 SelectedDate="{Binding dtComplete, Mode=TwoWay, ValidatesOnDataErrors=True}" />

This now behaves as I want, the select a date watermark is still there and the binding date value works.  Its all too obvious now.  Simple fix

A: The problem is actually that the standard behavior of the datepicker is to use the selected value to highlight the day on the calendar.  Since you are putting a non-date value in the value property, when the calendar is activated, it doesn't know what to do.  There is an event "dropdown" that fires when the datepicker calendar is opened.  You could set the value to today once it is opened, which will remove your error.
What I'm not clear on is how you are getting that text to display in the first place.  I thought the datepicker validated any value entered into it.


text:
Q: What is the preferred way to use Type when defining getters and setters for boolean property inputs when using angular-cdk's coerceBooleanProperty()? Angular Material2 & CDK make extensive use of coerceBooleanProperty in setters for boolean property inputs, but does not use Type consistently. Within their own code, in some cases we see both the getter return value and the setter argument as well as the internal property typed boolean. For example:
@Input()
get myProperty(): boolean { return this._myProperty; }
set myProperty(value: boolean) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty: boolean = false;

In other cases we see only the setter argument typed (this seems to be the most common pattern in Material2 & CDK):
@Input()
get myProperty() { return this._myProperty; }
set myProperty(value: boolean) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty = false;

Sometimes we see getter and setter typed as any:
@Input()
get myProperty(): any { return this._myProperty; }
set myProperty(value: any) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty = false;

Sometimes there is no typing on either, but the internal property is deliberately typed boolean:
@Input()
get myProperty() { return this._myProperty; }
set myProperty(value) { this._myProperty = coerceBooleanProperty(value); }
private _myProperty: boolean = false;

It seems to me that the first example - typing both the getter return value and the setter argument as boolean - is the 'correct' approach, because this forces the application or library typescript code to use the property properly. But the lack of consistency in their own code use makes me wonder if there's something I haven't considered. Or perhaps it is merely a matter of newer implementations improving upon older implementations.
What is the preferred pattern here and why?


text:
Q: How to save multiples refs into one document in MongoDB with mongoose? I'am trying to save multiple tags to a specific product I just created. I succeeded to push the tags into the product collection, but when I try to save it then I got an error : Can't save() the same doc multiple times in parallel.
I'am using mongoDB, node and Mongoose.
Here are my Schemas

var tagSchema = mongoose.Schema({
    tagname: String,
});

var tag = mongoose.model('Tag', tagSchema);

var Item = new Schema({
    title : String,
    description : String,
    price : Number,
    tags:  [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Tag"
    }]
});

var product = mongoose.model('Product', Item);

And here my code in node.js when I try to create a new product with the associated tags in the DB (coming from a HTML form)

product.create(req.body.product, function(err, newitem){
            if(err){
                console.log(err);
            }else{

             console.log(req.body.tags); // gives ["fun","cheap"] from the form
             req.body.tags.forEach(function(newtag){
             tag.findOne({tagname : newtag},function(err, finalcast){

             newitem.tags.push(finalcast);
             console.log(newitem); // gives the product with the tag collections in it.

               });
              newitem.save(); // error Can't save() the same doc multiple times in parallel.
              console.log(newitem); // the product collection has an empty tags[]

               });

                 res.redirect("/");

            }

        });

How can I save the tags collection direcly in the product all at once ? Is is better to create the product and then insert the tags one by one using push ?
Thanks a lot for your help !

A: The problem may be because you trying to push object rather than _id by doing
newitem.tags.push(finalcast);

Try to push object's _id like this:
newitem.tags.push(finalcast._id);

A: I think it has something to do with Asynchrone JS but i'am not sure. The loop doesn't seems to be a good Idea there...
How can I easily save multiples tags documents into one product document ?

A: Ok after hours of working on it i found a solution. I really don't know if it's a good way to do it but it works. I insert a if() inside the forEach to save only when the forEach loop is done:
 req.body.tags.forEach(function(newtag, index){
                    tag.findOne({tagname : newtag},function(err, finalcast){

                    newitem.tags.push(finalcast);

                    if(index + 1 == req.body.tags.length){
                    newitem.save();
                    res.redirect("/");

                    }
               });

A: You are performing them all at once in your forEach loop which makes it hard to know when the database operation is done. It also means that you are triggering res.redirect before the operation has actually finished. I would use async/await for this. I wrote this pretty quickly and haven't tested it but I think it should work:
const tagSchema = mongoose.Schema({
  tagname: String
})

const Tag = mongoose.model('Tag', tagSchema)

const itemSchema = new Schema({
  title: String,
  description: String,
  price: Number,
  tags: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Tag"
  }]
})

const Product = mongoose.model('Product', itemSchema)

const createProduct = async (req, res) => {
  const { tags, product } = req.body

  try {
    const product = new Product(product)

    for (let i = 0; i < tags.length; i++) {
      const tagName = tags[i]
      const existingTag = await Tag.findOne({ tagname: tagName })

      if (!existingTag) {
        await new Tag({ tagname: tagName}).save()
      }
    }

    await product.save()

    res.redirect('/')

  } catch (error) {
    console.log(error)
  }
}

In the code I've done a couple of things:

*

*Use async/await in order to do one thing at a time instead of doing them synchronously.

*Cleaned up the code: Indentation etc was a little messy (I've used StandardJS style)

*Used pascal case for models since they are object constructors. There's a reason why models start with a capital letter.

*Used for loop instead of forEach because forEach doesn't work with async.


text:
Q: Impossible to checkout a git commit I'm trying to checkout a specific commit that I see on GitHub:
https://github.com/mapbox/node-sqlite3/commit/b8907e79fc3fb52803b5a05c106948911dcd77ac
However, a local checkout fails:
$ git checkout b8907e79fc3fb52803b5a05c106948911dcd77ac
fatal: reference is not a tree: b8907e79fc3fb52803b5a05c106948911dcd77ac

A git reset failed with the same error.
Any ideas?

A: That commit was in that repository at one time.
It was subsequently deleted from the repository, so new clones of that repository do not get that particular commit.  (Deletion is a bit tricky, but for example, this can happen because a pull request gets modified—the commit was there because of the pull request, then the pull request itself gets updated with new-and-improved commits.  The replacement commit is the one ultimately used, and the original expires on its own after a few more days.)
It still is present on GitHub because GitHub does not always clean out everything immediately.  In this case, however, they have not cleaned things out for quite a long time, and it's not clear why it's still accessible via the GitHub web interface at all.  This commit is not reachable from a pull request either (there are 218 pull requests hanging on to commits but this is not among them).  I wonder if links from "issues" pages might also keep otherwise-unreachable commits alive, on GitHub.
Following this commit backwards, through its parent links on GitHub, reveals a whole sequence of commits that seem to have been replaced with new-and-improved versions at some point.

A: Depending on how frequently GitHub runs a git gc in each of its repository, that commit, if it was deleted, might still be on GitHub side.
A trick would then be to use the GitHub Tags API to create a tag object for that old commit.
You could the do a git fetch --tags, and that would be enough to enable a local checkout of that commit.


text:
Q: How to read a table from a Box shared link (url) in R? I need to read in a text file shared via Box.com - I'll use mtcars.txt as an example.
 WES.ped.exp <-
 read.table("https://ucsf.box.com/s/tht30egddqjqlq3koucqy7rhtzkh3ydi")

Problem is the shared link takes me to a viewer interface, from where one is supposed to click Download, and not directly to the plain .txt file.
When reading the table, it just reads HTML lines, like so:

I've tried curl, scan and just read.table , any ideas?

A: Go to the share setting of the file in question. Click on "Share", go to the settings, and make sure the file's shared link is set to "Anyone with the link can view and download this file", in order to generate a direct link.
Go to the little settings icon, copy the "Direct Link", and paste it into the following:
read.table("https://ucsf.box.com/shared/static/whateverthelinksays.txt")


text:
Q: Display Installment product prices with a shortcode by product ID in WooCommerce I am trying to display a formula installment price by product price using shortcode, but not getting the variant price
add_action('woocommerce_single_product_summary', 'display_product_installment_price', 15 );

function display_product_installment_price() {
    global $product;

    $id = $product->get_id();
    $a=$product->get_price();
    $b = 1.065;
    $c = 12;
    $d = $a * $b;
    $total = $d/$c;

    return "giá trả góp là $total đ/tháng" ;
}

add_shortcode( 'test', 'display_product_installment_price' );


text:
Q: CSS - Hover affecting two elements with two different background-colors I have a list element with two tags inside of it, anchor tag and a span - tag.
What I'd like to achieve is that when hovering over anchor tag, the actual
background would change to black where as the span tag's background would change to green.
Is this possible with CSS3 or do I need to use JavaScript?
I won't be pasting any code here, since it's pretty straight forward.
Thanks in advance!
Here's the CSS so far:
#left_control_links li a {

    font-family: 'Open Sans', sans-serif;
    font-size: 14px; padding: 15px 15px 15px 20px;
    font-weight: 600; float: left; width: 83%;
    color: #dfdfdf; text-decoration: none;
}
#left_control_links li a:hover {

    background: #272727;

}
span.list_total_count {

    display: inline-block; background-color: #2c2c2c; float:right; min-width: 31px;
    color: #fcfcfc ;padding: 5px 0 5px 8px;
    font-family: Verdana; font-size: 13px; position: relative; top: 0px; left: 15px;
}

HTML:

    Subjects
    <?=$total_subjects?>

    Users
    <?=$total_users?>

Kyselyiden seuranta

A: Sure
See this example:
http://jsfiddle.net/gWXhJ/
add the parent :hover and apply css added their children

    this is link
    Text test

A: For the code in question, CSS to change span background color on mouse over:
#left_control_links li a:hover span.list_total_count {
    background: none #aaa;
}

I am posting this, cause CSS specificity may have main rule in similar examples. Very good article at: http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/


text:
Q: NiFi SpringContextProcessor interrupts the flow I added a SpringContextProcessor to my NiFi flow, it executes as expected and updates the FlowFile content and attributes. But in the data provenance section of NiFi instead of seeing SEND/RECEIVE, I am seeing
03/27/2017 11:47:57.164 MDT RECEIVE 42fa1c3f-edde-4cb7-8e73-ce752f7e3d66
03/27/2017 11:47:57.163 MDT DROP    667094a7-8eef-4657-981a-dc9fdc6c4056
03/27/2017 11:47:57.163 MDT SEND    667094a7-8eef-4657-981a-dc9fdc6c4056

Looks like the original message is being dropped and replaced by a new message. I haven't seen this behavior in other components, i.e. they all seem to preserve the original Flow File UUID. Simplified version of the Spring processor code:
@ServiceActivator(inputChannel = "fromNiFi", outputChannel = "toNiFi")
public Message<byte[]> process1(Message<byte[]> inMessage) {
    String inMessagePayload = new String(inMessage.getPayload());
    String userId = getUserIdFromDb(inMessagePayload);
    String outMessagePayload = inMessagePayload + userId;

    return MessageBuilder.withPayload(outMessagePayload.getBytes())
            .copyHeaders(inMessage.getHeaders())
            .setHeader("userId", userId)
            .build();
}

Is there a way to preserve the original Flow File UUID in the outgoing message?

A: This is probably an oversight on our end, so yes please do raise a JIRA.
However as a workaround you can try to extract FlowFile attributes from the incoming Message headers and then propagate them back to the outgoing message.
public Message<byte[]> process1(Message<byte[]> inMessage) {
    String myHeader = inMessage.getHeader("someHeader");
    . . .
    return MessageBuilder.withPayload(outMessagePayload.getBytes())
            .copyHeaders(inMessage.getHeaders())
            .setHeader("userId", userId)
            .setHeader("someHeader", myHeader)
            .build();
}


text:
Q: libGDX compiles only a Black Screen SOLVED!!! Seems the image wasnt in a proportionate size, eg, 64x64, 128x128
Made a basic Hello World and this compiled all good, but when I try and get a basic graphic to display, all that shows is blackness. basically following a tutorial word for word and it still seems to be doing this. Any ideas anyone?
package com.me.mygdxgame;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class MyGdxGame implements ApplicationListener {

SpriteBatch batch;
BitmapFont font;
Texture mario;

    @Override
    public void create() {
        mario = new Texture(Gdx.files.internal("mario.jpeg"));
        batch = new SpriteBatch();
        font = new BitmapFont();
        font.setColor(Color.CYAN);
    }

    @Override
    public void dispose() {
        batch.dispose();
        font.dispose();
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(mario, 200, 200);
        batch.end();

    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

Just realised there was an error code coming up. file name is definitely correct.
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: data/mario.png
    at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:140)
    at com.badlogic.gdx.graphics.glutils.FileTextureData.prepare(FileTextureData.java:64)
    at com.badlogic.gdx.graphics.Texture.load(Texture.java:142)
    at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:133)
    at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:112)
    at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:104)
    at com.me.mygdxgame.MyGdxGame.create(MyGdxGame.java:30)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: data/mario.png (Internal)
    at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:133)
    at com.badlogic.gdx.files.FileHandle.length(FileHandle.java:563)
    at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:218)
    at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:137)
    ... 8 more

A:
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: data/mario.png (Internal)

It can't find the image "mario.png" in the data folder. Make sure you have the image in the android asset folder (Android Project -> Assets -> Data -> mario.png) .
You may want to look into how to read stack-traces (Big long error report thing) it will save you lots of time in the future.
Edit: Here is link for you on stack-traces

A: Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: data/mario.png (Internal)

He couldn't find mario.png. I recommend, if you don't use an Assets folder, to create another source folder containing all of your resources. After that, you can call Gdx.input.classpath(String classpath) to load a file from the actual exported .jar, without having to hardcode the paths.


text:
Q: How do I get the YouTube video ID from GDataEntryYouTubeVideo? I'm using the GData/YouTube direct upload api. When the upload is finish the following method gets called:
- (void)uploadTicket:(GDataServiceTicket *)ticket
  finishedWithEntry:(GDataEntryYouTubeVideo *)videoEntry
           error:(NSError *)error {

How can I get the YouTube video ID of the just uploaded video from the returned (GDataEntryYouTubeVideo *)videoEntry?

A: You can get the URL from
[[[[videoEntry mediaGroup] mediaContents] objectAtIndex:0] URLString];

This comes with some query string cruft, but the base URL is the video (once the processing's been completed).

A: Using this worked for me:
NSString * videoID = videoEntry.mediaGroup.videoID;


text:
Q: Spring AntPathMatcher behave differently when pattern last char is '/' The spring version I used is 4.3.7-SNAPSHOT and The default path separator is /
I found that when patter string last char is '/', while path string last char is NOT '/', the AntPathMatcher behave differently, please see the code below
public class AntPathMatcher4SpringTest {

private AntPathMatcher matcher = new AntPathMatcher();

@Test
public void test1() {
    String patter1 = "/com/abc/def/x.html/";
    String patter2 = "/com/**/abc/def/x.html/";
    String path1 = "/com/abc/def/x.html/";
    String path2 = "/com/abc/def/x.html";

    assertTrue(matcher.match(patter1, path1));
    assertTrue(matcher.match(patter2, path1));
    assertFalse(matcher.match(patter1, path2));
    assertTrue(matcher.match(patter2, path2));
  }
}

while, both patter1 and patter2 last char is '/', and path1 last char also is  '/', but path2 not.
path1 can match both patter1 and patter2
but path2 only math patter2, NOT patter1, why?

A: Well, You have made a very good point. It is the way it is(That is how it is designed).
But may be I can give some internal details. This is what I found after I debugged AntPathMatcher::match.
Reason why matcher.match(patter1, path2) is false  ===> / is considered as the default path separator. So what match method does internally is to split it using / as the separator and see if all the tokens match. But in the end there is a comparision line like this
return (pattern.endsWith(this.pathSeparator) == path.endsWith(this.pathSeparator));

Which is basically checking if both pattern and path end with / or not. Hence you are getting false.
Reason why matcher.match(patter2, path2) is true  ===> Well things get tricky when there is a  wildcard  ** involved.  If there is a wildcard involved then the logic is such that, initially the tokens are matched till ** is encountered. Once found, it checks for tokens from the last till the last occurence of **. In this case there is no check for trailing /. That is the main reason for this to work.
May be it is a bug. So the reason this case works is because of wildcard character.


text:
Q: Display attribute from child component to parent in angular 5 I have a parent component in which I want to display a title which is an attribute contained on a an object displayed on a child component. I would be something like this:
<parent-component>

{{title_i_want_to_display}}

<child-component>
{{object.title}}
</child-component>

<parent-component>

How can I capture that object.title and display it inside my h1 tag on the parent?

A: child.component.ts
@Output titleEvent = new EventEmiter<string>();
ngOnInit(){
  this.titleEvent.emit(object.title);
}

parent.component.ts
 public myTitle: string;

 onTitleFetch(title){
    this.myTitle = title;
 }

parent.component.html

{{myTitle}}

<child-component (titleEvent)="onTitleFetch($event)"></child-component>


text:
Q: DBCC CHECKDB getting terminated abnormally We have a SQL Server 2014 set up on Always on AG with one primary node and 2 secondary nodes.
On the primary node, DBCC CHECKDB for one of the databases is scheduled on SQL agent job. This job was running fine till last month and now its getting failed and the job logs read "DBCC CHECKDB terminated abnormally due to error state 6." when running the DBCC CHECKDB command manually, getting the same result.
During the job/Command runtime , there is a spike in I/O , Memory and CPU utilization is full. Storage team had also checked and reported that there are no storage related errors
On the Secondary nodes, the job runs fine without any issues.
I did try to restore the DB on a test instance and the DBCC CHECKDB runs fine.
Could anyone help me to find the cause of this.

A:
DBCC CHECKDB terminated abnormally due to error state 6

The error state 6 means process is killed or terminated by external process at least as far as my experience goes, this is not documented though. I have witnessed this and in my case this was due to a monitoring query running killing long running job. Please double, triple check is any user process/agent job/third part software (in some case) is killing the process.


text:
Q: CAEmitterLayer not timing correctly with CACurrentMediaTime() and sometimes not showing at all I am currently making a particle emitter using CAEmitterLayer and ran into the issue of the layer preloading the animation when I start it and hence the particles all over the place when I show it.
Many answers have said the culprit is CAEmitterLayer being preloaded and we simply have to set its beginTime to CACurrentMediaTime() on the emitter.
See:
CAEmitterLayer emits random unwanted particles on touch events
Initial particles from CAEmitterLayer don't start at emitterPosition
iOS 7 CAEmitterLayer spawning particles inappropriately
For me this solution has not worked, when running it on device, iPad Air running iOS 12.1, the emitter often does not show and sometimes it is showed with a great delay.
To illustrate this issue I made a project on github:
https://github.com/roodoodey/CAEmitterLayer/tree/master/CAEmitterLayerApp
Here is the main code, I have 7 different images for particles chosen at random and a button to show the emitter when pressed.
import UIKit

class ViewController: UIViewController {

    var particleImages = [UIImage]()
    var emitter: CAEmitterLayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.black

        // Populate the random images array for the particles
        for index in 1..<8 {
            if let image = UIImage(named: "StarParticle00\(index)") {
                particleImages.append(image)
            }

        }

        // Button pressed to make the emitter emit the particles
        let button = UIButton(frame: CGRect(x: view.frame.width * 0.5 - 60, y: view.frame.height * 0.5 - 40, width: 120, height: 80))
        button.setTitle("Emit!", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = UIColor.blue
        button.addTarget(self, action: #selector(changeButton(sender:)), for: .touchDown)
        button.addTarget(self, action: #selector(addEmitter(sender:)), for: .touchUpInside)
        view.addSubview(button)

    }

    @objc func changeButton(sender: UIButton) {
        sender.alpha = 0.5
    }

    @objc func addEmitter(sender: UIButton) {

        sender.alpha = 1.0

        // IF an emitter already exists remove it.
        if emitter?.superlayer != nil {
            emitter?.removeFromSuperlayer()
        }

        emitter = CAEmitterLayer()
        emitter?.emitterShape = CAEmitterLayerEmitterShape.point
        emitter?.position = CGPoint(x: self.view.frame.width * 0.5, y: self.view.frame.height * 0.5)
        // So that the emitter starts now, and is not preloaded.
        emitter?.beginTime = CACurrentMediaTime()

        var cells = [CAEmitterCell]()
        for _ in 0..<40 {
            let cell = CAEmitterCell()
            cell.birthRate = 1
            cell.lifetime = 3
            cell.lifetimeRange = 0.5
            cell.velocity = 500
            cell.velocityRange = 100
            cell.emissionRange = 2 * CGFloat(Double.pi)
            cell.contents = getRandomImage().cgImage
            cell.scale = 1
            cell.scaleRange = 0.5
            cells.append(cell)
        }

        emitter?.emitterCells = cells

        view.layer.addSublayer( emitter! )

    }

    func getRandomImage() -> UIImage {

        let upperBound = UInt32(particleImages.count)
        let randomIndex = Int(arc4random_uniform( upperBound ))

        return particleImages[randomIndex]
    }

}

Here is a short 20 second video of the app running on device, iPad Air running iOS 12.1, not run through xcode. https://www.dropbox.com/s/f9uol3yot67drm8/ScreenRecording_11-25-2018%2013-19-29.MP4?dl=0
If somebody could see if they can reproduce this issue or shed some light on this strange behavior it would be greatly appreciated.

A: I have a ton of experience with Core Animation although I have to admit not a lot with CAEmitterLayer.  Everything looks right and for a person that knows CALayer pretty well, setting the beginTime with CACurrentMediaTime() makes sense.  However, I ran your project and saw it was not working. For me setting the beginTime on the cell had the effect I would expect.
Meaning
//delay for 5.0 seconds
cell.beginTime = CACurrentMediaTime() + 5.0
cell.beginTime = CACurrentMediaTime() //immediate
cell.beginTime = CACurrentMediaTime() - 5.0 //5 seconds ago

Entire File
import UIKit

class ViewController: UIViewController {

    var particleImages = [UIImage]()
    var emitter: CAEmitterLayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.black

        // Populate the random images array for the particles
        for index in 1..<8 {
            if let image = UIImage(named: "StarParticle00\(index)") {
                particleImages.append(image)
            }

        }

        // Button pressed to make the emitter emit the particles
        let button = UIButton(frame: CGRect(x: view.frame.width * 0.5 - 60, y: view.frame.height * 0.5 - 40, width: 120, height: 80))
        button.setTitle("Emit!", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = UIColor.blue
        button.addTarget(self, action: #selector(changeButton(sender:)), for: .touchDown)
        button.addTarget(self, action: #selector(addEmitter(sender:)), for: .touchUpInside)
        view.addSubview(button)

    }

    @objc func changeButton(sender: UIButton) {
        sender.alpha = 0.5
    }

    @objc func addEmitter(sender: UIButton) {

        sender.alpha = 1.0

        // IF an emitter already exists remove it.
        if emitter?.superlayer != nil {
            emitter?.removeFromSuperlayer()
        }

        emitter = CAEmitterLayer()
        emitter?.emitterShape = CAEmitterLayerEmitterShape.point
        emitter?.position = CGPoint(x: self.view.frame.width * 0.5, y: self.view.frame.height * 0.5)
        // So that the emitter starts now, and is not preloaded.
        var cells = [CAEmitterCell]()
        for _ in 0..<40 {
            let cell = CAEmitterCell()
            cell.birthRate = 1
            cell.lifetime = 3
            cell.lifetimeRange = 0.5
            cell.velocity = 500
            cell.velocityRange = 100
            cell.emissionRange = 2 * CGFloat(Double.pi)
            cell.contents = getRandomImage().cgImage
            cell.scale = 1
            cell.scaleRange = 0.5
            cell.beginTime = CACurrentMediaTime()
            cells.append(cell)
        }

        emitter?.emitterCells = cells
        view.layer.addSublayer( emitter! )
    }

    func getRandomImage() -> UIImage {

        let upperBound = UInt32(particleImages.count)
        let randomIndex = Int(arc4random_uniform( upperBound ))

        return particleImages[randomIndex]
    }

}


text:
Q: FirebaseError: Expected type 'Tc', but it was: an object Following the firebase v9 docs I am trying to implement the onSnapshot to listen to a document change but I keep getting this error.

FirebaseError: Expected type 'Tc', but it was: an object

Here is some simple implementation:
const [channels, setChannels] = useState([]);
useEffect(() => {
    const rooms = collection(db, 'rooms');
    const unsub = onSnapshot(rooms, (snapshot) => {
        setChannels(snapshot.docs.map(doc => ({
            id: doc.id,
            name: doc.data().name
        })))
    },
    (error) => {
      console.log(error)
    });

  }, []);


text:
Q: Firewall security and SQL Server I have been receiving messages in my log file saying :-
"Login failed for user 'sa': Reason Password did not match that for the login provided. [Client:xx.xx.xx.xx]"
the xx are actual numbers.
In the MS firewall, I've added my IP to the "Remote IP address" list on the Scope tab.
When I have gone back to the log file, the message has stopped appearing.  Instead it says "its starting up ReportServerTempDB", does this mean that I've inadvertently by adding my IP to the remote IP list allowed anyone in?
By putting only my IP address in the scope means I've blocked everyone else apart from me connecting to the remote database?
Ultimately, I would like remote access allowed only to my IP.  If that is not possible, I want a block on all remote access.

A:
By putting only my IP address in the scope means I've blocked everyone else apart from me connecting to the remote database?

Correct.

Exceptions that you add to the firewall can restrict the opening of
  the port to incoming connections from specific computers or the local
  subnet. This restriction of the scope of the port opening can reduce
  how much your computer is exposed to malicious users, and is
  recommended.

https://learn.microsoft.com/en-us/sql/sql-server/install/configure-the-windows-firewall-to-allow-sql-server-access?view=sql-server-ver15#BKMK_additional_settings


text:
Q: PHP MySQL insert multimensional associative array building query from array keys I have tried both the links but I don't get the expected variables content in $fields and $newdata
** This question has developed in a new one here **
PHP how to extract keys names and values from associative array for mysql query (as explained I'm newbie and it took some work to get the question asked in the right way)
so I kindly print here some var_dump and cast to kindly ask your support.
For simplicity in my learning experiment, I'm working with a dummy table of just 5 fields, as you see they are: selected, user_id, user_name, user_company and user_email.
Finally I have inserted just 2 rows of values.
Using this code
$Arr = (array)$data;
print_r ( $Arr );

I can see this output
Array (
[0] => Array ( [selected] => [user_id] => 3 [user_name] => nome3 [user_company] => azien3 [user_email] => email3 )
[1] => Array ( [selected] => 1 [user_id] => 6 [user_name] => nome6 [user_company] => azien6 [user_email] => email6 )
)

next I try to apply the code of your links
24  $fields = implode(",", array_keys($Arr));
25  $newdata = "'" . implode("','", $Arr) . "'";
26
27  var_dump($fields);
28  echo "

";
29  var_dump($newdata);

But something is wrong in my interpreteation or in my code , because the output is
Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25

Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25
string(3) "0,1"

string(15) "'Array','Array'"
can you kindly point out what's wrong?
e.g. is my array properly formed?

ORIGINAL QUESTION
I'm newbie and after further readings I got the point and hopefully now my question could result more simple. Thank you for any hint.
I have a bidimensional array since its records are coming from an html table.
The collection made on the html side generates an associative array so each row is like in the following example where, also, you can see, the keys are many
[item] => Array (
    [0] => Array (
        [unit] => "car"
        [qty] => 3
        [description] => "Description 1"
        ....
        [key47] => "thin"
    )
    [1] => Array (
        [unit] => "bike"
        [qty] => 74
        [description] => "Description 2"
       ....
        [key47] => "large"
    )
)

The mysql table name where I want to insert the items is named items_table
"unit" "qty" and "description" and all the remaining keys (total 47) are exactly the same names of the items_table columns
When on the php side I'd like to have a sort of automatic query generation maybe with PDO that would pick the columns names from the inner array keys names and will insert the corresponding key value in the correct column.
The goal is to avoid creating such a awkward and extremely long query.
Preferred method would be with PDO, avoid binding 47 keys.
This sort of automatism is also useful because in the future columns in the mysql table may being added and or removed and or renamed, so I'd like to forget about the query thinking only about properly editing the html table (on that side the array is already automatically generated with some javascript)
Do you think is possible to do this?
If yes how to?
Does this still need some foreach loop?
Thank you for helping

A: E.g.:
core_table
id* unit quantity description
 1  car         3 Description 1
 2  bike       74 Description 2

adjunct_table
core_id* meta_key* meta_value
      1        47  Description of key n.47 first row
      2        47  Description of key n.47 second row

* = (component of) PRIMARY KEY


text:
Q: Configure Firebase Authentication to send INVALID_CREDENTIALS instead of EMAIL_NOT_FOUND or INVALID_PASSWORD I'm using free Firebase plan for testing my React apps and I'm working on authentication with email and password provider right now.
I'm using Firebase straight in my client.
I managed to handle authentication errors in UI and show users a message like Invalid credentials if either their email or password is wrong but I still get EMAIL_NOT_FOUND or INVALID_PASSWORD response from firebase in the network tab.
This is how I'm handling the UI
try {
  setFirebaseError("");
  await signInWithEmailAndPassword(auth, values.email, values.password);
} catch (err) {
  if (["auth/wrong-password", "auth/user-not-found"].includes(err.code)) setFirebaseError("Invalid credentials");
  else setFirebaseError(err.message);
}

But the response is either
{
  "error": {
    "code": 400,
    "message": "EMAIL_NOT_FOUND",
    "errors": [
      {
        "message": "EMAIL_NOT_FOUND",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

or
{
  "error": {
    "code": 400,
    "message": "INVALID_PASSWORD",
    "errors": [
      {
        "message": "INVALID_PASSWORD",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

and I don't want that.
Is there a way to configure Firebase Authenticaton to send custom error response?

A: Yes, you can do it
try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(
  email: "your_given_email",
  password: "your_given_password!"
);
} on FirebaseAuthException catch (e) {
            if (e.code == 'network-request-failed') {
              showErrorDialog(context, 'No Internet Connection');
              //devtools.log('No Internet Connection');
            } else if (e.code == "wrong-password") {
              return showErrorDialog(
                  context, 'Please Enter correct password');
              //devtools.log('Please Enter correct password');
              //print('Please Enter correct password');
            } else if (e.code == 'user-not-found') {
              showErrorDialog(context, 'Email not found');
              // print('Email not found');
            }  else if (e.code == 'too-many-requests') {
              return showErrorDialog(
                  context, 'Too many attempts please try later');
              //print('Too many attempts please try later');
            } else if (e.code == 'unknwon') {
              showErrorDialog(
                  context, 'Email and password field are required');
              //print('Email and password field are required');
            } else if (e.code == 'unknown') {
              showErrorDialog(
                  context, 'Email and Password Fields are required');
              //print(e.code);
            } else {
              print(e.code);
            }
          }


text:
Q: django filter and order by not being able to modify field? I have a BooleanField called 'used' in my LabHours model which has a default value of False (this is supposed to be an attendance system), and I want to set this to True based on a filter and ordering. Even though I explicitly set this field to be true, when I print out its value, it still displays False.
Here is my code for reference:
LabHours.objects.filter(used=False).order_by("endtime").first().used = True
for hours in LabHours.objects.all():
    hours.save()
    print hours.used

Console output:
False
False
False
False
False
False
False

Why does it not set this field to be True?

A: The change in the first line of your code goes unsaved, and then you're just looping through the queryset and triggering save on model instances with no changes.
You'll need to call save using the model instance on which you mutated state:
obj = LabHours.objects.filter(used=False).order_by("endtime").first()
obj.used = True
obj.save()

A: This happened because you didn't save the value that you updated.
first = LabHours.objects.filter(used=False).order_by("endtime").first()
first.used = True
first.save()
for hours in LabHours.objects.all():
    hours.save()
    print hours.used


text:
Q: Disallowed key characters error in codeigneiter When I enable the auto load for sessions in the autoload.php file and pass my encryption_key in the config file and set sess_use_database to TRUE, I got the disallowed key characters when I ran the application.

A: You can change of list allowed characters in application/config.php
$config['permitted_uri_chars'] = 'a-zA_Z 0-9~%.:_\-';

You can also read this topic - Permitted URI chars in codeigniter


text:
Q: Struggling with Ajax Post Image I've been really struggling posting image data to a Java server. I get 400 (Bad request every time).
Some things I've tried
var imgData = renderer.domElement.toDataURL();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;

ctx.drawImage(renderer.domElement,- (renderer.domElement.width/2 - canvas.width/2),- (renderer.domElement.height/2 - canvas.height/2), renderer.domElement.width, renderer.domElement.height);
var resizedImageData = canvas.toDataURL('image/png');
$("#sceneThumbImage").attr("src",resizedImageData);

var ajax = new XMLHttpRequest();
var url = '/scene/'+currentScene.id+'/thumb';

ajax.open("POST",url,false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(resizedImageData);

And
$.post('/scene/'+currentScene.id+'/thumb',resizedImageData,function(){console.log('success')},function(e){console.log('failed',e)});

The Java method
@ResponseBody
    @RequestMapping(value = "/scene/{sceneId}/thumb", method = RequestMethod.POST)
    public ResponseEntity<String> saveSceneThumb(
            @PathVariable("sceneId") String sceneId,
            @RequestParam("thumbName") String thumbName,
            DefaultMultipartHttpServletRequest request) {

        // If not logged in, return early
        if (!isLoggedIn(request))
            return getErrorResponse(1234, "not logged in");

        try {
            // Create and populate the thumb with the new bitmap
            //File file = new File(Constants.TEMP_DIR_PATH + thumbName);
            //request.getFile("thumb").transferTo(file);

            java.io.File file = new java.io.File(Constants.TEMP_DIR_PATH
                    + thumbName);
            request.getFile("thumb").transferTo(file);

            // upload thumb to the scenes bucket
            s3UploadService.uploadFile(assetsBucket, file);

            return getSuccessResponse();
        } catch (Exception e) {
            return getErrorResponse(1234, "Error uploading scene thumb");
        }
    }   }   }

Each and every time it's a bad request. If anyone knows of an easy way to debug this or can spot something I'm doing wrong, please let me know!


text:
Q: Auditing in Oracle I need some help in auditing in Oracle.   We have a database with  many tables and we want to be able to audit every change made to any table in any field.   So the things we want to have in this audit are:

*

*user who modified

*time of change occurred

*old value and new value

so we started creating the trigger which was supposed to perform the audit for any table but then had issues...
As I mentioned before we have so many tables and we cannot go creating a trigger per each table. So the idea is creating a master trigger that can behaves dynamically for any table that fires the trigger.   I was trying to do it but no lucky at all....it seems that Oracle restricts the trigger environment just for a table which is declared by code and not dynamically like we want to do.
Do you have any idea on how to do this or any other advice for solving this issue?

A: If you have 10g enterprise edition you should look at Oracle's Fine-Grained Auditing.  It is definitely better than rolling your own.
But if you have a lesser version or for some reason FGA is not to your taste, here is how to do it.  The key thing is: build a separate audit table for each application table.
I know this is not what you want to hear because it doesn't match the table structure you outlined above.  But storing a row with OLD and NEW values for each column affected by an update is a really bad idea:

*

*It doesn't scale ( a single update touching ten columns spawns ten inserts)

*What about when you insert a record?

*It is a complete pain to assemble the state of a record at any given time

So, have an audit table for each application table, with an identical structure.  That means including the CHANGED_TIMESTAMP and CHANGED_USER on the application table, but that is not a bad thing.
Finally, and you know where this is leading, have a trigger on each table which inserts a whole record with just the :NEW values into the audit table.  The trigger should fire on INSERT and UPDATE.  This gives  the complete history, it is easy enough to diff two versions of the record.  For a DELETE you will insert an audit record with just the primary key populated and all other columns empty.
Your objection will be that you have too many tables and too many columns to implement all these objects.  But it is simple enough to generate the table and trigger DDL statements from the data dictionary (user_tables, user_tab_columns).

A: You don't need write your own triggers.
Oracle ships with flexible and fine grained audit trail services. Have a look at this document (9i) as a starting point.
(Edit: Here's a link for 10g and 11g versions of the same document.)
You can audit so much that it can be like drinking from the firehose - and that can hurt the server performance at some point, or could leave you with so much audit information that you won't be able to extract meaningful information from it quickly, and/or you could end up eating up lots of disk space. Spend some time thinking about how much audit information you really need, and how long you might need to keep it around. To do so might require starting with a basic configuration, and then tailoring it down after you're able to get a sample of the kind of volume of audit trail data you're actually collecting.


text:
Q: Dynamically display objects according to the size WPF I have to display a ListView of objects. These objects are structured as a Grid with two columns. The first column contains the view of the Element, the second one, contains a collection of arrows (in a vertical way).
I created a control "Arrow" to display it in the second column like the following image:

My problem is: how can I put dynamically the right number of arrows in the second column, according to the Height of the object put in the first Column.
Which Structure to use to ensure that the second column will be flexible ? Grid, StackPanel or something else ?
Please consider that the arrows have a fixed size.

A: All you really need to do is generate a list, one item for each arrow, based on the space you need to fill. Lets start with a converter
public void MakeArrowListConverter : IValueConverter
{
  public double ArrowHeight {get;set;}

  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
     var verticalSpace = (double) value;
     int numberOfArrows = (int)(verticalSpace/ArrowHeight);
     return Enumerable.Range(0, numberOfArrows);
  }
}

This needs to convert sopmething which we have the height of, in this case I'd just use a ContentPresenter and Bind that to your view.
<ContentPresenter x:Name="content" Content="{Binding}"/>

So then we simply need to take the height and convert it into your list
<xxx.Resources>
  <convertors:MakeArrowListConverter x:Key="makeArrowListConverter" />
</xxx.Resources>

<ListBox ItemsSource="{Binding ElementName=content, Path=ActualHeight, Converter={StaticResource makeArrowListConverter}}">
  <ItemTemplate>
    <DataTemplate>
      <!-- Image or Shape, this is your red arrow-->
      <YourArrow/>
    </DataTemplate>
  </ItemTemplate>
</ListBox>

In fact we can put these two elements into another into a dataTemplate to convert each item of your data into its displayed form when its used in a list
<DataTemplate DataType="{x:Type MyView}">
  <!--This is your blue box-->
  <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
    <ContentPresenter x:Name="content" Content="{Binding}"/>
    <ListBox ItemsSource="{Binding ElementName=content, Path=ActualHeight, Converter={StaticResource makeArrowListConverter}}">
      <ItemTemplate>
        <DataTemplate>
          <!-- Image or Shape, this is your red arrow-->
          <YourArrow/>
        </DataTemplate>
      </ItemTemplate>
    </ListBox>
  </StackPanel>
</DataTemplate>

<!-- And this is your orange box-->
<ListBox ItemsSource="{Binding YourListOfViews}"/>


text:
Q: How to initialize a graphics g when building a RenderingEngine So a buddy of mine built a RenderingEngine where it pretty much contains the methods that graphics has. That way you only need to call the RenderingEngines class's methods to render stuff to the screen. Without looking and trying to learn instead of cheating, im trying to replicate it based off my knowledge. I ran into a problem though. All my methods work its just that when the RenderingEngine class get initialized in my game class the graphics g in my RenderingEngine class is null after trying to get the JPanel's graphics. I don't know if i'm not understanding how this works and would love an explanation, ill put the code down below.
RENDERING CLASS BELOW:
package game.Main;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class RenderingEngine extends JPanel
{
    private Graphics g;
    public RenderingEngine()
    {
        g = this.getGraphics();
    }

    public void setColor(Color color)
    {
        g.setColor(color);
    }

    public void fillRect(Rectangle rect)
    {
        g.fillRect(rect.x, rect.y, rect.width, rect.height);
    }

    public void drawRect(Rectangle rect)
    {
        g.drawRect(rect.x, rect.y, rect.width, rect.height);
    }

    public void setStringFont(Font font)
    {
        g.setFont(font);
    }

    public void drawString(String string, int x, int y)
    {
        g.drawString(string, x, y);
    }

    public void drawImage(BufferedImage image, Rectangle rect)
    {
        g.drawImage(image, rect.x, rect.y, rect.width, rect.height, this);
    }

    public void clear(Rectangle rect)
    {
        g.clearRect(rect.x, rect.y, rect.width, rect.height);
    }

    public int widthofString(String string, Font font)
    {
        String text = string;
        AffineTransform affinetransform = new AffineTransform();
        FontRenderContext frc = new FontRenderContext(affinetransform,true,true);
        Font f1 = font;
        int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
        return textwidth;
        //int textheight = (int)(font.getStringBounds(text, frc).getHeight());
    }

    public int heightofString(String string, Font font)
    {
        String text = string;
        AffineTransform affinetransform = new AffineTransform();
        FontRenderContext frc = new FontRenderContext(affinetransform,true,true);
        Font f1 = font;
        //int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
        int textheight = (int)(font.getStringBounds(text, frc).getHeight());
        return textheight;
    }

    public void paint()
    {

    }
}

WHERE I INITIALIZE RENDERINGENGINE IN THE GAME CLASS:
private void Load()
{
    frame = new JFrame();
    frame.setSize(800,600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    render = new RenderingEngine();
    frame.add(render);
    LoadContent();
    gameloop = new GameLoop();
    gameloop.Run();
}

A: You might consider it as unsatisfactory when I answer the question about "How to initialize a Graphics g" for a JPanel with ...
Not at all!
You might want to have a look at the Performing Custom Painting article, or the article about Painting in AWT and Swing (which unfortunately was slightly messed up during the transition from Sun to Oracle, but still contains valuable and more detailed information than the other article).
The Graphics of a JPanel is, so to say, managed by the operating system, and represents an area on the screen where the painting may happen. When the panel is not yet visible, the Graphics that is returned by a call to getGraphics() may be null. It may also be null at other occasions. Particularly, when it is accessed from a thread that is not the event dispatch thread.
In general, as a rule of thumb:
Never call getGraphics on a Component!
One possible solution for such a "RenderingEngine" class would be to use the Graphics object of a BufferedImage. This should not be too complicated, but you'll have to consider several aspects here:

*

*When will the image be initialized?

*When will the graphics be initialized?

*When will the graphics be disposed?

*What happens when the panel is resized?

*...

However, with this method, it should at least be possible to create such a "RenderingEngine" that is suitable for the intended usage.


text:
Q: How to apply width 100% with scroll able table body I am trying to implement the table body scrollable.  I am able to successfully did it but now I am facing issue with width 100%
Please check this jsfiddle https://jsfiddle.net/Ratan_Paul/stpgd6x6/

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

Can't I apply the width to thead and tbody ? any solution so I can use the scroll as well as set the width to 100%

A: There is a much simpler CSS solution to this. Instead of worrying about the widths and scroll of elements, wrap the table with a container div and use the style position: sticky to the th elements. Example snippet below -

.table-container {
  max-height: 160px;
  border: 1px solid red;
  overflow: auto;
}

th {
  position: sticky;
  top: 0;
  background: white;
}

td, th {
  padding: 4px 8px;
}

        Company
        Contact
        Country

        Alfreds Futterkiste
        Maria Anders
        Germany

        Centro comercial Moctezuma
        Francisco Chang
        Mexico

        Ernst Handel
        Roland Mendel
        Austria

        Island Trading
        Helen Bennett
        UK

        Laughing Bacchus Winecellars
        Yoshi Tannamuri
        Canada

        Magazzini Alimentari Riuniti
        Giovanni Rovelli
        Italy

A: Try this Code. I think this is best for you

table{
  width:100%;
}
tbody{
  width:100% !important;
  max-height: 50px;
  display: block;
  overflow-y:auto;
}
thead{
  min-width:100% !important;
}
thead tr{
  width:calc(100% - 17px) !important;
  display:inline-block;
}
tbody tr{
  width:100% !important;
  display:inline-block;
}
th, td{
  width:30% !important;
  display:inline-block;
  text-align:left;
}

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

A: If you want to make the table scrollable and set it's height, you only have to work with the table itself.
Remove all styling on your table, and add this css:
table {
  width: 100%;
  max-height: 80px;
  display: block;
  overflow-y: scroll;
  position: relative;
}

See this fiddle:
https://jsfiddle.net/stpgd6x6/3/

A: You'll need to clear a few styles that initially come with tables as well as set a width of 33% since you're using 3 column headers (100%/3)
See below:

table {
    width: 100%;
    border-collapse: collapse;
    border-spacing: 0;
    border: 2px solid black;
}

thead, tbody, tr, td, th { display: block; }

tr:after {
    content: ' ';
    display: block;
    visibility: hidden;
    clear: both;
}

thead th {
    height: 30px;
    line-height: 30px;
    text-align: left;
}

tbody {
    height: 100px;
    overflow-y: auto;
}

thead {
    /* fallback */
    width: 97%;
    /* minus scroll bar width */
    width: calc(100% - 17px);
}

tbody { border-top: 2px solid black; }

tbody td, thead th {
    width: 33%;
    float: left;
}

tbody td:last-child, thead th:last-child {
    border-right: none;
}

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

More detailed answer can be found here: HTML table with 100% width, with vertical scroll inside tbody


text:
Q: How can I save settings in VI? I have changed tab settings in VI with set tabstop=4. But when I restart VI, the settings are restored. How can I save the settings?

A: Create/edit a file named .exrc in your /home/ directory and write your settings like this
:set tabstop=4


text:
Q: Does suspension result in automatic loss of moderator privileges? It's long been policy that users may not stand for election as a moderator if they have been suspended anywhere on the network during the previous twelve months. If someone with a recent suspension is ineligible to be elected, it stands to reason that a current moderator who receives a suspension ought to lose their diamond (as they wouldn't be eligible to receive one in the first place), but I was unable to find any reference to such a scenario in our official moderator removal processes.
So, if I was elected moderator on Stuff Stack Exchange last month but am suspended today from Nonsense Stack Exchange, do I lose my diamond on Stuff.SE?

*

*Do I lose my diamond automatically by the very fact of being suspended elsewhere on the network?

*Does being suspended elsewhere on the network automatically trigger one of the formal moderator review processes, and the result of that process will determine whether I lose my diamond?

*Do I keep my diamond, but staff and/or my fellow moderators may decide to manually begin one of the formal moderator removal processes if they deem the circumstances of my suspension to be sufficiently grave to question my ability to continue moderating?

In response to a comment by Makoto, I am aware that many forms of behavior that would lead to a suspension are of such a nature and of sufficient gravity to form the basis for a moderator removal. My question, then, is a procedural one. Are suspended moderators still entitled to their "due process" through the formal moderator removal processes or does diamond loss come automatically, ipso facto from the very occurrence of being suspended (that is, there is no process, no meeting, no minutes, no filings, no opportunity to be heard, etc., just a "you were suspended, your diamond has been revoked" message)?

A:
Do I lose my diamond automatically by the very fact of being suspended elsewhere on the network?

No. It's worth pointing out that one of the main reasons we prevent these nominations is that they can cause a huge amount of drama during the election process. If someone's currently a moderator and they get suspended, that's unlikely to cause drama... in fact, getting removed as a moderator is likely to cause more drama than investigating the situation.
It's also worth mentioning that all moderators (save those who we remove under an emergency removal) get a warning the first time a specific issue is found to be worthy of action from us.

Does being suspended elsewhere on the network automatically trigger one of the formal moderator review processes, and the result of that process will determine whether I lose my diamond?

No. It's possible that we should automate this somehow but if a moderator gets suspended, we won't be aware of it unless someone specifically mentions it to us. The reality is, there are more cases of mods getting suspended "for science" than there are of cases where mods were suspended legitimately. In general mods don't get suspended, so we don't even check for it.

Do I keep my diamond, but staff and/or my fellow moderators may decide to manually begin one of the formal moderator removal processes if they deem the circumstances of my suspension to be sufficiently grave to question my ability to continue moderating?

If someone draws our attention to the suspension, it will likely lead to an informal investigation (as usual) which, if there are concerns found, will turn into a formal investigation. If this is a first time behavior issue, then the outcome could be any of the usual ones - anything from just a chat about what happened and some advice on how to avoid it to an official warning.
Regardless, we take each case as it comes to us. We sincerely hope (and it's largely the case) that moderators well understand the expectations of them and avoid problematic behaviors on sites they don't moderate.

A:
Do I lose my diamond automatically by the very fact of being suspended elsewhere on the network?

No. I think we've scienced this before, and I've heard about an actual case where this happened (but I'm not allowed to disclose the source).
Situations to consider:

*

*a user's account may be suspended if it shows signs of being compromised

*a moderator erroneously suspends the wrong user (there is a rather notorious case where a moderator accidentally destroyed the wrong user, so this isn't too far-fetched)

*another extreme example: a rogue moderator A of site B doesn't like moderator X of site Y and decides to suspend them on site B.

Automatic removal of moderator privileges is not desired in those cases (except maybe the first). Also, the suspension will usually be reversed quickly. Note that if this would happen to a regular user, it will not prevent them from running in an election. (The Community Team can override/ignore that specific rule when made aware of the circumstances.)
I do not know the answers to your other questions, but I assume if the matter is grave enough, it only makes sense that somebody makes the Community Team aware of it, and the Moderator Conduct Review Process will be started.


text:
Q: Install Scipy with MKL through PIP I am using PIP to install Scipy with MKL to accelerate the performance. My OS is Ubuntu 64 bit. Using the solution from this question, I create a file .numpy-site.cfg
[mkl]
library_dirs=/opt/intel/composer_xe_2013_sp1/mkl/lib/intel64/
include_dirs=/opt/intel/mkl/include/
mkl_libs=mkl_intel_lp64,mkl_intel_thread,mkl_core,mkl_rt
lapack_libs=

This file helps me to install Numpy with MKL successfully. However, using the same above file, installing Scipy prompts the error
ImportError: libmkl_rt.so: cannot open shared object file: No such file or directory

I also use
export LD_LIBRARY_PATH=/opt/intel/composer_xe_2013_sp1/mkl/lib/intel64

but the problem is still the same.
Anyone know how to fix this problem? I don't want to install Scipy manually so anyone give me some hints to fix it.

A: 2 years have passed since this question was asked.
There are now numpy/scipy wheels for linux that use a openblas compiled for avx2, so you can get much better performance without building packages. You may need to upgrade pip to get it to install the wheel:
pip install --upgrade pip
pip install numpy scipy

If you want MKL, then you can install Anaconda or Intel Distribution for Python. They use conda instead of pip to manage packages, but they are free and distribute packages that contain all the dependences, including MKL.

A: I have Win10 64Bit with Python 3.6.2 i have installed scipy through http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
I followed following steps :

*

*Step 1: Uninstall if you have any previous version of numpy,
       pip uninstall numpy

*Step 2 : Download numpy‑1.13.1+mkl‑cp36‑cp36m‑win_amd64.whl with
MKL(Math Kernel Library) from below link,
       http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

*Step 3: copy downloaded file into another location and launch command
prompt from that location.

*Step 4: run this command,
       pip install -U numpy-1.13.1+mkl-cp36-cp36m-win_amd64.whl

*Step 5: Now Download scipy library from,
       http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

*Step 6: Copy downloaded file into same location in which numpy is
copied.

*Step 7: In CMD prompt run this cmd,
       pip install scipy-0.19.1-cp36-cp36m-win_amd64.whl

Done!

A: If you are having trouble installing or running with specific version then first uninstall and then install
Step 1:
pip uninstall -v numpy

Step 2: download the wheel file and install
pip install -U numpy-1.13.0+mkl-cp36-cp36m-win_amd64.whl

In this example wheel file name is "numpy-1.13.0+mkl-cp36-cp36m-win_amd64.whl
"

A: I have been facing this problem the past few weeks on:
Windows 10 64 bit Python 3.5.2
My workaround:
First: pip install wheel
Next: Download Numpy and Scipy form Gholke's repo
Numpy and SciPy
Then:
pip install numpy_package.whl
pip install scipy_package.whl

A: Intel has been publishing wheels of packages like Numpy, Scipy and Scikit-learn to PyPI. These wheels have been built while linking against Intel MKL, and include various optimizations.
If you want Scipy built with Intel MKL:
#Remove existing Numpy and/or Scipy:
pip uninstall numpy scipy -y
#Install scipy built with Intel MKL:
pip install intel-scipy

More information available here

A: Since the actual question itself was not answered, let me give it a shot...
I think the problem here basically is that the BLAS/LAPACK libraries being used are spread out across multiple location, and numpy doesn't handle this well.
We have fixed this in EasyBuild, where we have been building numpy/scipy on top of Intel MKL for a while now, with this patch: https://github.com/hpcugent/easybuild-easyconfigs/blob/master/easybuild/easyconfigs/n/numpy/numpy-1.8.1-mkl.patch

A: For me, MKL came with Scipy library by conda install scipy
@rscohn2 solution gave me a hint for using packages.
For the reference, my environment is included Ubuntu, Anaconda, Python 3.6, Scipy 1.1 and MKL 2018.0.


text:
Q: Mapping in .net4 while going through video tutorials for mvc2 which i downloaded from microsoft's website, the traineer said that there is facility available in .net4 that we can map the fields of two object of different class and we need not to set there values one by one.
let say i have got a table named tblusermaster which contains 20 columns and i have created a model named usermasterModel which also contains almost same kind of fields and name.
so when i wants to assign values from object of tblusermaster  to object of usermasterModel i will have to set value for all 20 fields manually one by one but he was saying that there is a facility to map such thing and we will not have to write 20 lines to transfer values from one object to another (of different class but same type and name).
i have done google for this but not able to get answer that how to do that.
please help me out and give me link and any good tutorial for this.
Thanks
EDIT: its on http://www.asp.net/mvc  video names are asp.net mvc2 basic and another one is asp.net mvc2 ninja black belt by Scott Hanselman

A: Your probably referring to the AutoMapper project on CodePlex.
There is a screencast on it here.


text:
Q: Run Doxygen only on select files / modules? Recently I started writing some doxygen docs in an existing project which already has quite a lot of doxygen comments.
Since I'm learning a bit - I like to iterate with making edits and generating docs, since doc generation is quite slow - 3-5min. This becomes un-workable.
I managed by deleting most of the files in the source tree so doxy only found the ones I was editing but this is really a horrible solution and not something I'd want to do frequently.
Is there a way (command line arg or env variable for eg) - to limit which files/modules are used for generating docs - so rebuilding docs can be done much faster?

A: Yes, you can customize Doxygen's behavior from either the command-line or via environment variables. For example, if you only want to include one file (include/somefile.h), you could execute Doxygen like:
( cat Doxyfile ; echo "INPUT=include/somefile.h" ) | doxygen -

see the Doxygen FAQ's "Can I configure doxygen from the command line?" for more details on customizing behavior from the command line.
Alternatively, if you want to use environment variables, you could use specify something like the following in your configuration file:
INPUT = $(FILE)

Doxygen performs environment variable substitution on its configuration files, allowing you to specify which file(s) should be acted on using:
export FILE=include/somefile.h
doxygen Doxyfile

See Doxygen Configuration for details on using environment variables in configuration files.


text:
Q: Form Validation I am just getting started in Angular 2 and I'm trying to figure out how to validate a form so that it doesn't allow anything less than $.01 to be entered. I have tried a few different things, but so far, it will still allow the submit button to be pressed. Can anyone point me in the correct direction?

A: One way to achieve this is binding the 0.01 input with $scope.balance, binding the save button with $scope.save.
For example your template is like the following:

  <md-input-container>
    Balance
    <input ng-model="balance" type="number" required>
  </md-input-container>

{{error}}

  <md-button ng-click="answer()>Save</md-button>

Then in your controller:
$scope.balance = 0;
$scope.save = function() {
  if ($scope.balance < 0.01) {
    $scope.error = "Please enter some value that is no less than 0.01";
    return; // any invalidate number will not be saved.
  }
  // do your other save operation
}

By doing this, you have flexibility to do other validations and give your own error message to users.


text:
Q: Postfix Header_Check Regex 'Does Not Match' issue I am trying to configure Postfix to NOT accept outbound messages with FROM addresses other than my own domains.
The following regex successfully rejects only 3 domains:
/etc/postfix/header_checks:
/(^From:.*domain\.com|^From:.*domain\.net|^From:.*domain\.co\.il)/ REJECT SEND FROM THE RIGHT DOMAINS FFS!

I'd like to basically reverse it and block EVERYTHING BUT those 3.
So according to the manual:

!/pattern/flags result
                When  pattern  does  not  match the input string, use the corre-
                sponding result value.

However, this just blocks everything:
/etc/postfix/header_checks:
!/(^From:.*domain\.com|^From:.*domain\.net|^From:.*domain\.co\.il)/ REJECT SEND FROM THE RIGHT DOMAINS FFS!

A: The problem is postfix use header_checks for every header line. So if there is header line like
Subject: I love you :p

and postfix will apply that regex into this line. The result is postfix will reject this email.
The solution is adding if endif in your regex pattern
if /^From:/
!/(^From:.*domain\.com|^From:.*domain\.net|^From:.*domain\.co\.il)/ REJECT SEND FROM THE RIGHT DOMAINS FFS!
endif

Basically you tell postfix to apply the pattern into From header only. This will prevent postfix to evaluate the regex into another header line and causes rejected email.
See postfix manual
to further information


text:
Q: iis ,wordpress, PHP Fatal error: require_once() I relogin onedrive , then I visit "127.0.0.1" , get the below error .
PHP Warning:  require_once(E:\onedrive\webhome\wwwroot\wp-load.php): failed to open stream: Invalid argument in E:\onedrive\webhome\wwwroot\wp-blog-header.php on line 13
PHP Fatal error:  require_once(): Failed opening required 'E:\onedrive\webhome\wwwroot/wp-load.php' (include_path='.;C:\php\pear') in E:\onedrive\webhome\wwwroot\wp-blog-header.php on line 13

win10, iis, wordpress , onedrive, php 7.4 .
"E:\onedrive\webhome" folder , IIS_IUSER , full control .