text:
Q: Verify User from Android on Server-Side My Problem is the following:

1. The User signs-in on the Android App using the Google+ API
2. The User wants to submit content (e.g. a video), so he calls a
  PHP from the App script with all the post variables (video_name,
  creator, video_description, video_url)
3. The Server stores everything in a MySQL Database

The Problem is the Part in 2. when the Server stores the "creator" name

Creator = Google Plus Name

Because someone could decompile the App and build the POST request with custom POST variables so the "hacker" could enter any name as the creator name.
How can I prevent that and/or is there any workaround to pass the Username to the Server when the user is only authenticated in the Android App and not authenticated on the Server Side?

A: A good approach would be to submit the login details to the server too which in your case is in step #2, and do one more authentication there. I suppose you are going to use php on your server so please take a look at the following page, which i believe is what you need:
https://developers.google.com/+/web/signin/client-to-server-flow
Once you send the token, you need to do verification:
https://developers.google.com/+/web/signin/token-verification
Even more details here:
https://github.com/googleplus/gplus-verifytoken-php


text:
Q: Why comma, and other options associated with fractions are not active in the programmer view of default Windows 7 calculator? Notation system I set to decimal, but the options associated with decimals are inactive.
The problem is only in the programmer view (ALT + 3). In other views I can use the comma.

Does anyone know what causes the problem?

A: In Programmer's view the calculator will only handle integers, so there is no purpose to the decimal point

redpajama_set_name: RedPajamaStackExchange


text:
Q: Line break within an align-environment I want to write a long calculation with the align-environment. One of the lines is too long for one line though, so I want it to split into two lines , with the second line right-attached. Example: See picture.
I tried every combination with equation, align, aligned, split, multline, multlined,... I could think of, sadly nothing worked so far. At the moment I solve the problem with &\hspace + ..., but I want to have a solution that is independent of the chosen font, margin, etc.

Here is a more specific example, where I need this function. It is a split cross product and I think that it looks weird if the second part of the cross product is left attached:
\documentclass{article}
\usepackage{mathtools}
\begin{document}
    \begin{align*}
        \mathcal{A} &= \int_0^T\int_{K_1}\left[c(\alpha,n)+\alpha|u|^2-\alpha^2(u\cdot(x-x_0))^2\left(|x-x_0|^2+h^2 \right)^{-1} \right]\\
        &\hspace{7.2cm}\times\left[|x-x_0|^2+h^2 \right]^{\alpha}\tau~dx~dt\\
        &\leq K\int_0^T\int_{K_1}\pi~dx~dt
    \end{align*}
\end{document}

I want to replace the \hspace{7.2cm} with a margin-independent command.

A: IMHO, splitting long equations should always be done with more care from the author. So I always split my equations manually to get the desired output.
My preferred solution below uses the following tricks:

*

*A \phantomrel command which creates a "phantom" relation symbol that occupies the same space as the underlying symbol, thus the \phantomrel{=}.

*A \hphantom{\int_0^T \int_{K_1}} that creates a horizontal phantom space which serves as indent for the \times ... contents.

*A \diff command dedicated for differentials.

*A \abs command dedicated for absolute values, which must be created using \DeclarePairedDelimiter from the mathtools package. This \abs{...} has several advantages over |...|:

*

*Try typing $|-x|$ and $\abs{-x}$ to see the wrong spacing of the negative sign in the former expression.

*You get to enlarge the delimiters by variants \abs[\big]{-x}, \abs[\Big]{-x}, \abs[\bigg]{-x} and \abs[\Bigg]{-x}.

*There is another variant \abs*{-x} which extends delimiters automatically (like a \left and \right pair), but acts like \mathopen...\mathclose and not like \mathinner, which is better.

*Please don't abuse \left and \right. Sometimes they create delimiters that are too big or too small, and they create \mathinner. I used manual sizing throughout your example.
The environments you mentioned work perfectly fine.
\documentclass{article}
\usepackage{mathtools}% For `multlined' and loads `amsmath'
\newcommand*\phantomrel[1]{\mathrel{\phantom{#1}}}% My preferred typesetting
\newcommand*\diff{\mathop{}\!d}% Just in case your editor asks for \mathrm{d}
\DeclarePairedDelimiter\abs{\lvert}{\rvert}

\begin{document}
\noindent
Using \verb|align*| and \verb|multlined| works fine:
\begin{align*}
A & = \text{something something something} \\
  & = \begin{multlined}[t][10cm]
        \text{something something something anything anything} \\
        + \text{anything anything anything}
      \end{multlined} \\
  & = \text{anything anything anything anything}
\end{align*}
However, I~would typeset as follows instead:
\begin{align*}
A & = \text{something something something} \\
  & = \text{something something something anything} \\
  & \phantomrel{=} {} + \text{anything anything anything anything} \\
  & = \text{anything anything anything anything}
\end{align*}
So your specific example becomes
\begin{align*}
\mathcal{A} & = \int_0^T \int_{K_1}
    \Bigl[ c(\alpha,n) + \alpha\abs{u}^2
           - \alpha^2 \bigl(u\cdot(x-x_0)\bigr)^2
             \bigl(\abs{x-x_0}^2 + h^2\bigr)^{-1} \Bigr] \\
 & \phantomrel{=} \hphantom{\int_0^T \int_{K_1}}
    \times \bigl[\abs{x-x_0}^2 + h^2 \bigr]^\alpha \tau \diff x\diff t \\
 & \leq K \int_0^T \int_{K_1} \pi \diff x\diff t
\end{align*}
\end{document}

A: A few suggestions; the text before each of them should tell you what I'd prefer. ;-)
Another suggestion: don't use ~ for spacing differentials, but \,.
\documentclass{article}
\usepackage{mathtools}
\usepackage{showframe} % just for the example

\begin{document}

The ugly:
\begin{flalign*}
\mathcal{A}
&= \mathrlap{\int_0^T\int_{K_1}
     \bigl[
       c(\alpha,n)+\alpha|u|^2-\alpha^2(u\cdot(x-x_0))^2(|x-x_0|^2+h^2)^{-1}
     \bigr]} &\\
&&&\mathllap{{}\times\bigl[\,|x-x_0|^2+h^2\bigr]^{\alpha}\tau\,dx\,dt}\\
&\leq \mathrlap{K\int_0^T\int_{K_1}\pi\,dx\,dt}
\end{flalign*}

The bad:
\begin{flalign*}
\quad\mathcal{A}
&= \mathrlap{\int_0^T\int_{K_1}
     \bigl[
       c(\alpha,n)+\alpha|u|^2-\alpha^2(u\cdot(x-x_0))^2(|x-x_0|^2+h^2)^{-1}
     \bigr]} &\\
&&&\mathllap{{}\times\bigl[\,|x-x_0|^2+h^2\bigr]^{\alpha}\tau\,dx\,dt}\quad\\
&\leq \mathrlap{K\int_0^T\int_{K_1}\pi\,dx\,dt}
\end{flalign*}

The good:
\begin{align*}
\mathcal{A}
&= \int_0^T\int_{K_1}
   \begin{aligned}[t]
     &\bigl[
        c(\alpha,n)+\alpha|u|^2-\alpha^2(u\cdot(x-x_0))^2(|x-x_0|^2+h^2)^{-1}
      \bigr] \\
     &\qquad\times\bigl[\,|x-x_0|^2+h^2\bigr]^{\alpha}\tau\,dx\,dt
   \end{aligned}
\\[2ex]
&\leq K\int_0^T\int_{K_1}\pi\,dx\,dt
\end{align*}

\end{document}

The showframe package makes the text block evident by drawing a frame around it.


text:
Q: Bootstrap 3.3.6 - How to show/hide multiple elements via Nav Tabs on a single page Within Bootstrap 3.3.6, I get how nav tab and tab content regions work.  For every tab you click on, a relational content area will will display itself. But in my special case I am working with a 2 column layout that has nav tabs in one column, and an additional private list of links in another column called "private-list".
The demo can be viewed here
http://www.bootply.com/NJXUfgD5iE
When I click on my Section 2 nav tab, my section 2 content regions displays as it should with Bootstrap 3.  But how can I also tell my .private-list, located in my left column to only show when I click my Section 2 and 3 tab, and then hide again, when I click Section 1?
For instance, is there a class process (rather than an ID process) I can use to lock in multiple boostrap component elements to a single nav tab click?
Thanks

A: you can have your own click handler for the tabs:
$('.nav-tabs a').click(function (e) {
  e.preventDefault();
  $(this).tab('show');
  if($(this).attr("href") != "#tab1"){
     $(".public-list").hide();
     $(".private-list").show();
  }
  else{
     $(".public-list").show();
     $(".private-list").hide();
  }
})


text:
Q: Jquery removeClass is not a function Пожалуйста помогите понять, почему removeClass is not a function
document.querySelector('.js-articles-load-more').onclick = function (e) {
        e.preventDefault()
        loadArticles()
    }

    let currentIndex = 0;
    let step = 3;

    function loadArticles() {
        let i
        for (i = currentIndex; i < currentIndex + step; i++) {

            if ($('.articles__item--hidden')[i] === undefined) { // Данные кончились
                $('#articles .summary').hide(); // Скрыть кнопку добавления
            } else {
                $('.articles__item--hidden')[i].removeClass('articles__item--hidden');
            }

        }
        currentIndex = i;
        $('.summary__now').text($('.articles__item').length - $('.articles__item--hidden').length);
    }


text:
Q: Swift optional property using KVC causes crash I found that using KVC in Swift causes many problems, especially with optional properties.
Here is my specific problem:
Here is a Class named Person. It has a normal property called age,and a Optional(Int) property called ageOptional.
class Person: NSObject {

    var age: Int

    var ageOptional: Int?

    override init(age: Int){

        self.age = 0
    }
}

Now, I use KVC in Person's instance:
//new a instance
var person = Person()

//kvc for normal property: it work well
person.setValue(28, forKeyPath: "age")

//but, this time ,it doesn't work well!!!!
person.setValue(28, forKeyPath: "ageOptional")

The app crashes, and here is the exception:

2015-07-11 11:17:31.546 CFRuntime[4646:607] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]:
      this class is not key value coding-compliant for the key ageOptional.'

I found that, if a property is optional, KVC couldn't find the key. But,I can't find the useful key for an optional property ,and resolve this situation.

A: You have already solved the problem perfectly. You cannot use KVC on an Optional Int property, because KVC is Cocoa / Objective-C, and Objective-C cannot see an Optional Int - it is not bridged to Objective-C. Objective-C can only see types that are bridged to Objective-C:

*

*class types that are derived from NSObject

*class types that are exposed with @objc

*Swift structs that are bridged
Objective-C can also see an Optional wrapping any of those types - almost. It can see an Optional wrapping a bridged struct, but only if that struct is directly bridged. Int is not directly bridged; it is bridged to NSNumber, but not directly (it has to be wrapped). Thus, Objective-C cannot see a Swift member typed as an Int?.
If you really need this to be an Optional, and if you really need to use KVC on it, then declare it as NSNumber?, not Int?. Personally, I would doubt whether either of those things is true; since converting all my apps from Objective-C to Swift, I've found that I don't actually need KVC internally, and that all my KVC-based solutions can be done some other, better way.


text:
Q: jQuery show/hide div in direction I have three div in the code. One is fix, one is for info and one is for detail.
Functioning: Initially I want to show only fix and info part, once click on info I want to show detail and fix and on click on detail I want to show fix and info.
For this part please find the working link : Working Example
$( document ).ready(function() {
        $("#detail").hide();

    $("#info").click(function () {
            $("#info").hide();
            $('#detail').show();
    });

    $("#detail").click(function () {
            $("#info").show();
            $("#detail").hide();
    });
});

My question is:
In this example I want to show detail part moves towards the left side in a way that fix part should always be fixed.
Here you can see the fix part is shifting towards right.

A: $( document ).ready(function() {
    $("#detail").hide();

    $("#info").click(function () {
         $("#info").css({"width":'100%'}).animate({"width":'0%'},200).hide();
         $('#detail').show().css({"width":'0'}).animate({"width":'100%'},200);
    });

    $("#detail").click(function () {
         $("#info").show().css({"width":'0'}).animate({"width":'100%'},200);
         $("#detail").css({"width":'100%'}).animate({"width":'0%'},200).hide();
    });
});

you can use it. it will work.
for smoothness may be you have to use overflow hidden container

A: I put your detail and info inside fix, and then use position absolute to position them. Try the code snippet.. =)

$(document).ready(function() {
  $("#detail").hide();

  $("#info").click(function() {
    $("#info").hide();
    $('#detail').show();
  });

  $("#detail").click(function() {
    $("#info").show();
    $("#detail").hide();
  });
});
#info {
  position: absolute;
  width: 30px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  -khtml-border-radius: 4px;
  border-radius: 4px;
  font: normal normal 13px Arial, Helvetica, Geneva, sans-serif;
  color: #929392;
  background: lightblue;
  margin-left: -30px;
  text-align: left;
  float: none;
  display: inline-block;
  height: 400px;
}
#detail {
  position: absolute;
  width: 80px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  -khtml-border-radius: 4px;
  border-radius: 4px;
  font: normal normal 13px Arial, Helvetica, Geneva, sans-serif;
  color: #929392;
  background: silver;
  margin-left: -80px;
  text-align: left;
  float: none;
  display: inline-block;
  height: 400px;
}
#fix {
  width: 297px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  -khtml-border-radius: 4px;
  border-radius: 4px;
  font: normal normal 13px Arial, Helvetica, Geneva, sans-serif;
  color: #929392;
  background: grey;
  margin: 0 auto;
  margin-top: 50px;
  text-align: left;
  float: right;
  display: inline-block;
  height: 400px;
}
#main {
  margin-left: auto;
  margin-right: auto;
  width: 410px;
}

      Info

      Detail

    fix

