text:
Q: How to create a custom javascript in-bulit apply method Lets consider this example:-
function X(){
     var Y = function(arg1,arg2){
              document.write(arguments.length);
              document.write(arg2);
              };
     Y(arguments);
}

x(1,2,3,4,5);
/*Outputs  1 and undefined respectively.
  Because here i am actually passing an array like-object  to Y. */

By using apply here i am getting the desired results.
function X(){
     var Y = function(arg1,arg2){
              document.write(arguments.length);
              document.write(arg2);
              };
     Y.apply(this,arguments);
}

x(1,2,3,4,5) //outputs 5 and 2

I want to create an apply like method that takes an Array of argument and invoke that function by passing arguments as seperate parameter values.
Like:
var arr=[1,2,3,4];
Y.apply_like_method(arr);
//and returns like Y(1,2,3,4)

A: Given this code:
var arr=[1,2,3,4];
Y.apply_like_method(arr);
//and returns like Y(1,2,3,4)

To make that work:
Function.prototype.apply_like_method = function(args) {
    return this.apply(this, args);
}

Disclaimer: For illustration purposes only.
In other words, there's no way around .apply().

A: Just for shits and giggles using eval.
function myApply(fun, ar){
  var i, r = [];
  for(i=0; i<ar.length; ++i)
    r[i] = 'ar['+i+']';
  eval('fun('+r.join(',')+');');
}

A: You want to use the call method instead.  See the MDN.   What you are describing though is a hybrid of the call method and apply method; you want the ability to supply parameters individually, but to supply them to the function as an array.  That, to my knowledge, doesn't exist currently and it would be easier to use apply/call as it was originally intended, or use a javascript object to pass the params into the function.


text:
Q: Is a Markov chain the same as a finite state machine? Is a finite state machine just an implementation of a Markov chain? What are the differences between the two?

A: Markov chains can be represented by finite state machines. The idea is that a Markov chain describes a process in which the transition to a state at time t+1 depends only on the state at time t. The main thing to keep in mind is that the transitions in a Markov chain are probabilistic rather than deterministic, which means that you can't always say with perfect certainty what will happen at time t+1.
The Wikipedia articles on Finite-state machines has a subsection on Finite Markov-chain processes, I'd recommend reading that for more information. Also, the Wikipedia article on Markov chains has a brief sentence describing the use of finite state machines in representing a Markov chain. That states:

A finite state machine can be used as
  a representation of a Markov chain.
  Assuming a sequence of independent and
  identically distributed input signals
  (for example, symbols from a binary
  alphabet chosen by coin tosses), if
  the machine is in state y at time n,
  then the probability that it moves to
  state x at time n + 1 depends only on
  the current state.

A: Whilst a Markov chain is a finite state machine, it is distinguished by its transitions being stochastic, i.e. random, and described by probabilities.

A: I believe this should answer your question:
https://en.wikipedia.org/wiki/Probabilistic_automaton
And, you are on to the right idea - they are almost the same, subsets, supersets and modifications depending on what adjective describes the chain or the automaton. Automata typically take an input as well, but I am sure there have been papers utilizing 'Markov-chains' with inputs.
Think gaussian distribution vs. normal distribution - same ideas different fields. Automata belong to computer science, Markov belongs to probability and statistics.

A: I think most of the answers are not appropriate. A Markov process is generated by a (probablistic) finite state machine, but not every process generated by a probablistic finite state machine is a Markov process. E.g. Hidden Markov Processes are basically the same as processes generated by probabilistic finite state machines, but not every Hidden Markov Process is a Markov Process.

A: The two are similar, but the other explanations here are slightly wrong. Only FINITE Markov chains can be represented by a FSM. Markov chains allow for an infinite state space. As it was pointed out, the transitions of a Markov chain are described by probabilities, but it is also important to mention that the transition probabilities can only depend on the current state. Without this restriction, it would be called a "discrete time stochastic process".

A: If leaving the inner working details aside, finite state machine is like a plain value, while markov chain is like a random variable (add probability on top of the plain value). So the answer to the original question is no, they are not the same. In the probabilistic sense, Markov chain is an extension of finite state machine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Print preceding 0 when printing hex values in gdb I'm looking at unsigned char (byte) arrays in gdb, i.e.
(gdb) p/x buf@4
$76 = {0xac, 0xa, 0xb0, 0xa}

Is there a way of forcing the preceding 0s? i.e output like:
$76 = {0xac, 0x0a, 0xb0, 0x0a}

A: From the gdb documentation:

'z'
Like 'x' formatting, the value is treated as an integer and printed as hexadecimal, but leading zeros are printed to pad the value to the size of the integer type.

So...
(gdb) p/z buf@4


text:
Q: Why are there no simple, cross-platform, C/C++ GUI tookits for higher level languages? I have a little programming experience and I did get to work with Swing (Java) and wxPython.
Some years ago, I ended up having to port an app I did to OS X and all the problems I've had with wxPython just multiplied. I've started looking at alternatives and I could not find anything better than wxPython. QT was the only one that came even close. GTK was hell on Windows (last time I checked).
I don't think my predicament is unique, some other people might have reached the same position over the years.
So, why isn't there a GUI toolkit to have the following characteristics:

*

*Simple. Basic windows/dialogs (native open and save) + a basic set of widgets with SOLID Layout management. Additional (composite widgets) implemented as additional libraries.

*Actively maintained on OS X, Linux and Windows

*Actively maintained bindings to at least 3 high level languages.

*Actively maintained documentation for best practices GUI devel with examples using the toolkit. MVC/MVP properly explained. GUI HIG (Apple style) simply explained, complete with semantics, paradigms, best practices, alignment, proper spacing and TONS of best of their kind examples from successful pieces of software.

*A simple way of building a distributable executable for the 3 targeted platforms in each of the languages.

*Implemented as close to the metal using readily available libs like Clutter, cairo, etc.

Are these requirements too much to ask? If yes, why?
Help me understand why isn't there such a tiny lib available?

A: Have you tried Qt? It is a cross platform C++ GUI toolkit for higher level language (PyQt). And it seemed very simple to me.

A: What you ask is a simple lib with enormous flexibility. Be able to build 3 * 3 executables, having good documentation and using other libraries all with a different background. And all of that on different OS platforms. It is quite a challenge it think QT would com the closest but it does not meet all your criteria.

A: SWT? You can use it from Java, Python (well, Jython), Ruby (well, JRuby), Groovy, LISP (well, Clojure), and anything else that runs on the JVM.
It's simple-ish, it uses native widgets under the hood, it's actively maintained, and because you're distributing either a JAR or a JAR and some interpretable code, there's a unified build process. I can comment on its documentation, nor its proximity to any sort of metal.
I recognize that this is probably not the answer you were looking for.

A: My guess is that windows developers couldn't be bothered as they have wpf etc and linux developers couldn't be bothered as they are used to it. So only people who are sick of win developement and moving to linux would embrace it. Maybe its time for you to start an open source project :) I was thinking something like wpf but based on opengl would be a good start.

A: The Tk toolkit meets most of your requirements, except maybe for number four. It's very cross-platform, uses native widgets when possible, is easy to use, etc. The requirement for distribution is hard to meet because that depends on the language, but when used with tcl, you can use tclkits and starkits which are an absolutely fantastic way to distribute code (essentially, your single-file executable has an embedded virtual file system that can contain all your assets -- code, images, etc).
For more on the cross language, cross-platform features of tk see http://www.tkdocs.com

A: WXWidgets seems a good fit as well.


text:
Q: Knockout JS - concatenate function name with array value I have the following piece of code:
VIEW:

 // array of week days
   // 'dayOfWeek' being week day name, e.g. Monday, Tuesday etc.

    <input type="hidden" value="0" data-bind="attr: { name: 'ScheduledRequest[DayOfWeek][' + dayOfWeek + ']' }" />
    <input type="checkbox" data-bind="checked: $parent.schedule().Friday, value: 1, attr: { name: 'ScheduledRequest[DayOfWeek][' + dayOfWeek + ']' }" class="form-control" />

The data-bind in this part data-bind="checked: $parent.schedule().Friday should call the function whose name is the current dayOfWeek (in this hardcoded example, Friday - which works as expected for this particular day) in the schedule model. However, data-bind="checked: $parent.schedule().dayOfWeek with call function dayOfWeek in the schedule model which isn't what I want. I tried doing the following:
VIEW
checked: $parent.getCurrentDay(dayOfWeek)
MODEL:
self.getCurrentDay = function(day) {
var dayOfWeek = "";
if(day == 'Monday')
  dayOfWeek = '$parent.schedule().Monday';
if(day == 'Tuesday')
  dayOfWeek = '$parent.schedule().Tuesday';
if(day == 'Wednesday')
  dayOfWeek = '$parent.schedule().Wednesday';
if(day == 'Thursday')
  dayOfWeek = '$parent.schedule().Thursday';
if(day == 'Friday')
  dayOfWeek = '$parent.schedule().Friday';
if(day == 'Saturday')
  dayOfWeek = '$parent.schedule().Saturday';
if(day == 'Sunday')
  dayOfWeek = '$parent.schedule().Sunday';

return dayOfWeek;

}
But the data-bind returned is then a string: checked: $parent.schedule().Monday, etc.
I would greatly appreciate any help!

A: Sounds like you want brackets notation:
data-bind="checked: $parent.schedule()[dayOfWeek]"

or if dayOfWeek is observable (it doesn't look like it in your code, but)
data-bind="checked: $parent.schedule()[dayOfWeek()]"

As you've pointed out, .dayOfWeek looks for a property actually called dayOfWeek. [dayOfWeek] takes the value of the variable dayOfWeek (e.g, "Friday" or similar) and then looks up the property with that name.


text:
Q: html/css image overlap eachother i got one row working with four image but i wanted another row but it overlapp each other like this

this is what i want to achieve

index.html
<!DOCTYPE html>

<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="CSS/main.css">

Home

Contact

This is image 1

This is image 2

This is image 3

This is image 4

This is image 1

This is image 2

This is image 3

This is image 4

main.css
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    background-color: #360836;
    text-align:center;
}

li {
    display:inline;
}

li a {
    display: inline-block;
    color: #d14977;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    -o-transition:.5s;
    -ms-transition:.5s;
    -moz-transition:.5s;
    -webkit-transition:.5s;
    transition:.5s;
}

li a:hover {
    color: white;
}

div.main_image {
content:url(../Image/everest.jpg);
    max-width: 100%;
    height: auto;
    width: auto\9;
}

.imgContainer{
    float:left;
    width:25%;
    position:relative;
    margin:0 auto;

}

.imgContainer img{
    max-width:100%;
    height: auto;
    position:absolute;
    left:0;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
}

.imgContainer img.top:hover {
      opacity:0;
}

how can i make two rows or even more than two rows of image that stacks not overlap each other. I want to achieve this just using css and html and I dont want to use javascript or jquery. Thanks

A: The problem here actually isn't due to the float on your .imgContainer, though the symptoms may be misleading at first.
The behaviour you're seeing is actually because you placed position:absolute on all of your .imgContainer img elements, which means they are taken out of the flow of the document and don't affect the height of their parents at all. (The reason why the containers aren't down to 0 height is because the
 within each .imgContainer still takes space.) As a result, the images overlap each other because their parents are shorter than them.
