text:
Q: White Labeling oAuth login page We have a use case that requires our customers to login on our website.  Our customer identities are stored in salesforce as part of our communities section.
On our website we redirect users to
https://login.salesforce.com/services/oauth2/authorize
with the appropriate parameters so that they can login.  USing the oAuth WebServer flow (I Believe)
However the page is very much branded as salesforce. This would usually make sense as salesforce is the trusted entity, however our customers really don't need to know that we use salesforce and might actually be confused when shown the login page.
How do we whitelabel the oAuth login processes so that it contains our branding?

A: You'll want to see this section of Getting Started with Communities which includes instructions on how to brand your log-in page, revising your Apex CommunitiesLoginController, where to configure authentication provider options and more.


text:
Q: Detect array in angular template I have an array that I am iterating through and displaying. Sometimes, however, the item it finds is an array. I'd like to do something different with this, using an ng-if. I am unsure how to do this easily. It seems like a common issue but there doesn't appear to be an easy solution.

A: You can use Angular.isArray() (see doc) but it does not exist as a already defined filter so you might need to define your own.
Something like that :
angular.module('...', []).filter('isArray', function() {
  return function (input) {
    return angular.isArray(input);
  };
});

And then in your template usimply use {{ myVar | isArray }}.
My only concerne is ... is it really clean to do so ? I don't know but this will solve your problem.
By the way, was already asked on StakcOverFlow : Angular expression to check if model is array or object

redpajama_set_name: RedPajamaStackExchange


text:
Q: .htaccess htpasswd causes login prompts all over site I'm trying to protect a Wordpress install from brute force attacks on the login page (wp-login.php).  I configured the .htaccess file in the top directory of my site to look like so:
 # Wordpress START
 <IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
 </IfModule>
 # Wordpress END

 # Protect wp-login
 <Files wp-login.php>
 AuthName "Private Access"
 AuthType Basic
 AuthUserFile /home/passwords/.htpasswd
 require valid-user
 </Files>

The problem I'm experiencing is, this change is causing a password prompt to appear on every single page of my site, almost like the Files tag is being ignored.  I feel like I must be missing something but I can't figure out quite what.  Any help is greatly appreciated, thanks very much!

EDIT:  After taking things through with Sumurai8 below, I tried password protecting wp-admin instead of wp-login.php instead.  What I found is that a Wordpress plugin "Wordfence" was causing some problems on all the pages of my site, I guess because it was trying to load an admin-ajax.php file that was in the wp-admin directories.
This is what the .htaccess file in my wp-admin directory looks like now, and it appears to be working pretty well enough I think:
 AuthType Basic
 AuthName "Protected Area"
 AuthUserFile /home/passwords/.htpasswd
 AuthGroupFile /dev/null
 Require valid-user

 # This is the whitelisting of the ajax handler
 <Files "admin-ajax.php">
     Order allow,deny
     Allow from all
     Satisfy any
 </Files>
 <Files "*.css" >
    Order allow,deny
    Allow from all
    Satisfy any
 </Files>

Thanks again sumurai8!

A: According to this tutorial you need to protect the wp-admin folder, not the wp-login.php file. You do this by creating a .htaccess file in your wp-admin folder, then adding the following code to it:
AuthName "Private Access"
AuthType Basic
AuthUserFile /home/passwords/.htpasswd
require valid-user

For additional security, you might want to limit it to your ip only. If you do this with require, remember to use a <RequireAll> block, because otherwise it will satisfy on any require directive, rather than all directives contained in the block. As an additional note too: Some examples include the use of the <Limit> block to limit this to certain protocols. This poses a security risk on some setups due to improper handling of invalid protocols, and should therefore not be used.