A: You can also do that by updating your css/style.
Jsfiddle is below.

 $( document ).ready(function() {
       $("#detail").hide();

      $("#info").click(function () {
     $("#info").hide();
        $('#detail').show();
   });

   $("#detail").click(function () {
     $("#info").show();
        $("#detail").hide();
   });
  });

#fix {
 width: 297px;
 -moz-border-radius: 4px;
 -webkit-border-radius: 4px;
 -khtml-border-radius: 4px;
 border-radius: 4px;
 font: normal normal 13px Arial, Helvetica, Geneva, sans-serif;
 color: #929392;
 background: grey;
 margin: 0 auto;
 margin-top: 50px;
 text-align:left;
 position: absolute;
    right: 0;
    top: 0;
 display:inline-block;
    height: 400px;
}

#info {
 width: 30px;
 -moz-border-radius: 4px;
 -webkit-border-radius: 4px;
 -khtml-border-radius: 4px;
 border-radius: 4px;
 font: normal normal 13px Arial, Helvetica, Geneva, sans-serif;
 color: #929392;
 background: lightblue;
 margin: 0 auto;
 margin-top: 50px;
 text-align:left;
 display: inline-block;
 height:400px;
}

#detail {
 width: 80px;
 -moz-border-radius: 4px;
 -webkit-border-radius: 4px;
 -khtml-border-radius: 4px;
 border-radius: 4px;
 font: normal normal 13px Arial, Helvetica, Geneva, sans-serif;
 color: #929392;
 background: silver;
 margin: 0 auto;
 margin-top: 50px;
 text-align:left;
 display: inline-block;
 height:400px;
}

#info,
#detail{
    position: absolute;
    right: 297px;
}

#main{
 margin-left: auto;
    margin-right: auto;
    width: 410px;
    position: relative;
}

        Info

        Detail

        fix

A: Try using this, it should help -
$("#info").click(function () {
      $("#info").hide();
      $('#detail').show();
      $('#detail').css('margin-left', '-50px');
});

A: You'll have to change the order of your divs to

       fix

       Detail

      Info

and replace all your float: left by float: right, although there is always the question whether you should use floats here in the first place.

A: Here is the simple syntax to use this effect

selector.hide|show|toggle( "slide", {arguments}, speed );
  Following is a simple example a simple showing the usage of this effect −

        The jQuery Example

Click on any of the buttons

  <button id="hide"> Hide </button>
  <button id="show"> Show</button>


text:
Q: Excel Formula to return all rows and columns corresponding to search string I'm trying to lookup two sheets in Spreadsheet.
One has the search value and other has all the data corresponding to the search string.
I'm trying to find a formula that will search the value and return all the corresponding rows. Another thing is that it has to return the entire row and columns correspoing to that string and not only one.
I'm using this Vlookup formula as of now but any help will do:=
ArrayFormula(VLOOKUP(A1,Sheet2!A2:AE196,{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24},FALSE))

A2:is the seach string, and used array to define the Columns to be returned.
But the formula returns only one row corresponding to the string and not all the rows.
Is there a formula that returns all rows and entire values in those rows correspoinding to the search string?
EX :Sheet1:search criteria

Search

Apple

Mango

melon

Ex:Sheet 2: Data

Name
Colour
no

Apple
red
5

Banana
yellow
3

Apple
red
25

Mango
yellow
1

Mango
yellow
10

Expected result for Apple(A1 in the formula) as search string:

Name
Colour
no

Apple
red
5

Apple
red
25

Actual result:

Name
Colour
no

Apple
red
5

A: You should use FILTER or QUERY
=FILTER(Sheet2!A2:AE196,Sheet2!A2:A196=A1)
=QUERY(Sheet2!A2:AE196,"select * where A='"&A1&"'",1)


text:
Q: 2 overloaded operator>> methods gets called I have a Complex class with two overloaded operator>> methods, one for std::istream from console, second  one for std::ifstream.
std::istream& operator>>(std::istream& is, Complex& c)
{

    int re, im;
    std::cout << "input the real-part of the complex" << std::endl;
    while ( ! (is >> re))
    {
        std::cout << "Please give me a double!  Try again: \n";
        is.clear();
        is.ignore(1000, '\n');
    }
    std::cout << "input the imaginary-part of the complex" << std::endl;
    while ( ! (is >> im))
    {
        std::cout << "Please give me a double!  Try again: \n";
        is.clear();
        is.ignore(1000, '\n');
    }
    c = Complex(re, im);
    return is;
}

std::ifstream& operator>>(std::ifstream& ifs, Complex& c)
{
    int re, im;
    ifs >> re; ifs>> im;
    c = Complex(re,im);
    return ifs;
}

In my program, I'm able to insert array of complex numbers from console or file. To simplify inserting, I've created additional method:
void insertArray(std::istream& is, Complex* arr, int size)
{
    for (int i = 0; i < size; ++i)
    {
        is >> arr[i];
    }
}

Unfortunatelly I've noticed that when this method is called with std::ifstream object as an argument,
std::ifstream ifs("complex.dat");
insertArray(ifs, x, size);

both operator>> methods are called so the console contains additional output however data is properly loaded from file. The result presented in the image.

It's easy to notice that program asks for given value as for console buffer howver loads data from file buffer.
Is there any way to handle it except crating separate method insertArray2 with std::ifstream instead of std::istream?

A: You could consider templating insertArray:
template<class T>
void insertArray(T& is, Complex* arr, int size)

A: If I understand your question correctly, you could write:
if ( &is == &std::cin )
    std::cout << "Please give me a double!  Try again: \n";

which would generate this output only if the function was called with std::cin.  It wouldn't do that if you were using the function on a different fstream or sstream or whatever.


text:
Q: Is there any alternative for "limitTo" in Angular2 or plus As in Angularjs (Angular-1) there is a limitTo filter to limit your text that you have to display
Ex: If I have a string like
$scope.val = "hey there how are you";

and I have to display only limited text on HTML side so I used
{{val | limiteTo:10}}

So its display only 10 char from a string like :: hey there
I'm moved on Angualr2 and I don't know how can it be done here, I used the same filter but it won't work

A: Use SlicePipe

Creates a new Array or String containing a subset (slice) of the
  elements.

@Component({
  selector: 'slice-string-pipe',
  template: `

{{str}}[0:4]: '{{str | slice:0:4}}' - output is expected to be 'abcd'

{{str}}[4:0]: '{{str | slice:4:0}}' - output is expected to be ''

{{str}}[-4]: '{{str | slice:-4}}' - output is expected to be 'ghij'

{{str}}[-4:-2]: '{{str | slice:-4:-2}}' - output is expected to be 'gh'

{{str}}[-100]: '{{str | slice:-100}}' - output is expected to be 'abcdefghij'

{{str}}[100]: '{{str | slice:100}}' - output is expected to be ''

`
})
export class SlicePipeStringComponent {
  str: string = 'abcdefghij';
}

Or Else Create Custom pipe
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'slice'
})
export class SlicePipe implements PipeTransform {
  transform(value: any, start?: any, end?: any): any {
    if (start == null && end == null) {
      return value;
    }
    else {
      return value.slice(start, end);
    }
  }

}

Example:https://stackblitz.com/edit/angular-uv5gvs
Ref:https://angular.io/api/common/SlicePipe

A: There is slice pipe in Angular 4, you can use that and also below is the code snippet from tutorialspoint.com and below i have attached a link also for the same.

Json Pipe

  {{ jsonval | json }}

Percent Pipe

  {{00.54565 | percent}}

Slice Pipe

  {{months | slice:2:6}} // here 2 and 6 refers to the start and the end index

Angular 4 pipes
Built in pipes Angular


text:
Q: using xcodebuild command line to put an app on the iPhone Is this possible? How does Xcode actually deploy iPhone apps that were built into the iPhone?
Or is there another tool which I'm missing out on?
clarification: by "deploy" I mean actually install and run gdb on the iPhone like when you do run>debug

A: xcodebuild only builds targets, it does not run executables; there's no way for it to invoke the code that transfers an iPhone app to a device and starts the debugger.

A: xcodebuild is what Xcode uses under the cover the build iPhone apps. So you can definitely use it to build the app. Just cd into the directory in which your project resides and then execute xcodebuild:
cd myProjectDir
xcodebuild

This will build the project in that directory, much in the same way as if you'd hit Build from xcode.
One thing you cannot do with xcodebuild is deploy the app to the iPhone. If you want to do this I beleive the simplest way is to use Xcode. If you want to automate this I would suggest using AppleScript.
You can find out more about xcodebuild here, a page which includes the following description of xcodebuild:

Run xcodebuild from the directory
  containing your project (i.e. the
  directory containing the projectname.xcodeproj package). If you have multiple projects in this
  directory you will need to use -project to indicate which project should be built.
By default, xcodebuild builds the first target listed in your project,
  with the default build configuration. The order of the targets is a property of the project and is
  the same for all users of the
       project. The active target and active build configuration properties
  are set for each user of the
       project and can vary from user to user.


text:
Q: I am using Tinker Board with PiCamera v2.1. How do I set the Color format for the captured image and also how to set exposure params? I am able to capture NV12 format pictures using Tinker Board with PiCam.
I am using gstreamer pipeline with v4l2src plugin to capture images as follows:
gst-launch-1.0 v4l2src ! video/x-raw,format=NV12,width=1640,height=1232, framerate=20/1 ! jpegenc ! multifilesink location=./images/image_%02d.jpg

I have tried using all the formats that are specified using "gst-inspect-1.0 v4l2src" but none of those formats give me an RGB image as output. Please help me out on how to capture an RGB image!
Also I am unable to manually specify the exposure time for my Picam while capturing images.Any suggestions on how to do this will also be very helpful??


text:
Q: replacing blank not NA I have two variables a and b
a         b
vessel    hot
parts
nest      NA
best      true
neat      smooth

I want to replace blank in b with a
la$b[i1] <- ifelse(la$b[i1] == "",la$a[i1],la$b[i1])

But it is not working

A: We can use data.table.  Convert the 'data.frame' to 'data.table' (setDT(df1)), specify the condition in 'i' (b==''), and assign the values of 'a' that corresponds to TRUE values in 'i' to 'b'.  It should be fast as we are assigning in place.
library(data.able)
setDT(df1)[b=='', b:= a]
df1
#       a      b
#1: vessel    hot
#2:  parts  parts
#3:   nest     NA
#4:   best   true
#5:   neat smooth

Or we can just base R
i1 <- df1$b=='' & !is.na(df1$b)
df1$b[i1] <- df1$a[i1]

data
df1 <- structure(list(a = c("vessel", "parts", "nest", "best", "neat"
), b = c("hot", "", NA, "true", "smooth")), .Names = c("a", "b"
), class = "data.frame", row.names = c(NA, -5L))

A: instead of
# la$b[i1] <- ifelse(la$b[i1] == "",la$a[i1],la$b[i1])
# what is i1? it doesn't seem to have any obvious function here

... it should be:
la$b <- ifelse(la$b == "", la$a, la$b)

assuming that you want to replace blank in b with a and that applies to all blanks
it works:
df <- structure(list(a = c("vessel", "parts", "nest", "best", "neat"
), b = c("hot", "parts", NA, "true", "smooth")), .Names = c("a",
"b"), row.names = c(NA, -5L), class = "data.frame")

df$b <- ifelse(df$b=="", df$a, df$b)
# or, with `with`: df$b <- with(df, ifelse(b=="",a,b))
#  > df
#       a      b
# 1 vessel    hot
# 2  parts  parts
# 3   nest   <NA>
# 4   best   true
# 5   neat smooth


text:
Q: Compare awk vs. grep I have run below two commands for a very large files
grep -E 'string1|string2' 151103*.log|grep 'string3' | grep string4

awk '/string1|string2/ && /string3/ && /string4/' 151103*.log

It took almost same time for execution. But awk was much faster to show me the results which matched. grep too showed me the same result but at the end, when the process completed.
Both took same time for the process to complete, just want to know the logic behind both the searches for awk and grep.
Why is awk faster? Do both programs have different search logic? What if I jumble the strings in above search, does it make a difference to the search speed?

A: GNU grep buffers output but GNU awk does not. And even if you were not using GNU awk and were using some other variant it would likely still be line-buffered if you were printing to a terminal and so would flush output for each occurring \newline, but your grep writes to a pipe and so would block-buffer anyway. If you have a GNU grep you can use grep --line-buffered ... | grep ... for your comparison to see results as quickly. Likely grep will beat awk at practically any match tests - especially a GNU grep.
Here is a sed to do what you want as well:
sed -ne'/string4/{/string3/s/string[12]/&/p;}' <in >out

A: The grep pipeline could not output anything until the final grep for string4 matched something, and it only gets its input after the previous pipe buffer fills up. See related questions How big is the pipe buffer? and Turn off buffering in pipe .
Depending on the frequency of the strings in your input, you could see a difference in runtimes by putting the static searches first, to give the extended regexp's less to look at.

A: Your awk example is doing the entire regex search in one pass. For each line of input, if the first, second, and third regex is found, the line will be printed, and you'll see the output essentially immediately (upon processing of the matching line).
Your grep example is using 3 different invocations of grep (one for each regex) to do the same thing, but the output of each invocation becomes the input for the next, which means that each needs to complete before the next has anything to process.
If you had a single 1000 line file and only line 5 matched all three regex, the awk command would give you output after processing the 5th line, before processing the 6th line. Compare that to the piped grep statements. The 1st invocation of grep would find the 5th line and whatever other lines may match the 1st regex, and after processing the 1000th (final) line of input, its output becomes the input to the 2nd invocation of grep. The second invocation of grep processes however many lines the 1st output and outputs the lines that match both the 1st and 2nd regex, which then becomes the input to the 3rd invocation of grep. As the 3rd invocation of grep processes each line, it will output any line that matches its regex.
You can compare the best and worst cases of grep for the above example: if none of the lines match any of the regex except line 5, which matches all 5, then the first grep processes 1000 lines, the second grep processes 1 line, and the third grep processes 1 line: it will process 1002 lines before has any output (best case). If all the lines match the first two regex but only one line matches the third regex, then the piped grep construction will process 1000 + 1000 lines + 5 = 2005 lines before it finds the match on the 5th line and has some output (it will continue to process the remaining 995 lines from the second grep's output, but you won't see any more output because nothing else will match).
Compare that to the awk command, which checks all three regex simultaneously for each line and gives you output after processing the 5th line. The difference will be exaggerated as you check more files simultaneously.
For instance, compare if you see output faster if instead of running the grep command on all files simultaneously as you did above (theoretically, you should, but results may vary depending on distribution of hits throughout your files):
grep -E 'string1|string2' 151103*.log|grep 'string3' | grep string4

you instead run the series of grep commands on each file individually, like this:
for i in 151103*.log;
  do grep -E 'string1|string2' $i |grep 'string3' | grep string4;
done

This still won't produce output as quickly as the awk statement, but you may see a difference.

A: While grep and awk and sed can be used for similar tasks each has its strengths and weaknesses.
Awk works best for tabularised data or when you need to perform calculations etc.
Sed excells in replacing text.
Grep is best to select rows from input data so I was expecting that to be faster than awk for this task. Perhaps if you combine the 3 grep commands into one that's what you'll see. Right now grep is at the disadvantage since it needs to start 3 times and the second and third need to wait for input from the first. Which might explain why the result comes with a delay. Although I'm not sure about that.


text:
Q: How to pass JQuery instance in a Handlebars template context? I would like to use Handlebars to insert nested elements which could be jQuery elements such as:

var ul = Handlebars.compile($('#ul').html());
var li = Handlebars.compile($('#li').html());

let el = $(li({slot: 'Hello World!'})).data('foo', Object([42]))

$('#main').append(ul({slot: el}))

Unfortunately I am struggling with two issues:

*

*Handlebars expect a html content in the context, therefore I loose data-foo.

*Using {{{slot}}} might be unsafe

What would be the alternative?

A: To achieve expected result, use below option using

*

*Use attr instead of data(), as it only stores value and it will not set attribute on DOM

refer this link for more details - jQuery data attr not setting

*Split appending ul and el

Code sample - https://codepen.io/nagasai/pen/PvrLba?editors=1010

var ul = Handlebars.compile($('#ul').html());
var li = Handlebars.compile($('#li').html());

let el = $(li({slot: 'Hello World!'})).attr('data-foo', Object([42]))
$('#main').append(ul)
$('#main ul').append(el)

A: One solution to this problem is write a wrapper that look for jQuery instances in the template context. It replaces every instances with a plain text unique identifier then insert back the jQuery instances to the rendered template:
Handlebars.jQueryCompile = (template) => {
    let jQueryObjects = []

    let tag = id => `jQueryObject(${id})`

    let alter = (obj) => {
        if (!(obj instanceof Object)) return

        for (var prop in obj) {
            if (obj[prop] instanceof jQuery) {
                jQueryObjects.push(obj[prop])
                obj[prop] = tag(jQueryObjects.length - 1)
            } else {
                alter(obj[prop])
            }
        }
    }

    return (context) => {
        alter(context)
        let obj = $(template(context))
        jQueryObjects.forEach((jq, id) => {
            obj.find('*:contains("' + tag(id) + '")').html('').append(jq)
        })

        return obj
    }
}

Here your updated example:
var ul = Handlebars.jQueryCompile($('#ul').html());
var li = Handlebars.jQueryCompile($('#li').html());

let el = $(li({slot: 'Hello World!'})).data('foo', Object([42]))

$('#main').append(ul({slot: el}))

Notice that you don't need to use the {{{}}} mustaches because plain text is inserted instead of html elements.


text:
Q: Navigation between the pages I'm relatively new to ReactJs. Consider, we have following code:
index.js
import {BrowserRouter as Router, Route} from 'react-router-dom'
import MyComponent1 from 'path/to/component1'
import MyComponent2 from 'path/to/component2'
import App from './App'

****

const WrappedApp = (
  <Router>
    <Route path={App}/>
  </Router>
)

ReactDOM.render(WrappedApp, document.getElementById('root'));

App.js
import React from 'react'
import {Switch, Route} from 'react-router-dom'
import MyComponent1 from 'path/to/component1'
import MyComponent1 from 'path/to/component2'

    export default class App extends React.Component {
     render() {
       return (
         <Switch>
          <Route path='/' component={MyComponent1}>
          <Route path='/2' component={MyComponent2}>
         <Switch>
        )
     }

Problem
MyComponent2 has button, with onClick/submit should redirect to another  component, that is not specified in router.
How could i archieve that? Im using React Router 4.x
Many thanks for examples and suggestions

A: I don't know how your component2 is developed, but I see an error here:
import MyComponent1 from 'path/to/component1'
import MyComponent1 from 'path/to/component2'

Maybe you want to do:
import MyComponent2 from 'path/to/component2'

And you can also import Link from React Router, like this:
import { Link } from 'react-router-dom'
<Link to="/about">About</Link>

See the docs here


text:
Q: netbeans "Please wait - classpath scanning in progress..." When i try to compile netbeans projects i get this message/error :
"Please wait - classpath scanning in progress..."
and nothing happens , its like you have have to wait for enternity to conmpile "hello world"...
Now the first thing is that we have moved to a new office building, but the laptop is the same. It's a very secure enviroment with a lot of "security", can't connect anywhere almost.
Also i have changed the user dir in netbeans.conf to save my data in c:\Program Files\User
Any ideas how to fix this?
alrady tried reinstalling netbeans, changing save location between standart and newone...

A: Just some ideas to find the problem

*

*Look at the CPU - is netbeans busy (100% on one core) or blocking (95% idle)?

*Standard, ant or maven build? Where are your libraries and do you use absolute or relative paths?

*Start with a simple "hello world" project (no dependencies), then add one lib (log4j or something similiar), located in a project folder and - if this works - move that lib to other locations (choose locations similiar to the libs on the real classpath)

There is a chance, that you don't have access rights to the folders/shares that contain your libraries. Or, as you mentioned security, that some virus scanner blocks access to some highly dangerous libs...

A: I deleted all the files under the .netbeans/7.0/modules directory. Although I lost some configurations of the IDE, it started to work pretty fine.
http://wiki.netbeans.org/FaqWhatIsUserdir

A: I followed Andreas-d advise... after disabling the antivirus and restarting netbeans everything is back to normal.

A: This seems interesting issue as per you have specified ! Somewhere, the netbeans documentation writes that the issue has already been resolved. However, for your information please have a look on : Scanning Project Classpaths takes too long
This link may or may not be helpful to you. But, the discussion may provide chance to resolve it.
Thank you.

A: In my case, when adding JavaFX libraries in my project: properties >> libraries >> Compiler Tab >> Classpath option, I have accidentally added my root user (C:\users\paulo) along with the JavaFX jar files. That was making NetBeans to scan basically my whole harddisk. The solution was very simple: just to go back there in properties >> libraries >> Compiler Tab >> Classpath option >> Edit button and deleted that "c:\users\paulo" and almost immediately the scanning processes went away.


text:
Q: Cakephp hide field names when sorting pagination In cakephp, when sorting a paginated list, the field names are displayed in the url. For security, is there a way to hide the field names, or change the url somehow while keeping the sort?
For example: http://.../page:1/sort:Item.item_name/direction:asc
How can we change or hide Item.item_name while keeping the sort? Thanks very much.

A: you would have to write your own pagination helper that builds out a form and not links, then you can use POST to send the data. the form fields would still be in the html form though so no different to links.
Imo there is no point to hiding the field names, as this does not fix any security holes. people can still see the fields according to the forms as it is like data[ModelName][field_name].
doing it for the 'nice urls' fact is maybe a better reason, but then if that was the case people would not have invented the PRG pattern... http://en.wikipedia.org/wiki/Post/Redirect/Get
doing that means that search engines would have a hard time indexing your site.


text:
Q: Zend framework : no other Action except index action in the controller is callable I have a controller file with the two actions i.e :
class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function doLoginAction()
    {
        // action body
    }
}

and their corresponding view files.
i.e when i hit http://www.mydomain.com/index  it loads the index view.
The problem I am facing is that when I try to access the index action of this controller it will load the corresponding view but when I try to hit the dologin action it gives the
error
http://www.mydomain.com/index/dologin
*Message: Action "dologin" does not exist and was not trapped in __call()*
Request Parameters:
array (
  'controller' => 'index',
  'action' => 'dologin',
  'module' => 'default',
)

same is happening when I try it with another controller and action. The index action runs fine for that controller too but not any other action in the controller.
P.S : I have configured mod_rewrite module and AllowOverride ALL in apache config file

A: Camel-cased action names are expected to be dashed as params. Therefore, doLoginAction() will respond to /default/index/do-login, not dologin. If you wish the URL to be dologin, you should rename the action to dologinAction().

A: You can have hyphen(-) separated urls at controller level also.
Suppose you need a url like this:
http://www.mydomain.com/do-some-stuff/my-stuff/
Then your controller should be named as:
DoSomeStuffController (as class name) && DoSomeStuffController.php (as controller file name)

and
myStuffAction() (as your method name)


text:
Q: Member count of closed Facebook groups? Is it possible to get the member count of closed Facebook groups?

A: This isn't possible you can only retrieve 500 max currently via Graph API (https://graph.facebook.com/GROUP_ID/members)

All of the users who are members of this group (can only currently return the first 500 members)

Via FQL you can retrieve up to 5000 I believe
select gid, uid from group_member where gid = GROUP_ID

https://developers.facebook.com/docs/reference/api/group/
https://developers.facebook.com/docs/reference/fql/group_member/


text:
Q: ¿Cómo puedo agregar variables a mi cuerpo (Body) de email, si este es escrito en HTML y mi script en Python? Quiero enviar un correo con Python, el cuerpo del correo es una plantilla en HTML, sin embargo quiero que el usuario ingrese ciertos datos que se modifiquen en el cuerpo del correo al momento de enviarlo
self.body = """Cordial saludo:

                       Se adjunta informe de recepcion de la planilla **self.ent5.get()**  con placa  **self.ent6.get()** recepcionado de la ciudad de  **self.ent3.get()** el cual presenta:
"""


text:
Q: AWS - Metadata being set as lowercase So I have this issue that whenever I try to post a file to the s3 bucket with a pre-signed URL, the key for the metadata is being forced in lowercases?
I've looked at the Pre-signed URL it already sets the lowercase part when the URL has been genereted and Im wondering why? and how do I solve this issue?
I've tried to create a manual key-value pair in the s3 bucket on a file, where I clearly can set a key with capital letters as well?
   const params = {
        Bucket: 'buckets3',
        Key: 'hoho-fileUpload-' + uuid.v4(),
        Metadata: {"FooBar": "FooBar"},
        Expires: 600
    };

current output in the s3:
x-amz-meta-foobar: FooBar
Wishing output:
x-amz-meta-FooBar: FooBar

A: There is nothing you can do, AWS stores S3 metadata in lower case.

User-defined metadata is a set of key-value pairs. Amazon S3 stores
  user-defined metadata keys in lowercase.

From: Object Meta Data and scroll to the bottom.  It's the paragraph just above the Note.

A: On top of WaltDe's answered, I'd recommend you convert your metadata keys to kebab case when sending to aws s3 (foo-bar) so you can convert it back to pascal case in your lambda or code or wherever you use the metadata.


text:
Q: Access protected folder I have a list of the folders located in a certain partition .
I get the list of the folders in a treeview control but when I click a certain folder from the treeview , it must show me the folders/files of the selected folder in a listview but if the selected folder is protected I get "access is denied" .
I'm using Directory.GetFolders to get them.
Is there any way to bypass this?


text:
Q: What kind of List is List list = Database.getAllData();? I have the following question:
if I have the following line of code:
List<Position> allPos = posDBM.getAllPos();

Position is an object
posDBM is a SQLite Database Manager class, which manages the SQLite database,
getAllPos() returns all database data.
The return type of getAllPos() is List<Position>.
If I want to initialize a List<> like this List<Position> pos = new, I have to specify the type of the List (ArrayList, LinkedList, etc.) .
So back to my question, what kind of List do I have, after I filled the list from the database?
I would guess it's an ArrayList , but I can't find any source to back this up. It's just a matter of interest...

A: You don't have to know; that's the point.  The interface is what matters to you, not the implementation.
You can't know without looking at the source of that method.  But even if you do, it's immaterial to your client. All you call are List methods.