What I would suggest is only applying position:absolute to the image that appears on top (rather than both top and bottom), and also applying position:absolute to the
 so it can be positioned over top of the images (and won't end up between the image rows after the images are properly positioned).
So the CSS declaration blocks I would add/rewrite are:
.imgContainer img{
    /* position:absolute removed */
    display:block
    max-width:100%;
    height: auto;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
}

.imgContainer img.top {
    position:absolute;
    left:0;
    top:0;
}

.imgContainer p {
    position: absolute;
    margin: 0;

    /* So the element doesn't block hover event of image */
    pointer-events: none;

    /* Vertical centering */
    top: 50%;
    transform: translateY(-50%);
}

Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.
EDIT: Vertical spacing between image rows was removed by applying display:block to the child images. Sourced from this StackOverflow question.

A: Im not exactly sure why your code is giving you that result, it might have something to do with giving your images a position of absolute. But I made a little snippet below that does what you want. Instead of using the img tags I just created a div that acts like the images container and gave that div a background image of the image. I find it always makes the code more simple. When you view the code, view it in full page so you can see it more clearly.
Hope this helps!

.imgContainer{
  width:100%;
  background-color: red;
  margin-left: 10px;
 }
.imgBOX{
  height:350px;
  width:350px;
  background-image: url(http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/black-and-white-wallpaper-5.jpg);
  background-size: 100% 100%;
  display: inline-block;
  float: left;
 }
.imgBOX2{
  height:350px;
  width:350px;
  background-image: url(https://newevolutiondesigns.com/images/freebies/black-white-background-32.jpg);
  background-size: 100% 100%;
  display: inline-block;
  float: left;
 }


text:
Q: Why this beamer slide about sectioning fails on enumerates? I am trying to use the code from section title in \frametitle beamer
\documentclass{beamer}
\usetheme{Berkeley}

\newenvironment{slide}[1]
{\begin{frame}[environment=slide]
\frametitle{\insertsection-#1}}
{\end{frame}}

\begin{document}
\begin{slide}
\begin{enumerate}
\item lorem
\end{enumerate}
\end{slide}
\end{document}

but get the error
! LaTeX Error: Lonely \item--perhaps a missing list environment.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.15     \end{slide}

A: The definition of the slide environment here requires a title an the argument. Thus here \begin is being taken as the argument, we have no list starting and \item is misplaced (as the error says). You can fix by supplying something
\documentclass{beamer}
\usetheme{Berkeley}

%
\newenvironment{slide}[1]
{\begin{frame}[environment=slide]
\frametitle{\insertsection-#1}}
{\end{frame}}

\begin{document}
\begin{slide}{Foo}
\begin{enumerate}
\item lorem
\end{enumerate}
\end{slide}
\end{document}

If the frame title is not required then drop the argument entirely
\documentclass{beamer}
\usetheme{Berkeley}

%
\newenvironment{slide}
{\begin{frame}[environment=slide]
\frametitle{\insertsection}}
{\end{frame}}

\begin{document}
\begin{slide}
\begin{enumerate}
\item lorem
\end{enumerate}
\end{slide}
\end{document}

A: Easy to do without the newenvironment:
\documentclass{beamer}
\usepackage{xpatch}

\makeatletter
\patchcmd\beamer@@tmpl@frametitle{\insertframetitle}{\insertsection{} -- \insertframetitle}{}{}
\makeatother

\begin{document}

\section{Sec shun 2}
\begin{frame}{My title 2}
\begin{enumerate}
\item lorem
\end{enumerate}
\end{frame}

\end{document}


text:
Q: Change editted cell in datagridview on enter (vb.net) I have a datagridview table that is populated by using a datatable as a datasource. The datagridview has been set to edittable and I can change the values of cells but of course, the changes do not reflect in the original database table since the grid view is not directly bound. Is it possible to have the datagridview in such a way that when I press enter (when editting a cell), the focus shifts to the cell on the right (rather then selecting the row below)? This would need to keep on going until I reach the right most column, in which case the following edit cell would be the first cell in the following row.
Thanks in advance!

A: Try this:

*

*define a flag flag_edited that will be raised when an edit occurs (CellEndEdit event)

*define a function changeSelectionToNextCell that will undo default behavior's selection change (SelectionChanged event)
Here is a sample:
Private flag_edited As Boolean

Private Sub DataGridView1_CellEndEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    flag_edited = True
End Sub

Private Sub DataGridView1_SelectionChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.SelectionChanged
    changeSelectionToNextCell()
End Sub

Private Sub changeSelectionToNextCell()
    If flag_edited Then
        flag_edited = False
        If DataGridView1.CurrentCell IsNot Nothing Then
            Dim row_index As Integer = DataGridView1.CurrentCell.RowIndex - 1
            Dim col_index As Integer = DataGridView1.CurrentCell.ColumnIndex + 1

            If col_index = DataGridView1.ColumnCount Then
                col_index = 0
                row_index += 1
            End If

            DataGridView1.CurrentCell = DataGridView1.Rows(row_index).Cells(col_index)
        End If
    End If
End Sub


text:
Q: Комплексная оценка PC Суть проблемы: Есть два ПК которые полностью идентичны в плане железа и софта. (возможны незначительные различия по софту) При этом один из двух ПК (оба выполняют роль терминалов) заметно притормаживает по сравнению со вторым при выполнении одних и тех же программ (графика, несложные расчёты)
Поверхностная диагностика (на предмет выявления программ отжирающих процессорное время) результатов не принесла. Перечень запущенных служб и программ в автозагрузке идентичный.
Вопрос: Какая программа сможет провести комплексную оценку быстродействия (графика, проц, оперативка, жёсткий и т.п.) и выдаст удобочитаемые результаты?
Цель: Сравнить результаты оценки на 2-х терминалах и выявить первопричину "тормозов"

A: AIDA64 программа для оценки и тестирования пк


text:
Q: Java string separate number sequence I get a number generated as a string that always has the same length, for example:
0107612733631449211907028445

Now I wan't to get two separate strings with the last 10 digits:
010761273363144921**1907028445**

And another string with these digits
0107612733**63144**9211907028445

The positions of these needed numbers are always the same, the numbers at the beginning are not important for me and can be omitted.
How can I get these two strings?

A: Java docs .substring method
String number = "0107612733631449211907028445";
String last10 = number.substring(number.length()-10);

for middle numbers use substring(int beginIndex, int endIndex)


text:
Q: High Load Website. how to load balancing? i have the following problem:
 i have two servers (intel xeon 3,4 GHZ with 32GB RAM and RAID 10 (4x1TB Enterprise Harddiscs).
all servers are installed with vmware esxi 5.5 (free). webserver, dbserver all are virutal machines.
the first is a webserver with the newest debian x64 and apache 2. load: 50%
 the second server is a mysql database server with the newest debian x64. load : 95%
so now i have ordered two new server (i think i get the server on friday).
all four servers are internal connected via 1 gb lan.
the current website is:
 - a normal website with drupal and one ioncube application
 - with one mysql database
so i must setup a load balanced cluster, right?
so experts: do you have some informations or tutorials how i can setup the cluster fine?
the project starts in 2013, but now the website is so traffic intencive, ...
thank you very much!
many greets m.k.

A: Bunch of things going on here.  In the general category of performance tuning, there are multiple levels/steps in the process.  You seem to be skipping to the last step first.  Generally this is how I approach it in my work:

*

*User experience vs. Hardware statistics.

First rule:  if a site works fine for an end user, backend statistics are irrelevant.  They are useful for capacity planning but if a server is running 100% CPU and the site works fine, technically you do not have a performance problem.  You have a "no excess capacity if something goes wrong you're in trouble" kind of problem, but not a problem in the moment.
Conversely, if the servers are basically idle but the site is slow, then the fact the servers are idle is irrelevant - there is still something non-optimal in the mix.

*Different layers in the application stack.

There are two layers here it appears:  the web server layer and the database server layer.  Load balancing web servers will not, for example, help if it is your database server that is having performance issues.

*Optimizing individual layers.

You want to make sure each layer is configured to properly serve what is needed.  In this case the first poster's comment about disk performance is likely spot on.  Disk space is not sufficient for selecting a storage configuration, generally IOPS or throughput is the most important part.  Also, in the case of SATA vs. SAS, you want to use SAS disks because the storage interface supports more simultaneous connections.
For a CMS like Drupal, you're almost certainly using the database for everything, in which case you likely need far more physical disks to have the speed you need.  The specifics of that, unfortunately, are dependent on a number of variables including whether your site is mostly reads, mostly writes, or a combination, as well as how much data is being transferred in requests (if everyone gets the same front page, that's one transfer and things are likely cached vs. if everyone logs in and gets individual content, the data access will be all over the place).  You should start by optimizing your database server as much as possible, which will require looking at documentation specific to your database software and hardware.
In some cases optimizing the web server layer can be helpful.  Likely that is not a concern for you based on what I can see here.  (Technically, even tuning the "web server" layer has multiple places to optimize - e.g. do you put a proxy in front of it, separate static content, that kind of thing.  But I think you're not in a place to worry about that yet.)

*Optimizing the whole environment.

Once you have each individual element tuned, then you look at things like load balancing.  In the case of having dozens of servers, using load balancing to share resources better is a viable approach.  In the case of a small number of servers as seems to be the case here, it is better to think of load balancing as strictly a failover/availability measure, not something to use to compensate for performance issues.
So basically, tune your stack outward from the data.  The information you gain from that process will likely guide you in the process of determining how or whether to implement a specific load balancing solution.


text:
Q: Javascript Replace value from var Can anyone help me with this script?
I have to replace the value of a variable in a string (string variables are dynamic)
Here's an example:
var string = "#sport,#fotogallery,#sport,";
var element = "#sport";
string.replace(element+",","");
alert(string);

A: First, the replace function returns a string, it does not mutate the variable. So, proper usage is as follows:
source = source.replace('old', 'new');

You should take care to ensure that your input is in the exact format, because if there is no trailing comma after the last value, and you want to replace the last value, then simply using replace would fail.

A: Replace all instances of element followed by an optional comma:
str = str.replace(new RegExp(element + ",?", "g"), "")

Your string appears to be delimited, so this is also an option:
var str = "#sport,#fotogallery,#sport,";
var element = "#sport";
var newStr = str.split(",").filter(function(el) {
    return el !== element;
}).join(",");

Or, if you can't use filter, this will work, too:
var parts = str.split(",");
var res = [];
for (var i = 0; i < parts.length; i++) {
    if (parts[i] !== element)
        res.push(parts[i]);
}
var newStr = res.join(",");


text:
Q: Segmentation Fault on fclose I am getting Segmentation fault error while running program in Linux. Working fine in AIX.
And I get a seg fault with the message in gdb...
Program received signal SIGSEGV, Segmentation fault
fclose@@GLIBC_2.2.5 () from /lib64/libc.so.6

            #include<stdio.h>
            #include<string.h>
            #include<unistd.h>
            #include<time.h>
            #include<sys/types.h>
            #define _Monthly "99992016"

            FILE *source,*list,*wlist,*movlist,*biflis;
            char sf[85],sf1[85];
            char filename[85],filename1[85],name[140],fstring[140],iname[140],account[85];
            char *ptr="",*st="";
            int i,len,x,y,z,BIF_COUNT,PIN_COUNT,YOUR_MONTHLY_COUNT,count1,count2;
            char suffix[4]=".pin";
            char *nptr=" ";
            FILE *biflis;
             int p;
            int main()
            {
            long t;
            system("ls -l|sort -n >test.txt");
            system("cat test.txt|grep BH|awk '$5 <= 1610612736 {print $9}' > bhatia.out");
            system("cat test.txt|grep BH|awk '$5 > 1610612736 {print $9}' > bhatia1.out");
            if((list=fopen("bhatia.out","r"))==NULL)
            {  printf("\n Error opening bhatia.out\n\n "); return 0; }

             if((biflis=fopen("biffile_account.lis","w"))==NULL)
             {   printf("\n Error opening biffile_account.lis file\n\n");
              return 0; }
            BIF_COUNT=0;
            PIN_COUNT=0;
            YOUR_MONTHLY_COUNT=0;
            count1=0;
            while((fgets(filename,85,list))!=NULL)
            {
                ptr=filename;
             for(i=0;*ptr;i++,ptr++)
             {
              sf[i]=*ptr;
             }i--;
             sf[i]='\0';

             if((source=fopen(sf,"r"))==NULL)
             {
              printf("\nError Opening Source File %s\n",sf);
              return 0;
             }
            fseek(source,0,SEEK_END);
            fseek(source,-90,SEEK_CUR);
             while((fgets(name,140,source))!=NULL)
             {
              st=strstr(name,_Monthly);
             count2=0;
              if(st!=NULL)
              {
            YOUR_MONTHLY_COUNT++;
            strcpy(account," ");
            count2++;
            //sprintf(fstring,"%s~%s",filename1,account);
            }
             count1= count2 + count1;
            }
            fclose(source);
            if( count1 > 0 )
            {
              printf(" %s   GBIF file  has the correct footer    having ",sf,source);
                printf(" %d number of correct bills \n",count1);
            }
               else
            {
            printf(" %s   GBIF file has the footer missing and have  incorrect bills  \n",sf,source);
            //printf(" %d number of in incorrect bills \n",count1);
            }
                 count1=0;
            BIF_COUNT++;
            }

A: Here's one major bug:
printf(" %s   GBIF file  has the correct footer    having ",sf,source);

You also need to go through all the variables declared here:
FILE *source,*list,*wlist,*movlist,*biflis;

Every single one of them needs to have one call to fopen and one call to fclose, or they should be removed. Also you declare FILE *biflis; twice.
And there is no need to use global variables at all.


text:
Q: Completely destroy Fragment Instance I am using a custom Backstack to manage the Application screens. Basically, the custom BackStack is a List. The problem is that this method does memory leaks.
This method checks if there is a Fragment in the cell already:
    private fun addToBackStack(fragment: Fragment){
    try {
        if (backStack.isNotEmpty() && backStack[backStackPosition] != null)
            fragmentUtils.removeFragment(backStack[backStackPosition]!!)
    } catch (e: IndexOutOfBoundsException) {
        e.printStackTrace()
    }
    backStack.add(backStackPosition, fragment)
}

And this is how I try to remove it:
fun removeFragment(fragment: Fragment?){
    fm.beginTransaction().remove(fragment).commit()
}

But I still have memory leaks, according to LeakCanary. What am I doing wrong, or how to completely destroy a Fragment?


text:
Q: How to destroy one Game Object out of two having same script Problem:-
I have a Traffic system in my game I want to destroy a car that gets hit by another car. But the problem is both cars have the same script with the name TrafficCar. Here is the function inside the script which is responsible for the collision.
void OnCollisionEnter (Collision col)
{
  // I want to destroy car after 1 sec due to some reason
  if (col.gameObject.tag == gameObject.tag)
   Destroy (col.gameObject,1f); // or let suppose I'm using traffic pooling
}

In this case, both cars are destroyed. But I want to destroy the car which gets hits
Question:-

How I can destroy cars that get hits?

For example:- Car A hits Car B then Car B should be destroyed
Thanks In Advance

A: I think what you could do to tackle this is store a list of already known => already handled collisions and handle each collision pair only once
Something like e.g.
// struct that holds references to the two colliding gameobjects and implements
// GetHashCode and IEquatable regardless of the order of the two GameObjects
private readonly struct CollisionPair : IEquatable<CollisionPair>
{
    private readonly GameObject _a;
    private readonly GameObject _b;

    public CollisionPair(GameObject a, GameObject b)
    {
        _a = a;
        _b = b;
    }

    public bool Equals(CollisionPair other)
    {
        // return true regardless of the order of a and b
        return Equals(_a, other._a) && Equals(_b, other._b) || Equals(_b, other._a) && Equals(_a, other._b);
    }

    public override bool Equals(object obj)
    {
        return obj is CollisionPair other && Equals(other);
    }

    // return same HashCode regardless of the order of a and b
    public override int GetHashCode()
    {
        var hashA = _a.GetHashCode();
        var hashB = _b.GetHashCode();

        return HashCode.Combine(Math.Min(hashA, hashB), Mathf.Max(hashA, hashB));
    }

    public static bool operator ==(CollisionPair left, CollisionPair right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(CollisionPair left, CollisionPair right)
    {
        return !left.Equals(right);
    }
}

and then have collections and do e.g.
// stores the already handled collision pairs => if already know this collision => ignore
private static readonly HashSet<CollisionPair> _alreadyHandledCollisions = new();

// [OPTIONAL] stores objects that are already marked for destroy
// if collide with such thing or we are such thing => ignore
private static HashSet<GameObject> _alreadyMarkedForDestroy = new();

private void OnCollisionEnter(Collision col)
{
    // Tag doesn't match => ignore
    if (!col.gameObject.CompareTag(gameObject.tag)) return;

    // [OPTIONAL] This object will be destroyed within a second already => ignore
    if(_alreadyMarkedForDestroy.Contains(gameObject)) return;

    // [OPTIONAL] The other object will be destroyed within a second already => ignore
    if(_alreadyMarkedForDestroy.Contains(col.gameObject)) return;

    var collisionPair = new CollisionPair(gameObject, col.gameObject);

    // This colliso pair has already been handled (by the other object) => ignore
    // but also remove this collision pair since it has already been handled by the other collision partner
    if (_alreadyHandledCollisions.Contains(collisionPair))
    {
        _alreadyHandledCollisions.RemoveWhere(c => c == collisionPair);
        return;
    }

    // Otherwise you handle the collision and store it so he other one doesn't
    _alreadyHandledCollisions.Add(collisionPair);
    Destroy(col.gameObject, 1f);

    // [OPTIONAL]
    _alreadyMarkedForDestroy.Add(col.gameObject);
}

the additional things marked with [OPTIONAL] are to prevent that an object that will be destroyed within the next second causes new collisions with other objects. If this is desired anyway get rid of those lines.

As a little demo I additionally mark the object that is going to be destroyed in red so you can see it is always only one and once it is red all further collisions with this object are ignored

A: You can use Rigidbody to find out which car gets hits.
void OnCollisionEnter (Collision col)
{
  // I want to destroy car after 1 sec due to some reason
  if (col.gameObject.tag == gameObject.tag && IsFirstCar(col.gameObject)) Destroy (col.gameObject,1f);
}
bool IsFirstCar(GameObject other)
{
  var rb = GetComponent<Rigidbody>();
  var otherRb = other.GetComponent<Rigidbody>();
  return rb.velocity.magnitude > otherRb.velocity.magnitude;
}

if car A hits car B. that means car A's velocity greater than car B's. Then we can destroy car B


text:
Q: JavaScript converting a decimal to an integer I Have a php variable..
<?=number_format($total_commission,2)?>
this has the value
£3,400.00
I then have a JavaScript script which counts up to the value on the front-end
// Count Up
function animateValue(id, start, end, duration) {
  var obj = document.getElementById(id);
  var range = end - start;
  var minTimer = 50;
  var stepTime = Math.abs(Math.floor(duration / range));
  // never go below minTimer
  stepTime = Math.max(stepTime, minTimer);
  // get current time and calculate desired end time
  var startTime = new Date().getTime();
  var endTime = startTime + duration;
  var timer;

  function run() {
    var now = new Date().getTime();
    var remaining = Math.max((endTime - now) / duration, 0);
    var value = Math.round(end - (remaining * range));
    obj.innerHTML = value;
    if (value == end) {
        clearInterval(timer);
    }
  }

  timer = setInterval(run, stepTime);
  run();

}

var value1 = <?=$total_count?>;
var value2 = <?=$total_commission?>;
var value3 = <?=$active_refs?>;

animateValue("value1", 0, value1, 1750);
animateValue("value2", 0, value2, 1750);
animateValue("value3", 0, value3, 1750);

The problem I am having is when the php variable is used in javascript it is converting the number to an integer and loosing the decimal values. How can I keep the number as a decimal when going from PHP to JavaScript?
I tried using toFixed(2) on the end variable but no luck..

A: In JavaScript you cant define variable with zeros after dot
1.00
Javascript engine clear all zeros in the end of numbers after dot.
examples:

let oneZero = 1.0;
console.log('oneZero:',oneZero);
let twoZeros = 1.00;
console.log('twoZeros:',twoZeros);
let oneAndTen = 1.10;
console.log('1.10:',oneAndTen);
let threeZeros = 1.000;
console.log('threeZeros:',threeZeros)

For fix your problem you need just format like a string your number.
let formatedString =  1+".00";
But it's not best solution. You need use some like numeraljs library

A: In javascript you can try with using Number() function to convert a string to a number (integer or decimal) if needed, and you can use parseFloat(number) method.
Examples on using Number():
// Convert strings
Number('123'); // returns 123
Number('12.3'); // returns 12.3
Number('3.14someRandomStuff'); // returns NaN
Number('42px'); // returns NaN

Examples on using parseFloat():
var text = '3.14someRandomStuff';
var pointNum = parseFloat(text);
// returns 3.14

In your particular case however, this is how it could work as an example:
(Edited, updated code, using the OP's code, since I had a little more time now to clear this for later, useful reference)
<?php
$total_count = (string) "£3,400.00";
$total_commission = (string) "£3,500.25";
$active_refs = (string) "£4,400.87";
?>

And you can also check the result/output of the above code version here:
or if it was deleted already, then here
And maybe less importantly I'd like to point out that in your code the following line converted the decimal to integer which had to be edited too:
var value = Math.round(end - (remaining * range));

This one line would return back an integer number.


text:
Q: script shell in cronjob I was working on crontab, but I think it gives me a problem. When I run my script in crontab it work but it is empty, and when I execute my script manually, if it contains data.
Can you help me?
regards


text:
Q: How to rout to a web api when calling another web api I have ASP.Net web api2 odata service running as a separate project in our application server. Initially to consume this in our web server application we have used Breeze.js with angular and later we get the limitation that the service URL cannot be exposed through browser (even not declare as a javascript variable in breeze).
Conceptually we are advised to go with another approach that we have to create another api in the web server, the breeze will use this URL (not exposing the actual app server api) but the web server api should route the actual odata service in the app server
App Server
Asp.Net Web api 2 odata services
Web server
API services (calling this service routes the app server which running as a separate service)
Breeze.js: Entity Manager( should call the API service in the web server)
And the App server api is designed to consume in breeze that is added breeze attributes.
any help would be more appriciated

A: I have Come up with the solution to setup proxy API handler in the web server level that exposed as a service in the breeze and the service call, post and get will be managed with this proxy web api.
here is the sample
in the web server API, the following code has been added in APP_start/WebApiConfig.cs
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

    //The fist value "*" needs to change with the actual redirection Uri
        var cors = new EnableCorsAttribute("*", "*", "*", "DataServiceVersion, MaxDataServiceVersion");
        config.EnableCors(cors);

        config.Routes.MapHttpRoute(name: "Proxy", routeTemplate: "{*path}",
                                    handler: HttpClientFactory.CreatePipeline(innerHandler: new HttpClientHandler(),
                                    handlers: new DelegatingHandler[] { new ProxyHandler() }), defaults: new { path = RouteParameter.Optional },
                                    constraints: null);
    }

}

public class ProxyHandler : DelegatingHandler
{
    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var pathandquery = request.RequestUri.PathAndQuery;

    // APPserver webapi URL
        var uri = "http:localhost/api/";

        request.RequestUri = uri;

        if (request.Method == HttpMethod.Get)
        {
            request.Content = null;
            return base.SendAsync(request, cancellationToken)
                   .ContinueWith<HttpResponseMessage>(t =>
                   {
                       var response = t.Result;
                       response.Headers.Add("Access-Control-Allow-Origin", "*");

                       return response;
                   });
        }
        else
        {

            if (request.Method == HttpMethod.Post)
            {

                return base.SendAsync(request, cancellationToken)
                  .ContinueWith<HttpResponseMessage>(t =>
                  {
                      var response = t.Result;
                      response.Headers.Add("Access-Control-Allow-Origin", "*");
                      response.Headers.Add("Access-Control-Allow-Credentials", "true");
                      response.Headers.Add("Access-Control-Allow-Methods", "POST");
                      return response;
                  });
            }

            if (request.Method == HttpMethod.Put)
            {

                return base.SendAsync(request, cancellationToken)
                  .ContinueWith<HttpResponseMessage>(t =>
                  {
                      var response = t.Result;
                      response.Headers.Add("Access-Control-Allow-Origin", "*");
                      response.Headers.Add("Access-Control-Allow-Credentials", "true");
                      response.Headers.Add("Access-Control-Allow-Methods", "PUT");
                      return response;
                  });
            }
        }
        return base.SendAsync(request, cancellationToken);
    }
}

Exposing this web server API will bring the entire breeze controller metadata without exposing the appserver URL


text:
Q: jQuery issue when dynamically changing height jsFiddle I wrote a bit of jquery to give equal height to multiple elements on the same page. It looks nice with content inside of boxes. It works on page load, but the problem is when the window is resized, the text within the box starts to overflow out of the box, instead of the boxes recalculating their necessary height.
Here's a sample: http://jsfiddle.net/hV5AG/
Use your browser and resize it smaller horizontally to see what I'm talking about.
I tried adding:
    $( window ).resize(function() {
    equalHeight($(".equalheight"));
    });

But that didn't work.

A: Once you've set the height manually once, your <div>s aren't resizing automatically anymore. In your equalHeight function, reset the behavior to 'auto' before you calculate the max height:
group.css('height','auto');
var tallest = 0;
group.each(function() {
   var thisHeight = $(this).height();
   if(thisHeight > tallest) {
      tallest = thisHeight;
   }
});
group.height(tallest);

Of course, you need to remember to call your function when the window is resized. Here's a working fiddle: http://jsfiddle.net/MGfMh/

A: You can use this:
p {font-size: 2vw;}

fiddle

The viewport-percentage lengths are relative to the size of the
  initial containing block. When the height or width of the initial
  containing block is changed, they are scaled accordingly. However,
  when the value of overflow on the root element is auto, any scroll
  bars are assumed not to exist. Note that the initial containing
  block's size is affected by the presence of scrollbars on the
  viewport.

Viewport-percentage lengths

A: You can reset the boxes to auto before rechecking them
jQuery(function($) {

    function equalHeight(group) {
        var tallest = 0;
        group.css('height','auto').each(function() {
            var thisHeight = parseInt($(this).css('height'), 10);
            if(thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    }
    equalHeight($(".equalheight"));

    $( window ).resize(function() {
        equalHeight($(".equalheight"));
    });

});

FIDDLE
Minified a little, it would look like this
function equalHeight(group) {
    group.css('height','auto').height(Math.max.apply(null, group.map(function(_,el) {
        return $(el).height();
    })));
}

FIDDLE


text:
Q: How do I wire up spring oauth using spring eureka? I have created a Single Page Application using the Spring Tutorial for making one with AngularJS and OAuth and such found here:
https://spring.io/guides/tutorials/spring-security-and-angular-js/#_multiple_ui_applications_and_a_gateway_single_page_application_with_spring_and_angular_js_part_vi
This is the application.yml files for the SPA application:
security:
  user:
    password: none
  oauth2:
    client:
      accessTokenUri: localhost:7777/uaa/oauth/token
      userAuthorizationUri: localhost:7777/uaa/oauth/authorize
      clientId: acme
      clientSecret: acmesecret
    resource:
      user-info-uri: localhost:7777/uaa/user

zuul:
  routes:
    resource:
      path: /resource/**
      url: localhost:9000/resource
    user:
      path: /user/**
      url: localhost:7777/uaa/user

eureka:
  client:
    serviceUrl:
      defaultZone: ${vcap.services.eureka-service.credentials.uri:127.0.0.1:8761}/eureka/

---
spring:
  profiles: cloud
eureka:
  instance:
    hostname: ${APPLICATION_DOMAIN}
    nonSecurePort: 80

I want to know how I would change the zuul routes and the user-info-uri so that I don't have to specify the urls and all this can be done by using the service-id. I looked at the tutorial for using eureka here:
https://spring.io/blog/2015/01/20/microservice-registration-and-discovery-with-spring-cloud-and-netflix-s-eureka
but I don't quite understand how I can achieve my goal without adding all the java to my code, because the basic eureka server already seems to register all my services.

A: Had issue with using eureka service id, userInfoUri used to throw UnknownHost Exception all the time, @LoadBallanced restTemplate did not solve my issue, solution was to set prefer-token-info to false ( if true - no load ballancing for oauth )
security.oauth2.resource.service-id={Service ID as at eureka server registered}
security.oauth2.resource.userInfoUri= http://${security.oauth2.resource.service-id}/user/me
security.oauth2.resource.loadBalanced=true
security.oauth2.resource.prefer-token-info=false

no port number needed if service  ID used , but needed if ip or host used

A: If I do understand your question correct you can just use the config file in this pattern:
zuul:
  routes:
    <service_id>:
      path: /path/**

For example (if your oauth-service is registered as auth):
zuul:
  routes:
    auth:
      path: /user/**

Zuul will leverage Eureka and find the endpoints for the services. In addition to that it will provide client-side load-balancing.


text:
Q: MySQL (5.x) database backup/restore to file tool Welcome,
I'm looking for php class  what allow me to backup MySQL (5.x) databases under PHP.
I test many from phpclasses but most all are written for mysql 4 and under mysql5, generate wrong code.

*

*Class should allow me to dump my database into file.

*easy restore that file.

*generated file (.sql) should be compatible with phpmyadmin.

A: You will get better results using mysqldump as compared to phpMyAdmin's SQL Export especially when dealing with large databases and large strings of data
as @Dan mentioned, use exec() or shell_exec() to run the mysqldump command

A: MySQL has its own dump and import abilities. You can simply call use the mysqldump and mysql clients already installed on your server. If you want to wrap that functionality in a PHP script, build the commands as strings and use exec() or shell_exec() to run them on the system.


text:
Q: asp.net - Disable some content during certain period of time I want to change my content for example since 15:00 until 17:00. Disable labels or something like that. What can I use to do that?

A: VB.NET
If DateTime.Now >= New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 15, 0, 0) AndAlso DateTime.Now <= New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 17, 0, 0) then
   MyPanel.Visible = false
End If

Contain the UI Elements, such as labels, that you want to hide within MyPanel.


text:
Q: renaming particular files in the subfolders with full directory path experts, i have many folders and inside the folder there are many sub-folders and the sub-folders contain many files.However, in all the sub-folders one file name is same that is input.ps.Now i want to rename the same input.ps with full path plus file name
so input.ps in all directories should be renamed to home_wuan_data_filess_input.ps
i tried
#!/bin/sh
for file in /home/wuan/data/filess/*.ps
do
mv $file $file_
done

But it does not do the same as i expect,i hope experts will help me.Thanks in advance.

A:
so input.ps in all directories should be renamed to home_wuan_data_filess_input.ps

You may use this find solution:
find /home/wuan/data/filess -type f -name 'input*.ps' -exec bash -c '
for f; do fn="${f#/}"; echo mv "$f" "${fn//\//_}"; done' _ {} +

A: Ok, so file will end up being
/home/wuan/data/filess/input.ps

What we need here is the path, and the full, snake-cased name. Let's start by getting the path:
for f in /home/wuan/data/filess/*.ps; do
    path="${f%*/}";

This will match the substring of f up until the last occurrence of /, effectively giving us the path.
Next, we want to snake_case all the things, which is even easier:
for f in /home/wuan/data/filess/*.ps; do
    path="${f%*/}";
    newname="${f//\//_}"

This replaces all instances of / with _, giving the name you want the new file to have. Now let's put all of this together, and move the file f to path/newname:
for f in /home/wuan/data/filess/*.ps; do
    path="${f%*/}";
    newname="${f//\//_}"
    mv "${f}" "${path}/${newname}"
done

That should do the trick

Here's one of many sites listing some of the bash string manipulations you can use.
Sorry for the delayed update, the power in my building just cut out :)

A: while read line;
do
   fil=${line//\//_};                             # Converts all / characters to _ to form the file name
   fil=${fil:1};                                  # Remove the first -
   dir=${line%/*};                                # Extract the directory
   echo "mv $line $dir/$fil";                     # Echo the move command
   # mv "$line" "$dir/$fil";                      # Remove the comment to perform the actual command
done <<< "$(find /path/to/dir -name "input.ps")"


text:
Q: Is there a policy about removing "Thanks" from posts?
Possible Duplicate:
Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?

I understand posts don't need any fluff to them and just the questions, which is why I try and avoid any salutations or "autobiographies"; though I don't think adding a simple thanks to the end of the question hurts and many people like to thank the people that will read the question and possibly help them in advance.
This is a site filled with user content and whilst I understand editing the posts to make them more readable/easier to understand, doing unnecessary edits is just rude.
With that said, my question is, is this site policy?

A: This discussion isn't new. See Should 'Hi', 'thanks', taglines, and salutations be removed from posts?.
Everybody seems to agree that salutations and taglines should be removed (in fact, most salutation get removed automatically), but the community is a little more divided on the "thanks".
Personally, I think it should be removed, although an edit to do that and only that might not be worth it. It's unnecessary fluff. It makes sense if you think of the question as something personal, but the main purpose of your question and its answers is helping future visitors.
If you want to thank somebody, just use votes.

A: I think you're overblowing the problem*.  First, I looked through every one of your posts. Here's what I found:
As of this writing you've asked 128 questions. Exactly 7 of them had the "Thanks" edited out (in its various forms). What's funny is that of those 7 edits, only 2 weren't substantial edits.
What this tells me that during the course of improving your questions, some editors are editing out the "Thanks!" to make the question in line with Stack Overflow standards.  This may upset you, but that's how we do things here. That's what keeps us separated from mere forums.
Substantial Edits:

*

*Uploadify Alternative

*OSCommerce / Zencart / Cubecart, which is easier to consume?

*Get Amount of Rows when doing a MySql INTOFILE query

*InfiniDB options: how to set them?

*Writing Valid HTMLText Areas? cannot leave out rows and cols?
Non-substantial Edits:

*

*Absolute Positioning and Its Parent Element

*What happens when putting UTF-8 data into a latin1 database column?
If I include all questions you've asked across all Stack Exchange Sites, that only raises the total up another 5. You've had a grand total of 12 out of 157 questions edited to remove the Thanks!, and in the vast majority of those cases, the OP also made other edits that made the question better than it was before.

* This is a feature, not a problem. I wish more people took the time to edit other people's posts into shape. So yes, there's a problem, it's just not the problem you are bringing up.


text:
Q: Different keyStore for different product flavors in Gradle I have different productFlavors specified in my build.gradle file
 dev {
            applicationId "com.advancedprogressive.chare.dev"
            versionCode 83
            versionName "2.2.1"
        }
staging {
            applicationId "com.advancedprogressive.chare.qa"
            versionCode 119
            versionName "2.8.1"
        }

and have have signing configurations like
signingConfigs {
        release {
            storeFile
            storePassword
            keyAlias
            keyPassword         }
        debug {
            keyPassword
            storeFile
            keyAlias
            storePassword
        }
    }

I have different keystors for both flavors. I can specify different keystores for different build types e.g debug/release but how can i specify different keysotre for each flavor.

A: You can use somenthing like this:
android {
    signingConfigs {
        dev {
        }

        staging {
        }
    }

    productFlavors {
        dev {
            signingConfig signingConfigs.dev
        }

        staging {
            signingConfig signingConfigs.staging
        }
    }
}

A: You may also want to keep your credentials secured in a separate file.
In your app/build.gradle file
android{
    signingConfigs {
        free {
            def keystorePropertiesFile = rootProject.file("app/src/free/keystore.properties")
            def keystoreProperties = new Properties()
            keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }

        paid {
            def keystorePropertiesFile = rootProject.file("app/src/paid/keystore.properties")
            def keystoreProperties = new Properties()
            keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }

    ...

    flavorDimensions "default"
    productFlavors {
        free {
            applicationId "com.example.freeapp"
            versionCode 1
            versionName "1.0"
            signingConfig signingConfigs.free

        }
        paid {
            applicationId 'com.example.paidapp'
            versionCode 1
            versionName '1.0'
            signingConfig signingConfigs.paid
        }
    }
}

In your app/src/flavor_name/keystore.properties
storePassword=...
keyPassword=..
keyAlias=...
storeFile=src/flavor_name/keystore_file.jks //or any other path of jks file

A: Using below gradle you can achieve multiple productFlavors :
   android {
  signingConfigs {
    release {
        keyAlias 'alias'
        keyPassword 'password'
        storeFile file('first.keystore')
        storePassword 'password'
    }

    debug {
        keyAlias 'alias'
        keyPassword 'password'
        storeFile file('second.keystore')
        storePassword 'password'
    }
  }

  compileSdkVersion 23
  buildToolsVersion "23.0.2"
  defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
     }

      productFlavors{
        dev {
            applicationId "com.advancedprogressive.chare.dev"
            versionCode 83
            versionName "2.2.1"
            signingConfig signingConfigs.debug
        }
        staging {
            applicationId "com.advancedprogressive.chare.qa"
            versionCode 119
            versionName "2.8.1"
            signingConfig signingConfigs.release
        }
  }

      }

I hope its help you.

A: For me, when building, it´s aways using Release signingConfigs.


text:
Q: Need help with trigger to update second field after lookup field updated I have a Custom Object called "Product_Demo_List_c that has a lookup field (Product_c) from product which gets Product2.Name.  I also have a text field (Product_Code__c) in my Custom Object that i want to contain the same value from Product2.ProductCode for the record picked.
I can not seem to get this to work and any help would be appreciated.
trigger ProductDemoListTrigger on Product_Demo_List__c (before insert, before update){

    for(Product_Demo_List__c pd: trigger.new){
       for(Product2 p:[select Name,ProductCode from Product2 where Name=:pd.Product__c]){
           pd.Product_Code__c = p.ProductCode;
       }
    }
}

A: Are you certain that the Product_Demo_List__c.Product__c field has been populated and matches an actual Product2 Name before the record is inserted? If this isn't the case then the inner SOQL query won't return any Product2 records and the Product_Code__c won't be set.
A Lookup relationship to Product2 might be a better option for handling the relationship. Then, as Daniel Hoechst commented, you could use a formula field to expose the Product Code in you custom object.


text:
Q: combining images into timelapse movie I was going through the steps listed in:

How can I combine 30,000 images into a timelapse movie?

When I run the mencoder command, I get an error saying:
[mf] search expr: *.jpg
============ Sorry, this file format is not recognized/supported =============
=== If this file is an AVI, ASF or MPEG stream, please contact the author! ===
Cannot open demuxer.

Anyone help me out with why it isn't recognizing the .jpg files?

A: You could try out a program called 'chronolapse' which worked great for me when combining 80k+ images.
It's free and open source.
You can get it here:

http://keeyai.com/projects-and-releases/chronolapse/


text:
Q: how to reduce the height of panel in jQuery mobile I make a panel in jQm .I want to reduce the height of panel .I added height property with important but it not work .I also google it did not find any solution
can you please tell me how to reduce the height of panel .?
here is fiddle
http://jsfiddle.net/7Cmb3/8/
#mypanel{

    height:100px !important
}

Thanks

A: In JQM panel the min-height is 100%. So Try like the following in your style sheet.
.ui-panel{
   min-height:100px !important;
   max-height: 100px !important;
   min-width:100px !important;
   max-width: 100px !important;
   overflow-y:scroll;
   overflow-x:scroll;
}

Look at this FIDDLE DEMO
Check this for only reduce the height FIDDLE DEMO


text:
Q: ActiveRecord Sum Max Joins results in array with multiple nil ids Same Question as Rails activerecord : sum, max and joins
except getting strange results.
class CustomResumeline < ActiveRecord::Base
  has_many :resumeline_words
end

class ResumelineWord < ActiveRecord::Base
  belongs_to :custom_resumeline
end

CustomResumeline.joins(:resumeline_words).where(resumeline_words: {name: ["time", "data"]}).select('sum(resumeline_words.weight) as nb_votes').group('resumeline_words.custom_resumeline_id').order('nb_votes ASC')

Results
CustomResumeline Load (0.8ms)  SELECT sum(resumeline_words.weight) as nb_votes FROM "custom_resumelines" INNER JOIN "resumeline_words" ON "resumeline_words"."custom_resumeline_id" = "custom_resumelines"."id" WHERE "resumeline_words"."name" IN ('time', 'data') GROUP BY resumeline_words.custom_resumeline_id  ORDER BY nb_votes ASC
 => #<ActiveRecord::Relation [#<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, ...]>

My question is, why am I getting an array with a bunch of nil id CustomResumelines ?
Thanks

A: As per your query, you are using #select to
result =  CustomResumeline.joins(:resumeline_words)...

result returns a relation object, where id will added by Rails as you used #select, although you have not selected it. You can do now
result. map { |rec| rec.nb_votes }
# will give array of `nb_votes` values.

Some hints from Selecting Specific Fields guide :

Client.select("viewable_by, locked") - to select only viewable_by and locked columns. Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive: ActiveModel::MissingAttributeError: missing attribute: <attribute>. Where <attribute> is the attribute you asked for. The id method will not raise the ActiveRecord::MissingAttributeError, so just be careful when working with associations because they need the id method to function properly.

So The id method will not raise the ActiveRecord::MissingAttributeError,.. -- Why ? As #select add it by default it to each model object created by it with a value of id as nil.


text:
Q: Using Regex to split numbers and expressions I a working on a project where I can accept a string from the user, the user can input negative positive values all in one line.
I then use a regex to split it up on a space. I now need to be able to "fix" the array to have numbers and operators.
  "(?<=[\\(\\)\\+\\-*\\/\\^A-Za-z])|(?=[\\(\\)\\+\\-*\\/\\^A-Za-z])"

For example a user could input
-1 /2 - 1/2
I now need elements to be like
arr[1] = -1
arr[2] = 2 (or / would also be fine)
Currently it does:
-
1
/
2
-
1
/
2
I started writing cases to be like if arr[i].equals("-") then grab the next number also. Well that wont work since they can have a - in the middle.
Any ideas are appreciated.

A: I'm guessing that maybe, some expression similar to
-?\s*[0-9.]+|([+÷*-])

might be OK to start with, if validation would be done afterwards.
There might be some design issues in what you might be trying to accomplish here though.
Demo
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class re{

    public static void main(String[] args){

        final String regex = "-?\\s*[0-9.]+|([+÷*-])";
        final String string = "-1 /2 - 1/2.4\n"
             + "-1 /25 -- 1/23.2\n"
             + "-1 / 29 - 1/212.42\n"
             + "-1 / 2 - -1/2\n"
             + "-1 / 2 * -1/2\n"
             + "-1 / 2 + -1/2\n"
             + "-1 / 2 ÷ -1/2";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

Output
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: - 1
Group 1: null
Full match: 2.4
Group 1: null
Full match: -1
Group 1: null
Full match: 25
Group 1: null
Full match: -
Group 1: -
Full match: - 1
Group 1: null
Full match: 23.2
Group 1: null
Full match: -1
Group 1: null
Full match:  29
Group 1: null
Full match: - 1
Group 1: null
Full match: 212.42
Group 1: null
Full match: -1
Group 1: null
Full match:  2
Group 1: null
Full match: -
Group 1: -
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match:  2
Group 1: null
Full match: *
Group 1: *
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match:  2
Group 1: null
Full match: +
Group 1: +
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match:  2
Group 1: null
Full match: ÷
Group 1: ÷
Full match: -1
Group 1: null
Full match: 2
Group 1: null

If you wish to explore/simplify/modify the expression, it's been
explained on the top right panel of
regex101.com. If you'd like, you
can also watch in this
link, how it would match
against some sample inputs.


text:
Q: CSS Flip book style fading webpage I am a bit new to CSS and HTML codding but there is a button on the center of the screen. When you click the button it needs to fade out to show a few more buttons. Almost like a flip book every time you click the button it will go in a order to another set of button. A button appearing will fade in and buttons going out will fade out. I need some help on how to do this. I am stuck trying to fade the buttons and having them work like a flip book. Thanks!
HTML - http://pastebin.com/ApH8mG48
CSS - http://pastebin.com/PX66m4gy


text:
Q: Crash while downloading video via ASIHTTPRequest? Below is the stack trace by BUGSENSE:
Stacktrace:
0  libobjc.A.dylib 0x34a80464 0x34a7d000 13412
1  CoreFoundation 0x35818bbf -[NSObject(NSObject) performSelector:withObject:] 22
2  App-iPad 0x0002839d 0x1000 160669
3  CoreFoundation 0x35818bbf -[NSObject(NSObject) performSelector:withObject:] 22
4  Foundation 0x31181795 __NSThreadPerformPerform 268
5  CoreFoundation 0x358307dd __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ 12
6  CoreFoundation 0x358025b7 __CFRunLoopDoSources0 382
7  CoreFoundation 0x35801e5b __CFRunLoopRun 230
8  CoreFoundation 0x35801c87 CFRunLoopRunSpecific 230
9  CoreFoundation 0x35801b8f CFRunLoopRunInMode 58
10 GraphicsServices 0x320c84ab GSEventRunModal 114
11 GraphicsServices 0x320c8557 GSEventRun 62
12 UIKit 0x341dc329 -[UIApplication _run] 412
13 UIKit 0x341d9e93 UIApplicationMain 670
14 App-iPad 0x00003ac5 main 108

Any suggestions?

A: It looks to me that the delegate object that handles the ASIHTTPRequest has been deallocated.
Make sure you stop all pending requests when dealloc'ing your delegate.


text:
Q: Using Random number generation function in python Is there any way we can generate two random numbers that would satisfy the following condition:
18.5 <= num_1 / num_2**2 < 25 i.e this expression returns true.

A: There you go (2 random integers):
import random
import math

MAX_NUM_2 = 100
num_2 = random.randrange(1, MAX_NUM_2 + 1)
num_1 = random.randrange(math.ceil(num_2 ** 2 * 18.5), num_2 ** 2 * 25)


text:
Q: Strongly typed ASP.NET MVC ViewData extensions - where to put identifiers? Sometimes the overhead of creating a new model type is annoying. In these cases, I want to set ViewData, and the options seem to be:

*

*Simply set viewdata with a string key, and cast it out. This has obvious problems.

*Store the identifier (string key) somewhere (where? on the controller?) and cast it out on the viewpage. While solving one of the problems, I'm still casting, which is problematic, and kills type inference.

*Use the MVCContrib strongly typed Set/Get functions. These are nice sometimes, but if the type isn't very descriptive, say a boolean "IsNew", they don't work too well. It also kills type inference and it's still pretty much just doing a cast, so I must manually sync up the view and controller.
So, instead I'm thinking of using a phantom type to combine both the type and key identifier. It'd be equivalent to this psuedo-C#:
class ViewDataKey<T> = string

This would let me create identifiers in the controller like this:
public static readonly ViewDataKey<bool> IsNew = "IsNew";

With some simple extension methods, setting the data would be:
  ViewData.Set(IsNew, true);

Getting it out is just as easy:
var isNew = ViewData.Get(FrobNozzleController.IsNew);

Notice we don't need to specify the type of isNew, it's safely inferred. The key and type definitons are stored in one location.
Questions:

*

*Where should the key be stored? For "global-ish" ViewData, some common class works fine. But for View/Controller specific data? Is there any downside to putting it on the controller? (Apart from the long name of the controller?)

*Are there any easier ways, or things already built-in?

A: I think this is what the model does in the MVC pattern. Why you don't use a typed view instead?
I believe you just make things more complicated by introducing yet another dependency between the controller and the view. I don't see any specific benefit in terms of line of code or something like that. You have to declare the existence of the variable, which you'd also do in the model class definition.
You don't get any significant advantage by doing so.

A: One idea would be to create tuples for a strongly typed view in cases where you don't want to create a specific view model class:
class SimpleModel<T>

class SimpleModel<T, U>

class SimpleModel<T, U, V>

Then make a strongly typed view, as usual. Now you have the advantages of strong typing without having to make a new class for every case.
.NET 4.0 has Tuple, etc., built in.

A: I'd still use the ViewData dictionary, and instead of "casting it out" I'd just use ToString() and Html.Encode it. Why break the MVC pattern?

A: I just put up a post covering this topic.
http://agilefutures.com/index.php/2009/06/mvc-strongly-typed-global-viewdata
Hope it's of use.
Regards
Tobi


text:
Q: spacy similarity method doesn't not work correctly I am doing simple natural language processing using spacy.
I'm working on filtering out words by measuring the similarity between words.
I wrote and used the following simple code shown in the spacy documentation, but the result does not look like a documentation.
import spacy
nlp = spacy.load('en_core_web_lg')
tokens = nlp('dog cat banana')

for token1 in tokens:
    for token2 in tokens:
        sim = token1.similarity(token2)
        print("{:>6s}, {:>6s}: {}".format(token1.text, token2.text, sim))

the result of code is below.
   dog,    dog: 1.0
   dog,    cat: 2.307269867164827e-21
   dog, banana: 0.0
   cat,    dog: 2.307269867164827e-21
   cat,    cat: 1.0
   cat, banana: -0.04468117654323578
banana,    dog: -7.828739256116838e+17
banana,    cat: -8.242222286053048e+17
banana, banana: 1.0

Especially, similarity between "dog" and "cat" should be about 0.8, but it is not a nd very very small value.
In addition, similarity between "dog" and "banana" is 0.0 but similarity between 'banana' and 'dog' is -7.828739256116838e+17.
I don't know how to fix it.
please help me.

A: First install large EN model (or all models).
python3  -m spacy.en.download all
Next, try with sample code as per documentation using,
nlp = spacy.load('en_core_web_md')
If that doesnt work, Instead of above try loading,
nlp = spacy.load('en')
After doing above changes the result is as per documentation.
python3 /tmp/c.py
   dog,    dog: 1.000000078333395
   dog,    cat: 0.8016855098942641
   dog, banana: 0.2432764518408807
   cat,    dog: 0.8016855098942641
   cat,    cat: 1.0000001375986456
   cat, banana: 0.2815436412709355
banana,    dog: 0.2432764518408807
banana,    cat: 0.2815436412709355
banana, banana: 1.000000107068369

A: I solved this problem, finally.
just add code import numpy as np .
That's all.


text:
Q: Is it fine to use Getx for state management? I am building a big/complex e-commerce app and I am currently using Getx for state management. Some people are saying it is bad because it does a lot of things and if it breaks, your whole app will break while some others say it is good and I can go with it. Suppose that I will use this package for state management only, not for routing, dialogs, snackbars, etc. will that be fine? if not, can you suggest some alternatives for state management?

A: For better management performance and good architecture you can use riverpod or bloc
Riverpod

*

*riverpod can also works with hookswidget very well than help you to make your code more reusable

*riverpod is currently mostly used by developers

*riverpod have many built in providers like future provider strema provider etc
Bloc

*

*bloc also a good package it make you code more easily maintanable form

*you can easily separate your repository and logic and views and make your code more readable and maintable

*Bloc works best with streams and other soultuions


text:
Q: Full Windows 7 student edition UK What is the cheapest way to buy full Windows 7 (any flavour) for a UK student? I am building a new PC, so I don't have any old versions to upgrade from.

A: This link no longer is valid for windows 7, the offer has expired.
Depending on which institution you go to and what course you are doing you may be able to get windows 7 for FREE. Infact you can get lots of microsoft for free, except office, which is cheap if you do use the above link.
The way to get windows for free and things like visual studi etc is with MSDN AA.
The MSDN Academic Alliance.
Search here to see if you qualify: http://www.msdnaa.net/search/schoolsearchIntl.aspx

A: Microsoft's UK education page has some links to companies they claim offer educational discounts: http://www.microsoft.com/uk/education/studentoffer/default.aspx
I won't guarantee that this is the cheapest, but it's a good starting point, at least.


text:
Q: How to integrate Live555 in XCode (iOS SDK) I have to implement the live streaming from iphone to wowza server using rtsp h264. I did search and found one library Live555. I created the .a files along with include headers. But I am not able to use them in my XCode. As I used then then it start giving errors in understanding the c++ keyword "class". This is maybe because of .hh files.
Is anyone having idea, how to include live555 in ios application.
Thanks in advance...


text:
Q: Rails: multiple submit button outside simple form Say I have an Article model, and in the Article model 'settings' view I have two submit buttons outside of a form, "update Details" and "Next Template".
My question is how can I know which button is clicked in the controller. Both submit button is outside of a simple form.
I tried like:
 <%= f.submit "update Details",name: "update_details", class: "x-update" %>

<%= f.submit 'Next Template', name: "next_template", class: "x-next" %>

and the logic is the same on the controller
   if params[:update_details]
      [..]
   elsif params[:next_template]
      [..]
   end

but it doesn't work. How do I do that? I can't change the route, so is there a way to send a different variable that gets picked up by [:params]?

A: I think you can do something like this:
<%= f.submit "update Details",name: "update_details", value: true, class: "x-update" %>
<%= f.submit 'Next Template', name: "next_template", value: true, class: "x-next" %>

Optionally, I think you can use same names, and different values.
<%= f.submit "update Details",name: "next_template", value: false,  class: "x-update" %>
<%= f.submit 'Next Template', name: "next_template", value: true, class: "x-next" %>

And in the controller:
if params[:next_template]
  something
else
  something_else
end

A: I resolved it by putting in our html form template:
<input type="hidden" name= "action_type" id="action_type">

then in JavaScript file we added
$('.x-update').on 'click', ->
$("#action_type").val("exit")
$("#details-form").submit()

and then in controller file we checked the parameters:
if params[:action_type] == "exit"
  redirect_to #your desired path
else
  redirect_to #based on given path

That's It. It works.

A: Try in the controller to check, what params you getting when trigging the submit.
render plain: params

Additional You can use "hidden_field_tag" option in side a form.
<%= hidden_field_tag 'plan', params[:plan] = 2 %>

A: Please try to put both buttons inside form and then try with same logic.


text:
Q: Securing RESTful web service using Apache Shiro I am currently in the process of building RESTful web services using Jersey framework as a backend (for an Ipad\Iphone application) using Java, at the POINT I was trying to figure out a security( Authentication and Authorization) implementation of my the API, I came across Basic, digest and Oauth but at the point as my APIs are still not fully developed so I think Oauth seems to be a bit of an overkill to me...
My question is though Apache Shiro looks easy to grasp and start with is something that can usedfor securing RESTful web services like in the long run as my APIs logic grows?

A: Shiro is very customizable. It provides interfaces for doing your Authentication and Authorization. If you ever need to change your authentication from Basic to Oauth, all you have to do is implement a new class and plug it in.
The interfaces to look into are Realm, AuthenticatingRealm, AuthorizingRealm, Subject, AuthenticationToken and SimpleAuthorizationInfo.


text:
Q: how to get GWT RequiresResize.onResize to respond to zooming? onResize is not called after zooming.
Current GWT implementation:
public native void initWindowResizeHandler() /*-{
    var oldOnResize = $wnd.onresize;
    $wnd.onresize = $entry(function(evt) {
      try {
        @com.google.gwt.user.client.Window::onResize()();
      } finally {
        oldOnResize && oldOnResize(evt);
      }
    });
  }-*/;

The only solutions I found for capturing resize events use polling.

*

*Is polling the best (only) way? If so, how can the Scheduler be used for optimal performance?

*Once the event is captured, does calling com.google.gwt.user.client.Window::onResize() seem like a good idea?
Thanks
Current solution looking for improvements
@Override
  protected void onLoad() {

    Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {

      @Override
      public boolean execute() {

        if (listOuter.getOffsetWidth() != knownWidth)
          onResize();

        return SomeListViewImpl.this.isAttached();
      }
    }, 200);

  }

onResize is called on Window.onresize and on zooming.
 @Override
  public void onResize() {

    knownWidth = listOuter.getOffsetWidth();
    GWT.log("resize: " + knownWidth);

    //some magic

  }


text:
Q: Whole component re renders when modal opens in react <ThemeProvider theme={theme}>
          <GlobalStyle />
          {componentName !== 'questionaire' &&
            componentName !== 'activityResult' && <CardWrapper />}

          <ErrorModal
            errorModal={errorModal}
            handleErrorModal={handleError}
            errorMsg={error}
          />
          {successModal && successMsg  ? (
            <SuccessModal successModal={successModal} successMsg={successMsg} />
          ) : (
            <Grid
              className="card-layout"
              style={
                componentName === 'questionaire'
                  ? { margin: '20px', height: 'calc(100% - 40px)' }
                  : { margin: '30px 20px' }
              }
            >
              {customTagProps.meterId && (
                <CustomTag type={componentName} propData={customTagProps} />
              )}
            </Grid>
          )}
        </ThemeProvider>

I have a modal component, which on load re renders the entire component. I want to prevent the re render of the entire component.

A: lack of Information
may I only suggest you try using useRef instead of useState
you could use useMemo() to return the component


text:
Q: Inequality of polynomial on neighbour quadrilaterals Let $\mathbb{Q}_p$ (in $\mathbb{R}^2$) denotes the vector space of polynomials of degree $\le p$ in each variable $x_1,x_2$. Let $v_h\in \mathbb{Q}_p(K\cup K')$, where $K,K'\subset \mathbb{R}^2$ are two quadrilateral of $diam\sim h$, $h>0$ fixed, both affine to the square $(0,1)^2$, which either share a vertex either a side (note that we are in the finite element context).
It holds
$$
\|v_h\|_{L^\infty(K)}\le C \|v_h\|_{L^\infty(K')}.
$$
What does $C>0$ depend upon? What happens if $\operatorname{dist}(K,K')\sim C_1 h$?

A: Before I start, I'll like to point out:
The coefficient $C$ is invariant under global affine transformations of the plane. In particular, $C$ doesn't depend on $h$ explicitly. If you place $K$ and $K'$ at a distance $C_1 h$ apart
and scale $K$, $K'$ and their separation by same amount, same $C$ follows.
With this in mind, we can transform the question as follows:

*

*Pick a fixed integer $p > 0$.

*Let $Y \subset \mathbb{R}[x,y]$ be the set of polynomials in $x,y$ whose degree in both $x, y$ are at most $p$.

*Let $K'$ be the square $[-1,1]^2$ and $K$ be another square of side $2$.

*For any $f \in Y$, let $\|f\|_K$ and  $\|f\|_{K'}$ be the sup-norm of $f$ over $K$ and $K'$.

*

*$\|f\|_K = \sup\limits_{(x,y) \in K} |f(x,y)|$

*$\|f\|_{K'} = \sup\limits_{(x,y) \in K'} |f(x,y)|$

*Let $Y_1 = \{ f \in Y \;|\; \|f\|_{K'} \le 1 \}$
The questions become what are the coefficient $C$ to make following works:
$$\|f\|_K \le C \|f\|_{K'}, \;\forall f \in Y
\quad\iff\quad \|f\|_K \le C,\;\forall f \in Y_1$$
This is equivalent to $\sup\limits_{f\in Y_1} \|f\|_K\;\le\; C$. Independent of
where $K$ is located, what we need is compute/estimate $\sup\limits_{f\in Y_1} \|f\|_K$.
To my surprise, it is possible to compute this value.
To do this, we need to look at a related 1-dim problem.

*

*Let $X \subset \mathbb{R}[x]$ be the set of polynomials in $x$ with degree at most $p$.

*For $f \in X$, let $\|f\|_I$ be the sup-norm of $f$ over $I = [-1,1]$.

*

*$\|f\|_I = \sup\limits_{x\in I}|f(x)|$.

*Let $X_1 = \big\{ f \in X : \|f\|_I \le 1 \big\}$
The new problem is given $t \in \mathbb{R}$, what is $\Delta(t) \stackrel{def}{=} \sup\limits_{f \in X_1}|f(t)|$?
Let's consider what happens when $t > 1$.
For any $f \in X_1$ and $\epsilon > 0$, consider the function:
$$g(x) = (1+\epsilon)T_p(x) - f(x)$$
Let $x_k = \cos\frac{k\pi}{p}$ for $k = 0,1,\ldots,p$. Since $T_p(x)$ reaches $+1$ and $-1$ alternatively at these $p+1$ points, we find
$$g(x_0) > 0, g(x_1) < 0, g(x_2) > 0,\ldots$$
This forces $g(x)$ to have at least $p$ roots $\lambda_1,\ldots,\lambda_p$ with $\lambda_i \in (x_{i},x_{i-1})$. Since $g(x)$ is a polynomial of degree at most $p$, these are all the roots of $g(x)$.
$g(x)$ can be factorized as $A\prod_{i=1}^p(x - \lambda_i)$ for some constant $A$. Since  $g(x_0) > 0$ and $x_0 > \lambda_i$ for all $i$, we find $A > 0$.
Since $t > 1 = x_0$, this leads to
$$(1+\epsilon)T_p(t) - f(t) = A\prod_{i=1}^p(t - x_i) > 0
\implies (1+\epsilon)T_p(t) > f(t)
$$
Apply a similar argument to $-f(x)$, we can deduce $(1+\epsilon)T_p(t) > |f(t)|$.
Since this is true for all $f \in X_1$, we get $(1+\epsilon)T_p(t) \ge \sup_{f\in X_1}|f(t)|$
Since this is true for all $\epsilon > 0$, we obtain $T_p(t) \ge \sup_{f\in X_1}|f(t)|$
Since the bound $T_p(t)$ can be reached by taking $f(x)$ to $T_p(x)$, we have
$$\Delta(t) = \sup_{f\in X_1}|f(t)| = T_p(t)\quad\text{ for } t > 1$$
It is clear $\Delta(t) = 1$ for $|t| \le 1$ and $\Delta(t)$ is an even function in $t$. This implies
$$\Delta(t) = \max(1,|T_p(t)|)$$
With this 1-dim result at hand, we can ask a similar 2-dim question:
What is
$\Delta(x,y) \stackrel{def}{=} \sup\limits_{f\in Y_1}|f(x,y)|$?

*

*If $(x,y) \in K' = I^2$, $\Delta(x,y)$ is trivially $1$.

*If one of $x,y \in I$, say $y \in I$, then for any $f\in Y_1$, $f(\cdot,y) \in X_1$. By above 1-dim result, it is easy to deduce $\Delta(x,y) = \Delta(x)$.  Similarly, $\Delta(x,y) = \Delta(y)$ when $x \in I$.

*When both $x, y \not\in I$, we can apply result in step 2. to deduce
$|f(x,s)| \le \Delta(x)$ for all $f \in Y_1, s \in I$. Apply the 1-dim result
to $h \in X_1$ where $h(s) = \frac{f(x,s)}{\Delta(x)}$, we can deduce
$$\sup_{f\in Y_1}\left(\frac{f(x,y)}{\Delta(x')}\right) =
\sup_{f\in Y_1} h(y) \le \sup_{h\in X_1} h(y) = \Delta(y)$$
This leads to $\Delta(x,y) = \sup\limits_{f\in Y_1}f(x,y) \le \Delta(x)\Delta(y)$. Since the bound on RHS is achieved by $f(s,t) = T_p(s)T_p(t)$, we can conclude $\Delta(x,y) = \Delta(x)\Delta(y)$ in this case.
Combine all these, we have
$$\Delta(x,y) = \Delta(x)\Delta(y) = \max(1,|T_p(x)|)\max(1,|T_p(y)|)$$
Armed with this function, it is easy to see the target "sup" can be computed by following formula.
$$\bbox[border:1px solid blue;padding: 1em]{C_{optimal} = \sup_{f\in Y_1} \|f\|_K =  \max_{(x,y)\in K}\Delta(x)\Delta(y)}$$
For example,

*

*When $K$ is sharing an edge with $K'$, say $K = [1,3]\times[-1,1]$, the largest $\Delta(x,y)$ in $K$ is achieved at $(3,\cdot)$.
In this case, $C_{optimal} = \Delta(3) = T_p(3)$.

*When $K$ is axis aligned and sharing an vertex with $K'$, say $K = [1,3]^2$,
the largest $\Delta(x,y)$ in $K$ is achieved at $(3,3)$. In this case, $C_{optimal} = \Delta(3,3) = \Delta(3)^2 = T_p(3)^2$.
For other configuration where $K$ is separated by a distance $C_1h$ from $K'$, one can compute the optimal $C$ in a similar manner.
Let's say $K$ and $K'$ are related by a translation of distance $C_1h$. Under the affine transformation which
maps $K'$ to $I^2$, the center of $K$ will be located at a distance $c = \sqrt{8}C_1$ from the origin.
Let's say the center is  $(c\cos\theta,c\sin\theta)$ for some $\theta \in [0,\frac{\pi}{2}]$. Over $K$,
$\Delta(x,y)$ will be maximized at the vertex $( 1 + c\cos\theta, 1 + c\sin\theta )$. In this case
$C_{optimal} = T_p(1+c\cos\theta)T_p(1+c\sin\theta)$.
When $K$ is not axis aligned with $K'$, it is not immediately obvious which point in $K$ will maximize $\Delta(x,y)$. I'll leave the fun (or mess?) to you.


text:
Q: How to add custom columns to datatable? I am using
gem 'jquery-datatables-rails', '3.4.0'
gem 'ajax-datatables-rails'

My data table look like

My CoffeeScript for this table looks like
# Datatables
$ ->
  table = $('#qr-submissions-table').dataTable
    dom: 'C<"clear">lfrtip'
    processing: true
    serverSide: true
    ajax: $('#qr-submissions-table').data('source')
    pagingType: 'full_numbers'
    columns: [
      {data: 'custom_columns'}
      {data: 'delivery_number' }
      {data: 'qpi_department' }
      {data: 'qr_client' }
      {data: 'date_submitted'}
      {data: 'bay_number' }
      {data: 'submitted_by'}
      {data: 'delivery_note'}
      {data: 'ops' }
    ]
    "order": [[ 3, "desc" ]]
    columnDefs: [
      { "orderable": false, "targets": [3, 7, 8]},
      {"targets": 1, visible: ($("#delivery_number_show").val() == 'true')},
      {"targets": 2, visible: ($("#division_show").val() == 'true')},
      {"targets": 3, visible: ($("#client_show").val() == 'true')},
      {"targets": 4, visible: ($("#scan_time_show").val() == 'true')},
      {"targets": 5, visible: ($("#delivery_location_show").val() == 'true')}
      {"targets": 6, visible: ($("#submitted_by_show").val() == 'true')},
      {"targets": 7, visible: ($("#delivery_note_show").val() == 'true')},
      {"targets": 8, visible: ($("#photo_show").val() == 'true')},

    ]

Here the custom column field is hash like '{ "name1" : "value1", "name2" : "value2" }' .. How can i display this as coulm names and values. name1 and name2 will be column headers and value1 and value2 will be corresponding row values.each row has different values for 'value1' and 'value2'. Is there any way to do this? Please help?

A: Unfortunately I don't know Ruby-on-rails, but I DO know jQuery DataTables.
If your JSON response looks like this:
[{ "Id": "1", "Name": [{ "FirstName": "Tiger", "LastName": "Nixon"}], "Position": "System Architect", "Office": "Edinburgh", "Age": 61 },
{ "Id": "2", "Name": [{ "FirstName": "Garrett", "LastName": "Winters"}], "Position": "Accountant", "Office": "Tokyo", "Age": 63 },
{ "Id": "3", "Name": [{ "FirstName": "Ashton", "LastName": "Cox"}], "Position": "Jr. Technical Author", "Office": "San Francisco", "Age": 66 }];

AND the name of your columns will be fixed (in your example: "name1" and "name2"), you can do something like this (I'll provide you 2 ways of achieving it in the same example):

var jsonData = [
    { "Id": "1", "Name": [{ "FirstName": "Tiger", "LastName": "Nixon"}], "Position": "System Architect", "Office": "Edinburgh", "Age": 61 },
  { "Id": "2", "Name": [{ "FirstName": "Garrett", "LastName": "Winters"}], "Position": "Accountant", "Office": "Tokyo", "Age": 63 },
  { "Id": "3", "Name": [{ "FirstName": "Ashton", "LastName": "Cox"}], "Position": "Jr. Technical Author", "Office": "San Francisco", "Age": 66 }];

var table = $('#example').DataTable({
  LengthChange: false,
  data: jsonData,
  columns: [
      { data: 'Id'},
      { data: 'Name[0].FirstName' }, // 1st Way
      {
         data: null,
         title: "LastName",
         render: function(data, type, full, meta) { // 2nd Way
            return data.Name[0].LastName;
         }
      },
      { data: 'Position' },
      { data: 'Office' },
      { data: 'Age' }
    ]
});
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>

      Id
      FirstName
      LastName
      Position
      Office
      Age

Note: In this case I'm trying to emulate your custom column field with the key Name
But, if your columns will be dynamic (names could change), you'll need to do something like this:
Example


text:
Q: How to download a web page I have Index.cshtml with following code:
@using (Html.BeginForm("DownloadPage", "Home", FormMethod.Post, null))
{
    <input type="submit" value="Download"/>
}

And Sample.cshtml with code like this:
@model string
<h1>@Model<h1>

I want to download Sample page when I press a button on Index.cshtml, like if I click right mouse button and select 'Save as..." line. How to do that?


text:
Q: evaluateJavaScript on WKWebView running slow Running evaluateJavaScript on a WKWebView to inject a JS script can take quite some time to run on a device.
The JS script is quite complex, but is is normal for evaluateJavascript to take 20-30 seconds to run?


text:
Q: Validar una URL con PHP Tengo una gran duda de sobre como puedo validar una URL desde PHP pero que, además, ésta tenga protocolo https o de lo contrario sea incorrecta.
Basándome en esto podría decir si una URL es válida:
Codigo:
<?php
    // Variable to check
    $url = "http://www.w3schools.com/";

    // Remover los caracteres ilegales de la url
    $url = filter_var($url, FILTER_SANITIZE_URL);
    echo $url;
    // Validar url
    if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
        echo("$url es una URL valida");
    } else {
        echo("$url no es una URL valida");
    }
    ?>

Ahora solo debo saber si tiene el protocolo https.

A: Para esto PHP ya trae una función nativa, parse_url.
$url = "http://www.w3schools.com/";

$urlparts= parse_url($url);

$scheme = $urlparts['scheme'];

if ($scheme === 'https') {
    echo("$url es una URL valida");
} else {
    echo("$url no es una URL valida");
}

A: En ese caso debes usar lo siguiente

$urls = array('http://www.website.com', 'https://www.website.com', 'http://website.com', 'https://website.com', 'www.website.com', 'website.com');
foreach($urls as $url) {
    if (preg_match('#^(https?://|www\.)#i', $url) === 1){
        echo $url . ' matches' . "\n";
    } else {
        echo $url . ' fails' . "\n";
    }

Salida:

http://www.website.com matches
https://www.website.com matches
http://website.com matches
https://website.com matches
www.website.com matches
website.com fails

A: Si queremos comprobar por PHP si navegamos a través de protocolo seguro o no utilizaríamos la siguiente condición:

if (isset($_SERVER['HTTPS'])) {
    // Codigo a ejecutar si se navega bajo entorno seguro.
} else {
    // Codigo a ejecutar si NO se navega bajo entorno seguro.
}


text:
Q: Ошибка при передаче элементов структуры в функцию fgets Программа компилируется нормально, но при исполнении завершается аварийно. Проблема где-то в цикле, кажется, при обращении к элементам структуры.
Файл записан исправно и читается, а ошибка - стандартное прекращение работы программы.

Структура
typedef struct university_notes {//LAB2 == 80
  char fac[LAB2][LAB2];
  char spec[LAB2][LAB2];
  int am;
} unotes;

Функция с ошибкой
void read_data(unotes *un) {
  FILE* f;
  un->am = -1;
  if((f = fopen("2ndfac.txt", "r")) == NULL) {
    fprintf(stderr,"Error reading 1st file");
    return;
  }
  while(!feof(f)) {
    un->am++;
    fgets(un->fac[un->am], LAB2, f);
  }
}


text:
Q: Google Colab zone I need to find out to place my dataset in GCS in the same zone so that I avoid charges when running training on TPU's and reading large datasets from GCS.
Does anyone know how to find out current Google Colab instance zone?

A: The data should be stored in a bucket that is in the same zone as the Cloud TPU (or the same region if that specific zone isn't available); to the best of my knowledge Colab itself doesn't play a role in the situation.

A: Running (within Colab)
!curl ipinfo.io

You get something similar to
{
  "ip": "3X.20X.4X.1XX",
  "hostname": "13X.4X.20X.3X.bc.googleusercontent.com",
  "city": "Groningen",
  "region": "Groningen",
  "country": "NL",
  "loc": "53.21XX,6.56XX",
  "org": "AS396XXX Google LLC",
  "postal": "9711",
  "timezone": "Europe/Amsterdam",
  "readme": "https://ipinfo.io/missingauth"
}

Which tells you where you Colab is running.


text:
Q: Enum Inner Class is not recognized as Enum Consider the following Enum classes:
public enum APlanet {
    VENUS   ()  {public void stuff(){}},
    EARTH   () {public void stuff(){}},
    MARS    ()  {public void stuff(){}};
    public abstract void stuff();
}

public enum BPlanet {
    VENUS   (),
    EARTH   (),
    MARS    ();
}

Then APlanet.MARS.getClass().isEnum() returns false whereas BPlanet.MARS.getClass().isEnum() returns true. Why?
Notice that APlanet.getDeclaringClass().isEnum() correctly returns true.
Specifically, I'm trying to reliably test if an Object is Enum:
Object a = APlanet.MARS;
Object b = BPlanet.MARS;
a.getClass().isEnum() /* returns false */
b.getClass().isEnum() /* returns true  */

yet
Enum.class.isAssignableFrom(a.getClass()); /* returns true */

It's a little confusing that the inner class APlanet.MARS is not an Enum yet you can assign it to an Enum, as in:
Enum<?> m = APlanet.MARS;

A: From JLS Section 8.9.1 - Enum Constants:

The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors.

You have declared the constant-specific class body in your first enum:
 MARS ()  {public void stuff(){}}; // The curly braces defines a class body

This creates an anonymous class. So, MARS.getClass() will return the Class instance for this anonymous class, which is not an Enum.

This is similar to case where you create an instance of anonymous subclass of an interface, or any other class like this:
SomeInterface obj = new SomeInterface() { /** Method definitions **/ };

and then obj.getClass() wouldn't return SomeInterface but, ClassContainingThatDeclaration$1.

Notice that APlanet.getDeclaringClass().isEnum() correctly returns true

I suspect that should be - APlanet.MARS.getDeclaringClass().isEnum(). That would return true, as per the documentation of Enum#getDeclaringClass() method:

Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (The value returned by this method may differ from the one returned by the Object.getClass() method for enum constants with constant-specific class bodies.)

But I thought an enum can't be subclassed?
Now the doubt that can come to one's mind is, an enum can't be subclassed. So, how can the anonymous subclass of enum be created? How can it extend the enum? That's because, an enum is final unless it declares some constant-specific class body, as per JLS Section 8.9 - Enums:

An enum type is implicitly final unless it contains at least one enum constant that has a class body.

You still can't explicitly extend an enum:
Even though the constant-specific class body implicitly creates an anonymous sub-class, you can't explicitly extend an enum. As per JLS Section 8.1.4 - Superclasses and Subclasses:

It is a compile-time error if the ClassType names the class Enum or any invocation of it.


text:
Q: Delete before shut down! c# android I want to delete all file in camera folder of my internal smartphone's storage before it goes off!
How can i do?
    namespace App1
{
    [Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
           SetContentView (Resource.Layout.Main);

            Button delete = FindViewById<Button>(Resource.Id.deleteid);

             delete.Click += delegate
             {
                 File dir = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "/Camera");

                 if (dir.IsDirectory)
                  {
                       int i = 0;
                       string[] children = dir.List();
                          while ( i < children.Length)
                       {
                        var file = new File(dir, children[i]).Delete();

                           i++;
                       }

                      Toast.MakeText(this, "The folder exist", ToastLength.Short).Show();
                  }

                  else
                  {
                      Toast.MakeText(this, "Not Works", ToastLength.Short).Show();
                  }
             };
        }
    }

}

I tried to use this code to delete the content of folder but the app crashes.

A: You need to create receiver for listen a shutdown event. For this needs you should implement class Service and don't foget to add following lines in manifest file:
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.intent.action.QUICKBOOT_POWEROFF" />

Also, for delete users data, make shure that you have permissions to do that:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />