text:
Q: Amazon XML deserialize processingreport and getting null values I am trying to read an xml file into a class to return its values.  The classes were created via the xsd.exe from xsd files from Amazon.  The code im using to try and deserialize is:
string FeedSubmissionID = "8395421750";
FileStream responseFile = new FileStream(("d:/Amazon/SubmissionResult-" +  FeedSubmissionID + ".txt"), FileMode.Open, FileAccess.Read);
ProcessingReport _report = new ProcessingReport();
XmlSerializer _des = new XmlSerializer(typeof(ProcessingReport), new XmlRootAttribute("AmazonEnvelope"));
_report = (ProcessingReport)_des.Deserialize(responseFile);

The code im using in ProcessingReport is:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://mws.amazonaws.com/doc/2009-01-01/", IsNullable = false)]
public partial class ProcessingReport
{

    private string documentTransactionIDField;

    private ProcessingReportStatusCode statusCodeField;

    private ProcessingReportProcessingSummary processingSummaryField;

    private ProcessingReportResult[] resultField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "positiveInteger")]
    public string DocumentTransactionID
    {
        get
        {
            return this.documentTransactionIDField;
        }
        set
        {
            this.documentTransactionIDField = value;
        }
    }

    /// <remarks/>
    public ProcessingReportStatusCode StatusCode
    {
        get
        {
            return this.statusCodeField;
        }
        set
        {
            this.statusCodeField = value;
        }
    }

    /// <remarks/>

    public ProcessingReportProcessingSummary ProcessingSummary
    {
        get
        {
            return this.processingSummaryField;
        }
        set
        {
            this.processingSummaryField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Result")]
    public ProcessingReportResult[] Result
    {
        get
        {
            return this.resultField;
        }
        set
        {
            this.resultField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public enum ProcessingReportStatusCode
{

    /// <remarks/>
    Complete,

    /// <remarks/>
    Processing,

    /// <remarks/>
    Rejected,
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ProcessingReportProcessingSummary
{

    private string messagesProcessedField;

    private string messagesSuccessfulField;

    private string messagesWithErrorField;

    private string messagesWithWarningField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
    public string MessagesProcessed
    {
        get
        {
            return this.messagesProcessedField;
        }
        set
        {
            this.messagesProcessedField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
    public string MessagesSuccessful
    {
        get
        {
            return this.messagesSuccessfulField;
        }
        set
        {
            this.messagesSuccessfulField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
    public string MessagesWithError
    {
        get
        {
            return this.messagesWithErrorField;
        }
        set
        {
            this.messagesWithErrorField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
    public string MessagesWithWarning
    {
        get
        {
            return this.messagesWithWarningField;
        }
        set
        {
            this.messagesWithWarningField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ProcessingReportResult
{

    private string messageIDField;

    private ProcessingReportResultResultCode resultCodeField;

    private string resultMessageCodeField;

    private string resultDescriptionField;

    private ProcessingReportResultAdditionalInfo additionalInfoField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
    public string MessageID
    {
        get
        {
            return this.messageIDField;
        }
        set
        {
            this.messageIDField = value;
        }
    }

    /// <remarks/>
    public ProcessingReportResultResultCode ResultCode
    {
        get
        {
            return this.resultCodeField;
        }
        set
        {
            this.resultCodeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "positiveInteger")]
    public string ResultMessageCode
    {
        get
        {
            return this.resultMessageCodeField;
        }
        set
        {
            this.resultMessageCodeField = value;
        }
    }

    /// <remarks/>
    public string ResultDescription
    {
        get
        {
            return this.resultDescriptionField;
        }
        set
        {
            this.resultDescriptionField = value;
        }
    }

    /// <remarks/>
    public ProcessingReportResultAdditionalInfo AdditionalInfo
    {
        get
        {
            return this.additionalInfoField;
        }
        set
        {
            this.additionalInfoField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public enum ProcessingReportResultResultCode
{

    /// <remarks/>
    Error,

    /// <remarks/>
    Warning,
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ProcessingReportResultAdditionalInfo
{

    private string sKUField;

    private string fulfillmentCenterIDField;

    private string amazonOrderIDField;

    private string amazonOrderItemCodeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "normalizedString")]
    public string SKU
    {
        get
        {
            return this.sKUField;
        }
        set
        {
            this.sKUField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType = "normalizedString")]
    public string FulfillmentCenterID
    {
        get
        {
            return this.fulfillmentCenterIDField;
        }
        set
        {
            this.fulfillmentCenterIDField = value;
        }
    }

    /// <remarks/>
    public string AmazonOrderID
    {
        get
        {
            return this.amazonOrderIDField;
        }
        set
        {
            this.amazonOrderIDField = value;
        }
    }

    /// <remarks/>
    public string AmazonOrderItemCode
    {
        get
        {
            return this.amazonOrderItemCodeField;
        }
        set
        {
            this.amazonOrderItemCodeField = value;
        }
    }
}

And finally the xml file:
<?xml version="1.0" encoding="UTF-8"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
    <DocumentVersion>1.02</DocumentVersion>
    <MerchantIdentifier>??????????????</MerchantIdentifier>
</Header>
<MessageType>ProcessingReport</MessageType>
<Message>
    <MessageID>1</MessageID>
    <ProcessingReport>
        <DocumentTransactionID>8395421750</DocumentTransactionID>
        <StatusCode>Complete</StatusCode>
        <ProcessingSummary>
            <MessagesProcessed>1</MessagesProcessed>
            <MessagesSuccessful>0</MessagesSuccessful>
            <MessagesWithError>1</MessagesWithError>
            <MessagesWithWarning>0</MessagesWithWarning>
        </ProcessingSummary>
        <Result>
            <MessageID>1</MessageID>
            <ResultCode>Error</ResultCode>
            <ResultMessageCode>5000</ResultMessageCode>
            <ResultDescription>XML Parsing Error at Line 22, Column 24: cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'LongStringNotNull'.</ResultDescription>
            <AdditionalInfo>
                <SKU>MySKU</SKU>
            </AdditionalInfo>
        </Result>
    </ProcessingReport>
</Message>
</AmazonEnvelope>

The _report object returned has all null values.
Can anyone see where i have gone wrong?

A: Problem solved.
What needed to happen was that the result stream of the amazon feed needed to be saved to a file first and then access the created file and read into the class. Whereas i was trying to read the result directly from the stream.
Hope this helps others


text:
Q: Find all permutations code Problem (Java) I wrote this code to find all possible permutations of some numbers. But i dosen't want to use one digit twice:
123,132,213 are OK, but it produces numbers like 122, 121 etc.
What am i doing wrong?
import java.util.HashSet;

public class main {

public static void main(String[] args) {

    HashSet<Integer> l = new HashSet<Integer>();
    for(int i=0;i<=3;i++){
        l.add(i);
    }
    perm(l,3,new StringBuffer());

}

 static void perm(HashSet<Integer> in, int depth,StringBuffer out){
    if(depth==0){
        System.out.println(out);
        return;
    }

    int len = in.size();
    HashSet<Integer> tmp = in;

    for(int i=0;i<len;i++){
        out.append(in.toArray()[i]);
        tmp.remove(i);

        perm(tmp,depth-1,out);

        out.deleteCharAt(out.length()-1);
        tmp.add(i);
    }
}
}

A: tmp.remove(i) is wrong. You need to remove the ith element from tmp... you are removing the element "i". So, do tmp.remove(in.toArray()[i]). I think that will fix this up. For instance, if the zeroth element is 17, doing tmp.remove(i) will remove all zeroes from the HashSet, not "17".

A: It looks like Autoboxing is getting you.  When you call the remove with 'i', My guess is that 'i' has been boxed to a different object and is thus not found in your HashSet.

A: Here's a much simpler implementation using a HashSet. I'm using strings but the concept remains the same.
public void printPermutations(String str){
    HashSet<String> hs = new HashSet<>();
    printPermutations("", str, hs);
}

public void printPermutations(String prefix, String end, HashSet<String> hs){
    if(end.equals(""))
        System.out.println(prefix);
    for(int i = 0; i < end.length(); ++i)
        if(hs.add(prefix + end.charAt(i))){
            printPermutations(prefix + end.charAt(i),
                    end.substring(0,i) + end.substring(i + 1, end.length()), hs);
        }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Infinite arctan series
I know that usually these types of problems deal with pattern recognition. There would be specific pattern as one proceeds from one term to another. But, in this problem I'm unable to recognize one. So, please give me some hints on starting the solution to this problem.

A: Note that
$$\arctan{A}-\arctan{B} = \arctan{\frac{A - B}{1+A B}}$$
What if $A=2^{k+1}$ and $B=2^k$?...

A: Hint regarding the pattern of terms:
$ x_0 = \frac13 = \frac{2^0}{2^{2\cdot 0+1}+1} $
$ x_1 = \frac29 = \frac{2^1}{2^{2\cdot 1+1}+1} $
$ x_2 = \frac4{33} = \frac{2^2}{2^{2\cdot 2+1}+1} $
...
$ x_k =  \frac{2^k}{2^{2k+1}+1} $


text:
Q: How to make a d3 sankey link flow out the bottom of the diagram? With a d3.js sankey diagram, how can I make a link flow out of a node and off the diagram towards either the bottom or top? This necessitates a 90deg turn in the link and for it to not end at a node (or at least not one in the diagram) and symbolizes a flow going out of the modeled system.
I want it to look something like the 'Finished Petroleum Products' link in this diagram.
Specifically I'm using this boilerplate, but a more generic answer is fine I'm stuck on which methods I can use to make this happen but once I know what to use and how to use them I can implement it.
Update: Basically, what I'm wondering is how to re-write one of the d3 functions (which?) to make a link terminate with a horizontal line (ie flush with the SVG ceiling or floor) instead of a vertical line (ie another node's side face).

A: The code below is a function I used to create a link path which leaves a node on its right, goes horizontally briefly, bends upwards with a quarter-circle and exits the ceiling of the diagram. I was naive in that the solution had nothing to do with re-writing a D3 function..it just took learning how to use the SVG path language.
  function drawPathLeavingDiagram(link) {
     var x0 = link.source.x + link.source.width,
         x1 = x0 + link.source.width / 4,
         x2 = x1 + link.source.width / 2,
         y0 = link.source.y + link.sourceY + link.thickness / 2,
         y1 = y0 - link.source.width / 2,
         rx = link.source.width / 2,
         ry = link.source.width / 2;
     return "M" + x0 + "," + y0 + "L" + x1 + "," + y0 +
            "A" + rx + "," + ry + "," + 0 + "," + 0 + "," + 0 + "," + x2 + "," + y1 +
            "V" + 0;
  }


text:
Q: find special cases while comparing files in reverse order #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BS 12

void reverse(char * buffer, int size)
{
  char tmp;
  int i;
  for(i = 0; i < size / 2; i++)
  {
    tmp = (char)buffer[i];
    buffer[i] = buffer[size - i - 1];
    buffer[size - i - 1] = tmp;
  }
}

int compare_bin(char * buffer, char * buffer2, int size)
{
  // because strncmp is only for string without \x00, so there must be a customized compare function
  int i;
  for(i = 0; i < size; i++)
  {
    if(buffer[i] != buffer2[i])
      return 0;
  }
  return 1;
}

int main (const int argc, const char** argv)
{
  if(argc != 3)
    exit(-1);

  int equal = 1;
  char * buffer = malloc(BS), * buffer2 = malloc(BS);
  FILE * f1, * f2;
  f1 = fopen(argv[1], "r");
  f2 = fopen(argv[2], "r");

  fseek(f1, 0, SEEK_END);
  fseek(f2, 0, SEEK_END);

  long i = ftell(f1), j = ftell(f2);
  if(i != j)
  {
    equal = 0;
    goto endp;
  }

  fseek(f2, 0, SEEK_SET);

  int need = 0;
  int count;
  int f2_pos = 0;

  do
  {
    i = i - BS;
    if(i < 0)
    {
      need = BS - abs((int)i);
      i = 0;
    }
    else
      need = BS;

    fseek(f1, i, SEEK_SET);
    count = fread(buffer, need, 1, f1);

    reverse(buffer, count * need);
    // fwrite(buffer, count * need, 1, f2);
    fread(buffer2, need * need, 1, f2);

    // printf("compare...\n");
    // for(int i = 0; i < need * count; i++)
    // {
    //   printf("%02hhX", buffer[i]);
    // }
    // printf("\n");
    // for (int i = 0; i < need * count; i++)
    // {
    //   printf("%02hhX", buffer2[i]);
    // }
    // printf("\n");

    if(compare_bin(buffer, buffer2, need * count) == 0)
    {
      equal = 0;
      break;
    }

    f2_pos += need * count;
    fseek(f2, f2_pos, SEEK_SET);

    if(i == 0)
      break;
  }while(i > 0);

  fclose(f1);
  fclose(f2);
  free(buffer);
  free(buffer2);

  endp:
  if(equal)
    return 0;
  else
  {
    printf("2 files not equal is reversed order\n");
    return 1;
  }

  return 0;
}

So I write a program to compare file content in reverse order. I have already considered \x00 in binary file and strncmp isn't used. But there is still flaw. There is a test server to test this program. But I dont have access to it. This program always fails on that server. So there must be some special cases to make it fail. Any idea?
There are other ways around it. For instance, calculating MD5. But I want to fix this.

A: For the very first iteration where you read data you have
fread(buffer2, need * need, 1, f2);

The problem is that in that case need is 12, which is the size of the memory allocated for buffer2, but you ask to read 12 * 12 bytes.
If the second file is large enough, you will write out of bounds in the memory, leading to undefined behavior. If the file is not large enough then you won't read anything.
Also note that the order of the two middle arguments to fread matter. If you changed the order you would write out of bounds of the buffer both if the file is larger than need * need or not. You should really read count byte-sized object (the second argument should be 1 and the third should be count, which of course mean you need to change the order in the first call as well).
In short, your two fread calls should be
count = fread(buffer, 1, BS, f1);
fread(buffer2, 1, count, f2);

PS. Don't forget error checking.


text:
Q: Как правильно изменить путь к папке в jQuery File Upload? Всем привет!
Столкнулся со следующей задачей:
Имеется проект, в котором есть несколько динамических страниц, т.е. их содержимое меняется в зависимости от GET-параметра в адресной строке.
На каждой странице работает плагин jQuery File Upload.
Если загружать файлы с его помощью на страницу, плагин создает новую папку с именем GET-параметра (пусть это будет hash). И загружает эти файлы только туда.
Соответственно и уже загруженные файлы он должен отображать только из этой папки.
Структура файлов такая:
images/
fileupload/
index.php

Разобрался, что пути редактируются в UploadHandler.php
Сейчас они выглядят так:
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'../../../../images/' . $_SESSION['hash'] . '/',

'upload_url' => $this->get_full_url().'../../../../images/' . $_SESSION['hash'] . '/',

Здесь $_SESSION['hash'] - это название папки, которое захватывается на странице с GET-параметром и передается в сессию при загрузке.
Работает корректно, но только на локальном сервере. Да и по сути своей понимаю, что написана ерунда, пусть выглядит некорректно при просмотре через панель разработчика.
Если не менять путь и оставить стандартный путь к /files/ внутри плагина, все также работает, но тогда страницы не отображают содержимое папки с картинками.
Как эту проблему можно правильно решить?
Заранее спасибо!

A: Честно сказать, замучился я настраивать jQuery File Upload под свои нужды.
Тяжел он и много зависимостей.
Поэтому нашел другое решение, более простое и гибкое:
DropZone
Надеюсь, что кто-то прочитает этот ответ раньше, чем начнет копаться и тратить массу времени на разбор File Upload-а.


text:
Q: ORM Inheritance Has anyone really wanted and used inheritance support on ORM tools, and if yes which one do you think offers the best support?
Or is ORM Inheritance a "pie in the sky" concept?

A: I have used inheritance with Hibernate (and some with Django), and regreted it dearly.
The "composition over inheritance" principle is especially true for domain classes. While I agree that there is a few cases where inheritance makes sense at the model level, in most cases inheritance will give you a very static domain model, where one object will not be able to change to another class.
I also find that most developers are not comfortable with the concept of inheritance at the database level, so maintenance becomes more complicated.
And last, there are some technical problems, like proxies put in place by Hibernate that will hide the actuall class of an object. It makes "instance of" behave stangely. Of course, you might say that "instance of" is a code smell and that maybe it is another hint that composition is probably a better solution ...

A: I like this question a lot. I've used ORM tools (Toplink, now eclipselink, Hibernate) for a while and I've always seen this as referenced in JPA documents but I've never really had a need for it. Basically my philosophy is the ORM is just there to prevent you from writing tedius code to pull out records for the database. That really is the huge timesaver and it prevents you from making stupid mistakes. Sure you can do fancy stuff with this, but why not save it for the controller (if you're following MVC) than stick it in the model?

A: If you mean inheritance in the domain classes, I use it all the time with NHibernate and/or Castle ActiveRecord, they support the three mapping strategies:

*

*http://nhibernate.info/doc/nh/en/#inheritance

*http://old.castleproject.org/activerecord/documentation/trunk/usersguide/typehierarchy.html

A: If you're writing complex business software, you need it.
Let's say you want to be able to sell stuff to individuals or organizations. On a sales order, the buyer would be one or the other. How do you do that without inheritance?
With inheritance, you'd do something like this:
@Entity
@Inheritance
public abstract class Party {

  @Id
  private Long id;

  ...
}

@Entity
public class Individual extends Party {
  ...
}

@Entity
public class Organization extends Party {
  ...
}

@Entity
public class SalesOrder {

  private Party buyer;

  ...
}

Then you can do:
salesOrder.setBuyer(someOrganization) or salesOrder.setBuyer(someIndividual)


text:
Q: Is there a way to disable onscroll event from preventing page from full scroll, wordpress Please can anyone help me concerning wordpress on how to disable onscroll from theme homepage not able to scroll very well, I want full scroll no stopping just full scroll please if anyone can help thanks.

A: It is hard without seeing any code, but if I have to guess putting this at the top of the page before any other Javascript might work.
document.addEventListener('scroll', function(e) {
    e.preventDefault();
    e.stopImmediatePropagation();
});


text:
Q: MySQL DELETE takes many (40) seconds for few records while a SELECT of the same data is fast Can any one give some insight on why DELETE statement taking more time to execute? We have not created any TRIGGER or CASCADE. We started to notice this issue when migrated to 8.0 from 5.5. Is it a issue related to 8.0 parameter tuning?
DELETE s FROM storefront s LEFT JOIN MASTER m  ON m.userid=s.userid WHERE m.userid IS NULL

9 row(s) affected
Execution Time : 40.816 sec
Transfer Time  : 0.001 sec
Total Time     : 40.817 sec

At the same time, the SELECT statement takes a few mill seconds only.
SELECT s.userid FROM storefront s LEFT JOIN MASTER m  ON m.userid=s.userid WHERE m.userid IS NULL

Total Time     : 0.05 sec

Any help would be appreciated. We have a better server hardware with 16 GB of RAM.
Here is the PROFILING info for DELETE statement.
It is CPU_user(19.046875 seconds) and CPU_system(43.156250 seconds) taking most of the time out of the total execution time 50.24 seconds ....

A: The keyword is "MyISAM".  There are multiple reasons why it might be taking a long time.
(I assume both tables have an index on userid?  And the column definition is the same?)

*

*SELECT will be very fast because it will just use the index to find the userids in question.  0.05 seconds almost seems "too slow".

*MyISAM will do a table lock for the duration of the DELETE.

*MyISAM stores each row somewhere in the .MYD file.  The index is in the .MYI file, even for the Primary Key.

*I think a row is deleted by changing the initial byte of the row.  (Actually a byte whose sole purpose is to indicate deleted.

*In MyISAM, normally, a row is a contiguous stream of bytes in the .MYD.  Deletes and some Updates will leave holes in the .MYD.

*Inserts prefer to fill in the holes first, growing the file if that fails.  Note that a large row will be a linked list of pieces.  This leads, potentially, to slower and slower full-row Selects.

*Oracle plans to get rid of MyISAM.

Those do not really add up to an explanation for 40 seconds to delete only 9 rows.
 Please provide SHOW CREATE TABLE and EXPLAIN DELETE ...; there may be details you left out or that I am falsely assuming.
Bottom Line:  Change to InnoDB, and these problems will go away.

A: This is not the Answer, but it can help to find where so much time is spend. Use PROFILING
SET PROFILING=ON;

Manual
**sample**

mysql> SET PROFILING=ON;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> select * from photons where photons >= 100;
+----+---------------------+---------+
| id | mytime              | photons |
+----+---------------------+---------+
|  1 | 2020-02-26 12:00:00 |     100 |
|  3 | 2020-02-26 12:01:00 |     100 |
|  4 | 2020-02-26 12:05:00 |     200 |
+----+---------------------+---------+
3 rows in set (0.01 sec)

mysql> SHOW PROFILE ALL;
+----------------------+----------+----------+------------+-------------------+---------------------+--------------+---------------+---------------+-------------------+-------------------+-------------------+-------+-----------------------+----------------------+-------------+
| Status               | Duration | CPU_user | CPU_system | Context_voluntary | Context_involuntary | Block_ops_in | Block_ops_out | Messages_sent | Messages_received | Page_faults_major | Page_faults_minor | Swaps | Source_function       | Source_file          | Source_line |
+----------------------+----------+----------+------------+-------------------+---------------------+--------------+---------------+---------------+-------------------+-------------------+-------------------+-------+-----------------------+----------------------+-------------+
| starting             | 0.000130 | 0.000071 |   0.000057 |                 0 |                   0 |            0 |             0 |             0 |                 0 |                 0 |                 0 |     0 | NULL                  | NULL                 |        NULL |
| checking permissions | 0.002022 | 0.000127 |   0.000103 |                 2 |                   0 |          160 |             0 |             0 |                 0 |                 2 |                 1 |     0 | check_access          | sql_authorization.cc |         802 |
| Opening tables       | 0.000474 | 0.000040 |   0.000033 |                 1 |                   0 |            8 |             0 |             0 |                 0 |                 1 |                 1 |     0 | open_tables           | sql_base.cc          |        5715 |
| init                 | 0.000043 | 0.000023 |   0.000020 |                 0 |                   0 |            0 |             0 |             0 |                 0 |                 0 |                 0 |     0 | handle_query          | sql_select.cc        |         121 |
| System lock          | 0.000811 | 0.000046 |   0.000035 |                 2 |                   0 |           16 |             0 |             0 |                 0 |                 2 |                 2 |     0 | mysql_lock_tables     | lock.cc              |         323 |
| optimizing           | 0.000474 | 0.000027 |   0.000023 |                 1 |                   0 |            8 |             0 |             0 |                 0 |                 1 |                 1 |     0 | optimize              | sql_optimizer.cc     |         151 |
| statistics           | 0.000027 | 0.000014 |   0.000012 |                 0 |                   0 |            0 |             0 |             0 |                 0 |                 0 |                 0 |     0 | optimize              | sql_optimizer.cc     |         367 |
| preparing            | 0.000763 | 0.000044 |   0.000036 |                 2 |                   0 |           16 |             0 |             0 |                 0 |                 2 |                 2 |     0 | optimize              | sql_optimizer.cc     |         475 |
| executing            | 0.000007 | 0.000003 |   0.000003 |                 0 |                   0 |            0 |             0 |             0 |                 0 |                 0 |                 0 |     0 | exec                  | sql_executor.cc      |         119 |
| Sending data         | 0.000103 | 0.000057 |   0.000046 |                 0 |                   0 |            0 |             0 |             0 |                 0 |                 0 |                 0 |     0 | exec                  | sql_executor.cc      |         195 |
| end                  | 0.001408 | 0.000062 |   0.000050 |                 1 |                   0 |          248 |             0 |             0 |                 0 |                 1 |                 0 |     0 | handle_query          | sql_select.cc        |         199 |
| query end            | 0.000378 | 0.000029 |   0.000022 |                 1 |                   0 |            8 |             0 |             0 |                 0 |                 1 |                 1 |     0 | mysql_execute_command | sql_parse.cc         |        4946 |
| closing tables       | 0.000409 | 0.000022 |   0.000020 |                 1 |                   0 |            8 |             0 |             0 |                 0 |                 1 |                 1 |     0 | mysql_execute_command | sql_parse.cc         |        4998 |
| freeing items        | 0.000030 | 0.000017 |   0.000012 |                 0 |                   0 |            0 |             0 |             0 |                 0 |                 0 |                 0 |     0 | mysql_parse           | sql_parse.cc         |        5610 |
| cleaning up          | 0.000026 | 0.000014 |   0.000012 |                 0 |                   0 |            0 |             0 |             0 |                 0 |                 0 |                 0 |     0 | dispatch_command      | sql_parse.cc         |        1924 |
+----------------------+----------+----------+------------+-------------------+---------------------+--------------+---------------+---------------+-------------------+-------------------+-------------------+-------+-----------------------+----------------------+-------------+
15 rows in set, 1 warning (0.00 sec)

mysql>


text: Q: Oauth in node.js with soundcloud I am trying to get music information from soundcloud using node.js, however I can't figure how to get the Oauth value to use this https://www.npmjs.com/package/node-soundcloud npm package to access this music data. I appreciate any ideas on how I can retrieve the Oauth code for soundcloud in advance.


text:
Q: How to make gnuplot handle fractions as float in pgfplots If I use gnuplot inside pgfplots it doesn't seem to recognize fractions properly as floats, thus I have to type 3/7. instead of 3/7 which is annoying. Is there a way to change this behaviour globally?
\documentclass{article}

\usepackage{pgfplots}
\begin{document}

\begin{tikzpicture}
  \begin{axis}[no markers,samples=100]
    \addplot gnuplot {2/7*x^2};
    \addplot {2/7*x^2};
    \addplot gnuplot {2/7.*x^2};
  \end{axis}
\end{tikzpicture}

\end{document}

A: There is no such functionality in pgfplots.

If you use gnuplot in order to improve accuracy and speed, you may be interested in the following suggestion: you can use lualatex in order to compile your documents. In this case, pgfplots makes a good effort to compute math expressions by means of lua -- which results in high accuracy and high speed. The only prerequisite is to write \pgfplotsset{compat=1.12} (or newer) into your preamble.
If pgfplots figures that your plot contains TeX code or something which is unsupported by the current lua backend, it will automatically fall back to the pdflatex implementation without any user action.


text:
Q: Redirect screen in react native I am using the stack navigator of react-navigator to build my project, I want to redirect the user to the home screen after the user signed in.
I am using navigation.navigate to redirect, but it will cause the home screen to display a back button to the login screen.
if (this.state.user) {
  this.props.navigation.navigate('SignIn');
}

Is there any way to reset the navigation? or any other method I can perform without reset the navigation?

A: The way i would do it is to reset the navigation stack and then redirect it to the home page. Luckily there's a method for doing such thing called NavigationActions.reset which replace the navigation state with a new one.
So for your case i would do the following:
if (this.state.user) {
  let newStack= NavigationActions.reset({
   index: 0,
   actions: [
     NavigationActions.navigate({ routeName: 'Home'})
   ]
  })
  this.props.navigation.dispatch(newStack);
}

This code will create a new stack with the first page of the stack being the home page (you can change it with your custom routeName), and then use this new stack as our new navigation stack.
You can find more about the reset method on the official docs.
https://reactnavigation.org/docs/navigators/navigation-actions#Reset


text:
Q: Python hangman game. Python 3 I am trying to create a simple Hangman game using Python. I have faced a problem which I can't solve and would be grateful to receive some tips from you guys.
Okay I will provide you with a sample of my code and below it, I will explain what my issue is:
# Here is my list of words
words = ['eight', 'nine', 'seven'...]
# Choosing a random word from the list
word = random.choice(words)

# Creating an empty list to store the result
secret_word = []

# Creating a count variable which I will use later to determinate if the player wins
count = 1

for letter in word:
    secret_word.append('_')
secret_word[0] = word[0]

user_guess = input("Enter a letter: ")

# Here if the user guesses a letter
# We will place that letter on it's spot in our secret_word
while user_guess:
    if user_guess in word:
        print("Correct letter.")
        # adding 1 to count for every guessed letter
        count += 1
        # replacing the '_' with the letter
        for letter in range(len(word)):
            if user_guess == word[letter]:
                secret_word[letter] = word[letter]
        # here I am checking if the user has won
        if count == len(word):
            print("You Win!")

I gave you only a part of my program because I don't think that there's a need for the entire code.
My problem is in the count variable. As you can see I am adding + 1 to the variable every time when the user guesses a correct letter so when the count variable = len(word) my little program will know that the user had won.
Anyways when one single letters appears twice in the word like for example the word SEVEN haves the letter E two times my count variable still goes up by only 1 so  the user cant win in a case like this. I have absolutely no idea how to fix this and would be happy to receive some hints.
Thank you and please excuse my bad English and coding skills

A: You could increment count whenever you replace an underscore with the correct the letter. That way, count will be equal to the number of letters correct in the word so far.
To be more clear, move count += 1 to be in the if statement when you replace underscores with the actual letter.
One problem I see with this is you're giving the player the first letter and initializing count to 1. I don't know why you're doing this, but if the first letter occurs more than once, it won't be reflected in the word, and the player will still have to guess that letter anyways.

A: Move the count to where you are replacing the letter.
while user_guess:
    if user_guess in word:
        print("Correct letter.")
        # replacing the '_' with the letter
        for letter in range(len(word)):
            if user_guess == word[letter]:
                # adding 1 to count for every guessed letter
                count += 1
                secret_word[letter] = word[letter]
        # here I am checking if the user has won
        if count == len(word):
            print("You Win!")


text:
Q: converting list to tuple I have few command-line options (5 for example) and I want to convert them to tuple. The problem is that I expect them to appear in correct order, so tuple can be easily built from list using pattern-match, but in real life options can be provided in random order, so I don't know if head of the list contain Verbose option or log file name?
I tried to think how to do that using continuation-passing style, however nothing useful comes into my mind.
Is that ever possible?
I think that I can "sort" the list to have it in predicted order, but it does not look good.
Also I could get rid of the tuple and create data record - however that will still lead up to checking the type of attribute and set the correct field of the record. Still a lot of typing.

A: Given what you describe, I think you have two options.  Of the two, I would say that converting to a dictionary would be easiest, but converting to a Tuple would work and only be a little clumsy
So, take this definition:
options :: [OptDescr (String, String)]
options = [Option ['a'] ["alpha"] (ReqArg (\a -> ("alpha", a)) "empty") "",
           Option ['b'] ["beta"] (ReqArg (\a -> ("beta", a)) "empty") "",
           Option ['g'] ["gamma"] (ReqArg (\a -> ("gamma", a)) "empty") ""]

main = do
    args <- getArgs
    let (opts, nonopts, errs) = getOpt Permute options args
    putStrLn $ show opts

From this, a couple of my example outputs are:
[("beta","b"),("alpha","a")]
[("alpha","a"),("gamma","g"),("beta","b")]

and so on.  Same order as on the command line.  But, because of the way I set it up above, I basically have an association list, so... if I in particular want a Tuple that has the values (alpha, beta, gamma), then my best option is...
(lookup "alpha" opts, lookup "beta" opts, lookup "gamma" opts)

You resulting data type would be (Maybe String, Maybe String, Maybe String), in the order of "alpha", "beta", and "gamma".


text:
Q: Screen resolution locked at 800x600 I have reviewed the answers that exist.  I trialed Ubuntu 14.04 on my Novatech U50SI1 and it ran perfectly albeit slowly, so I installed it in place of Windows XP.
When I booted up 14.04 my screen resolution locked at 800x600 and I do not have the option in settings to have anything other than this resolution.
The text is therefore very large and the screen overflows so that I cannot scroll to some of the command buttons.
Xrandr just errors out with "invalid resolution", no matter what I type (even 800x600).
When I boot from the disk the screen resolution is fine.  I think the video card for this model is SIS Mirage 3 but I am not sure how to check.  The only driver updates I have found are for windows not Ubuntu and they all have .exe files my Ubuntu install will not run.
I hope this is now clear. My question is how do I change the resolution and also run .exe programs?

A: I would suggest going to System Settings/Software & Updates/Additional Drivers/Selecting a driver for your video card, assuming this was not done already. I had the same problem after installing Ubuntu and that is how i solved it.


text:
Q: Is it possible to prioritize which folders get synced first when using Ubuntu One? I face the problem that u1 syncs my files to a given order. I'd like to change that order. Consider that: On a week end I work and I may also copy the content of my photo SD card onto my notebook. The next time I boot my work computer, I might be sitting there and waiting for some hours until U1 synced/downloaded all the photos to my workstation and the files I need for work are the last in the '--waiting' list.
I don't mind if Ubuntu One is a slow downloader, I would be just happy if I could define that all files in a certain folder (and all of it subfolders) always need to be downloaded first.
I'm aware that there was once the possibility to move some files to the beginning of the sync list. But that was a very clumsy way with providing the folder id etc. and in the current version of u1 I can't even find it any more.
Any suggestions on how to prioritize always the same folder?

A: Short answer is no, there is no way to prioritize the order in which files are synchronized. There is however, a workaround for situations like yours.
Instead of having all files under the ~/Ubuntu One folder, you can have different files under different folders within your home directory, which are each individually synchronized with Ubuntu One. You can then choose to only have certain folders synchronized to certain machines, and you can disable and enable the folders being synchronized on any one machine, in the Ubuntu One control panel application. Thus you could disable ~/Photos from being synchronized, until after ~/Documents has finished synchronizing, for example.


text:
Q: If determinants $D$ and $D_1$ are given, how do we find the determinant $D_2$ such that $D_2=\frac{D}{D_1}$? The following question is taken from the practice set of JEE exam.

If the determinant $D=\begin{vmatrix}
1 & 1 & 1\\
\alpha+\beta & \alpha^2+\beta^2 & 2\alpha\beta\\
\alpha+\beta & 2\alpha\beta & \alpha^2+\beta^2
\end{vmatrix}$ and $D_1=\begin{vmatrix}
1 & 0 & 0\\
0 & \alpha & \beta\\
0 & \beta & \alpha
\end{vmatrix}$, then find the determinant $D_2$ such that $D_2=\frac{D}{D_1}$.

I calculated $D=(\alpha^2-\beta^2)(\alpha-\beta)(\alpha+\beta-2)$
And $D_1=\alpha^2-\beta^2$
Thus, I thought the answer would be $(\alpha-\beta)(\alpha+\beta-2)$
But the answer given is $\begin{vmatrix}
1 & 1 & 1\\
1 & \alpha & \beta\\
1 & \beta & \alpha
\end{vmatrix}$
If I calculate its value, it indeed matches with that of mine. But how do we find the answer in the required format?
Before this question, a note was written: "If $D_1$ is the determinant formed by replacing the elements of determinant $D$ of order $n$ by their corresponding cofactors then $D_1=D^{n-1}$"
Not sure if this note is meant for this question, but I tried writing cofactors for each element but still couldn't solve this question. Any help? Thanks.

A: That's a somewhat weird formulation of the problem, in my opinion, but what they meant was presumably that the matrices $A$ and $A_1$ are given, and you want to find some matrix $A_2$ such that $D_2 = \det(A_2)$ equals $D/D_1=\det(A)/\det(A_1)$. And the matrix that they have chosen is $A_2 = A_1^{-1} A$. (You can check quite easily that $A_1 A_2 = A$.) But it's not the only possible answer, since there are many matrices with the same determinant.


text:
Q: How do I save my game in LittleBigPlanet 2 on PS3? I keep looking up how to save, and I cannot find a way to save my game.
How do I save my LittleBigPlanet 2 game on PS3?

A: The game automatically saves for you. If you are playing online, you will see a little spinning planet at the bottom left of the screen when it is saving, and if you are playing offline you will see a little running Sackboy image in the bottom left of the screen.
In general, if you have returned to your pod before quitting the game, you can safely assume it has saved. It does not save your progress mid-level, though - you will have to start levels over from the beginning when you play again. It does remember what stickers or objects you found, though.
However, if you are making new levels of your own in the level creator, you will have to tell the game to save in one of two ways:

Start > Switch to Play Mode > Save Changes

or:

Start > Save/Save As

A: Much like little big planet 1, your character actually saves automatically after each level. And each time you log out from your pod or whatever. Just look for the little logo down in the bottom right corner to see when it is saving.

A: To save your level (created by selecting a slot on "Your Moon") you press Start and select "Save Changes"
Or, you could "Switch to Play Mode" which will bring up a prompt asking you if you want to save your level.


text:
Q: Initialize method not invoking I want to add a spinner in my javafx project including maxmimum(1) and minimum(5).
The problem is that the initialize method is not invoking.
When does the initialize should be invoked? Why doesn't it?
This is the App.java code:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class AverageApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

This is my FXMLController.java Code
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;

import javafx.scene.input.*;

public class FXMLDocumentController implements Initializable{

    @FXML private Spinner spi;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        System.out.println("HI");
        this.spi.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 5));
    }

}

And This is my FXMLDocument.fxml code:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.web.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="714.0" prefWidth="584.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <AnchorPane layoutX="108.0" layoutY="30.0">
         <children>
            <Spinner fx:id="spi" />
         </children>
      </AnchorPane>
      <Label layoutX="278.0" layoutY="34.0" text="تعداد واحد :" />
      <Label layoutX="510.0" layoutY="34.0" text="نام درس :" />
      <TextField alignment="CENTER" layoutX="380.0" layoutY="30.0" nodeOrientation="LEFT_TO_RIGHT" prefHeight="25.0" prefWidth="120.0" />
      <Button layoutX="34.0" layoutY="98.0" mnemonicParsing="false" text="اضافه کردن" />
      <Label layoutX="520.0" layoutY="123.0" text="Label" />
      <Label layoutX="520.0" layoutY="162.0" text="Label" />
   </children>
</AnchorPane>

A: Based on @fabian, your FXML is missing something like:
fx:controller="yourpackagename.FXMLDocumentController ">

It should be a part of your root node:
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="714.0" prefWidth="584.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="yourpackagename.FXMLDocumentController ">


text:
Q: (Define a macro to) facilitate OpenGL command debugging? Sometimes it takes a long time of inserting conditional prints and checks to glGetError() to narrow down using a form of binary search where the first function call is that an error is first reported by OpenGL.
I think it would be cool if there is a way to build a macro which I can wrap around all GL calls which may fail which will conditionally call glGetError immediately after. When compiling for a special target I can have it check glGetError with a very high granularity, while compiling for typical release or debug this wouldn't get enabled (I'd check it only once a frame).
Does this make sense to do? Searching for this a bit I find a few people recommending calling glGetError after every non-draw gl-call which is basically the same thing I'm describing.
So in this case is there anything clever that I can do (context: I am using GLEW) to simplify the process of instrumenting my gl calls this way? It would be a significant amount of work at this point to convert my code to wrap a macro around each OpenGL function call. What would be great is if I can do something clever and get all of this going without manually determining which are the sections of code to instrument (though that also has potential advantages... but not really. I really don't care about performance by the time I'm debugging the source of an error).

A: Try this:
void CheckOpenGLError(const char* stmt, const char* fname, int line)
{
    GLenum err = glGetError();
    if (err != GL_NO_ERROR)
    {
        printf("OpenGL error %08x, at %s:%i - for %s\n", err, fname, line, stmt);
        abort();
    }
}

#ifdef _DEBUG
    #define GL_CHECK(stmt) do { \
            stmt; \
            CheckOpenGLError(#stmt, __FILE__, __LINE__); \
        } while (0)
#else
    #define GL_CHECK(stmt) stmt
#endif

Use it like this:
GL_CHECK( glBindTexture2D(GL_TEXTURE_2D, id) );

If OpenGL function returns variable, then remember to declare it outside of GL_CHECK:
const char* vendor;
GL_CHECK( vendor = glGetString(GL_VENDOR) );

This way you'll have debug checking if _DEBUG preprocessor symbol is defined, but in "Release" build you'll have just the raw OpenGL calls.

A: BuGLe sounds like it will do what you want:

*

*Dump a textual log of all GL calls made.

*Take a screenshot or capture a video.

*Call glGetError after each call to check for errors, and wrap glGetError so that this checking is transparent to your program.

*Capture and display statistics (such as frame rate)

*Force a wireframe mode

*Recover a backtrace from segmentation faults inside the driver, even if the driver is compiled without symbols.


text:
Q: Set the path of Google Binary on Webdriverio+Selenium How can I set the path of the Google Binary on the stack Webdriverio+Selenium+GoogleDriver? It expects the binary on /usr/bin/google-chrome but since I am using Heroku I cannot write the Google binary on that folder.

A: You can specify the binary path in your capabilities:
var client = require('webdriverio').remote({
    desiredCapabilities: {
        browserName: 'chrome',
        'goog:chromeOptions': {
            binary: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
        }
    }
})

A: You can include the chromedriver executable by providing the following argument when running the java server standalone:
-Dwebdriver.chrome.driver="C:\PATH-TO-CHROMEDRIVER\chromedriver.exe"


text:
Q: Is there a way to stop JQuery Mobile from Duplicating Events? I am attaching a click event to an image on my page.
$('.ui-block-b img').click(function(event) {}

I am using a jQuery mobile fixed footer.
I have tried to initialize this using both the pagecreate and pageinit event.
When I click on the links (being loaded with Ajax) in the footer and then come back to the page with the click handler the pagecreate and pageinit are being refired.  This is attaching another click event, so when I click on the image 2 events are being fired.
I am wondering is there a jquery Mobile event that address this?? Did i miss something in the documentation?
I have addressed this problem by checking if the event exists before attaching it but it seems like jQuery mobile should have something to that handles this? I have done
var events = $('.ui-block-b img').data('events');
if (typeof events == 'undefined') { // attach handler}

Perhaps jQuery mobile already addressed this issue and I'm just missing something?

A: You shouldn't load JS with a new page, as you know the issue you're having is that the JS is running everytime the page is created and each time it binds another click event.
The solution is to reference your elements with the native jQM pointer $.mobile.activePage which is available after the pageshow event fires. Or by putting a jQuery on listener at the root page div (not the document) in the pageinit event.
By using $('.ui-block-b img').click(function(event) {} you are potentially attaching a bind event to elements in more than one page (since jQuery appends pages to the DOM), which is what you're doing.
<script type="text/javascript">
   $("div:jqmData(role='page'):last").bind('pageinit', function(){
      //your code here - $.mobile.activePage not declared, but you can setup
      // "on" events here that handle elements ONLY on this page
      //e.g. $(this).on('click', 'img.ui-block-b', function(){});
      // this puts a live event listener that only listens for this page
   });

   $("div:jqmData(role='page'):last").bind('pageshow', function(){
      //your code here - $.mobile.activePage works now
   });
</script>

Now when you bind events you are ensuring you are only affecting the elements on the current page.

Organizing this is a bit of a pain so I have outlined a better solution I gave to another question here: Jquerymobile - $.mobile.changepage


text:
Q: DNAT generically? How would you setup iptables to generically send packets of some port say tcp port 80 to the correct machines (which are not all in the same subnet)?
For ex:
iptables -t nat -A PREROUTING -s 0.0.0.0//0 -p tcp -d $NATIP -j DNAT --to-destination $machineIP
iptables -t nat -A POSTROUTING -s $machineIP -p tcp -d 0.0.0.0//0 -j SNAT --to-source $NATIP
The above would send packets correctly to and from a single machine, but how would you do this for n machines. As I don't believe a generic destination such as 192.168.1.0/25 would work.
Do you somehow tag the packets so when they comeback you can send them to the correct IP?
Is this done with some other command?

A: Some considerations first. If you have 0.0.0.0/0 as source or destination, you don't have to specify it on your rule.
Now considering your question, if you have one NATIP for each machine, it's just a question of making one pair of rules for each machine. If you want to use the same NATIP to multiple machines you need something to differentiate, if not the port, then the source IP. Otherwise iptables, per se, can't choose where to send the package. (will get back to this matter)
To make the output NAT you can make one rule.for each machine, or create a table and set there all the IPs and subnets you wish to translate.
iptables -t nat -N addrTranslate
iptables -t nat -A OUTPUT -s x.x.x.x -j addrTranslate
iptables -t nat -A OUTPUT -s y.y.y.y/24 -j addrTranslate
iptables -t nat -A addrTranslate -j SNAT --to z.z.z.z

One alternative for multiple machine NAT with one single IP address is to setup a proxy with apache.


text:
Q: XC8 : Connot use defined variable I define a struct as following:
struct _connection_info_t{
char unique_name[5];
char ip[16];
char port[5];
}WIFI_connection_info_g[2],zz[3];

And use WIFI_connection_info_g[0] variable in "sprintf" function :
sprintf(buffer,"AT+CIPSTART=\"TCP\",\"%s\",%s",WIFI_connection_info_g[0].ip,WIFI_connection_info_g[0].port);

When i compile above code,the compiler generate following error :

wifi_tempalte.h:290: error: (1402) a pointer to eeprom cannot also point to other data types

But when i change "sprintf" function and use "zz" variable like following:
sprintf(buffer,"AT+CIPSTART=\"TCP\",\"%s\",%s",zz[0].ip,zz[0].port);

It compile successfully.
Note 1:
My target device is 16f1829
Note 2:
Compiler version is 1.30

A: Probably too big to declare in one go.
You may have to declare different instances of it in different C files.
xc8 can get confused. The compiler is targeting an 8 processor and it
tends to keep things
in the same page (256 RAM blocks) where it can. It can get confused though.


text:
Q: passing default theme in material UI5 can somebody explain how pass in the defauklt theme in Material UI5
in Material UI6   i use to do it like this
const useStyles = makeStyles((theme) => ({
  home: {
    display: "flex",
    paddingTop: "8rem",
    width: "100vw",
    height: "100vh",
    backgroundColor: theme.palette.primary.dark,
    color: "white",
  },
}));

but as i got throught M-UI5 docs (as far as i found)  there is no explanation on how it can be done  , the only part they mention about makeStyle it contains this code in this page docs
+import { makeStyles } from '@mui/styles';
+import { createTheme, ThemeProvider } from '@mui/material/styles';

+const theme = createTheme();
 const useStyles = makeStyles((theme) => ({
   background: theme.palette.primary.main,
 }));
 function Component() {
   const classes = useStyles();
   return <div className={classes.root} />
 }

 // In the root of your app
 function App(props) {
-  return <Component />;
+  return <ThemeProvider theme={theme}><Component {...props} /></ThemeProvider>;
 }

so am i suppose to run  createTheme() on every component to get the theme?  , apology if i missed out an obvious thing in the docs , probably coz my poor english

A: The part you are missing is from this part of the migration guide: https://mui.com/material-ui/guides/migration-v4/#style-library.

if you are using JSS style overrides for your components (for example overrides created by makeStyles), you will need to take care of the CSS injection order. To do so, you need to have the StyledEngineProvider with the injectFirst option at the top of your component tree.

Without this, the default styles for the MUI Card in your About component win over the styles specified via classes.about where the styles overlap (e.g. background).
Changing your AllProviders component to the following (just adding <StyledEngineProvider injectFirst>) fixes it:
import React from "react";
import CountriesProvider from "./countries-context";
import QuestionsProvider from "./questions-context";
import {
  ThemeProvider,
  createTheme,
  StyledEngineProvider
} from "@mui/material/styles";
const theme = createTheme();

const AllProviders = (props) => {
  return (
    <StyledEngineProvider injectFirst>
      <QuestionsProvider>
        <ThemeProvider theme={theme}>
          <CountriesProvider>{props.children}</CountriesProvider>
        </ThemeProvider>
      </QuestionsProvider>
    </StyledEngineProvider>
  );
};

export default AllProviders;

https://codesandbox.io/s/funny-flower-w9dzen?file=/src/store/AllProviders.js:303-342
The theme was being passed in fine without this change (otherwise you would have had errors when it tried to access parts of the theme), but the CSS injection order was not correct.


text:
Q: How to load a linked list from a text file? Greetings I've been working on a homework in which I must create a linked list program which can save and restore its data from a text file. I have gotten most of it working but I'm having some problems with restoring the linked list using the data from the text file that was created from it. When I restore it the last element is repeated twice. I believe it has something to do with the loop but as I'm not sure I'm including the whole scope of my assignment.
Below is the code I've written so far of the program:
ListNode.h
#pragma once
template<class T> class List;
template<class T>

class ListNode
{
 friend class List<T>;
public:
 ListNode(const T&);
 T getData()const;
private:
 T data;
 ListNode<T>*next;
};//end ListNode class

template<class T>
ListNode<T>::ListNode( const T &info):data(info), next(NULL)
{
}//end default constructor
template<class T>
T ListNode<T>::getData()const
{
 return data;
}//end function getData

List.h
#pragma once
#include<iostream>
#include <fstream>
using namespace :: std;
#include "ListNode.h"
template<class T>
class List
{
private:
 ListNode<T> *head;
 int size;
 ListNode<T> *find(int index) const;
public:
 List();
 List(const List<T> &aList);
 ~List();
 int getLength() const;
 void insert (int index, T tempData);
 void remove(int index);
 void retrieve(int index, T &tempData);
 bool isEmpty() const;
 void print() const;
 void save();
 void restore();
};//end List class

Broken function:
template <class T>
void List<T>::restore()
 {
     ifstream inFile;
     inFile.open("listFile.txt");

     T value=0;
     int index, check =0;

     cout << "Now reading the data from the text file..." << endl;
         //inFile >> value;
         //cout << "Value is : " << value << endl;

        while (inFile != NULL)
        {
            inFile >> value;
            index = getLength();
            cout << value << endl;
            insert(index+1, value);

            inFile.close();

        }

 } // end function restore

The linked list data that was saved to the text file during the test was :
35
45
55
65

When the linked list was restored from the text file this was the content of it:
35
45
55
65
65

How can I solve this problem?

A: It amazes me that your restore function works at all. But yes, it's repeating the last element. Try this instead:
while(inFile >> value)
  ...

EDIT:
All right, just try this much:
while(inFile >> value)
{
  cout << value << endl;
}

Does it display the values correctly?

A: I had this problem a while ago with one of my programs. It took me a while to figure out and I am not sure if it is the same problem, but check your input file one more time. If you leave an extra line after the last number, the compiler will return the last number twice.
example:
1
2
3
4
5
(extra line)
Just delete the extra line.

A: Which one is the head of your list? You can use a while loop or even an if statement to traverse through each node and load them all.


text:
Q: How to get the Tumblr ProfileName from user accesstoken I have unable to handle the Tumblr profile name after login for using ConsumerKey and ConsumerSecretKey.Here i have to want some Tumblr functionality like ,whenever i go to my IOS Application, in that i had to show all the share options like Facebook,Twitter,Email and Tumblr with using to Connect and Disconnect Buttons.While Connect to the Facebook i get the profile name and displayed into the FB Label and Twitter Label.
But here i have login into the Tumblr but i didn't get the Profile name or Blog name.
For using these code
- (void) signAndSendWithTokenKey:(NSString *)key andSecret:(NSString *)secret {
    [self signRequestWithClientIdentifier:tumblrConsumerKey secret:tumblrConsumerSecret tokenIdentifier:key secret:secret usingMethod:ASIOAuthHMAC_SHA1SignatureMethod2];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

Any Suggestions ...Thanks In Advanced

A: I'd suggest making an API request to api.tumblr.com/v2/user/info in order to get the Tumblr's Name.
EDIT: Here is a link to the appropriate Tumblr API reference: http://www.tumblr.com/docs/en/api/v2#user-methods


text:
Q: tar directory to send only modified blocks of files Deep and complex directory structure can be modified: files can be moved (prefix changed) and simultaneously content of the files can be changed partially.
I want to decrease an amount of data to transmit over network.
rsync works with chunks of data of 4k size (if I remember correctly).
Can I use some kind of concatenation (tar-like) preserving meta information about file system structure and attributes, which places the file's content starting from offsets of multiple 4k bytes for each next file to enable rsync algorithm advantages?
The problem I want to solve is omission of rsync: it unable to detect if file content changed and file is moved at the same time between synchronizations to use matching blocks of destination files to reduce data transfer.

A: Based on your suggestion in a comment (which should really be in your question), this seems to be what you want
cd /path/to/directory
tar cf /var/tmp/directory.tar .
rsync -azv /var/tmp/directory.tar remote:/var/tmp/directory.tar
ssh remote 'cd /path/to/destination && tar xf /var/tmp/directory.tar'

You need enough space to store directory.tar on both sides.

I've been asked whether this apparently trivial solution can work in the situation where a small amount, such as a single byte, is added (or removed) from the beginning of the tar file.
Hopefully this sample will illustrate how good rsync is at handling such situations. It works best if you have an equivalence (certificate key) login for the remote server so that no time is spent entering a password.
# Generate some data
dd iflag=fullblock bs=1M count=200 </dev/urandom >200M.dat

# See how long it takes to transfer
time rsync -av 200M.dat remote:

# See how long it takes to transfer "nothing"
time rsync -av 200M.dat remote:

# Generate one byte of data and prepend it to another data file
dd bs=1 count=1 </dev/urandom >1b.dat
cat 1b.dat 200M.dat >200M1b.dat

# Copy the new file across to the original target
time rsync -av 200M1b.dat remote:200M.dat

# Clean up
rm 1b.dat 200M.dat 200M1b.dat
ssh remote rm 200M.dat

If the algorithm can handle the single byte inserted at the beginning of the data stream the transfer should take but a few moments. If it can't you would expect the transfer time to be broadly similar to the first.

A: Here's another suggestion for you. The hrsync tool, which I've found on GitHub, appears to be pretty good at maintaining a memory of files when you rename them or move them between directories of a source tree.

*

*It can track moves and edits to files within the source tree

*It is a shell script and does not require administrative privileges to install on the source system, although putting it into /usr/local/bin does have advantages

*It requires both local and remote systems to have a filesystem capable of handling hard links

*It is not able to track changes to a file where that file is renamed and replaced (i.e. deleted and then recreated, rather than edited in place)

Example
hrsync /path/to/directory/ remote:/path/to/destination/

A: I found the solution using bash and command-line utilities only. It is possible to optimize the solution: sort files by size in ascending order and place as many small files as possible to every chunk (knapsack problem here =), but it would be overengineering):
pack.bash:
#! /usr/bin/env bash

set -e

[[ -d "$1" ]]
[[ -d "$( dirname '$2' )" ]]

BLOB="$2.blob"
FSIZES="$2.sizes"
OFFSET=0

shopt -s globstar
for f in "$1"/* "$1"/**/*
do
    if [[ -f "$f" ]]
    then
        SIZE=$( stat -c %s "$f" )
        echo "$SIZE" >> "$FSIZES"
        COUNT=$(( ($SIZE + 4096 - 1) / 4096 ))
        dd if="$f" of="$BLOB" bs=4096 seek=$OFFSET count=$COUNT conv=notrunc
        OFFSET=$(( $COUNT + $OFFSET ))
    fi
done

cp --recursive --archive --attributes-only "$1" "$2.dir"
XZ_OPT="-9e --threads=$(( $( nproc ) + 1 ))" tar cpJf "$2.tar.xz" -C "$2.dir" .
rm --recursive "$2.dir"

unpack.bash:
#! /usr/bin/env bash

set -e

BLOB="$2.blob"
FSIZES="$2.sizes"

[[ -f "$BLOB" ]]
[[ -f "$FSIZES" ]]

mkdir --parents "$1"
[[ ! "$( ls -A '$1' )" ]]

tar xpJf "$2.tar.xz" -C "$1"

SIZES=($( < "$FSIZES" ))

i=0
OFFSET=0
shopt -s globstar
for f in "$1"/* "$1"/**/*
do
    if [[ -f "$f" ]]
    then
        SIZE=${SIZES[i]}
        dd if="$BLOB" of="$f" bs=4096 skip=$OFFSET count=$SIZE iflag=count_bytes
        OFFSET=$(( $OFFSET + ($SIZE + 4096 - 1) / 4096 ))
        i=$(( $i + 1 ))
    fi
done


text:
Q: How do I create an array of the objects that are on the outside of a cluster? Hello dear programmer,
I am working on a little program (in C#) where some objects are clustered. The clusters can change shape in the program but I always want a line between (or even around) the outer objects (a little bit like a cell wall in biology). My approach is trying to get the coordinates of the outer objects in an array and draw a polygon between the coordinates. Can anyone give me a suggestion on how I can achieve this or show me an example of how it is done elsewhere?
Thanks for your help!
A


text:
Q: How can I create array from two other arrays? I have two arrays with same size.
Dim arr1() As String = {"Hello", "world", "I'm", "some", "text"}
Dim arr2() As String = {"Hello2", "world2", "I'm2", "some2", "text2"}

I need to create another *one array from these two arrays.
Edited:
Something like this.
Dim arr3(0) As String = {"Hello", "Hello2"}
Dim arr3(1) As String = {"world", "world2"}
Dim arr3(2) As String = {"I'm", "I'm2"}
Dim arr3(3) As String = {"some", "some2"}
Dim arr3(4) As String = {"text", "text2"}

A: You could also use Enumerable.Zip
Dim res = arr1.Zip(arr2, Function(a,b) {a,b})

A: You're looking for Zip:

Enumerable.Zip(Of TFirst, TSecond, TResult) Method
Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

Example:
Dim arr1() As String = {"Hello", "world", "I'm", "some", "text"}
Dim arr2() As String = {"Hello2", "world2", "I'm2", "some2", "text2"}

Dim arr3 = arr1.Zip(arr2, Function(a, b) {a, b}).ToArray()


text:
Q: appWidgetIds and best way to define multiple size (or resizable) widget I want to define multiple size widgets I have sees in other questions that a common practice is to define multiple receivers and providers, however in the onUpdate method I have noticed that there is an array named appWidgetIds eg
public void onUpdate(Context c, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        for (int i = 0; i < appWidgetIds.length; i++) {
.....
....
  }
}

so I'm wondering what is the purpose of this array and if could be used for define multiple size widget without create different providers and receivers.
Note that my different size widget use the same design with the difference that in smaller widgets some elements are missing, for this reason a way to avoid to define multiple providers that do almost the same things is welcome.

A: The array is in case they put multiple instances of the widget, so they can all be updated. Most of the time you call the same update code on all widget id's, but this allows you to pick different actions such as if your app has multiple accounts on it, they can have different widgets.
Sizes are specified with the receivers as described in older apis, while newer ones are capable of resizing.


text:
Q: Visual Basic Iterative enabling of Textbox's Si I'm working on an assignment where I have 10 RadioButtons indicating how many contesters I have, and depending on what I pick between 1 to 10, I need that many of my corresponding TextBoxes to be enabled so I could fill it with names!
Is there a way for me to make a For loop between 1 and the number I picked from the RadioButton and say something like
For i = 0 to Size
{
    TextBox&i.Enabled = True
}

Since my TextBoxs are called TextBox1 to TextBox10
I know you can add strings together using &, but how can I do that for an object name?
As of right now I literally have the dumbest way of doing it, which is a click event inside each RadioButton that manually enables the correct number of TextBoxes...
Thank you in advance!

A: You can iterate over all controls like this:
For Each ctr In Me.Controls
Dim indx As String = ctr.Name
If TypeOf (ctr) Is Textbox Then
 ' Now compare the name with TextBox&i and do smth
End If
Next

A: It's not possible to just concatenate a string and use it as an object variable reference like that, but you can search the form's controls by their name property (which is a string) and do it that way. Here's an example:
Private Sub EnableTextBoxes(ByVal Size As Integer)
    For i As Integer = 1 To Size
        Dim matches() As Control = Me.Controls.Find("Textbox" & i.ToString, True)
        If matches IsNot Nothing AndAlso matches.Length = 1 Then matches(0).Enabled = True
    Next
End Sub


text:
Q: How to handle the user logout in browser multiple tab? I am using codeigniter session to store user login. When user opens in multiple tab, on logout in one tab , I want the page to be auto refreshed while user visiting the other tab. Is this possible?

A: Just tested it out, and the easiest way I can see (which seems to work in Chrome at least, but may need further testing) is setting a cookie.
On logout do something like setcookie('loggedout',1). You'll also need to do the opposite on login - unset($_COOKIE['loggedout'])
Then you just need some simple Javascript...
function readCookie(name) {
    var nameEQ = escape(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}
window.setInterval(function() {
    if(readCookie('loggedout')==1) {
        window.location.assign('loggedout.html')
        //Or whatever else you want!
    }
},1000)

That'll check each second to see if the cookie is set. Magic.

A: Here is my below code to solve the issue. I set the cookie While login and deleted at logout. viceversa at Logout and Login also.
Script:
function readCookie(name) {
var nameEQ = escape(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}

function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}

window.setInterval(function() {
if(readCookie('loggedout')==1) {

    window.location.reload();

   setCookie('loggedout',2,3);
    //Or whatever else you want!
}
 else if(readCookie('loggedin')==1) {

    window.location.reload();

   setCookie('loggedin',2,3);
    //Or whatever else you want!
}
},2000)

Controller:
Login:
$this->load->helper('cookie');
    $cookie = array(
'name'   => 'loggedin',
'value'  => '1',
'expire' => '86500'
);
set_cookie($cookie);
$domain= preg_replace("/^[\w]{2,6}:\/\/([\w\d\.\-]+).*$/","$1", $this->config->slash_item('base_url'));
$path = explode($domain,base_url());
delete_cookie('loggedout');
    delete_cookie('loggedout',$domain, $path[1] );

Logout:
$cookie = array(
'name'   => 'loggedout',
'value'  => '1',
'expire' => '86500'
);
set_cookie($cookie);
$domain= preg_replace("/^[\w]{2,6}:\/\/([\w\d\.\-]+).*$/","$1", $this->config- >slash_item('base_url'));
$path = explode($domain,base_url());
delete_cookie('loggedin');

delete_cookie('loggedin','localhost', '/<!-- Your path -->/');

delete_cookie('loggedin',$domain, $path[1] );


text:
Q: Ubuntu can't find Scrapy I am using Ubuntu 14.04, and I have Python 3.4 and Python2.7 installed. I installed scrapy using
sudo pip install scrapy

and if I try to rerun this, the terminal outputs :
Requirement already satisfied (use --upgrade to upgrade): scrapy in /usr/local/lib/python2.7/dist-packages

But when I try to start a new project, I get this :
$ scrapy startproject tutorial
bash: /usr/local/bin/scrapy: No file or directory of this type

How should I change the path to Scrapy ?
Thanks a lot !

A: First find where scrapy is installed
whereis scrapy

Then add that path to environment variable PATH
lets say its /usr/bin
export PATH=$PATH:/usr/bin

Then you can call scrapy from anywhere.

A: I know my answer is too late. I faced this issue today and resolved it so I am adding answer so that it might help someone in future.
It happened because I installed scrapy as local user and not root. When you install it as user with pip install scrapy --user the scrapy script is not copied to /usr/bin. So in order to get it working you need to install it in one of the two ways:

*

*Install as as root by using sudo pip install scrapy

*Save this script somewhere in your home folder and run it whenever you ant to run scrapy(I have a ~/.scripts folder added to $PATH in which I store my scripts or just make an alias for the script )

#!/usr/bin/python

# -*- coding: utf-8 -*-
import re
import sys
from scrapy.cmdline import execute
if __name__ == '__main__':
  sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
  sys.exit(execute())

A: The program installs into /usr/bin


text:
Q: RecyclerView crea un registro fantasma al eliminar Tengo un problema al eliminar un elemento de mi RecyclerView (el cual está enlazado a una base de datos SQLite). Después de eliminar correctamente el dato tanto de la base de datos como de la vista, se muestra la animación de eliminado, pero después aparece un nuevo elemento al final, también con una bonita animación.
Al comprobar la base de datos veo que el registro en cuestión sí que está eliminado.
Podría solucionar esto instanciando un adaptador nuevo cada vez que elimino un registro, pero entonces la animación no se muestra.
Código:
Método del Adapter:
public void removeItem(int position){
    db = new DBAdapter(context);
    db.open();
    mCursorAdapter.getCursor().moveToPosition(position);
    int idnota = mCursorAdapter.getCursor().getInt(0);
    db.borra_nota(idnota); //it deletes the row (delete_note)
    db.close();
}

Main Activity:
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

    //if (direction == ItemTouchHelper.LEFT) {

    listAdapter.removeItem(position);
    listAdapter.notifyItemRangeChanged(position, listAdapter.getItemCount());
    listAdapter.notifyItemRemoved(position);

La solución cutre (sin animación) pasaba a ser algo así:
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

    int position = viewHolder.getAdapterPosition();
    sticky = (RecyclerView) findViewById(R.id.lista_notas);
    linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    sticky.setLayoutManager(linearLayoutManager);

    listAdapter = new ListAdapter(MainActivity.this);
    sticky.setAdapter(listAdapter);

En cuyo caso, pasaría los removeItem y demás dentro del Adapter.
¿Alguna solución para que al borrarse el registro, la animación se muestre correctamente y además no cree un registro fantasma al final?

A: Vale, solucionado...
El problema residía en que estaba eliminando de todos sitios menos del CursorAdapter en sí.
El método del ListAdapter queda ahora así, funcionando correctamente:
    public void removeItem(int position){
        db = new DBAdapter(context);
        db.open();
        mCursorAdapter.getCursor().moveToPosition(position);
        int idnota = mCursorAdapter.getCursor().getInt(0);
        db.borra_nota(idnota); //it deletes the row (delete_note)

        items = db.consulta_todos(); //select all from db again
        mCursorAdapter.changeCursor(items);
    }

Saludos, espero que sea útil a quien se haya topado con mi problema.


text:
Q: how do i reduce a 17000 page document to less pages by reducing font? I have a big pdf. I tried to convert word then changed the font size of the entire document but it leaves giant spaces in between the pages, I tried to make it continuous but I cannot figure it out. please help thanks.

A: If your only goal is to reduce the number of pages you can group them like 2 pages in 1 or so. I mean:
---------------
|  ---   ---  |
|  |1|   |2|  |
|  ---   ---  |
---------------

That would make it 17k/2 = 8500 pages, but you could go with 4 per page and get 4250 pages.
Maybe this works for you? If not, can you clarify what you mean by

leaves giant spaces in between the pages

Does it show like text reduced on top of each page with big blank on the bottom?
Or does it leave a bunch of blank pages?

A: Converted documents are always a pain to edit in Word. How bad it is depends on the original content and conversion process, but it is never straightforward. Conversion gives you something that looks good but may have all sorts of formatting anomalies.
Try the following in a copy of your document.

*

*Replace ^m with ^p.

*Replace ^b with ^p.

This is drastic. It removes all manual page breaks and all section breaks. It may leave you with substantial work.
I would advise going through and using styles to format your document. Start by formatting everything in the normal style. Then go to your headings and apply the relevant heading styles.

A: I have had this problem when doing a mail merge (not a pdf, I realize, but still had lots of blank space!) The data source I was merging into the document called for over a hundred pages of mail merge-ready template, and I only had 2 pages of template. Every time the template "started over" there would be about 3/4 of a page of blank space. Backspacing did not get rid of it. Showing the paragraph marks did not help. I found clicking right after the last word before the odd space started and then clicking "delete" on my keyboard fixed the problem. I hope this is helpful!


text:
Q: Is it not possible to store function as JSON key value in .json file in angular 5 We have an Angular 5 project in which we have a .json file which we're loading in a .ts file using XMLHttpRequest.
The .json file have the following content:
{
    stringKey: "stringValue",
    functionKey: function() {
        console.log('function called!')
    }
}

It throws the error: [json] value expected

If I open Chrome Devtool and set the above object as value - it works fine but not in the project

var obj = {
  stringKey: "stringValue",
  functionKey: function() {
    console.log('function called!')
  }
}

obj.functionKey();

Edit:
Is there a work around for storing functions in pure JSON?

A: You can't put a function inside a json file because it is a data format language,
but you can do it in a js file with a JS Object like you did:
var obj = {
  functionKey: function() {
    console.log('function called!')
  }
}
obj.functionKey();

A: There is no function data type in JSON.
See the documentation. JSON supports objects, arrays, strings, numbers, booleans and null.
It is a data format, not a programming language. It doesn't make much sense for it to support functions.

A: var obj = {
  stringKey: "stringValue",
  functionKey: function() {
    console.log('function called!')
  }
}

obj.functionKey();

Here you are just creating an Object obj not JSON.
Just try to convert this Object to JSON using JSON.stringify(obj) it will remove the functionKey as its not a string.

A: See if that helps (functionKey needs to be a string, you would then use eval to get result)
var obj =  {
stringKey : "stringValue",
functionKey: "(function() { console.log('function called')})()"
}

var result = eval(obj.functionKey);

https://jsfiddle.net/spdr80c7/


text:
Q: Trigonometric limit I couldn't find this limit , can someone help me?
$$\lim_{x \to \infty} \frac{\arctan(x+1) - \arctan(x)}{\sin\left(\frac{1}{x+1}\right) - \sin\left( \frac 1x\right)}$$

A: Use identities:
$$
\sin\theta -\sin\varphi=2\sin\left(\theta-\varphi\over2\right)\cos\left(\theta+\varphi\over2\right)\\
\arctan x-\arctan y=\arctan\left(x-y\over1+xy\right)
$$
Then,
$$
\lim_{x \to \infty} \frac{\arctan(x+1) - \arctan(x)}{\sin\left(\frac{1}{x+1}\right) - \sin\left( \frac 1x\right)}=
\lim_{x \to \infty} \frac{\arctan\left(\frac{1}{1+x(x+1)}\right)}{2\sin\left(\frac{1}{x+1}-\frac{1}{x}\over2\right)\cos\left( \frac{1}{x+1}+\frac{1}{x}\over2\right)}\to\\
\lim_{x \to \infty}\frac{\arctan\left(\frac{1}{1+x+x^2}\right)}{2\sin\left(-\frac{1}{2x(x+1)}\right)\cos\left(\frac{2x+1}{2x(x+1)}\right)}\to-\frac{1}{2}\lim_{x \to \infty}\frac{\arctan\left(\frac{1}{1+x+x^2}\right)}{\sin\left(\frac{1}{2x(x+1)}\right)}
$$
Now, use corollaries from the first remarkable limit:
$$
-\frac{1}{2}\lim_{x \to \infty}\frac{\arctan\left(\frac{1}{1+x+x^2}\right)}{\frac{1}{1+x+x^2}}\frac{\frac{1}{2x(x+1)}}{\sin\left(\frac{1}{2x(x+1)}\right)}\frac{\frac{1}{1+x+x^2}}{\frac{1}{2x(x+1)}}\to
-\frac{1}{2}\lim_{x \to \infty}\frac{\frac{1}{1+x+x^2}}{\frac{1}{2x(x+1)}}\to\\
-\frac{2}{2}\lim_{x \to \infty}\frac{x+x^2}{1+x+x^2}=-1
$$
Which implies:
$$
\lim_{x \to \infty} \frac{\arctan(x+1) - \arctan(x)}{\sin\left(\frac{1}{x+1}\right) - \sin\left( \frac 1x\right)}=-1
$$

A: Note that
$$\arctan(x+1)- \arctan(x) = \int_x^{x+1} \frac{dt}{1+t^2}.$$
A lower bound for this integral is $1/(1+(1+x)^2)\cdot 1,$ an upper bound is $1/(1+x^2)\cdot 1.$ We also have
$$\sin(1/x) - \sin (1/(x+1)) = \int_{1/(x+1)}^{1/x} \cos t\, dt.$$
Here a lower bound for the integral is $\cos (1/x)\cdot (1/x- 1/(x+1)),$ an upper bound is $\cos (1/(x+1))\cdot (1/x- 1/(x+1)).$ Noting $1/x- 1/(x+1) = 1/(x(1+x)),$ we can put all this together to see
$$\frac{1/(1+(x+1)^2)}{\cos (1/(x+1))(1/x(1+x))} \le \frac{\arctan(x+1)- \arctan(x)}{\sin(1/x) - \sin (1/(x+1))} \le \frac{1/(1+x^2)}{\cos (1/x)(1/x(1+x))}.$$
Both bounding functions $\to 1,$ hence so does the middle expression. Since I switched the sign of the denominator at the beginning (because it was easier for me to think about), the desired limit is $-1.$

A: Hint. By using Taylor series expansions, as $u \to 0$, one has
$$
\begin{align}
\arctan u&=u-\frac{u^3}{3}+o(u^3)
\\\sin u&=u-\frac{u^3}{6}+o(u^3)
\end{align}
$$ giving, as $x \to \infty$ $\big($with $u=\frac1{x}$ or $u=\frac1{x+1}$$\big)$,
$$
\begin{align}
\arctan x&=\frac{\pi}2-\arctan \frac1x =\frac{\pi}2-\frac1x+O\left(\frac1{x^3} \right)
\\\arctan (x+1)&=\frac{\pi}2-\arctan \frac1{x+1} =\frac{\pi}2-\frac1x+\frac1{x^2} +O\left(\frac1{x^3} \right)
\\\sin \frac1x&=\frac1x+O\left(\frac1{x^3} \right)
\\\sin \frac1{x+1}&=\frac1x-\frac1{x^2} +O\left(\frac1{x^3} \right)
\end{align}
$$ then, as $x \to \infty$,

$$
\frac{\arctan(x+1) - \arctan(x)}{\sin\left(\frac{1}{x+1}\right) - \sin\left( \frac 1x\right)}=\frac{\frac1{x^2}+O\left(\frac1{x^3} \right)}{-\frac1{x^2}+O\left(\frac1{x^3} \right)} \to -1.
$$


text:
Q: How-to kill my app without killing the service it sarted (debugging) My android application starts a service when runned for the first time. That service handles network connection.
If the device is out of free space, my application can be killed, but the service will remain alive (except on certain extreme case, I know.). When the app will be restarted, it will need to restore it state according to the service state (no problem for that).
Here's my question: How can I kill my application, but not the associated service ? That's only for debugging purpose, I would like to test if the state is correctly restored.
When I try to kill the app with adb, ddms or advanced task killer, the service is killed too.
Any ideas ?
Thanks,
Code: I start my service like that:
final Intent intent = new Intent(this, Service.class);
mStartServiceResult = startService(intent);
mIsBound = bindService(intent, mConnection, 0);

and use startForeground / setForeground to prevent my service to be killed.

A:
If the device is out of free space, my application can be killed, but the service will remain alive (except on certain extreme case, I know.).

No. Some or all of your activities might be destroyed, which would leave the service running. Or your process may be terminated, in which case your service will also shut down.

How can I kill my application, but not the associated service ?

That is not possible, sorry.


text:
Q: Script Sends me to search.html? instead of the desired website Alright, so basically, index.html contains a search bar that doesn't do what it's supposed to- when enter is pressed, it should take me to google.com/(gsecode)q=(what i typed), but instead it sends me to index.html? instead of that I want it to use a JQuery Script to trigger a button click. I have looked for solutions but they don't seem to work.
HTML:
<input type="text" id="text-box" size="size">
<input type="submit" id="submit" onclick="(javascriptcode)" name="Google Search">

JQuery:
document.getElementById("id_of_button").onclick = function() {clickFunction()};

function clickFunction() {
  document.location.href = 'https://cse.google.com/cse?cx=009002930969338329916:kta6o_isob0&q=' +
  escape(document.getElementById('search-box').value)
}

$("text-box").keyup(function(event){
  if(event.keyCode === 13){
      $("#submit").click();
  }
});

A: The first problem is that your IDs was different in the Javascript and HTML.
The second point is that in the keyup function you didn't use the "#" in the selector. If you want to select the element by ID, you need to use the "#" char and the name. If you want to select using class name you need to use "." instead of "#".
And I rewrite your code using only jQuery. I.E.: document.getElementById is the native way in JavaScript to select an element, and I replace to use jQuery selector.
Try this:

$(document).ready(function () {

  $("#submit").click(function () {

    var url = 'https://cse.google.com/cse?cx=009002930969338329916:kta6o_isob0&q=' +
           escape($('#text-box').val());

    document.location.href = url;
  });

  $("#text-box").keyup(function(event){
      if(event.keyCode === 13){
         $("#submit").click();
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="text-box" size="size">
<input type="submit" id="submit" value="Google Search">

A: I'm not sure if your code is just a loose example or final product, but you have a lot of things wrong here.  I'm just going to post an example that works instead, and you can follow that.
Your ids are not properly named or matching to your jquery selectors.  You have an onclick event that isn't needed
Heres the fiddle!
$(document).on('click', '#myButtonId', function() {
    clickFunction();
});

function clickFunction() {
    alert('normally this would run your document location href, but were in jsfiddle so...');
      document.location.href = 'https://cse.google.com/cse?cx=009002930969338329916:kta6o_isob0&q=' +
  escape($('#mySearchBoxId').val());
}

$('#mySearchBoxId').keyup(function(event){
      if(event.keyCode === 13){
      $("#myButtonId").click();
  }
});

and
<input type="text" id="mySearchBoxId" size="30">
<input type="submit" id="myButtonId" value="Google Search">


text:
Q: Free Floating, Customized, Toolbox for PowerPoint 2010 and above in order to be faster while creating slides in PowerPoint (PP) 2010 or above
I want to create a toolbox. This toolbox - that I want to be able to move around within the PP-Window as needed, from left to right, from top to bottom - will have about 30 icons. Each icon will have one function. Most fuctions are typical PP-Functions such as "Align shapes right" etc. Put some will be self programmed functions for which I will create an icon.
Here is my question: How do I best realize the toolbox (not a ribbon that only stays at the top!)? Is there a given functionality in PP 2010 or above to do so? Or what is the best way? As a newbie I don't have a clou what I'm searching for.
And second question: In a long run this toolbox - or at least the custom functions in it - should be loaded at PP start-up from a server for easier maintanance if used by many clients. what is the best way/procedure/architecture to do so?
Many many thanks.

A:

How do I best realize the toolbox

As a UserForm.  And when you .Show the user form, show it modelessly, which means it'll stay visible until you close it but won't block other operations.

In a long run this toolbox - or at least the custom functions in it - should be loaded at PP start-up from a server for easier maintanance if used by many clients. what is the best way/procedure/architecture to do so?

The best way to do this is not to do it.  PowerPoint will bite you.  Instead, consider creating the toolbox as a PPT add-in, installing it on each PC, then if need be, have the user's logon script check for a newer version of the add-in on the server, copy it to the local computer if so.


text:
Q: How to reset the default settings store path in Visual Studio 2017? With importing and exporting settings I've somehow changed the default save location for the settings in VS 2017 - they're landing on my Desktop. Also a settings reset did not help.
I want it do be the default path again. Any ideas are welcome. Btw. it's VS 2017 Enterprise with all latest updates.
Thanks.

A: I've found it by myself.
The filename and path can be changed under "Options" -> "Environment" -> "Import and Export Settings". And the default path and filename is: c:\users\USERNAME\documents\visual studio 2017\settings\CurrentSettings.vssettings.

A: When you say 'default save location', is it the location you're prompted to save when you create a solution first?
If so, go to Tools > Options > Projects and Solutions > General, and you can change those locations there.


text:
Q: Setup vsftpd server so that I can access the web root Probably getting fed up with the amount I have posted today lol.
I am trying to find a tutorial which will show me how to correctly install and setup vsftpd on centos 5.5... This is probably one of the most simplist of tasks, however I am still a newbie and just trying to setup a server on our local network which will act as an intranet.
I have everything else installed and working... Anonymous ftp works and I can get to the /var/www/html/ directory, however I just can't seem to get user accounts to work.
*** CuteFTP 8.3 - build Aug 25 2008 ***

STATUS:>    [06/08/2010 15:04:49] Getting listing ""...
STATUS:>    [06/08/2010 15:04:49] Connecting to FTP server... 192.168.1.136:21 (ip = 192.168.1.136)...
STATUS:>    [06/08/2010 15:04:49] Socket connected. Waiting for welcome message...
        [06/08/2010 15:04:49] 220 (vsFTPd 2.0.5)
STATUS:>    [06/08/2010 15:04:49] Connected. Authenticating...
COMMAND:>   [06/08/2010 15:04:49] USER j0nR
        [06/08/2010 15:04:49] 331 Please specify the password.
COMMAND:>   [06/08/2010 15:04:49] PASS *****
        [06/08/2010 15:04:52] 530 Login incorrect.
ERROR:>     [06/08/2010 15:04:52] Not logged in.
STATUS:>    [06/08/2010 15:04:54] Connection closed.

I am about ready to smack my head on the table!
I am not sure I have even setup the ftp users correctly, any further information you require please do let me know but you will have to talk to me like the newbie that I am.
Thanks in advance, and happy friday :)

EDIT
listen=YES
anonymous_enable=NO
#anon_root=/var/www/html/
#anon_upload_enable=YES
#anon_mkdir_write_enable=YES
local_enable=YES
virtual_use_local_privs=YES
write_enable=YES
connect_from_port_20=YES
secure_chroot_dir=/var/run/vsftpd
pam_service_name=vsftpd
guest_enable=YES
user_sub_token=$USER
local_root=/var/www/html/$USER
chroot_local_user=YES
hide_ids=YES
tcp_wrappers=YES
userlist_enable=YES
userlist_deny=NO

That is my vsftpd.conf file.

A: It would probably be more useful to paste your vsftpd config, but check the following:

*

*The username is allowed to login to FTP. If the username is in /etc/vsftpd/user_list then you need to ensure that, in /etc/vsftpd/vsftpd.conf, userlist_enable=YES and userlist_deny=NO. If the username is not present then you need to make sure that, if userlist_enable=YES then userlist_deny=NO or is not present.

*Check the shell and home directory in the passwd file. Type vipw and check that the shell is not /bin/false (change it to /sbin/nologin if it is) - I'm not sure why this is an issue
but I've seen it cause problems before. Next, set the home directory to wherever you want the user to login to. Not essential, but more secure.

*Ensure that the user has access to the directory. Do su j0nR - and then try to cd into their home directory. If it works, it's probably a password issue. Type passwd j0nR and set it to what you think it should be.
Good luck.

A: Check /etc/shells to ensure that the shell your user account is set to is included there.  If it isn't, the account can't use ftp, period.  Usually I specify /bin/false for ftp-permitted non-interactive-shell users, and /sbin/nologin for users which I don't want to have a shell OR ftp access.
If you have userlist_enable=yes, then you need a userlist_file=/etc/ftpusers (or some other file).  Add the users you want to permit access to that file (unless you have userlist_deny=yes as well, in which case users will be permitted if they are not in that file).

A: edit
/etc/vsftpd/vsftpd.conf

and check if chroot_local_user=YES is there..if it's not there , add it..it makes sure that they user that we are gonna create will be able to access only the directory assigned to him . and also local_enable=YES
adding user
useradd -d /path/to/your/directory jonraw

this will add a  user called jonraw.
then set password
passwd jonraw

there are many more things to take care of  like changing permissions of the directory , disabling ssh login for the user etc..
you can read more options about vsftpd in the below url.
 http://vsftpd.beasts.org/vsftpd_conf.html


text:
Q: Checking for Nonetype in Numpy arrays Python I am getting 2 different errors when I run the code below, which are motioned below. I am trying to return a Nonetype or a numpy array from the func(value) function. it is required to use a.any() or a.all() whilst testing empty numpy arrays but it gives an error when A is None since a.any() or a.all() is not a valid function for Nonetype. how could i make the code below work?
import numpy as np

def func(value):
    if value == 1:
        A= np.array([12,3,4,55,6,12,3])
    else:
        A= None
    return A

for n in range(2):
    output = func(n)
    if output != None:
        print("None type")
    else:
        print("None")

Error when if if output != None
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Error when if if output.any() != None
AttributeError: 'NoneType' object has no attribute 'any'


text:
Q: What return type annotation to use if a function returns a module in Python? I'm writing a function to help with an optional dependency (similar to pytest.importorskip) and I'd like to type it, but unsure what type to use. Since I'm always returning a specific module or None, I think I can be more specific than "Any".
def try_import_pyarrow():
    try:
        import pyarrow
    except ImportError:
        pyarrow = None
    return pyarrow

A: The type of a module is accessible as types.ModuleType.