A: That you will find in getAllPos() source code. List<Position> due to Polymorphism will accept all classes implementing List interface.

A: The returned List<Position> is a generic or a Strongly Typed list. The option that you were asking is about ArrayList which specifies a list that can take up any object. This will require an overhead of Boxing and Unboxing when writing / reading using the ArrayList.

A: Ideally you should not worried about the actual implementation , once you have List returned from the method call , you can just iterate over it like this .
List<Position> allPos = posDBM.getAllPos();
for(Position position : allPos){
   //Your code goes here
 }

And if you want to initialize a new list you can do it in many ways by using different implementations of List interface , now which implementation you want to choose very much depends on your requirement.

A: It you are just curious, then one way to find out is to do something like this:
    List<Position> allPos = posDBM.getAllPos();
    System.out.println("The class is " + allPos.getClass().getName());

Of course, you don't need to know ... because you don't need to instantiate the list implementation class yourself.  The database management code deals with that.

A: I would suggest you to add a breakpoint and see allPos variable after posDBM.getAllPos(), the debugger should tell you the Type.


text:
Q: Invalid Icon I can not find which icon is missing or invalid I have an error message..  Exception has occurred.
PlatformException (PlatformException(INVALID_ICON, The resource grocery could not be found. Please make sure it has been added as a drawable resource to your Android head project., null))
The issue is that I can not find which asset or icon is missing.
The error is appearing when running flutterLocal NotificationPlugin.initialize

The app freeze after signing in.
All the files are upto date.

A: error is showing because you have not added the icon for notification. Notification icon can be you app icon itself or any other icon you want to show in notification.
To add icon go to
android/app/src/main/res/mipmap-hdpi/

and copy your app icon (it would be in png format) then paste icon here
android/app/src/main/res/drawable/

drawable file
Then copy your icon folder name and initialize into initializationSettings.
Note: only name of file like  ic_launcher(folder name ic_launcher.png).
final AndroidInitializationSettings initializationSettings =
AndroidInitializationSettings('ic_launcher');
await flutterLocalNotificationsPlugin.initialize(
InitializationSettings(android: initializationSettings),
     onSelectNotification: (String payload) async {
if (payload != null) {
  debugPrint('notification payload' + payload);
 }
});

github repo refer my code for more or can ask if still find difficulty.

A: You have to follow these steps.

*

*Add the icon to drawable and mipmap folders which you want to show in the notification bar.

*Then add this in the manifest file inside <application tag.
android:icon="@mipmap/ic_launcher"

*Finally initialize the plugin
 Future<void> showNotification(String title, String subtitle, String action) async {
 var androidPlatformChannelSpecifics = AndroidNotificationDetails(
     'your channel id', 'your channel name', 'your channel description', style: AndroidNotificationStyle.BigText,
     importance: Importance.Max, priority: Priority.High, ticker: 'ticker', icon: "@mipmap/ic_launcher");
 var iOSPlatformChannelSpecifics = IOSNotificationDetails();
 var platformChannelSpecifics = NotificationDetails(
     androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
 await flutterLocalNotificationsPlugin.show(
     0, '$title', '$subtitle', platformChannelSpecifics,
     payload: action);}

Call the function where you configure the receiver of the notification.

A: Here's a quick fix:
Add this to AndroidNotificationDetails
icon: '@mipmap/ic_launcher'
This will solve the issue.


text:
Q: Eigenvalues of block matrix related What are the eigenvalues of following block matrix?
$$\begin{bmatrix}
A & B \\
B^T & O
\end{bmatrix}$$
Here, $A$ and $B$ are any square matrices of order $n$, $O$ is zero matrix of order $n$.

A: Generally, determinant of block matrix can be obtained following formula.
$$
\det
\begin{bmatrix}
A_{0} & B_{0} \\
C_{0} & D_{0}
\end{bmatrix}
=
\det(D_{0})
\det(A_{0}-B_{0}D_{0}^{-1}C_{0})
$$
Then, this problem's case: $(A_{0},B_{0},C_{0},D_{0})=(A-\lambda E,B,B^{\text{T}},-\lambda E)$, where $\lambda$ is eigenvalue. Therefore,
$$
\begin{align}
\det
\begin{bmatrix}
A-\lambda E & B \\
B^{\text{T}} & -\lambda E
\end{bmatrix}
=&
\det(-\lambda E)
\det((A-\lambda E)-B(-\lambda E)^{-1}B^{\text{T}}) \\
=&
\det(-\lambda(A-\lambda E)-B B^{\text{T}}) \\
=&
\det(\lambda^2 E -\lambda A -B B^{\text{T}})
\end{align}
$$
This determinant only cannot identify the eigenvalues as far as $A$ and $B$ are not supplied concrete elements. However, we can get ingredients of matrices how this quadratic matrix polynomial is made to decompose. To sum up, we can see what eigenvalues are constructed by $n$ orders matrices. Hence, we attempt to factorize above determinant.
$$
\begin{align}
\det(\lambda^2 E -\lambda A -B B^{\text{T}})=&\det(X-\lambda E)(Y - \lambda E) \\
=&\det(X-\lambda E)\det(Y - \lambda E) \\
\end{align}
$$
Above determinants are changeable so that following conditions can be applied to solve these matrices as $X,Y$. Especially, secondly condition is allowed commutative.
$$
\begin{cases}
X+Y=A \\
XY=YX=-BB^{\text{T}}
\end{cases}
$$
Because,
$$
\begin{cases}
\det(X-\lambda E)(Y - \lambda E)=\det(\lambda^2 E-\lambda(X+Y)+XY) \\
\\
\det(Y-\lambda E)(X - \lambda E)=\det(\lambda^2 E-\lambda(X+Y)+YX)
\end{cases}
$$
Thus, $X,Y$ are estimated below.
$$
\det\biggl(\cfrac{A+\sqrt{A^2+4BB^{\text{T}}}}{2}-\lambda E\biggr)
\det\biggl(\cfrac{A-\sqrt{A^2+4BB^{\text{T}}}}{2}-\lambda E\biggr)
=0
$$
In conclusion, eigenvalues $\lambda$ show these matrices.
Its means that the block matrix includes $X$'s eigenvalues $\lambda_{X}$ and $Y$'s eigenvalues $\lambda_{Y}$.
Incidentally, $A=\pm 2i\sqrt{BB^{\text{T}}}$ are special cases owing to multiple root as $X=Y$. Then, eigenvalues $\lambda$ correspond to just half $A$'s eigenvalues $\lambda_{0.5A}$.


text:
Q: Send udp packet from chrome Researching on the internet ( How to send udp to udp node.js server?, JavaScript WebSockets with UDP?) I have found that it is not possible to send udp packets with javascript.
On the other hand some pages claim that chrome browser is able to do so. For example the link:
http://blog.alexmaccaw.com/chrome-tcp-udp
claims that google chrome is able to send udp packets. Maybe I am doing something wrong. If it is true that chrome can send udp packets I will appreciate if someone can post a hello world example. I have tried the example from the link I showed and it does not work. Maybe I am doing something wrong.

A: From the linked page:

Chrome Canary now has support for raw TCP and UDP sockets in its
  'experimental' APIs. These features are only available for extensions
  and, although documented, are hidden for the moment.

So, develop an extension and it should work. Actually, that article from May '12 seems to be outdated as the chrome.socket module now has lost its experimental status. For the HelloWorld, you might check out their udp sample which is linked from the official pages.


text:
Q: Sending Array of Objects to MongoDB Atlas using node.js I am connected to my database using node.js.
Now I want to send some data to the database which is as follows:

data

const service=[
    {ServiceChoseByUser:'Cleaning',PriceForService:'100'},
    {ServiceChoseByUser:'Painting',PriceForService:'300'},
    {ServiceChoseByUser:'Electrician',PriceForService:'400'},
    {ServiceChoseByUser:'Plumbing',PriceForService:'50'},
    // may be increased as the number of services selected by the user.
}

My schema is described as :

Schema.js

import mongoose from 'mongoose';

const serviceSchema = new mongoose.Schema({
    service: [
        {
            id: {
                  type: String,
                  trim: true,
                  unique: true
            },
            ServiceChoseByUser: {
                  type: String,
                  trim: true,
                  unique: true,
                  lowercase:true
            },
            PriceForService: {
                  type: String,
                  trim: true,
                  lowercase:true,
                  unique: true,
           },
       },
    ]
});

let Service = mongoose.model('service', serviceSchema);

export default Service;

And my controller of data is :

controller.js

import Service from ".Schema.js";

export const sendService = async (req, res) => {
    try {
        const serviceByUser = req.body;
        console.log(serviceByUser);
        const newService = new Service(service);
        console.log(newService);
        await newService.save();
        console.log('Service data stored');
        res.send(200 + 'Service data stored')
    } catch (error) {
        res.send(500 + ' Error occured');
        console.log('Error: from service controller ', error.message);
    }
}

The app is connected successfully to the database. But when I am sending data to the database, it always shows
Error: from service controller  E11000 duplicate key error collection: HouseDeck-Cluster.services index: services_1 dup key: { services: null }
I checked for that by using console.log() as you can see in controller.js. When I am displaying the data it shows the data is correct but when I do console.log(newService).
It always shows
{ _id: new ObjectId("6234720c80a5f440ade88d24"), service: [] }
It states that something is wrong with the schema. I tried various things like:

Already Tried These For Schema

1. service=[Object]

2. service=[
       {
          id:String,
          ServiceChoseByUser:String,
          PriceForService:String
       }
    ]

3. service=Array

4. service={
      type:Array
     }

5. service=[
      {
          type:Object
      }
   ]

6. // already provided above

I tried many things, also searched for it, read the documentation but I couldn't find any solution.
Please help

A: You have indicate in your schema that all fields are unique.
So, all data you insert in all fields must be unique.
Try modifying your schema like this:
const serviceSchema = new mongoose.Schema({
            id: {
                  type: String,
                  trim: true,
                  unique: true
            },
            ServiceChoseByUser: {
                  type: String,
                  trim: true,
                  lowercase:true
            },
            PriceForService: {
                  type: String,
                  trim: true,
                  lowercase:true
           }
});

And then insert your datas with something like this:
newService.insertMany(service);


text:
Q: Passing a large dataset to the client - Javascript arrays or JSON? I'm passing a table of up to 1000 rows, consisting of name, ID, latitude and longitude values, to the client.
The list will then be processed by Javascript and converted to markers on a Google map.
I initially planned to do this with JSON, as I want the code to be readable and easy to deal with, and because we may be adding more structure to it over time.
However, my colleague suggested passing it down as a Javascript array, as it would reduce the size greatly.
This made me think, maybe JSON is a bit redundant. After all, for each row defined, the name of each field is also being outputted repetitively. Whereas, for an array, the position of the cells is used to indicate the field.
However, would there really be a performance improvement by using an array?
The site uses GZIP compression. Is this compression effective enough to take care of any redundancy found in a JSON string?
[edit]
I realize JSON is just a notation.
But my real question is - what notation is best, performance-wise?
If I use fully named attributes, then I can have code like this:
var x = resultset.rows[0].name;

Whereas if I don't, it will look less readable, like so:
var x = resultset.rows[0][2];

My question is - would the sacrifice in code readability be worth it for the performance gains? Or not?

Further notes:
According to Wikipedia, the Deflate compression algorithm (used by gzip) performs 'Duplicate string elimination'. http://en.wikipedia.org/wiki/DEFLATE#Duplicate_string_elimination
If this is correct, I have no reason to be concerned about any redundancy in JSON, as it's already been taken care of.

A: JSON is just a notation (Javascript Object Notation), and includes JS arrays -- even if there is the word "object" in its name.
See its grammar on http://json.org/ which defines an array like this (quoting) :

An array is an ordered collection of
  values. An array begins with [ (left
  bracket) and ends with ] (right
  bracket). Values are separated by ,
  (comma).

This means this (taken from JSON Data Set Sample) would be valid JSON :
[ 100, 500, 300, 200, 400 ]

Even if it doesn't include nor declare nor whatever any object at all.

In your case, I suppose you could use some array, storing data by position, and not by name.
If you are worried about size you could want to "compress" that data on the server side by yourself, and de-compress it on the client side -- but I wouldn't do that : it would mean you'd need more processing time/power on the client side...
I'd rather go with gzipping of the page that contains the data : you'll have nothing to do, it's fully automatic, and it works just fine -- and the difference in size will probably not be noticeable.

A: I suggest to use a simple CSV format. There is a nice article on the Flickr Development Blog where they talked about their experience with such a problem. But the best would be to try it on your own.


text:
Q: Connecting to Information Security SE somehow disconnected me from other sites Information Security asked me to "join" and when I did, it (as I expected from previous sites) seemed to accept my existing info from other sites.  But afterward, Travel asked me to join instead of allowing a log in.
Why?  What should I do about it?

A: Not entirely sure what went sideways there, but I merged your new account with your old one. You should be able to access it again without problems. Sorry about that.


text:
Q: How to make the height of a TextField and a search button equal in Flutter? I'm creating a Flutter app. The app has a TextField and an IconButton, I want to make their height equal. Here is the current code:
import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: SafeArea(
              child: Row(
                children: [
                  const Expanded(
                    child: TextField(
                      decoration: InputDecoration(
                        fillColor: Colors.yellow,
                        filled: true,
                        hintText: "Input here...",
                        isCollapsed: true,
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            width: 0,
                            style: BorderStyle.none,
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Ink(
                    decoration: const BoxDecoration(
                      color: Colors.yellow,
                    ),
                    child: IconButton(
                        onPressed: () => {},
                        icon: const Icon(Icons.search)
                    ),
                  )
                ],
          )),
        ),
      ),
    );
  }
}