text:
Q: Get selected class in a "ul" How can I get the selected class of the li-item in with this code?
Now it loops all of the classes inside the ul, not just the selected.
$('
Choose Type'
  + '
'
  + '
Checkbox
'
  + '
 Alternatives
'
  + '
 Dropdown
'
  + '
 Text
'
  + '

').appendTo(field_secondchild).addClass("metro three-d")
.click(function() {
$('#chooseCustomField' + field_id + ' li').each(function() {
    alert($(this).attr('class'))
});
});

A: Looks like you want the clicked li
$('
Choose Type'
  + '
'
  + '
Checkbox
'
  + '
 Alternatives
'
  + '
 Dropdown
'
  + '
 Text
'
  + '

').appendTo(field_secondchild).addClass("metro three-d")
.on('click', 'li', function() {
    alert($(this).attr('class'))
});

A: Your html is poorly formatted as it is, so i fixed that, then i separated the html and js so we can see this actually working.
Here is the working fiddle:
http://jsfiddle.net/acturbo/LmXz4/1/
javascript:
var field_id = "#chooseCustomField" + "555";
var field_secondchild = "#secondchild";

// new logic
$(field_id).appendTo( field_secondchild ).addClass( "metro three-d");

// easier way to assign a click event to each li
$(field_id + ' li').on("click", function() {
    alert($(this).attr('class'))
});

html (needed for testing)

for testing only

should be last

  Choose Type

Checkbox

 Alternatives

 Dropdown

 Text


text:
Q: How to do SSL on a domain only accessable through current network? To Set The Context
I am using Node.JS on Mac OS. I am hosting a server on the network domain quicvo.local. I am curious how to have proper SSL without the browser giving a warning saying something along the lines of:

This website may be impersonating "quicvo.local" to steal your personal or financial information. You should go back to the previous page.

Of course, the user can trust this website on their device, but that is not ideal and makes my website look very sketchy. I have tried using Let's Encrypt, but it doesn't allow domains in the .local extension. I figured that someone else has tried this and succeeded, so I thought I might ask. I have gotten this far with OpenSSL by self-signing a certificate.

Here Is What I Have Tried
OpenSSL Command Line In Terminal At ./security/ Context
openssl req -nodes -new -x509 -keyout server.key -out server.cert

Node.JS require('https').createServer Options
const security = {
    key: fs.readFileSync('./security/server.key'),
    cert: fs.readFileSync('./security/server.cert')
};


text:
Q: Stop caching for a specific node (by nid) Drupal 7 Ideally i want to set custom params for caching in some particular nodes using conditions in my template.php
E.g. algorithm: for node with known nid set custom caching params
But that's enough for my purpose simply exclude from caching particular node.
I fond this solution: Stop caching for a specific node type Drupal 7 this is exacly what im looking for but how i can change condition of checking from node type to nid.
I know about CacheExclude module, but for me unwanted to install module for just exclude one node for caching.
I'll be very grateful for helping me.

A: As per the example you gave in the link, add a custom module, implement a hook_init function (don't forget to clear the cache when you do this) and add the following to the hook function:
$node = menu_get_object();
if (!empty($node) && $node->nid == '<NODE ID HERE>') {
  drupal_page_is_cacheable(false);
}


text:
Q: How to find and remove blank paragraphs in a Google Document with Google Apps Script? I am working with Google documents that contain hundreds of empty paragraphs. I want to remove these blank lines automatically.
In LibreOffice Writer you can use the Find & Replace tool to replace ^$ with nothing, but that didn't work in Google Docs.
My search for ^$ or ^\s*$ returned 0 results even though there should be 3 matches
How can I remove the blank paragraphs with Google Apps Script?
I already tried body.findText("^$");, but that returns null
function removeBlankParagraphs(doc) {
    var body = doc.getBody();
    result = body.findText("^$");

}

A: I think there has to be a last empty paragraph but this seems to work.
function myFunction() {
  var body = DocumentApp.getActiveDocument().getBody();

  var paras = body.getParagraphs();
  var i = 0;

  for (var i = 0; i < paras.length; i++) {
       if (paras[i].getText() === ""){
          paras[i].removeFromParent()
       }
}
}

A: Adding to Tom's answer and apmouse's comment, here's a revised solution that: 1) prevents removing paragraphs consisting of images or horizontal rules; 2) also removes paragraphs that only contain whitespace.
function removeEmptyParagraphs() {
  var pars = DocumentApp.getActiveDocument().getBody().getParagraphs();
  // for each paragraph in the active document...
  pars.forEach(function(e) {
    // does the paragraph contain an image or a horizontal rule?
    // (you may want to add other element types to this check)
    no_img = e.findElement(DocumentApp.ElementType.INLINE_IMAGE)    === null;
    no_rul = e.findElement(DocumentApp.ElementType.HORIZONTAL_RULE) === null;
    // proceed if it only has text
    if (no_img && no_rul) {
      // clean up paragraphs that only contain whitespace
      e.replaceText("^\\s+$", "")
      // remove blank paragraphs
      if(e.getText() === "") {
        e.removeFromParent();
      }
    }
  })
}

A: function DeleteEmpty(doc)
{
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();
  for (var i = 0; i < paragraphs.length; i++) {
      var paragraph = paragraphs[i];
      if (paragraph.getNumChildren() == 0 && paragraph.getPositionedImages().length == 0) {
        paragraph.removeFromParent();
      }
  }
}

This solution takes into account PositionedImages, which were missing in other solutions and could be removed


text:
Q: Zero polynomials, null polynomials and characteristic 2. The canonical example that a non-null polynomial might be identically zero is to take $x^2 - x$ over a field of characteristic 2.
I wonder if this feature is exclusive to characteristic 2, i.e., is it true that if char$F \neq 2$ then the only identically zero polynomial is the null polynomial?
Thanks in advance.

A: As long as a field is finite, say $F=\{x_1,\dots,x_n\}$, you can use the polynomial
$$P(X) = (X-x_1)(X-x_2)\dots (X-x_n).$$
It is easy to see that each $x_i$ is a root of $P$, so as a function it is zero on $F$, but it has degree $n$.

A: First, your distinction between null and identically zero is nonstandard. If you told me a polynomial was either null or identically zero, my first thought would be what you mean by "null," i.e., all coefficients zero.
Instead, for what you are calling "identically zero," I would use $f(\alpha)=0$ for all $\alpha\in \Bbb{F}_2$.
Note (though you seem to be aware of this) that there is a distinction between a polynomial and a function, and that a polynomial defines many functions depending on the domain and the embedding of the coefficients into the domain. Thus it's weird to say $x^2+x$ is identically zero in $\Bbb{F}_2[x]$, because (for example) the induced function $\Bbb{F}_4\to  \Bbb{F}_4$ is nonzero. $\Bbb{F}_4 \cong \Bbb{F}_2[x]/(x^2+x+1)$, so if $\theta = \overline{x} \in \Bbb{F}_4$, we see that $\theta^2+\theta = \overline{x^2+x} = 1 \in \Bbb{F}_4$.
Finally, for any finite commutative ring $R$, there is always a polynomial $g\in R[x]$ such that $g(\alpha) = 0$ for all $\alpha \in R$. I'll leave it to you to come up with the construction.


text:
Q: Ajax запрос - загрузка данных Добрый вечер! Столкнулась с проблемой: на странице необходимо загрузить картинки с помощью Ajax запроса, при первой загрузке страницы необходимо, что бы выводились случайные картинки, но если в поле поиска ничего не вводить картинки не должны загружаться. Как правильно это реализовать?
$(function () {
      function renderList() {
        var pic = $('.search__box__input').val();
        var API_KEY = '2671443-f70b44031fad9176b9185b139';
        $.ajax({
            url: "https://pixabay.com/api/?key=" + API_KEY + "&q=" + pic + "&per_page=7&lang=ru",
            success: function(data) {
              if ( parseInt(data.totalHits) === 0  || pic === '')  {
                return false;
              } else
                // console.log(data);
                var piclist = tmpl($('#grid-template').html(), data);
                $('.grid').remove();
                $('.activity-grid').append(piclist);
                 $('.grid').masonry({
                    // options
                    itemSelector: '.grid__item',
                    columnWidth: 300
                });
            }
        });
    }
    $('#search__form').submit(function(e) {
        e.preventDefault();
        renderList();
    });
    renderList();
 });

Также HTML :
div class="activity-grid">

Discover holiday activity ideas

                Discover holiday activity ideas

            <form action="#" method="GET" id="search__form">

Hi! What are your holiday interests?

                <input class="search__box__input" type="text" name="" placeholder="Enter your interests">
                <input class="search__box__submit" type="submit" name="" value="Search partners">
            </form>

A: возможно необходимо проверить есть ли что то в поле ввода поиска и затем реализовать логику в зависимости от результата.
if (!document.getElementsByClassName("search__box__input")[0].value) {
    /* если поле ввода поиска пустое */
};


text:
Q: How to add two textview with orientation vertical(One below other) in a table row without using xml? I want add two textview with orientation vertical(One below other) in a table row without using xml that is by programatically. Can anyone suggest me how to do this? Is there any other way than this? Already there are many textviews in a tablerow(horizontally).

A: Put a LinearLayout in the TableRow cell. Put the two TextView widgets in the LinearLayout. Use Java constructors to create the LinearLayout and the TextView widgets. Use addView() to add the TextView widgets to the LinearLayout.


text:
Q: How can I exit Openbox in an orderly manner? When I exit Openbox by selecting Exit from its desktop menu or by running openbox --exit from a Terminal window, it seems to instantly kill all the processes and then terminate. This results in processes not exiting cleanly. For example, when I edit an open file in vim again, it gives me the prompt about recovering an interrupted session.
How can I exit Openbox in such a way that a Quit command gets sent to running applications, or so that if any applications haven't saved current information, they can reject the attempt to exit? Basically, I'm looking for something analogous to logging out in most desktop managers.


text:
Q: wcf datamemberattribute casing In my WCF Service I have a property declared as such:
public string PropertyName
{
    get { return propertyName; }
    set { propertyName = value; }
}

In my Client, when I add a service reference to the service, the imported .cs file has the same property, except it has lost its casing, as such:
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string propertyName
{
    get
    {
        return this.propertyNameField;
    }
    set
    {
        this.propertyNameField = value;
    }
}

(Notice the lowercase p on propertyName.)
Is there anything I can do so that consumers actually get the property with the intended Casing, ie: PropertyName, not propertyName?

A: Have you tried explicitly setting the Name in the DataMember?  For example:
[DataMember(Name="PropertyName")]
public string PropertyName { get { ... } set { ... } }

A: Do you have the DataContract attribute in place correctly? Also make sure that you're applying the DataMember to the property and not the private string.
[DataContract]
public class DataObject {

    string propertyName;

    [DataMember]
    public string PropertyName {
        get { return propertyName; }
        set { propertyName = value; }
    }
}

The full code of the class would be helpful.


text:
Q: How to modify an R-algorithm (Loop function) to work for a level of one categorical variable I have an algorithm which works with the following two data sets.
# First dataset
 Age<-c(2,2.1,2.2,3.4,3.5,4.2,4.7,4.8,5,5.6,NA, 5.9, NA)
 R<-c(2,2.1,2.2,3.4,3.5,4.2,4.7,4.8,5,5.6,NA, 5.9, NA)
 df1<-data.frame(Age,R)

# Second dataset
Age2<-seq(2,20,0.25)
Mspline<-rnorm(73)
df2<-data.frame(Age2, Mspline)

res2 <- lapply(1:nrow(df1), \(x){
  age <- df1[ x, 'Age' ]
  age2 <- df2[ , 'Age2' ]
  R <- df1[ x, 'R' ]
  lwr_ind <- max(which(age2 <= age))
  upr_ind <- min(which(age2 >= age))
  data.frame(Age = age,
             Mspline = df2[ lwr_ind, 'Mspline' ] +
               ((age - df2[ lwr_ind, 'Age2' ]) / 0.25) *
               (df2[ lwr_ind, 'Mspline' ] - df2[ upr_ind, 'Mspline' ]),
             R)
})
res2 <- do.call(rbind, res2)

I was wondering how I can modify the code in order that could be used when there is gender as a categorical variable in the data set. I need to ask the algorithm that if sex in the first data set,df1, is 0=Male then use df2.M (instead of df) for calculation and if sex is 1=female then use df2.F (instead of df) for calculation (it means we need to add a Mspline column into df1 but for Male and Female different algorithms (based on df2.M and df2.F need to be used).
Age<-c(2,2.1,2.2,3.4,3.5,4.2,4.7,4.8,5,5.6,NA, 5.9, NA)
R<-c(2,2.1,2.2,3.4,3.5,4.2,4.7,4.8,5,5.6,NA, 5.9, NA)
sex<-c(1,0,1,1,1,1,1,0,0,0,NA, 0,1)
df1<-data.frame(Age,R,sex)

# Second dataset:
Age2<-seq(2,20,0.25)
Mspline<-rnorm(73)
df2.F<-data.frame(Age2, Mspline)

Age2<-seq(2,20,0.25)
Mspline<-rnorm(73)
df2.M<-data.frame(Age2, Mspline)

It would be something like the following function, but I need to modify in way that work for both df2.F and df2.M at the same time based on whether the obs is M or Female.
res2 <- lapply(1:nrow(df1), \(x){
      age <- df1[ x, 'Age' ]
      age2 <- df2.F[ , 'Age2' ]
      R <- df1[ x, 'R' ]
      lwr_ind <- max(which(age2 <= age))
      upr_ind <- min(which(age2 >= age))
      data.frame(Age = age,
                 Mspline = df2.F[ lwr_ind, 'Mspline' ] +
                   ((age - df2.F[ lwr_ind, 'Age2' ]) / 0.25) *
                   (df2.F[ lwr_ind, 'Mspline' ] - df2.F[ upr_ind, 'Mspline' ]),
                 R)
    })


text:
Q: Trouble creating for loop with multiple commands to read csv files I'm trying to create a for loop that reads prints the file name, alphabetizes fields, and  adds html tags that would ultimately create an html file that looks like

 file

 field2(field3)

 field2(field3)

 field2(field3)
...

 file

and so on.
So far I have this:
     for file in *.csv; do
         awk 'FNR == 1{ print "
" file "
" }' | sort -t"," -k2 | awk -F "," '{print "
" $2 "(" $3 ")<\li>" }' > *.html
     done

The last two commands work well together, but the first one messes them all up and I end up getting an empty html file. I'm also unsure if I'm even creating the right for loop for this situation.

A: You have (reformatted slightly for readability):
for file in *.csv; do
  awk 'FNR == 1{ print "
" file "
" }' |
    sort -t"," -k2 |
    awk -F "," '{print "
" $2 "(" $3 ")<\li>" }' > *.html
done

*

*That first awk command doesn't make any sense. It is neither receiving any input on stdin nor is it receiving a list of files as arguments: in other words, it's not processing anything.
→ We need to provide input to awk, either like this:
awk '...awk script here...' "$file"

Or by feeding it input on stdin.

*You're attempting to reference the awk variable file. but there is no such variable. There is of course a shell variable by that name, but awk doesn't know anything about it.
→ We need to feed the file variable to awk. We can do something like:
awk -v file="$file" ...

*The way you've attempted to insert a sort between two awk calls seems awkward.
→ Let's call sort first and then feed the output to awk

*You're never creating the
...
 around your list elements.
→ Let's make sure to include those elements in our output.

*You're trying to redirect the output to *.html, but that's not going to do what you want. That will produce different behavior depending on what files exist in the current directory.
→ We should construct the output filename based on the input filename. If for an input file named something.csv we want to output to something.html, we can write:
"${file%.csv}.html"

The expression ${file%.csv} is a bash expression that strips the .csv from the contents of the file variable.
It looks like maybe you want something like:
#!/bin/bash

for file in *.csv; do
  sort -t"," -k2 "$file" |
  awk -v file="$file" -F"," '
    BEGIN {
      printf "
%s
\n", file, file
      printf "
\n"
    }
    {
        printf "
%s (%s)
\n", $2, $3
    }
    END {
      printf "
\n"
    }
  ' > "${file%.csv}.html"
done

Given the input:
alice,8,alice,alice,alice
bob,6,bob,bob,bob
carol,7,carol,carol,carol
david,5,david,david,david
edith,4,edith,edith,edith
frank,3,frank,frank,frank
grace,2,grace,grace,grace

This produces as output:

file1.csv

2 (grace)

3 (frank)

4 (edith)

5 (david)

6 (bob)

7 (carol)

8 (alice)

(You could replace my use of printf in the awk script with print, but I find printf easier to work with.)


text:
Q: How to send data with Angular to spring boot application..? I have made an login application in angular 2 and its working...
My app.ts
import {bootstrap, Component} from 'angular2/angular2';
import {DemoForm} from './form';
//import {FormBuilder, ControlGroup} from "angular2/angular2";

@Component({
  selector: 'my-app',
  template: `
    <demo-form></demo-form>
  `,
  directives:[DemoForm]
})
class AppComponent {
  constructor(){}
}

bootstrap(AppComponent,[]);

and my form.ts
import {Component, View, FORM_DIRECTIVES} from 'angular2/angular2';

@Component({
  selector: 'demo-form'
})
@View({
  directives: [FORM_DIRECTIVES],
  template: `

    <form #f="form" (submit)="onSubmit(f)">

        id
        <input type="text" class="form-control" ng-control="id" placeholder="id" required>

        name
        <input type="text" class="form-control" ng-control="name" placeholder="name" required>

      <button type="submit" class="btn btn-default" [disabled]="!f.valid">Submit</button>
    </form>

    submitted : {{submitted|json}}

  `
})
export class DemoForm {
  private submitted:object = {};
  onSubmit(f) {
    this.submitted = f.value;
  }
}

and when submitted i my username and password will in json format as
submitted : { "id": "Test", "name": "password" }
Now i have to  send the username and password from my Angular application to spring boot controller...
so that i can use that username and password in my back-end...
i have no idea how to start it.. so if you have some tutorials and or simple plunker example that can help me with this.. share it

A: You don't have to find an A-Z document on how to do it. You can learn pieces at a time.
Basically, you need to have:

*

*some method of input: Angular 2 Forms

*a way to send that input to the backend: Angular 2 HTTP Services

*a secure login on the backend: Spring Security Getting Started
Other links

*

*Spring + Angular2: https://github.com/borysn/spring-boot-angular2

*Angular 2 login: http://jasonwatmore.com/post/2016/09/29/angular-2-user-registration-and-login-example-tutorial


text:
Q: System.Timers.Timer for long time intervals Is System.Timers.Timer good enough for invoking a method in longer time intervals? I.e. for daily jobs and similar things. Is something better out there what I should use for something like that?
Example:
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoTimedWork);
timer.Interval = 1000 * 60 * 60 * 24; // 24 Hours
timer.Start();

Thanks!

A: How is your application process initiated? Using a System.Timers.Timer with a 24-hour interval is fine, provided you can guarantee your process will still be alive to handle the timer callback - your process might have a memory-leak or resource-leak that causes the OS to kill it, or it might be hosted in an environment that routinely "recycles" processes (such as Application Pools in IIS).
A better solution would be to have both: start the timer in your application, but also have a cron-job ("Scheduled Task" on Windows) that will start your program if it isn't already running - you can use a systemwide named mutex and other IPC means to ensure only 1 instance of your application runs at a time.

A: As long as your process is actually alive during this time (for example because it's a windows service) then a timer is fine.
If you need to do something at a specified time and cannot guarantee your process is running, using the Windows Task Scheduler might be a good option.
If you need more options, you might want to look into scheduling libraries like Quartz.

A: I use Hangfire for it. There are awesome features, like Fire-and-forget tasks, delayed tasks, recurring tasks. Background jobs are saved into a persistent storage like SQL Server, Redis, PostgreSQL, MongoDB and others. You can run it as a console application, Windows Service, Azure Worker Role, etc. Also is open source and completely free for commercial use


text:
Q: How to apply SUBTOTAL count distinct in Libre Office Calc? I've applied =SUBTOTAL(3, RANGE:RANGE) but I need to count only the unique values.
is there any way like this =SUBTOTAL('function-distinct', RANGE:RANGE)
How to apply SUBTOTAL count distinct in Libre Office Calc ?


text:
Q: DB2 & SQL Table Views I am attempting to pull some information from a DB2 table to be inputted into an SQL view/ table. I have the AQT application and the Primary key is an account number in both the SQL and DB2 table.
An example would be a db2 with the account number and customer name. The information I'm looking to add to my SQL view is the customer name from that db2 table
Where would I start to enable this to happen automatically on a daily basis?

A: To run something on a regular schedule in DB2 you can either use external services like cron or the built-in DB2 Administrative Task Scheduler. The latter has some SQL interfaces, uses the built-in security, and can be monitored.


text:
Q: Why must absolute value be used in this equation? I have a simple equation:
$(x-2)^2 < 3$
My first solution was:
$x-2 < \sqrt{3}$
But this gives me only:
$x < \sqrt{3} + 2$
Which is only one solution, so it's not enough. I've figured it out that I must use:
$|x-2| < \sqrt{3}$
Then, solutions are:
$-\sqrt{3} + 2 < x < \sqrt{3} + 2$
My question is how can I know that here:
$(x-2)^2 < 3$
I must use absolute value after square rooting both sides of inequality? Like: $|x-2| < \sqrt{3}$

A: Because, if $b>0$, then $a^2<b\iff\lvert a\rvert<\sqrt b$. This is so because\begin{align}a^2<b&\iff b-\lvert a\rvert^2>0\\&\iff\left(\sqrt b-\lvert a\rvert\right)\left(\sqrt b+\lvert a\rvert\right)\\&\iff\sqrt b-\lvert a\rvert>0\text{ (since $\sqrt b+\lvert a\rvert>0$)}\\&\iff\lvert a\rvert<\sqrt b.\end{align}

A: The quantity $(x-2)^2$ is derived by the squaring of the quantity $(x-2)$. But, you do not know whether this expression is positive or not. Thus, by square-rooting (as you did), you must take into consideration both cases, which is only yielded by using the absolute value.
Note, that the absolute value represents the essence of distance in the set of reals $\mathbb R$. The expression $|x-2| < \sqrt{3}$ means that the distance of $x$ from $2$ is less than $\sqrt{3}$. But $x$ can be either positive or negative, exactly as we wanted.
Thus, a rigorous solution in such case when you're trying to solve for every $x \in \mathbb R$, shall be as:
$$(x-2)^2 < 3 \Rightarrow |x-2| < \sqrt{3} \Leftrightarrow -\sqrt{3} + 2 < x < \sqrt{3} + 2$$
A simple example to understand the importance of the absolute value: Take into account the equation $x^2 = 4$. If you do not use the absolute value and thus not taking into consideration the negative value case, you will only get $x=2$. But, isn't also $(-2)^2 = 4$ ? Thus, the right way to go is $x^2 = 4 \Rightarrow |x| = 2$.

A: If you are not comfortable using $|x-2|$ then you can divide your derivation into two cases as follows:
Case 1: $x-2\ge 0$ :
$(x-2)^2 < 3 \\ \Rightarrow 0 \le x-2 < \sqrt 3 \\ \Rightarrow 2 \le x < 2+\sqrt{3}$
Case 2: $x-2< 0$ :
$(x-2)^2 < 3 \\ \Rightarrow -\sqrt 3 < x-2 < 0\\ \Rightarrow 2-\sqrt 3 < x < 2$
Taking the union of the intervals from the two cases, we get $2-\sqrt{3}<x<2+\sqrt{3}$. The case by case approach is useful for more complex inequalities e.g. $2 < (x-2)^2<3$.

A: Because $\sqrt{x^2} = |x|$ for $x \in \mathbb{R}$. When $x-2$ is negative, a square root doesn't just negate the exponent.

A: Set $y:=x-2$, then
$0\le y^2<3$;
$y^2-3\lt0$;
$(y+√3)(y-√3)\lt 0$;
Only viable option:
$y +√3 \gt 0$ and $y -√3 \lt 0$.
$y \gt -√3$, and $y \lt √3$ i.e.
$-√3 <y<√3$, or $-√3 <x-2<√3$.


text:
Q: Filtrar datos de un gridview segun una segunda tabla Estimados,
Tengo la siguiente duda, en visual basic, con base de datos sql server, quiero que en un datagridview se me muestre los datos de una tabla de mi base de datos llamada listado_marcas_autos, pero que se filtre sin mostrar las marcas de los autos que estan almacenadas en otra tabla que se llama marcas_ya_ingresadas
por ejemplo, la tabla listado_marcas_autos contiene las marcas de todos los autos que serian: chevrolet, toyota, kia, jeep, hyndai
si yo en la otra tabla llamada marcas_ya_ingresadas que en un comienzo esta vacia, ingreso la marca "toyota". entonces al cargar el gridview deberia mostrar todas las marcas que salen en la tabla listado_marcas_autos, exceptuando las marcas que esten en la tabla marcas_ya_ingresadas, en este caso "toyota".

A: Pienso que la consulta sería así:
SELECT LMA.*
FROM listado_marcas_autos AS LMA
FULL JOIN marcas_ya_ingresadas AS MYI ON LMA.ID = MYI.ID
WHERE MYI.ID IS NULL


text:
Q: Find these linear functionals I'm trying to solve this question:

Let $E \subset \mathbb{R}^n$ be a vector subspace of dimension $m$. Prove that there are $n-m$ linear functionals $f_1, \dots, f_{n - m} : \mathbb{R}^n \longrightarrow \mathbb{R}$ such that $E = \{x \in \mathbb{R}^n \mid \ f_1(x) = \dots = f_{n - m}(x) = 0\}$.
Prove also that there is a linear surjective map $A: \mathbb{R}^n \longrightarrow \mathbb{R}^{n - m}$ such that $E = A^{-1}(0)$.

My attempt of solution:
If $x\in E$, see $x$ in the first $m$ coordinates of $\mathbb R^n$ (can we do this?). I know how to find linear functionals such that $f_1(x)=\ldots = f_{n-m}(x)=0$. It suffices to define $f_1,\ldots,f_{n-m}$ vanishing in the first $m$ elements of the basis. However, I don't know which it will be the values in the rest of the elements of the basis in $f_1,\ldots,f_{n-m}$.
Am I going the right way? I thought this approach a little bit informal because of the argument in the first line.
I need help to finish this proof.
Thanks.


text:
Q: Unable to execute the Producer while adding delay header I want to delay the message by a particular time being scheduled to be delivered by the broker.
Producer.java
    @Component
public class kafkaProducerRoute extends RouteBuilder{
    @Override
    public void configure() throws Exception {

        int delayMs=10000;

       from("timer:time")
                // loop over the route 10 times
                 .setHeader("delay", constant(delayMs))
                 .setBody().constant("Hello, World!")
                .to("kafka:hell1?brokers=localhost:9092")  // send the message to a Kafka topic using the Kafka producer endpoint
                .log("Message is produced");

    }
}

After Running the Routes I am getting an error ":"java.lang.IllegalArgumentException: Magic v1 does not support record headers"

How to Solve this, Or is there any alternative way to Produce delay message.


text:
Q: Elaboration of a vector space over $GF(2)$ with symmetric difference as addition operation. The example given below is from Golan's "Linear Algebra":

But I have some questions regarding it.
My questions are:
1- What is the meaning of $GF(2)$ in this example, does it mean $\mathbb{Z}/(2)$ and why is scalar multiplication defined specifically in this way?
2- How do we note that there is a bijective function from $V$ to $GF(2)^A$? And why does this bijective function assign a characteristic function? How do we know this?
3- How can I prove that $\chi_{A} + \chi_{B} = \chi_{A+B}$ and $\chi_{A} \chi_{B} = \chi_{A\cap B}$?
Thanks!

A: Question 1
Yes
Question 2
In general, for set $E$ with cardinal $\vert E \vert$, the cardinal of the power set $\mathcal P(E)$ is $2^{\vert E \vert}$. As $GF(2)$ has $2$ elements, the cardinal of $GF(2)^A$ is equal to the one of $V$ which is $2^{\vert A \vert}$. Equally of cardinals implies the existence of a bijection. You can verify that $X \mapsto \chi_X$ is indeed such a bijection.
One of the axioms of a vector space $V$ is that $1 \cdot x =x$ for all $x \in V$. This is why $1 \cdot B$ is defined as $B$. Also in a vector space, one can prove that $0 \cdot x = x$ for all $x \in V$, therefore the definition here of $0 \cdot B = B$.
Question 3
Look at the different cases $x \in A \setminus B$, $x \in B \setminus A$ and $x \in A \cap B$ to prove the requested equalities. For example if $x \in A \setminus B$, you have $\chi_A(x) = 1$, $\chi_B(x) = 0$ and $\chi_{A+B}(x) = 1$.

A: *

*$GF(2)$ is the field $\mathbb{Z/(2)}$. Scalar multiplication is defined in this way so that it satisfies the 4 scalar multiplication axioms for a vector space.

*The function $V \rightarrow GF(2)^{A}$ is given to you as $B \mapsto \chi_{B}$. To see that it's bijective, verify that its inverse is the function $GF(2)^{A} \rightarrow V$ defined by $f \mapsto \{a\in A:f(a)=1\}$. Why a characteristic function was chosen is because it does the job.

*Using $A$ here is possibly a typo; I think they should be using arbitrary elements $B,C \in V$. So to prove $\chi_{B}+\chi_{C}=\chi_{B+C}$ and $\chi_{B}\chi_{C}=\chi_{B\cap C}$ for any $B,C \in V$, you must show that $\chi_{B}(a)+\chi_{C}(a)=\chi_{B+C}(a)$ and $\chi_{B}(a)\chi_{C}(a)=\chi_{B\cap C}(a)$ for any $a \in A$. These require a tedious examination of cases: (i) $a \notin B \cup C$; (ii) $a \in B \setminus C$; (iii) $a \in C \setminus B$; (iv) $a \in B \cap C$.


text:
Q: How to read PDF without using 3rd party dll in asp.net C# I am trying to read a PDF without using any third party dll.
I searched in Google but didn't find a good link to proceed.
In some links I found that: we can't read the content of PDF because its in binary format.
Is there any way to read PDF without third party dll or we have to use third party dll to read a PDF?

A: You'll have to use 3rd party solution
I recommend PDFSharp

A: Try it ,
byte[] yourByteData = .. assign your pdf data here ....
Response.ClearHeaders();
Response.Clear();
Response.AddHeader("Content-Type","application/pdf");
Response.AddHeader("Content-Length",yourByteData.Length.ToString());
Response.AddHeader("Content-Disposition","inline; filename=sample.pdf");
Response.BinaryWrite(yourByteData);
Response.Flush();
Response.End();


text:
Q: Make excel recognize foreign date format I am trying to import a text file (tab-separated columns) into excel. The log file uses MM/DD/YYYY HH:MM:SS,mmmm  (where mmmm is milliseconds), which excel treats as string.
How can I get excel to recognize it as a date, so I can sue it as X axis for charts, reformat it etc?
(System is W7 Ultimate set to use an English/US UI, Excel is German)

A: You can add a new column after import and then convert the strings into an Excel datetimes with:

=DATE((MID(A1,7,4)),(MID(A1,1,2)),(MID(A1,4,2)))
 +TIME(MID(A1,12,2),MID(A1,15,2),MID(A1,18,2))

You can also add the fractional part if you need that resolution with:

=DATE((MID(A1,7,4)),(MID(A1,1,2)),(MID(A1,4,2)))
 +TIME(MID(A1,12,2),MID(A1,15,2),MID(A1,18,2))
 +VALUE(MID(A1,21,4))/(86400*10000)

These examples assume your string is in cell A1.


text:
Q: PHP : how to get original value of number after being scaled (for zoom logic) currently i am making some "zoom in / zoom out" logic in php,
and now i have some problem with scaling value and reverting it back to original value in php (if applicable to js it would be awesome).
here is the codes
$scale          = 1;
$currentScale   = 1;
$position       = 50;
$step           = 5; // or 10

for($index = 1; $index <= $step; $index++){
    echo('-----------------------------------------------------
');

    $currentScale       = $scale / $index;
    $position           = $position * $currentScale;
    $originalPosition   = (($scale / $currentScale) * $position) * (($scale / $currentScale) / $scale);

    echo('current scale : ' . $currentScale . '
');
    echo('current position : ' . $position . '
');
    echo('original position : ' . $originalPosition . '
');
}

the goal is to make the $originalPosition value same as the first $position value (on every scale), i have tried many formula but no luck, hope you guys can help.
thanks in advance.
rule $originalPosition not stored before loop

A: ok, i think i found out the solution, i'll leave this code here in case somebody facing same problem
    $scale          = 1;
    $currentScale   = 1;
    $position       = 80; // change it to any value
    $step           = 5;

    echo('original position : ' . $position . '
');

    for($i = $step; $i >= 1; $i--){
        echo('-----------------------------------------------------
');

        $currentScale       = ($scale / $step) * $i;
        $position           = $position * $currentScale;
        $originalPosition   = $position;

        $maxLoop = $step - $i;

        if($maxLoop){
            for($j = $maxLoop; $j >= 0 ; $j--){
                $tempScale          = $scale - (($scale / $step) * $j);
                $originalPosition   = $originalPosition / $tempScale;
            }
        }

        echo('max rescale loop : ' . $maxLoop . '
');
        echo('current scale : ' . $currentScale . ' ( ' . $currentScale * 100 . '% )
');
        echo('current position : ' . $position . '
');
        echo('original position : ' . $originalPosition . '
');
    }
    exit;

here is the result, the original position stays the same as initial value


text:
Q: is there any way to access a class instance in other cs file? I just defined a static class instance to realize this, but my program has some bugs, I'm wondering is that the static instance cause the bug.
so is there any good way to access a class instance in other cs file?
My code is below:
public class AdvCANIO
{
   private IntPtr hDevice;
   //Device handle
   private IntPtr orgWriteBuf = IntPtr.Zero;
   // Fields
   private Win32Events events;
   private Win32Ovrlap ioctlOvr;
   .....
    public AdvCANIO()
    {
      hDevice = INVALID_HANDLE_VALUE;
        .......
    }
    ~AdvCANIO()
    {
       if (hDevice != INVALID_HANDLE_VALUE)
       {
          AdvCan.CloseHandle(hDevice);
          Thread.Sleep(100);
          ........
          Marshal.FreeHGlobal(lpCommandBuffer);
          hDevice = INVALID_HANDLE_VALUE;
       }
    }

xx.cs
public static AdvCANIO Device ;
public MainWindow()
{
    InitializeComponent();

    Device = new AdvCANIO();
}

yy.cs
xx.Device.hDevice... ;  //Device is the class instance in xx file.


text:
Q: Connexion Python framework set multiprocesses I try to configure Connexion to set the number of processes or threads as is possible in Flask framework. This is possible in Flask but it seems that Connexion is not sending this configuration to Flask. I read the Connexion documentation but I didn't find anything. Is this possible?
app = connexion.App(__name__, specification_dir='swagger/', debug=False, processes=4)
app.run(port=8080, server='gevent')

I try to set the parameters in connexion.App but you can't set this kargs.
Connexion version:
connexion==1.1.9

A: I found a workaround for this. To run the application with uWSGI. You can use the Flask WSGI app with any WSGI container. Using Flask with uWSGI
Here is an example:
$ sudo pip3 install uwsgi
$ uwsgi --socket 0.0.0.0:8080 --protocol=http --callable app --file app.py --master -p 4  # use 4 worker processes


text:
Q: Implement Authentication using ASP Identity With 2 Tables Instead of the default 5 tables, I would like to use just UserLoginsTable and UserTable. Because I just have one 'User' type (Admin) and there's no point of having the other tables.
I'm using ASP MVC 5 framework and Entity Framework 6 (Code First approach).
How can I achieve this in my application?

A: You create your own User inheriting IdentityUser like this:
public class User : IdentityUser
{

}

Then you ignore the other classes in your DbContext, including the original IdentityUser, including your Users DbSet:
public class MyDbContext : IdentityDbContext
{

    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // avoid some base class sets...

        modelBuilder.Ignore<IdentityUser>();
        modelBuilder.Ignore<IdentityUserRole>();
        modelBuilder.Ignore<IdentityRole>();
        modelBuilder.Ignore<IdentityUserClaim>();

        // keep identity's original configurations for AspNetUsers and AspNetUserLogins
        EntityTypeConfiguration<User> configuration = modelBuilder.Entity<User>().ToTable("AspNetUsers");
        configuration.HasMany<IdentityUserLogin>(u => u.Logins).WithRequired().HasForeignKey(ul => ul.UserId);
        IndexAttribute indexAttribute = new IndexAttribute("UserNameIndex")
        {
            IsUnique = true
        };
        configuration.Property((Expression<Func<User, string>>)(u => u.UserName)).IsRequired().HasMaxLength(0x100).HasColumnAnnotation("Index", new IndexAnnotation(indexAttribute));
        configuration.Property((Expression<Func<User, string>>)(u => u.Email)).HasMaxLength(0x100);
        modelBuilder.Entity<IdentityUserLogin>().HasKey(l => new { LoginProvider = l.LoginProvider, ProviderKey = l.ProviderKey, UserId = l.UserId }).ToTable("AspNetUserLogins");

    }

}

The reason why I ignored the original IdentityUser and created my own User is because of this exception:

The navigation property 'Roles' is not a declared property on type
  'IdentityUser'. Verify that it has not been explicitly excluded from
  the model and that it is a valid navigation property.

I tried using modelBuilder.Entity<IdentityUser>().Ignore(u => u.Roles); but it didn't solve, though if someone knows how to solve this, we could keep things simpler, I would appreciate any suggestions.

A: when you run add-migration "ApplicationDbContext", its give you the code of migration file which contains all the queries, what you need here is write the code to delete other 4 tables like:
enable-migrations
add-migration "drop tables" //selected specific context

write down the below code inside the migration code class
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.AspNetRoles");

finally run the below command
update-database


text:
Q: Pan Image in Xamarin Forms I try to create a ContentPage, where i can do an article presentation with rotation (just multiple images), comparable to this solution: http://www.360-javascriptviewer.com/index.html. When the user does a Pan Gesture the image needs to be exchanged.
View:
<ContentPage.Content>
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
  <Image Source="{Binding SelectedArticleImage.ImageSource}"
         VerticalOptions="FillAndExpand"
         HorizontalOptions="FillAndExpand">
    <Image.GestureRecognizers>
      <PanGestureRecognizer PanUpdated="OnPanUpdated"/>
  </Image.GestureRecognizers>
  </Image>
  <Label Text="A simple Label for test purposes"/>
</StackLayout>
</ContentPage.Content>

Viewmodel/Model:
public partial class RotationPage : ContentPage
{
    public RotationPage()
    {
        InitializeComponent();
        BindingContext = App.Locator.Rotation;
    }

    public void OnPanUpdated(object sender, PanUpdatedEventArgs e)
    {
        App.Locator.Rotation.OnPanUpdated(sender, e);
    }
}
public class RotationViewModel : ViewModelBase
{
    private double panValueBeginning;
    private double panValueRunning;
    private double screenWidthFactor = 100;
    private List<ArticleImage> articleImages;

    private ArticleImage selectedArticleImage;
    public ArticleImage SelectedArticleImage
    {
        get
        {
            return (selectedArticleImage == null ? articleImages.FirstOrDefault() : selectedArticleImage);
        }
        set
        {
            Set(() => SelectedArticleImage, ref selectedArticleImage, value);
        }
    }

    public RotationViewModel()
    {
        articleImages = new List<ArticleImage>();
        LoadImageList();
    }

    private void LoadImageList()
    {
        for (int i = 0; i < 64; i++)
        {
            string name = "_" + (i + 1).ToString("D2") + ".jpg";
            articleImages.Add(new ArticleImage(name));
        }
    }

    public void OnPanUpdated(object sender, PanUpdatedEventArgs e)
    {
        Debug.WriteLine(e.StatusType.ToString() + ": " + e.TotalX);
        switch (e.StatusType)
        {
            case GestureStatus.Started:
                panValueRunning = 0;
                break;

            case GestureStatus.Running:
                panValueRunning = e.TotalX;
                SelectImage(e.StatusType, e.TotalX);
                break;

            case GestureStatus.Completed:
                panValueBeginning = panValueRunning;
                SelectImage(e.StatusType, e.TotalX);
                break;

            case GestureStatus.Canceled:
                panValueBeginning = 0;
                break;

        }
    }

    private void SelectImage(GestureStatus status, double totalX)
    {
        double panValueRelative = (panValueBeginning + panValueRunning) % screenWidthFactor;
        double panValueAbsolute = (panValueRelative < 0 ? screenWidthFactor : 0) + panValueRelative;
        int index = Convert.ToInt32(Math.Max(1, Math.Min((panValueAbsolute / screenWidthFactor) * articleImages.Count, articleImages.Count))) - 1;
        SelectedArticleImage = articleImages[index];
    }
}

public class ArticleImage
{
    public string Path { get; }
    public ImageSource ImageSource { get; set; }

    public ArticleImage(string path)
    {
        Path = path;
        ImageSource.FromFile(path);
    }
}

I hope you understand what i tried to do: OnPanUpdated loads a new Image from the Filesystem, depending on how far the user panned. On UWP Platform it is working, but far away from running... very laggy and no "realtime" rotation.
On Android I get an out of memory exception after 2 successful pans.
Is my approach generally wrong? How could I handle the image changing?
Thanks for any answers!

A: It sort of looks like you are trying to emulate what a CarouselView does. You may want to take a look at using this control which will allow you to swipe between images. It also is virtualized, so you will likely not run into those memory issues.
There is a post on the Xamarin blog to help get started, here.
This package is available on NuGet and is currently a pre-release version, so make sure you are searching with Include PreRelease Packages checked in Visual Studio.
Sample from blog post:
Since the CarouselView is in a separate assembly, we must bring in the CarouselView's namespace in root of our page:
xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
Then, add the control to your page content:
<cv:CarouselView ItemsSource="{Binding Images}" x:Name="CarouselImages">
    <cv:CarouselView.ItemTemplate>
      <DataTemplate>
        <Grid>
          <Image Source="{Binding Url}"/>
        </Grid>
      </DataTemplate>
    </cv:CarouselView.ItemTemplate>
  </cv:CarouselView>

If you are building applications for Windows, a DataTemplate needs to be added to the Application Resources in the App.xaml of the application.
First add a new namespace in the root node:
xmlns:uwp="using:Xamarin.Forms.Platform"
Then add the following to the Application.Resources node:
<DataTemplate x:Key="ItemTemplate">
    <uwp:ItemControl HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</DataTemplate>

It should look something like this:
<Application
    x:Class="MyApp.UWP.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uwp="using:Xamarin.Forms.Platform"
    xmlns:local="using:MyApp.UWP"
    RequestedTheme="Light">
    <Application.Resources>
        <DataTemplate x:Key="ItemTemplate">
            <uwp:ItemControl HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
        </DataTemplate>
    </Application.Resources>
</Application>

Linker Considerations
To ensure that the CarouselView does not get "Linked-out" when compiling in release mode ensure that you are using Compiled XAML by adding the following code into the project's AssemblyInfo.cs where your XAMLexists:
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]

Or add the following code after the Forms.Init(); call in each project:
var cv = typeof (Xamarin.Forms.CarouselView);
var assembly = Assembly.Load(cv.FullName);

Additional Resources:
Forms Documentation
Source code for sample


text:
Q: Change color of repeat single character using NSAttributeString? I have a scenario to change the color of single repeat characters '#' in a string just like as image shown below.
I m using this code.
    let textTag = lblNewsTag.text
    let range = (textTag! as NSString).rangeOfString("#")
    let attributedString = NSMutableAttributedString(string:textTag!)
            attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
    lblTag.attributedText = attributedString


text:
Q: Disable built in hash from cakephp Oke, so I have been messing around for 5 hours straight right now and I finally managed to get my own hashed password into the post data of cakephp ( 2.x ). It has come to my attention that the login() function also hashes the password. If not, then there is something else wrong and I'm not sure what.
I hashed the password which an user filled in and it is equally to the one in my database. However, when I use $this->Auth->login() it fails to login. It keeps returning false. When it returns false, I'm checking what the current data is ( $this->request->data['account']['password'] and this does equal to my password in the database.
Is there any ( simple ) way to remove the has from cakephp so I can use my own?
The code of which I am talking about is as following;
public function index() {
    if($this->Session->check('Auth.User')){
        $this->redirect(array('controller' => 'Authentication', 'action' => 'test'));
    }

    if ($this->request->is('post')) {
        $password = $this->request->data['account']['username'];
        $this->hashPasswords($this->request->data);
        if ($this->Auth->login()) {
            $this->Session->setFlash(__('Welcome, '. $this->Auth->user('username')));
        } else {
            $this->Session->setFlash(__('Invalid username or password; '. $this->request->data['account']['username'] ."--". $this->request->data['account']['password'] ));
            $this->request->data['account']['password'] = $password;
        }
    }
}


text:
Q: Setting a HTTP response code in PHP (under Apache) Given the following two methods for setting a HTTP response code in PHP (specifically, under Apache):
Method 1:
http_response_code(404);

Method 2:
header("HTTP/1.0 404 Not Found");

My questions are:

*

*Aside from the fact that http_response_code is only available in PHP 5.4 or greater, what are the differences between the two approaches and why/when to use one over the other?

*Where does the Reason Phrase come from when using the first example? (I've checked and a Reason Phrase is generated from somewhere)

A: Since I'm being downvoted into oblivion for no apparent reason, I've managed to answer this myself by scouring through the PHP source code.  Hopefully this serves as a reference for anyone else trying to work this out.
The two methods are essentially functionally equivalent. http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h.
Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method. Note also that http_response_code is only available in PHP 5.4.0 and higher.
In summary - The differences between http_response_code and header for setting response codes:

*

*Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.

*Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header function.

*http_response_code is only available in PHP 5.4.0 and higher


text:
Q: Django permission check in template based on current user Given some models:
class MailingList(models.Model):
    name = models.CharField(max_length=200, unique=True)

class Recipient(models.Model):
    email = models.CharField(max_length=200)
    mailingList = models.ForeignKey(MailingList)

class ListAdministrator(models.Model):
    username = models.CharField(max_length=200)
    mailingList = models.ForeignKey(MailingList)

I would like to accomplish the following in clean MVC fashion without unnecessary code duplication: The currently logged in user may only delete a Recipient from a MailingList if he is listed as one of the ListAdministrators or is a superuser.
The permission check should happen in two places:

*

*The view deleteRecipient(request, recipient_id) should check for the required permissions before deleting a recipient. This part is easy, all the required information is right there in request.user and the listadministrator_set of Recipient.objects.get(pk=recipient_id).mailingList.

*In a template listing all mailing lists with all respective recipients, only those which the current user is allowed to delete should display a "Delete Recipient" link next to them. This is where I struggle:

*

*I cannot give the model a method userMayDelete(self, user) and call that method from the template passing the current user, because Django won't allow parameter passing from templates.

*I cannot give the model a method currentUserMayDelete(self) without the user parameter because a model can't access the current user implicitly.

*Passing the template two sets of mailing lists, those which the user can delete recipients from and those he can't, seems cumbersome. And it wouldn't allow a combined alphabetically sorted display of all list.

What is a clean (and preferably simple) way to accomplish this?

A: You can set additional attribute to the MailingList instance before passing it into to template:
def show_lists(request):

    username = request.user.username
    lists_under_control = [la.mailingList for la in
                           ListAdministrator.objects.filter(username=username)]

    mailing_lists = list(MailingList.objects.all())
    for mailing_list in mailing_lists:
        mailing_list.user_may_delete = (mailing_list in lists_under_control)

    return render(request, 'app/mailing_lists.html',
                           {'mailing_lists': mailing_lists})

And then use this attribute in the template:

{% for mailing_list in mailing_lists %}

{{ mailing_list }}

        {% for recipient in mailing_list.recipient_set.all %}

{{ recipient.email }}
                {% if mailing_list.user_may_delete %}

                        Delete recipient

                {% endif %}

        {% endfor %}

{% endfor %}

The other (much worse) option is to create template filter and use it like this:
{% if user|may_delete:mailing_list %}


text:
Q: Save the final value of a linked list to a variable in Java I want to save the final value on a LinkedList of 5000000 integers by using an iterator. For this assignment, I need to traverse through the entire list (I know this is not the most efficient way). Here is the code that I have:
//method 1:
        ListIterator ls = list.listIterator();
        while (ls.hasNext()) {
            var save = ls.next(); //my attempt to save the final value
            ls.next();
        }

What is the best way for me to save the value at the last index to a variable?

A:
What is the best way for me to save the value at the last index to a
variable?

Keeping in mind that there are 5.000.000 elements the most efficient way to access the last element is to make use of the fact that LinkedList implements the Deque interface:
        List<Integer> list = new LinkedList<>();
        .....
        Integer last = ((Deque<Integer>) list).peekLast();

Note:

*

*any element in the list could be null and application will crash if you'll try to assign null to an int variable;

*in order to invoke the method peekLast() first you have to cast the list to the appropriate type.

But, if for this task you have to use a ListIterator at all costs, then I advise you to fix the code you've provided like that:
    public static Optional<Integer> getLast(List<Integer> list) {
        ListIterator<Integer> ls = list.listIterator();
        Integer last = null;
        while (ls.hasNext()) {
            last = ls.next();
        }
        return Optional.ofNullable(last);
    }

A: ListIterator<Integer> ls = list.listIterator();
int last = -1;
while (ls.hasNext()) {
  last = ls.next();
}

A: Alternatively, don't save the value as you go through the list:
while (ls.hasNext()) {
  ls.next();
}
// Assuming the list isn't empty:
var last = ls.previous();

A: You can use
list.getLast();

to get the last item from the list.


text:
Q: order by with multiply custom name in brackets failed It failed when I put the column name in brackets:
select id as "gid", coalesce(name, 'apple') as "name"
from test
order by ("gid", "name") desc

And I want the above code to achieve the same result as this:
select id as "gid", coalesce(name, 'apple') as "name"
from test
order by (id, name) desc;

And it will work fine with:
select id as "gid", coalesce(name, 'apple') as "name"
from test
order by "gid" desc, "name" desc

So why can't Postgres find "gid"? And is order by (a, b) the same as order by a,b?
Here is my create sql:
CREATE TABLE test ( "id" serial NOT NULL, "name" text NOT NULL, PRIMARY KEY ("id") );
INSERT INTO test (name) VALUES ('Apple');
INSERT INTO test (name) VALUES ('Orange');
INSERT INTO test (name) VALUES ('Pear');

A: Postgres allows column references in the ORDER BY.
However, it does not allow expressions on column references.  The parentheses turn the ORDER BY keys into an expression, specifically one that creates an anonymous record.
If you want to do this, you can use a lateral join to define the columns:
select v.*
from test t cross join lateral
     (values (id, coalesce(name, 'apple'))) v("gid", "name")
order by (v."gid", v."name") desc;

The aliases are needed in the order by only because "name" is defined in both tables.


text:
Q: Why does Thunderbird always return immediately after sending mail through MAPI? Why does Thunderbird always return immediately after sending mail through MAPI?
Other clients, like Outlook Express, returns only when the mail is sent or when the user was cancelled the request. But Thunderbird always return SUCCESS every time.
Somebody knows why or knows how to fix it?
Thanks in advance.

A: Not all email clients behave the same.  The specific behavior does not need to comply (AFAIK) to any standard.  My copy of Thunderbird, by the way, first sends the file, and I can see the "sent" progress line while it does so.
However, Microsoft Outlook may consider a mail as "sent" when it is placed into the "Outgoing" folder (I last checked in the beginning of the 2000s... so maybe has changed).
Depending on the actual requirements of your application, you may want to consider to log the message ID or handle when sending it, and then track it inside Thunderbird (programmatically) to locate whether it has moved into the "Sent" folder.

A: Here is another try at your problem.  The Activity Manager documented on Mozilla's Thunderbird API documentation webpage, is a new component available from version 3.
Among other things, it listens to events, and tells you when something has occured, and its progress.  They have an example for sending mail.
Hope this helps.


text:
Q: angular-file-upload breaks IE9 I`m trying to upload a file via angular-file-upload and on IE9 it falls back to legacy upload via flash.
The steps to reproduce this are:

*

*Press the file input to upload file

*Select file and press open

*IE9 completely breaks with an error of "Internet Explorer has stopped working" and it restarts.

The way I am uploading the file is via a $watch on the file input so basically the upload should start automatically after selecting the file.
Has anyone encountered this?
Thanks.

A: It's breaking in IE9 because IE9 does not support canvas. IF you view this URL in IE9 angular-file-upload you will see they have the es5-shim library:
<!-- Fix for old browsers -->
    <script src="http://nervgh.github.io/js/es5-shim.min.js"></script>
    <script src="http://nervgh.github.io/js/es5-sham.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="../console-sham.js"></script>


text:
Q: Is it really necessary to use fstrim on Samsung SM843T SSDs? Should we schedule periodical fstrims on Samsung SSD drives?
What happens if we don't run such periodical scripts?
I am highlighting the model on the Title because I am assuming that the answer is model/manufacturer specific.
What we are using:
2 SSDs Samsung model SM843T
Centos 7.1

A: Over time, SSD's will start to degrade because when they write and erase a lot, it will not be able to tell which blocks have been erased so it moves on to new fresh locations, and this will cause fragmentation. So eventually it just writes to the whole SSD, after which it will start 'write amplification.' Meaning that it will have to go through a cycle of read-erase-modify-write for every write, this is what slows it down.
So depending on your machine, as in how much read/write you will be doing and the SSD's capacity, I would say it is not necessary for now. But later on, it would not hurt to start fstrim.
Edit* - I do not think its vendor specific. I didn't find anything wrong with this model of SSD. But my answer above is for all SSD's in general.


text:
Q: Django's FILE_UPLOAD_PERMISSIONS not working for directories I'm trying to use Django's FILE_UPLOAD_PERMISSIONS to set permissions when a user uploads a file. The file itself is created with the correct permissions (775), but any directories created seem to be stuck with the default (755).
Example:
If a file (foo.jpg) is uploaded for a user (id = 123), it should save to media/123/foo.jpg, creating the 123 directory if it does not already exist. foo.jpg has 775 but 123 has 755.
How can I get directories saving with the correct permissions? I am using Apache with mod_wsgi in a httpd Docker container if it is relevant.

A: Django has a seperate setting for file directory permisions. It is FILE_UPLOAD_DIRECTORY_PERMISSIONS. You should set this as 0o775 in your settings.py file.
FILE_UPLOAD_DIRECTORY_PERMISSIONS documentation
File storage API documentation


text:
Q: Longitude / Latitude to quaternion I've got a longitude and latitude and want to convert this to a quaternion and wondering how I can do this? I want to use this, because I've got an app which projects the earth on a sphere and I want to rotate from one location to another one.
Best!

A: There's a way to go about this without using matrices or vectors, similar to this numpy implementation. We can think of longitude/latitude as two quaternion rotations composed together.
Let's work with a Z-up right-handed coordinate system. Let's call longitude φ and latitude θ, and the point represented by the two as (φ, θ). For visualization, the red axis corresponds to X, green to Y, and blue to Z.
We want to find the quaternion representing the rotation from (0, 0), in red, to (a, b), in green:

We can represent this rotation as a combination first of the longitudinal rotation, then of the latitudinal rotation, like so:

First, we rotated by a along the Z axis, which transforms the X and Y axes. Then, we rotated by b along the new local Y axis. Thus, we know two sets of axis/angle information for this rotation.
Luckily, the conversion from axis/angle to quaternions is already known. Given an angle α and an axis vector ω, the resulting quaternion is:
(cos(α/2), ω.x*sin(α/2), ω.y*sin(α/2), ω.z*sin(α/2))

So the first rotation is represented by a rotation of a degrees along the world (0, 0, 1) axis, giving us:
q1 = (cos(a/2), 0, 0, sin(a/2))

The second rotation is represented by a rotation of b degrees along the transformed/local (0, 1, 0) axis, giving us:
q2 = (cos(b/2), 0, sin(b/2), 0)

We can multiply these two quaternions to give us a single quaternion representing this compound rotation from (0, 0) to (a, b). The formula for quaternion multiplication is a bit lengthy, but you can find it here. The result:
q2*q1 = (cos(a/2)cos(b/2), -sin(a/2)sin(b/2), cos(a/2)sin(b/2), sin(a/2)cos(b/2))

Not that it means much, but we can confirm that this formula is the same as the numpy implementation mentioned before.
JCooper mentioned a great point that one degree of freedom is still left, along the X axis in this case. If θ stays within ±90 degrees, we can imagine that the Z axis always pointing upwards. This has the effect of constraining the X axis rotation and is hopefully what you want.
Hope this helps!

edit: Notice that this is essentially the same thing as working with 2 Euler angles. So to reverse this conversion, you can use any quaternion to Euler angle conversion, provided that the rotation order is the same.

A: Maybe you could look into how the boost C++ library implements it. (or perhaps even using it) http://www.boost.org/doc/libs/1_46_0/libs/math/doc/quaternion/html/boost_quaternions/quaternions/create.html
Longitude and lattitude are pretty much analogous to the azimuth (theta - [0, 2*PI]) and inclination (rho? [0,PI]) angles in spherical coordinates (radius r=1 of course for surface).  Boost has a function for spherical to quaternion in the link i posted.

A: Latitude and longitude aren't enough to describe a quaternion.  Latitude and longitude can describe a point on the surface of a 3d sphere.  Let's say that's the point whose normal points directly out through the screen.  You still have a degree of freedom left.  The sphere can spin around the normal vector of the point specified by lat-lon.  If you want a quaternion that represents the orientation of the sphere, you need to fully specify the rotation.
So let's say that you want to keep the north-pole of the sphere pointed upward.  If the north pole is aligned with the object's +z axis and 'up' on the screen is aligned with the world's +y axis, and then you want to rotate the sphere so that point R on the surface of the sphere is pointed directly out at the screen (where R is found using lat-lon to euclidean as you mentioned in your comment), then you create the rotation matrix as follows.
You want object's R to align with the world's +z (assuming an OpenGL-like view-coordinate system) and you want object's +z to align with world's +y (as close as possible).  We need the third axis; so we normalize R and then find: P = crossP([0 0 1]^T,R).  We normalize P and then enforce orthogonality onto the second axis: Q = crossP(R,P).  Finally, normalize Q.  Now we have 3 orthogonal vectors P, Q, R that we want to align with the world's x,y,z respectively.
I'm assuming that P, Q, and R are column vectors; so to create a transformation matrix, we just stick 'em together: M = [P Q R].  Now M is the matrix that would transform a point in world coordinates into object coordinates.  To go the opposite direction, we find the inverse of M.  Fortunately, when the columns of a matrix are orthonormal, the inverse is the same as the transpose.  So we get:
             [ P^T ]
M^-1 = M^T = [ Q^T ]
             [ R^T ]

From that, if you need, you can find a quaternion using matrix to quaternion conversion.  And then you can interpolate between quaternions using slerp or your method of choice.


text:
Q: Is the author's code correct? - B. Stroustrup's PPP using C++: Chapter 7, Section 7.2 - Input & Output I'm learning C++ using B. Stroustrup's PPP using C++, 1st edition. This chapter 7 is an extension to chapter 6 in which a basic calculator, which takes expressions (like 1+2;) to produce output (';' is for terminating expression), is developed. (I'm using Visual Studio 2013)
In section 7.2, to improve the layout of the program for the user, the author expects this -
> 2+3;
=5
> 5*7;
=35
>

and (inputting multiple expressions)
> 2+3; 5*7; 2+9;
=5
> =35
> =11
>

by using this code -
main():

double val = 0;
while (cin) {
    cout << "> "; // print prompt
    Token t = ts.get(); // get token from Token_stream ts
    if (t.kind == 'q' ) break; // 'q' for quit
    if (t.kind == ';' )      // ';' to print value
        cout << "= " << val << '\n'; // print result
    else
        ts.putback(t);  // put back token in Token_stream ts
    val = expression();  // evaluate expression
}

But to my knowledge, this piece of code cannot generate such output and works something like this,

*

*Read a token

*If it is to quit or print some value, then do it, else put that
token back into the Token_stream.

*Then, calculate the value of an expression (assuming that there is
an expression entered by the user). If there is no expression/token to read, the program just waits for the input (in primary() function).

*After the expression is evaluated, go to step 1.

So, the value of the expression will only be printed when a ';' is detected by main(), and > will be printed every time, even before printing the value of the expression, and even the output for a simple expression, 1+2; by my program is -
> 1+2;
> =3
2+3;
> =5
_

with cursor (underscore is used intentionally) in 3rd line.
So, am I correct that the author is using the wrong code? or am I simply out of my mind and something else is there too which I'm unable to see?
Here is the complete code for the calculator.
Here is the library std_lib_facilities.h.

A: You are not crazy.
It's not unheard of for published books to have bugs. Often times, the corresponding website for a book will have an online "errata" sheet that contains all the corrections pending for the next printing.
I just checked.  I found a few typos on Stroustrup's website itself.  Here is the link to the errata for his book: http://www.stroustrup.com/Programming/PPP2errata.html
I didn't see anything for chapter 7.  But if you are certain you have found a bug, do send him an email. There's a chance he might reply back and thank you.
I think the block of code you have is only marginally bugged because of this line:
cout << "> "; // print prompt

It prints the > char on every token consumption.
I think this is more reasonable:
double val = 0;

cout << "> "; // print prompt the first time.

while (cin)
{
    Token t = ts.get();              // get token from Token_stream ts

    if (t.kind == 'q' )
    {
        break;          // 'q' for quit
    }

    if (t.kind == ';' )  // ';' to print value
    {
        cout << "= " << val << '\n'; // print result
        cout << "> ";                // print new prompt
    }
    else
    {
        ts.putback(t);  // put back token in Token_stream ts
    }

    val = expression();  // evaluate expression
}


text:
Q: SLACK-MODALS Custom Leave/permission approval or deny custom app Can anyone please help me by giving me an idea on how to build a custom slack app for leave/permission approval or denial. Any suggestions will very useful.Thank you.

A:  Based on the comment, you can start looking into the examples provided by Slack.
Developing approval workflows

*

*https://api.slack.com/best-practices/blueprints/approval-workflows

*https://github.com/slackapi/template-announcement-approvals
Further documentation:
 https://github.com/slackapi


text:
Q: How to add
* tag into hyperlink helper As per title above, I am currently facing the problem while adding a nested

 tag to the hyperlink html helper.  My code is as follows...
echo $this->Html->link($this->Html->tag('li', 'home'), '/home', array('target' => '_blank'));

It printed
Home
 on the page... May I know how can I make the

 as html instead of showing in text form?

A: Add 'escape' => false to the options (3rd argument)


text:
Q: Ruby modify hash value if value array I've got a ruby hash like this :
hash = {properties: [13], attributes: [11, 15, 15], places: [66]}

I want to convert my hash to this :
hash = {properties: 13, attributes: [11, 15], places: 66}

All values that have array lenght more than 1, keep them as they are (an array), all others first element. Tried this with couple of ifs, didn't turn out the way I wanted
hash.map{ |k,v| { k => v.uniq } }.reduce(&:merge)

A: Here is how I'd do :
Hash[hash.map { |k ,v| [k, v.size > 1 ? v.uniq : v.first] }]
# => {:properties=>13, :attributes=>[11, 15], :places=>66}
# or
hash.map { |k ,v| [k, v.size > 1 ? v.uniq : v.first] }.to_h
# => {:properties=>13, :attributes=>[11, 15], :places=>66}

A: def convert(h)
  Hash[h.map {|k,v| [k, v.size == 1 ? v.first : v.uniq]}]
end

convert(hash)
# => {:properties=>13, :attributes=>[11, 15], :places=>66}

A: Here's another way:
hash.merge(hash) { |*_, v| (v.size==1) ? v.first : v.uniq }
 => {:properties=>13, :attributes=>[11, 15], :places=>66}


text:
Q: How do I generate a new GUID and then write to a new file in a specified path, using that GUID as the filename? I have created a Scanner application  using C# in visual studio.I am trying to directly save the scan data in GUIDs as the file name
How do I generate a new GUID and then write to a new file in a specified path, using that GUID as the filename?
Thanks in Advance!

A: Something like this
var somepath = Path.GetTempPath(); // tempFolder if you want it
var fileName = Path.Combine(somepath,$"{Guid.NewGuid()}.dat");

// Do something with your file name

Add pepper and salt to taste

Additional resources
Path.Combine Method

Combines strings into a path.

Guid.NewGuid Method

Initializes a new instance of the Guid structure.

Example
public static void Main()
{
    Guid g;
    // Create and display the value of two GUIDs.
    g = Guid.NewGuid();
    Console.WriteLine(g);
    Console.WriteLine(Guid.NewGuid());
}

Output
0f8fad5b-d9cb-469f-a165-70867728950e
7c9e6679-7425-40de-944b-e07fc1f90ae7

A: the Guid type has a Guid.NewGuid() method that generates a 'random' guid.
also check out this post that discusses pros and cons of newing up a guid type v using the built in newguid().
Guid.NewGuid() vs. new Guid()


text:
Q: C# Print list of string array How do I print a list of string arrays? I can do it from string[] using Console.WriteLine, but if I do that for a list with foreach it just prints out System.String[]. How do I write an index when using a foreach?

A: So you have list of string arrays, like this:
 List<string[]> data = new List<string[]>() {
   new string[] {"A", "B", "C"},
   new string[] {"1", "2"},
   new string[] {"x", "yyyy", "zzz", "final"},
 };

To print on, say, the Console, you can implement nested loops:
 foreach (var array in data) {
   Console.WriteLine();

   foreach (var item in array) {
     Console.Write(" ");
     Console.Write(item);
   }
 }

Or Join the items into the single string and then print it:
 using System.Linq;
 ...

 string report = string.Join(Environment.NewLine, data
   .Select(array => string.Join(" ", array)));

 Console.Write(report);

Or combine both methods:
 foreach (var array in data)
   Console.WriteLine(string.Join(" ", array));

A: This works for me:
var strArray = new string[] {"abc","def","asd" };
strArray.ToList().ForEach(Console.WriteLine);

A: The simplest way to achieve this is:
using String.Join
string[] arr = new string[] { "one", "two", "three", "four" };
Console.WriteLine(String.Join("\n", arr));

Hope this helps.

A: string[] arr = new string[2]{"foo","zoo"}; // sample Initialize.

// Loop over strings.
foreach (string s in arr)
{
    Console.WriteLine(s);
}

The console output:
foo
zoo

A: In a string array to get the index you do it:
string[] names = new string[3] { "Matt", "Joanne", "Robert" };

int counter = 0;
foreach(var name in names.ToList())
{
 Console.WriteLine(counter.ToString() + ":-" + name);
 counter++;
}


text:
Q: C#, .NET, Check for null in function which converts request to string I have a function which takes a request and converts it to a string:
private string CreateEmailData(Models.V2.RequestPaymentModel data)
{
   var emailRequest = new ApiRequest<RequestPaymentEmailModel>
   {
      Id = id,
      DateUtc = DateTime.UtcNow,
      Data = new Utils.EmailRequest.RequestPaymentEmailModel
      {
         LanguageCode = data.LanguageCode,
         DeviceID = data.DeviceId,
         CoreSystem = data.CoreSystem,
         Transaction = new Utils.EmailRequest.TransactionEmail()
         {
            Country = data.CountryCode,
            TransactionType = data.Transaction.Type,
            Amount = data.Transaction.Amount,
            Currency = data.Transaction.Currency,
            Authorization = "",
            Type = data.Transaction.Type,
            Description = data.Transaction.Description,
            PaymentNetwork = data.PaymentNetwork,
            ReferenceId = data.Transaction.ReferenceID,
            CartValue = data.Transaction.CartValue,
            PaymentFrequency = data.Transaction.PaymentFrequency,
            InvoiceNumber = data.Transaction.InvoiceNumber,
            GoodsType = data.Transaction.GoodsType,
            ProductID = data.Transaction.ProductId
         },
         CreditCard = new Utils.EmailRequest.EmailCreditCard()
         {
            Number = data.DataPaymentMethod.CreditCard.Number,
            Month = data.DataPaymentMethod.CreditCard.Month,
            Year = data.DataPaymentMethod.CreditCard.Year,
            FirstName = data.DataPaymentMethod.CreditCard.FirstName,
            LastName = data.DataPaymentMethod.CreditCard.LastName
         },
         PaymentMethod = data.PaymentMethod,
         DataSecurity = data.DataSecurity,
         ExtraParameter = data.DataPaymentMethod.ExtraParameter,
         Buyer = data.DataPaymentMethod.Buyer,
         Payer = data.DataPaymentMethod.Payer,
      }
   }.ToJson();

   return emailRequest;
}

But sometimes some values in a request like Payer can be null.
How can I check values for null in this function?
Right now if value null it crashes the app and returns:

$exception    {"Object reference not set to an instance of an
object."} System.NullReferenceException

A: You can use convert a null value to a string
This example means that if Transaction is null, then use empty string instead
TransactionType = data.Transaction?.Type ?? ""

This example means that if CountryCode is null, then use empty string instead
Country = data.CountryCode ?? ""

The syntax itself is basically an inline if statement, there's more to it at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

A: You'll need to include null checks.  Your problem isn't that it can't be converted into a string.  It's that you're referencing null objects.  What you need to do is replace your code where lines that look like this
Payer = data.DataPaymentMethod.Payer

are re-written to look like this
Payer = data?.DataPaymentMethod?.Payer

This way if "data" is null then then Payer is null.  If data.DataPaymentMethod is null then Payer is null.  Finally if data.DataPaymentMethod.Payer is null then Payer is null.  If your version of C# supports this syntax then this is what I would go with.  Else you'll either need to write an ugly turnary or create a method that will handle the null checks.


text:
Q: Conversion of Java object into XML and parse it using DOM/SAX I need to convert Java object into XML object and send it across to client browser from server.
And in client browser, i need to parse the obtained XML object using DOM/SAX or anything that suits and display it in UI.
Which one suits the above? Could any of them help me out in this?

A: You can use the JAXB API for your problem. JAXB(Java Architecture for XML Binding) uses annotations to convert Java object to / from XML Content. JAXB solves the following puposes:
Marshalling – Convert a Java object into a XML Content.
Unmarshalling – Convert XML content into a Java Object.
You can find the simple example of JAXB at here.

A: Here is a sample JAVA Class uses JAXB to convert JAVA Object into XML Content
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;

class JavaToXMLContent {
    public static void main(String[] args) throws Throwable {
        // =============================================================================================================
        // Setup JAXB
        // =============================================================================================================

        // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
        final JAXBContext context = JAXBContext.newInstance(JavaObject.class);

        // =============================================================================================================
        // Marshalling OBJECT to XML
        // =============================================================================================================

        // Create the marshaller, this is the nifty little thing that will actually transform the object into XML
        final Marshaller marshaller = context.createMarshaller();

        // Create a stringWriter to hold the XML
        final StringWriter stringWriter = new StringWriter();

        // Create the sample object we wish to transform into XML
        final JavaObject javaObject = new JavaObject();
        javaObject.setName("Json");
        javaObject.setRole("Moderator");
        javaObject.setAge(28);

        // Marshal the javaObject and write the XML to the stringWriter
        marshaller.marshal(javaObject, stringWriter);

        // Print out the contents of the stringWriter
        System.out.println(stringWriter.toString());

        // =============================================================================================================
        // Unmarshalling XML to OBJECT
        // =============================================================================================================

        // Create the unmarshaller, this is the nifty little thing that will actually transform the XML back into an object
        final Unmarshaller unmarshaller = context.createUnmarshaller();

        // Unmarshal the XML in the stringWriter back into an object
        final JavaObject javaObject2 = (JavaObject) unmarshaller.unmarshal(new StringReader(stringWriter.toString()));

        // Print out the contents of the JavaObject we just unmarshalled from the XML
        System.out.println(javaObject2.toString());
    }

    /**
     * JavaObject is the sample object we've created to use for marshalling to and from XML.
     * Make sure you have the @XmlRootElement annotation at the top there as well or JAXB
     * might moan.
     */
    @XmlRootElement
    private static class JavaObject {

        private String name;

        private String role;

        private int age;

        public JavaObject() {

        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Name [" + this.name + "], Role [" + this.role + "], Age [" + this.age + "]";
        }
    }
}

Hope this will help you.

A: have a look at simplexml, it use annotation for mapping between xml and java field, very handy.


text:
Q: whas is diffrence of in-line and out-line call mehtod in dart? I used this method in my Bloc in two types
first:
 on<MyEvent>(
      (event, emit) async {
        var datastate =
            await _productUsecase.getCategories();
        emit(
          state.copyWith(
            categories: datastate,
          ),
        );
      },
    );

and this :
on<MyEvent>(
      (event, emit) async {
        emit(
          state.copyWith(
            categories: await _productUsecase.getCategories(),
          ),
        );
      },
    );

but they change my app in two ways.
why?

A: i found the mistake,
its about scopes, my first code is await out side of copyWith, and after fetch data it set it in state and then emit
but, in the 2end one it await in CopyWith method, this cause to during await , save state variable and copyWith method will set this fetched data to state of befor await, and may be during fetching , it change with other events.


text:
Q: Facebook Issues Success
Possible Duplicate:
IOS: SECURITY WARNING: The above URL is not valid for a cash card or gift card

I am Facing this issues from today only. Please help me because I want to upload IPA today and its started just now. Till today It was working fine.
SECURITY WARNING: The above URL is NOT NOT VALID FOR A CASH CARD OR GIFT CARD. Giving away the URL may result in your account being HIJACKED.
And My Facebook functionality stopped without changing any code.


text:
Q: how to get compiled nodeValue from an angular element The basic premise is that I'm trying to access the element's value attribute after it compiles and copy it into a variable.  For example: if vm.datasource.data['+ i +'].HolidayName compiled into "Christmas" I want to grab that value and store it in a variable.
Is it possible to copy the compiled value into a variable?
var link = function(scope, elem, attrs){

      setTimeout(function(){
        var checkboxCellArray = elem.find('.md-checkbox-cell');

        _.forOwn(checkboxCellArray, function(node, i) {
          if(angular.element(node).hasClass('md-checkbox-cell')){
            var element = angular.element('

')
            var compiled = $compile(element)(scope);

            setTimeout(function(){
              console.log(compiled);
            }, 500)
          }
        });
      }, 1000)
    }

A: Seems after hours of toiling i've found the solution 5 minutes after posting...
simply add scope.$apply() after compiling and the variable will have the updated values.

A: The real problem was you were using setTimeout function and updating stuff of angular from it. setTimeout asynchronous event which is modifying angular scope from from outside angular world doesn't intimate angular digest system to run digest cycle. You have to kick off it manually to update binding over an HTML page. This problem can be easily fix by using using $timeout instead of setTimeout, which run your function in setTimeout & will run digest cycle after it.
Code
$timeout(function(){
    var checkboxCellArray = elem.find('.md-checkbox-cell');

    _.forOwn(checkboxCellArray, function(node, i) {
      if(angular.element(node).hasClass('md-checkbox-cell')){
        var element = angular.element('

')
        var compiled = $compile(element)(scope);

        $timeout(function(){
          console.log(compiled);
        }, 500)
      }
    });
  }, 1000)
}


text:
Q: how could I link my HTML project to laravel? I'm trying to create a webpage using laravel but there's not a lot of info online on how to actually set up everything together. I already downloaded ui:auth and there's already the login option in the laravel welcome page, my question is how do I link this to my HTML page? I already tried looking up for a file where the login info might be but whenever I link it in my HTML proyect it simply links to the raw file. So I must be doing something wrong. any help at all?

A: Have a read through the basics section on the docs, good ones that you'd need to use initially to get started are:

*

*https://laravel.com/docs/8.x/routing

*https://laravel.com/docs/8.x/controllers

*https://laravel.com/docs/8.x/views

*https://laravel.com/docs/8.x/blade
In the simplest way possible, you'll define in your routes a url path that you want to define, and then pass in the controller and method it is refering to. You can put in some basic 'business logic' (basically server logic on data) in there.
Then the controller will return a view, with view('some.blade.file') possible with some data using ->with('data', $data) if you want.
Then in your view you will have your html, which is actually blade syntax, which under the hood gets complied to php, and then that gets complied to the raw html your browser sees when hitting that route.
You can stitch together blade files so they extend off other blade files, and you can have a blade file that adds in the auth nav bar if that's what you want.


text:
Q: dpc_watchdog_violation. Am I safe? How do I fix it? I bought a new ASUS screen (VN247) today and I'm using it together with my laptop ASUS N550JV. I made the new screen primary, and laptop screen secondary.
Symptom: This happened 3 times today while I was playing Heroes of the Storm and it never happened before. What happens is the game froze, I wait a bit and then I can alt tab for a short period. After that it freezes completely.
On the first two occurrences, I was also watching twitch while playing the game so I thought it may be the cause because it happened in 2 games out of 3 games (~30 min each). Later I was playing but there was nothing on my other screen and the game froze. So I waited this time instead of restarting the computer and got dpc_watchdog_violation BSOD.
I ran online crash analysis and the culprit seemed to be csrss.exe.

I googled this process, some say it's system process, some say it's virus. I expected it to be about graphics drivers but it appears to be about remote access.
My anti virus is on, my display drivers (or any other) are up to date. No unusual activity was going on on my laptop today, except for the new screen. So what causes this and how can I mitigate the further occurrences of this BSOD?

A: After checking it a bit, I see that the nVIDIA GPU driver is involved:
0xffffd000e1022cc8 : 0xfffff803c7e59e18 : nt!KeAccumulateTicks+0xa8
0xffffd000e1022d18 : 0xfffff803c7e56a71 : nt!KeClockInterruptNotify+0x91
0xffffd000e1022d48 : 0xfffff803c7f7172c : nt!KiIpiInterruptSubDispatch+0x7c
0xffffd000e1022d68 : 0xfffff803c7ef78f5 : nt!KiIpiProcessRequests+0x135
Unable to load image \SystemRoot\system32\DRIVERS\nvlddmkm.sys, Win32 error 0n2
*** WARNING: Unable to verify timestamp for nvlddmkm.sys
*** ERROR: Module load completed but symbols could not be loaded for nvlddmkm.sys
0xffffd000e1022d88 : 0xfffff803c7f7172c : nt!KiIpiInterruptSubDispatch+0x7c
0xffffd000e1022da8 : 0xfffff803c7f714ff : nt!KiIpiInterrupt+0xff
0xffffd000e1022dc8 : 0xfffff803c7f7172c : nt!KiIpiInterruptSubDispatch+0x7c

Loaded symbol image file: nvlddmkm.sys
Image path: \SystemRoot\system32\DRIVERS\nvlddmkm.sys
Image name: nvlddmkm.sys
Timestamp:        Wed Nov 12 21:51:31 2014

try a different driver.


text:
Q: i want to know what is this window in android?
it's a youtube app and I want to know how to add the configuration window

A: It is called overflow menu.
See the image and its description below: Google Design Guidelines - Menu.

*

*The action overflow in the app bar will emit a menu.

*This particular action overflow menu contains four menu items: Refresh, Help & feedback, Settings, and Sign out.


text:
Q: Codenvy add postgresql to the project error I am new at Codenvy so my question can be very stupid, by the way this is my problem:
I created my project then to add the DB (postgresql) i created a new docker file and i pasted in it the code in this file: https://github.com/codenvy/dockerfiles/blob/master/base/jdk7_postgresql/Dockerfile
I saved it then i ran the project with the runner just created, but i have this error:
[DOCKER] Setting up dh-python (1.20141111-2) ...
[DOCKER] Processing triggers for systemd (215-17+deb8u2) ...
[DOCKER] Processing triggers for libc-bin (2.19-18+deb8u1) ...
[DOCKER] Processing triggers for dbus (1.8.20-0+deb8u1) ...
[DOCKER] Starting PostgreSQL 9.3 database server:
[DOCKER] main
[DOCKER] .
[DOCKER] CREATE ROLE
[DOCKER] ---> 77b708d3360b
[DOCKER] Removing intermediate container cdd908fb498e
[DOCKER] Step 4 : ADD startup.sh /home/user/startup.sh
[DOCKER][ERROR] startup.sh: no such file or directory
[ERROR] We are having trouble starting the runner and deploying application. Either necessary files are missing or a fundamental configuration has changed.
Docker image build failed

Any idea to how can i solve the problem?
thanks in advance!

A: This PostgresSQL image uses startup.sh script to start postgresql service. You can find it at https://github.com/codenvy/dockerfiles/blob/master/base/jdk7_postgresql/startup.sh
To solve this problem you can either create a new file startup.sh with an identical content in the root of your project, add it as a source (e.g. ADD $src$/startup.sh /home/user/startup.sh). You will also need to inject project sources to make it work as expected, so as a result your Dockerfile may look like this:
FROM codenvy/jdk7

ENV DEBIAN_FRONTEND noninteractive

RUN sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 && \
    echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list && \
    sudo apt-get update && \
    sudo -E bash -c "apt-get install -y python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3 pwgen" && \
    sudo service postgresql start && \
    CODENVY_POSTGRESQL_PASSWORD=$(pwgen -N 1) && echo "export CODENVY_POSTGRESQL_PASSWORD=$CODENVY_POSTGRESQL_PASSWORD" >> /home/user/.postgresrc && \
    CODENVY_POSTGRESQL_DB=testdb_$(pwgen -N 1) && echo "export CODENVY_POSTGRESQL_DB=$CODENVY_POSTGRESQL_DB" >> /home/user/.postgresrc && \
    CODENVY_POSTGRESQL_USER=codenvy && echo "export CODENVY_POSTGRESQL_USER=$CODENVY_POSTGRESQL_USER" >> /home/user/.postgresrc && \
    sudo -u postgres psql --command "CREATE USER $CODENVY_POSTGRESQL_USER WITH SUPERUSER PASSWORD '$CODENVY_POSTGRESQL_PASSWORD';" && \
    sudo -u postgres createdb -O $CODENVY_POSTGRESQL_USER $CODENVY_POSTGRESQL_DB

#Inject project sources
ADD $app$ /home/user/$app$
RUN unzip -q /home/user/$app$ -d /home/user
ENV ARGUMENTS $args$

#Add file to the container
ADD $src$/startup.sh /home/user/startup.sh

RUN sudo chmod +x /home/user/startup.sh

#EXPOSE 5432

CMD sudo /home/user/startup.sh

Or you can simply use Codenvy default PostgreSQL 9.3 + Java 7 runner, which you will find on the Runners panel > Configs tab.


text:
Q: Adding a multiple columns to a dataframe with apply and regexpr I have a data.frame with 2 columns. One of these column is used to store the colors of each product (in rows). I also have a list of colors
See example below :
df <- data.frame(Product = c("a","b","c"),
           Color = c("black-white-silver-red","black-white-red","black-white"))
colorNames <- list('black','red','silver')

I am trying to add new columns to the data.frame based on thelist of color. The purpose of the column would be to return 0 or 1 depending whether the color is in the product. Ideally the output would look like this:
    Product                  Color   black   red   silver
1        a black-white-silver-red        1     1        1
2        b        black-white-red        1     1        0
3        c            black-white        1     0        0

I have tried to use the regexpr function combined with lapply.
The following code doesn't work:
lapply(colorsNames, function(color){
  transform(df, df[[color]] = as.integer(regexpr(color,df$Color)>0) )
 })

However, this one works fine but I am not able to apply it to a vector of color:
transform(df, black = as.integer(regexpr('black',df$Color)>0) )

I would really appreciate if soemone knew how to apply the last code to a vector of colors.
Thank you in advance.
Best regards,

A: Here a quick solution using stringi package. Currently returns counts that might be binarized. There are certainly more clever ways to achieve this, but I think as an initial approach this is what you need.
If your data set is really large I would recommend to use data.table instead of data.frame. Furthermore, you might consider using text2vec package (or other similar packages) to create your counts by considering your Color as a document and apply text mining on this column. However, I guess, that in your case, this would be overshoot. Otherwise, please let me know and I can provide an alternative solution.
check_occurrence <- function(df, check_col, patterns) {
 occurrence <-  sapply(patterns, function(x) {
    stri_count_regex(df[,check_col], x) #maybe stri_count_fixed suffices (would be faster)
  })
 colnames(occurrence) <- patterns
 cbind(df, occurrence)
}

check_occurrence(df = df, check_col = 2, patterns = colorNames)
#   Product                  Color black red silver
# 1       a black-white-silver-red     1   1      1
# 2       b        black-white-red     1   1      0
# 3       c            black-white     1   0      0

#to binarize results do something like
#df[df > 1] <- 1

A: Thanks to Manuel, here is my final code (in case some people have kind of the same issue).
    check.colorsOccurrence <- function(list,colorsList){

  if(is.data.frame(list)){  checkedColors <- sapply(colorsList, function(color){
       ifelse(regexpr(color, list$Color) < 0,0,1)
    })
    colnames(checkedColors) <- colorsList
cbind(list,checkedColors)
 }
    else  lapply(list, function(listElmt){
    if(!is.data.frame(listElmt)) check.colorsOccurrence(listElmt, colorsList)
    else {  checkedColors <- sapply(colorsList, function(color){
  ifelse(regexpr(color, listElmt$Color) < 0,0,1)
  })
  colnames(checkedColors) <- colorsList
  cbind(listElmt,checkedColors)
   }
 })
}