This is the result:

You can see that their height is not the same. There are some suggestions on the Internet to make their height equal, but none of them worked for me. Most suggest using a contentPadding inside TextField, like this:
TextField(
  decoration: InputDecoration(
    fillColor: Colors.yellow,
    filled: true,
    hintText: "Input here...",
    isCollapsed: true,

    // Add this
    contentPadding: EdgeInsets.all(12),

    border: OutlineInputBorder(
      borderSide: BorderSide(
        width: 0,
        style: BorderStyle.none,
      ),
    ),
  ),
),

This seems to work. My complaint with this method is that I need to manually try the correct padding, which is 12 in the above code. Does the number always work on all devices? I'm not sure.
Some suggest using a SizedBox, I've tried it, it doesn't work for me either. Here is my code:
import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: SafeArea(
              child: Row(
                children: [
                  const Expanded(
                    child: SizedBox(
                      height: 80,
                      child: TextField(
                        decoration: InputDecoration(
                          fillColor: Colors.yellow,
                          filled: true,
                          hintText: "Input here...",
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  SizedBox(
                      height: 80,
                      child: Ink(
                        decoration: const BoxDecoration(
                          color: Colors.yellow,
                        ),
                        child: IconButton(
                            onPressed: () => {},
                            icon: const Icon(Icons.search)),
                      ))
                ],
              )),
        ),
      ),
    );
  }
}

Here is the screenshot:

My question is, what's the correct way to make it work?

A: It works by removing extra padding from Top and Bottom of TextField, and now both are the same size
Row(
            children: [
              const Expanded(
                child: TextField(
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.only(left: 15,right: 15),
                      fillColor: Colors.yellow,
                      filled: true,
                      hintText: "Input here...",
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          width: 0,
                          style: BorderStyle.none,
                        ),
                      ),
                    ),
                  ),
                ),

              const SizedBox(width: 10),
               Ink(
                    decoration: const BoxDecoration(
                      color: Colors.yellow,
                    ),
                    child: IconButton(
                        onPressed: () => {},
                        icon: const Icon(Icons.search)),
                  )
            ],
          )

A: I would suggest putting the icon directly inside your TextField instead of separating it.
Put the search icon via suffixIcon inside your InputDecoration().
TextField(
   decoration: InputDecoration(
     hintText: 'Input here...',
     suffixIcon:
     Ink(
     child: IconButton(onPressed: () {},
     icon: Icon(Icons.search))
     )


text:
Q: How to secure communication between Self-Hosted integration runtime nodes in Azure Data Factory I have read the Microsoft documentation https://learn.microsoft.com/en-us/azure/data-factory/create-self-hosted-integration-runtime#high-availability-and-scalability and tried to setup the multi-node Self-Hosted IRs in ADF. The problem is during the second node setup it asks for the TLS/SSL certificate. The documentation does not specify exactly what to do. AS per the documentation, I added the SSL certificate (that I added in First node) in Trusted Root certificates of second node, but it asks to add the certificate inside the Self-Hosted IR. Not sure how to add the certificate in the second node.
MS documentation says "Each integration runtime node must trust this certificate." What this means? Where I need to put the original certificate in second node? Do I need to create a new certificate for the another node?
I'm using Azure Windows VMs for IR setup.


text:
Q: Install new version over existing on Windows (upgrade) I have Python 2.7.3 and considering to install new 2.7.5 version, but I can't find information if it's possible to upgrade current (and keep my modules intact) or is it advised to install as separate and reinstall all my modules one by one (which I don't want to do)?

A: Just install Python2.7.5 over 2.7.3 and everything is fine. (I do that)
The folder where your libraries are installed to site-packages will be left untouched.
Also Python2.7.3 has the same c-Interface as Python2.7.5 so you will be able to use compiled modules as well.
I remember uninstalling Python and it deleted only the files it brought to my computer. All my programming work was left untouched.
If you really encounter issues that I do not know of, you can simply reinstall the older version.
The great thing about this is if you choose the advanced option to compile files, it will even go through your installed modules and compile them.


text:
Q: How I can evaluate row data as an array? Can anyone explain how I evaluate my rows e as an array and not on an individual (row) level? Is this the best way to improve performance?
Dim x As Integer, i As Integer, y As Long

Set wsCountry = Sheets("Country Data")
Set wsInstructions = Sheets("Instructions")

LastRow = wsCountry.Range("E" & Rows.Count).End(xlUp).Row

For x = 9 To 9
    For i = 9 To LastRow

If wsCountry.Range("E" & i) <> wsInstructions.Range("C" & x) Then
   wsCountry.Range("A" & i & ":P" & i).ClearContents
End If

    Next i

'Delete Blanks
For y = Cells(Rows.Count, 3).End(xlUp).Row To 1 Step -1
    If Cells(y, 3) = "" Then
        Rows(y).Delete
    End If
Next y

'Save workbook AS to FILE

Next x

A: Using 2 AutoFilters:

*

*remove rows where column C contains blank values

*remove rows where column E doesn't contain the value in Instructions sheet cell C9

.
Option Explicit

Sub parseRows()
    Dim wsCountry As Worksheet, wsInstructions As Worksheet
    Dim lastRow As Long, instructionsVal As String, rowRng As Range

    Set wsCountry = Worksheets("Country Data")
    Set wsInstructions = Worksheets("Instructions")
    instructionsVal = wsInstructions.Range("C9")

    Application.ScreenUpdating = False

    lastRow = wsCountry.Cells(wsCountry.Rows.Count, 5).End(xlUp).Row
    Set rowRng = wsCountry.Range("C8:C" & lastRow)

    With wsCountry.UsedRange    'Filter col 3 (C) - make blanks visible
        .AutoFilter Field:=3, Criteria1:="="
        rowRng.SpecialCells(xlCellTypeVisible).EntireRow.Delete
        .AutoFilter
    End With

    lastRow = wsCountry.Cells(wsCountry.Rows.Count, 5).End(xlUp).Row
    Set rowRng = wsCountry.Range("E8:E" & lastRow)

    With wsCountry.UsedRange    'Filter col 5 (E) - values <> instructionsVal
        .AutoFilter Field:=5, Criteria1:="<>" & instructionsVal
        rowRng.SpecialCells(xlCellTypeVisible).EntireRow.Delete
        .AutoFilter
    End With

    Application.ScreenUpdating = True
End Sub

A: Your code seems fine. However, you are asking for optimal performance. That would be done by looping on an array instead of a range, which can get slow when the range is big. It is better to dump the range into an array, like so:
Dim Arr() As Variant
Arr = Sheet1.Range("A1:B10")

And looping on the array instead. Since this creates a 2d array, you can elect to loop on one of the dimensions (row) only. I hope I answered your question correctly.


text:
Q: iPhone keyboard return key I need to customize the iphone keyboard. How can I do it? Also it is needed to place the return key of the keyboard with my project logo. How is it possible?

A: You cannot customize the apple iOS's default keyboard.
As such you can create a custom control similar to apple iOS's keyboard and make it look and customize as you want but then there ar more chances than not that your app may be rejected when you try to submit your app on the Apple's app store.
So it is not preferable to create custom keyboard.
Hope this helps you.

A: What have we done in one of our apps and you can do is create custom uibutton that is same size as return key, then register for  UIKeyboardWillShowNotification and UIKeyboardWillHideNotification.
when one of those fire you should add/remove that uibutton to window with animation that tracks keyboard showing/hiding animation...
Ugly way to do it, but it served its purpose...

A: Some of the tutorials are incomplete or are much older. This tutorial works from IOS 4.3 onwards and I checked it. Save the two image graphics, and paste in the code. There is very little to change. Here is the link.
ps. I am not affiliated in any way with this article, but found it to be complete.
http://www.neoos.ch/blog/37-uikeyboardtypenumberpad-and-the-missing-return-key


text:
Q: GPU Temp is weird? I am not sure if this has anything to do with it but I just upgraded my kernel in Ubuntu 13.10 from 3.11.0-15 to 3.11.0-17. I never thought about temperatures before but I just decided to download a monitor to see what the temperatures were. I have a AMD Radeon 4870 which at idle will sit at 84-86 Celsius. The weird thing is that even when I am playing a game like Counter Strike my GPU temp will stay at about 87-88 Celsius which is not much higher than at idle. Counter Strike is a pretty graphically intense game. Maybe it is just the temp that my card like to be at. Even when I put my fans from low to medium the temperature stayed the same. Should I be concerned at those temperatures or is it not that big of a deal?

A: That is normal for radeons -- they run hot.  It speeds its own fan up when it runs hard to stay about that temperature.

A: I agree with psusi.
104C is the maximum safe temperature according to AMD/ATI. (although I couldn't find any documents from AND to substantiate that).  I have an AMD AIW, and that hits 75C-80C easily.
Now, the fact that your 4870 is OLD, and it has a better processor than my card, that might be OK. Keeping that in mind, it may very well be full of dust. make sure that you clean the fan real well.  You may want to take it to an auto shop, and use there air drier to blow the dust out, or you can get a can of compressed air to do that.

A: Ubuntu doesn't now switch between your GPU automatically.
With the latest release of Ubuntu, Hybrid Graphics are now officially supported by Ubuntu.
You need to install following package
1.fglrx
2.fglrx-pxpress
After then you can switch you AMD gpu when needed.
Type sudo apt-get install fglrx fglrx-pxpress to install it.
I have not tested it yes but you can find more on webupd8.


text:
Q: snprintf not printing out a converted timeval using strftime? I have taken this answer from SO:
https://stackoverflow.com/a/2409054/997112
so that I can print timeval structs in a friendly format. I had to change "%s.%06d" for "%s.%06ld" because I was getting compiler warnings:
void printTimeval(struct timeval& tv){

    time_t nowtime;
    struct tm *nowtm;
    char tmbuf[64], buf[64];

    nowtime = tv.tv_sec;
    nowtm = localtime(&nowtime);

    strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
    snprintf(buf, sizeof buf, "%s.%06ld", tmbuf, tv.tv_usec);
}

However, when I pass a valid time nothing prints.
I checked the number of seconds in the timeval I passed-in, before calling my function and it returns 1404120855, so I am confident my timeval is correct and the problem lies with the function?

A: All snprintf() does is format a string. You never actually print out the resulting string in buf. Add something like:
printf("%s\n", buf);

or
puts(buf);

Also, you should have a cast to long for that tv_usec field, since you can't know the type of the typedef to be long.


text:
Q: How do I Import a CSV into a nested document on mongodb For Example how do I import this
---> test.csv
tesingImport ,hi there

---> What I tried
./mongoimport -d channeladvisor -c products --type csv --file ./test.csv -fields Sku, a.b.c

somehow I get this imported
{
  "_id" : ObjectId("53e6eb0eeb5228df491a0f50"),
  "Sku" : "tesingImport",
  "a.b.c" : "hi there"
}

I can make a script to do this but I wasn't sure if I could use the import to make it faster

A: Unfortunately, this is not really possible as of MongoDB 2.6. mongoimport is a very simple import program that's not designed to have all the features to support complex import use cases. I recommend that you write your own script to construct the proper documents and insert them into the database.
There's also an open issue about this capability, SERVER-3691, that you might want to comment on, watch, or upvote.


text:
Q: RabbitMQ: Bi-directional federated brokers, how do you make all queues pop the message? I have two brokers configured[1] with federation plugin. Both are pointing to each other as upstream.
My test is:

*

*publish a message on broker A

*consume on broker B

The result is:

*

*consuming on broker B works

*< good > the queue on broker B pops the message

*< not good > the queue on broker A still has the message

*

*< reason why this is not good > The issue I see is: if I always publish on one broker and then always consume on the other --> then the queue on the publishing broker will grow until it's full and start dropping messages.

The result I would like is:

*

*both queues on broker A and B pop their messages when the consumer consumes on broker B

How do I configure RabbitMQ to pop the message from all queues when a consumer consumes the message on broker B? Right now I am trying to do so with RabbitMQ Federation plugin.

[1] The two brokers point to each other as upstreams and I configure them the same way as described in the "simple example" given by the documentation except that there are two brokers each pointing to each other as upstream. The code for the publisher looks like this and the code for the consumer looks like this.

A: @Trevor Boyd Smith, probably option 2 or 3 as shown below are something you could consider.
Option 1: Bidirectional federated exchange
A message will end up in the both broker A and B, one copy each broker, independent of each other. In other words, e.g., even after broker B has delivered the message to its consumer, the other copy of the message still remains in broker A.
Advantage: You will always have two copies of the message, one in each broker, which is highly available.
Disadvantage: You need to have a consumer connected to each broker.
Option 2: Bidirectional federated queue
A message will end up in one of the two brokers. By default, the broker where the message has been published will have the priority to enqueue the message; however if only the other broker has got a consumer, the message will move to the other broker.
It does not matter which broker the message ends up in, the message will be delivered once and once only by a consumer connected to either of the brokers.
Advantage: The message will be delivered once and once only to a consumer connected to either of the brokers.
Disadvantage: There will be only one copy of the message. If the broker that has got the message goes down, the other broker can not get the message. But if you are fine with eventual consistency, this option is OK. The reason is when the problematic broker comes back up running, the message would be available, eventually.
Option 3: Bidirectional federated exchange and queue
In this case, a message will end up in both brokers, one copy each broker. The same message will be delivered to a consumer connected to either of the brokers, twice! Once the message has been delivered twice, it will be gone in both brokers. (If there are two consumers, one connected to each broker, each broker will deliver the same message to its consumer once.)

Advantage: The consumer can connect to either of the brokers, and the message in each broker will be delivered and dequeued.
Disadvantage: The same message will be delivered twice. The workaround would be, before handling the message, check if the same message has already handled.
Note:
It does not mean which option is better than the other one or ones. It all depends on your use case, and there are many other configurations that can come into play, which could change the behaviour.

A: I created this environment:
Server A, Server B.
Created a bidirectional federated in this way:
Federation Upstream: Server_B = amqp://servera
Federation Upstream: Server_A = amqp://serverb
Then created the same policy on both the servers:
Pattern : ^fed\.
Apply to: all
federation-upstream-set:all

Created one queue to the Server A called: fed.test1 then created a consumer to the Server B as:
 ConnectionFactory factory = new ConnectionFactory();
 factory.setHost("localhost");
 factory.setPort(5673);
 Connection connection = factory.newConnection();
 Channel channel = connection.createChannel();

Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                        throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Message   '" + message );
                }
            };
channel.basicConsume("fed.test1",  true, consumer);

Then published a message to the Server A ---> fed.test1
The message has been consumed to the Server B and the queues messages count is zero to both the queues (Server A, Server B).
This works as you expected.
Hope it helps.


text:
Q: PHP - PSR 0 - Configuration Constants This question is about PSR-0 autoloaded libraries and the way main configuration constants should be declared and used.
From your point of view (lib/framework developer), where/how should be declared your library configuration PHP constants (such as ESCAPE_SOMETHING, USE_DOM, API_URL, ...) in such a way that

*

*your code can easily address them

*client code can easily modify them depending on needs

Is there any convention, recommendation, or even something I missed in PSR-0 I should be aware of?

A:
This question is about PSR-0 autoloaded libraries

I think you're conflating two different issues. Finding and loading the PHP code for FooClass is (or ought to be) a different problem from how new FooClass() or FooClass::staticThing() should behave.
Ideally, FooClass shouldn't care whether I (the guy using the library) relied on an autoloader or whether I hard-coded my own require_once() statement.

library configuration PHP constants

One ground-rule first... never with constants from define(). Polluting the global namespace is a bad idea, and IIRC even the new namespace features are a little weird in that regard. Class-constants on the library classes are acceptable, but as the library-consumer you probably aren't hand-editing those.

From your point of view (lib/framework developer), where/how should be declared your library configuration PHP constants

You mean, how would I prefer for consumer code to set options that affect my code? I'd prefer something like:
FooLibraryConfigurator::set("a","b");
FooClass::doStuffThatNeededConfData();

In other words, configure my library based on a mechanism I created for you to use. :p


text:
Q: category of non-welldefined linear maps I was wondering whether the following category already has been used somewhere and whether it already has been named.
Let us fix a field $k$ (or more generally a ring). An object is just a $k$-vector space and a morphism $f:U\rightarrow V$ consists of a choice of a sub-vectorspace $V_f\subset V$ and a well-defined linear map $\overline{f}:U\rightarrow V/V_f$.
The composition of $f:U\rightarrow V$ and $V\rightarrow W$ is given by
$$W_{g \circ f} = p_{W\rightarrow W/W_g}^{-1}(g(V_f)),$$
$$\overline{g\circ f}(x) := [\overline{g}(y)],$$
where $p_{W\rightarrow W/W_g}$ denotes the canonical projection $y\in V$ is a representative of $\overline{f}(x)\in V/V_f$.
The reason behind this is that I wanted to compose maps this way quite often, and one could either

*

*give a new name to $V/V_f\rightarrow (U/W_g)/g(V_f)$ and work in the category of vectorspaces. Now I would have to introduce a lot of new names for the map $g$ depending on with which maps I compose them, which makes things worse to read.

*Try to lift each map $U\rightarrow V\rightarrow V/V_f$ to a map $U\rightarrow V$. This involves a choice which might affect the rest of the arguments. Now one has to argue that things do not depend on the choice for no other reason than that we have introduced

*The naive idea that there should be a functor from this category back to vectorspaces sending $f$ to $\overline{f}$ does not work, since this does not respect composability (The target of $f$ is $V/V_f$ and the source of $g$ is $V$.
So I think using this category might be the cleanest way and so I am wondering whether it has already been used/named before.

A: As Denis Nardin pointed out in the comments, the name total correspondence is a good choice.


text:
Q: Improving browsing and voting by a "voted" visual clue in question lists (EDIT: I now see after having posted that it has already been proposed. But I think it is worth considering again.)
It is different from a previous feature request (about close votes).
And I am not requesting to vote directly from the question list because I believe you should read the whole question before deciding to vote.
The idea is to have a visual sign that you have upvoted/(downvoted) a given question in question lists and in particular in favorite lists.
One has already a visual clue that a question has been accepted and that one has favorited a question. I think that it would be useful, especially in the favorite list (where by definition you have only questions that you have favorited), to have a visual clue that you have voted this question up as well.
Your use of the site may vary, but I often favorite a question when I intend to go back to it later, as a kind of reminder. I do not always upvote the question or its answer since I may need time to read and assess it carefully.
It would among other things allow to go on recently changed questions for which you have still the possibility to upvote.
Another use on classical question lists is to allow to go quickly to potential interesting questions that you can upvote if it is deserved.
Going through old questions (especially with ambiguous titles), this is also quite handy to check if one has already been there or not.


text:
Q: Rstudio very slow when editing large code RStudio is working well in general (v 2021.09.1 Build 372).
But when a large code (7000 lines, a collection of functions) is being edited, even a click on the text or unfolding takes about 4 seconds to respond.
I've tried to disable diagnostics, but the problem still occurs.
Is there any setup that can help?

A: It seems that disabling "use real-time spell-checking" solve the problem.
Before, I've  tried other solutions, like disabling "Diagnostics", without results.
Besides, to avoid the slow debugging of that big file, when debug is needed, specific functions are copied to a temp.R and then "debugSourced"


text:
Q: Async iterative to update UI I have one problem. I want to update the state of a switch on the main UI on the base of what I receive from a server. As we know, android not allow the internet connection on main thread.
So I used Async. Unfortunately, inside of Async i'm not able to modify the UI. I would like an AsyncTask that do a "while(true)" with my code inside. It ask the server and on the base of reply update the UI ever and ever.
Somebody can help me?
Thanks in advance and sorry for my bad English!
Edit: I'm talking of an Android application.

A: AsyncTask has methods that intended to work with UI, for example onPostExecute. But AsyncTask should only be used for operations that take quite few seconds and may hang other AsyncTasks. So

do a "while(true)" with my code inside

is not an option. For chatting with server you may want to use service.
Check more information about processes and some gotchas.


text:
Q: P/Invoke a C delegate with structure to C# I am trying to convert the following C code to C#... but I seem to be stuck when converting a structure to that callback properly. Compiles fine but during runtime the stack turns out imbalanced.
C
INT32 RegisterCallback4ThirdParty(BtSdkCallbackStru* call_back);

typedef struct  _CallbackStru
{
    BTUINT16 type;                  /*type of callback*/
    void *func;                     /*callback function*/
}CallbackStru, *PBCallbackStru;

The following is my conversion:
C#
[DllImport("SDK.dll")]
[return: MarshalAs(UnmanagedType.I4)]
public static extern Int32 RegisterCallback4ThirdParty(ref CallbackStru callback);

public class CallbackStru
{
    public ushort type; //type of callback
    public object func; //callback function
}

When calling the routine in C#:
CallbackStru cb = new CallbackStru();
AppInquiryInd appInquiryInd = AppInquiryInd;
cb.type = 0x04;
cb.func = appInquiryInd;
RegisterCallback4ThirdParty(ref cb);

Where AppInquiryInd is this delegate:
public delegate void AppInquiryInd(UInt32 deviceHandle);

It fails at RegisterCallback4ThirdParty(ref cb);
Am I simply overlooking something?
Cheers.

A: The delegate declaration is probably not correct, try:
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void AppInquiryInd(UInt32 deviceHandle);

And be sure to declare the struct to match so the function pointer can be properly marshaled:
    [StructLayout(LayoutKind.Sequential)]
    private struct _BtSdkCallbackStru {
        public ushort type;        //type of callback
        public AppInquiryInd func; //callback function
    }

I changed class to struct, now the ref argument is correct:
    [DllImport("SDK.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern int RegisterCallback4ThirdParty(ref CallbackStru callback);

The stack imbalance was caused by the missing CallingConvention.
You furthermore have to ensure that the delegate object stays visible to the garbage collector, it cannot see that the native code uses it.  Which requires storing it in a static field or allocating an extra handle for it with GCHandle.Alloc().  So, roughly:
    CallbackStru cb = new CallbackStru();
    AppInquiryInd callback = new AppInquiryInd(myCallbackMethod);
    ToCleanupLater = GCHandle.Alloc(callback);
    cb.type = 0x04;
    cb.func = callback;
    RegisterCallback4ThirdParty(ref cb);

Where "ToCleanupLater" is a place-holder variable so you can call GCHandle.Free() when the native code can no longer make callbacks.  If there is no mechanism to stop callbacks then don't bother freeing it.


text:
Q: Flutter: how to prevent accidentally dragging a Draggable that is a child of a SingleChildScrollView from moving the Draggable instead of scrolling? I have Draggable widgets inside a SingleChildScrollView and to prevent the Draggable from being dragged when users' intention is to scroll, I thought to change them into LongPressDraggable with a delay, code blow:
         LongPressDraggable(
            delay: Duration(milliseconds: 200),
            axis: Axis.vertical,
            data: block,
            feedback: Opacity(
              opacity: kScheduledBlockFeedbackOpacity,
              child: Material(
                elevation: 10.0,
                shadowColor: Colors.black,
                child: scheduleBlock(block, scheduledBlockFeedbackColor),
              ),
            ),
            child: GestureDetector(
              onTap: () {
                print('onTap triggered 1');
                // go to details
                ...
              },
              child: block.action == 'pulling'
                  ? Opacity(opacity: kScheduledBlockFeedbackOpacity, child: scheduleBlock(block, scheduledBlockColor))
                  : scheduleBlock(block, scheduledBlockColor),
            ),

            childWhenDragging: Container(),
            onDragStarted: () {
              ...
            },
            onDragUpdate: (DragUpdateDetails d) {
              ...
            },
            onDragEnd: (DraggableDetails d) {
              ...
            })

The problem is whenever the LongPressDraggable's delay property is present, its child GestureDetector's onTap doesn't trigger.  Even if the delay is set to 0, making it work with same as a Draggable.
How can I get around this problem?  Or is there a better way to prevent dragging on a Draggable within a SingleChildScrollView from moving the Draggable instead of scrolling?

A: If I understand it correctly, you want to disable the scrolling property of the child inside SingleChildScrollView()?
Try setting physics to NeverScrollableScrollPhysics() in your child scrollable widget.


text:
Q: Repmat in Python v/s MATLAB For a given matrix, I'm subtracting the maximum of each row from the row.
In MATLAB, I'd do something like
Xm = X - repmat(max(X,[],2), 1, size(X,2));

For Python, I've been toying with variations of
Xm = X - np.matlib.repmat(np.max(X,axis = 1), 1, len(X[0])) but to no avail!
Where exactly am I missing out? Thanks a lot.

A: In Python/NumPy, explicitly replicating an array to make it match another is not necessary. Dimensions of size 1 (singleton dimensions) are automatically expanded in a process they call "broadcasting".
For example, given
X = np.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]])

you can write
X - np.max(X, axis=0)

The array returned by np.max has a shape of (5,), which is compatible with the shape of X ((3, 5)). NumPy aligns the shapes starting at the last dimension, and fills in singleton dimensions at the front if one array has fewer than the other.
However, this process sometimes needs a little bit of help. Because np.max returns an array with fewer dimensions than the input, broadcasting cannot, in general. match up these arrays. For example, X - np.max(X, axis=1) doesn't work.
The best solution is to use the keepdims argument to np.max:
X - np.max(X, axis=1, keepdims=True)

The other option is to add singleton dimensions using np.newaxis in indexing:
X - np.max(X, axis=1)[:, np.newaxis]


text:
Q: Solenoid emits electromagnetic radiation, why? A sinusoidal electric current is applied to the solenoid. The solenoid emits electromagnetic radiation, why?

A: You may theoretically calculate it as magnetic dipole radiation. However, in physics, the "why" works in the opposite direction from what you assume. Classical electromagnetism allows you to calculate things like this because it is crafted to mathematically reproduce results from experiments.

A: An electric current is applied to the solenoid.
The coil radiates because the moving electrons are guided in a circle (spiral path) and any acceleration of the electrons - and movement in a circle is such - is accompanied by the conversion of kinetic energy into EM radiation.
A sinusoidal electric current is applied to a conducting wire.
The conduction radiates because the electrons are constantly being moved back and forth and these accelerations are accompanied in nature by a conversion of kinetic energy into EM radiation.
Why?
The process is more complex. In both described cases, a magnetic field also appears. Free electrons have an electric field and a magnetic field. Electrons with kinetic energy are deflected sideways in an external magnetic field and radiate. The deflection is associated with a spin. This spin is aligned parallel or anti-parallel to the intrinsic magnetic field of the subatomic particles. An established theory of how these properties lead to the emission of photons is not available.