text:
Q: UPDATE FROM in SQL with matching key How can I UPDATE FROM in SQL? I want to copy the FamilyID from my FamilyGuardian table:
dbo.FamilyGuardian
PupilID   FamilyID    GuardianID
---------------------------------
1         100002      555
2         100003      556
3         100004      557
4         100005      558
5         100006      559
6         100007      1146
7         100008      561
8         100009      562
9         100010      563
10        100011      564

Into the Guardians table where GuardianID is equal.
dbo.Guardians
GuardianID  Name        FamilyID
---------------------------------
555         Smith       NULL
556         Patel       NULL
557         Andrews     NULL
558         Brown       NULL
559         Abdul       NULL

dbo.Guardians after INSERT FROM
GuardianID  Name        FamilyID
--------------------------------
555         Smith       100002
556         Patel       100003
557         Andrews     100004
558         Brown       100005
559         Abdul       100006

A: you have to use an UPDATE query
UPDATE T1
SET T1.FamiltyID = T2.FamilyID
FROM dbo.Guardians AS T1 INNER JOIN dbo.FamilyGuardian AS T2
ON T1.GuardianID = T2.GuardianID

A: There is no such thing as INSERT FROM - you're looking for UPDATE, not INSERT:
Update  G
Set     FamilyId = F.FamilyId
From    FamilyGuardian  F
Join    Guardian        G   On  G.GuardianId = F.GuardianId

A: You might use an updateable CTE for this
WITH UpdateableCTE AS
(
    SELECT g.FamilyID
          ,fg.FamilyID AS newValue
    FROM dbo.Guardians AS g
    INNER JOIN dbo.FamilyGuardian AS fg ON g.GuardianID=fg.GuardianID
)
UPDATE UpdateableCTE SET FamilyID=newValue;

But you must be aware, that this design is - uhm - weak...
What would happen if one Guard is responsible for more than one family? What happens, if the information on one side changes, but the other side does not change?
I think, this should not get into a physically defined column at all. This should be taken with a JOIN whenever you read this data.

A: you mean an UPDATE, not an INSERT, right?
In that case you should use an structue like:
UPDATE dbo.Guardians
SET FamilyID = (SELECT DISTINCT FamilyID FROM dbo.FamilyGuardian fg WHERE fg.GuardianID  = GuardianID )

Notice that the DISTINCT is only necessary when there are more than 1 familyId per guardianId.


text: Q: Why do we use field resolvers in graphql? So I have been following Ben Awad's 14 hr GraphQL and React series and I came across field resolvers and I have been a little confused about their use-case. I understand that field resolvers can be used to modify a certain data in the server. In this particular case, he uses it to slice the text of huge user posts, so in this context I am guessing that fetching large chunks of data is time consuming as the data grows, so field resolvers can be used to modify appropriate data to optimise the server. Am i right? Because this makes sense to me and this is how i understand it. Is there more to what they offer or is this it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sequential pattern mining on single sequence Can someone give me a hint about a good approach to find a frequent patterns in a single sequence.
For example there is the single sequence
3 6 1 2 7 3 8 9 7 2 2 0 2 7 2 8 4 8 9 7 2 4 1 0 3 2 7 2 0 3 8 9 7 2 0

I am looking for a method that can detect frequent patterns in this ordered sequence:
3 6 1 [2 7] 3 [8 9 7 2] 2 0 [2 7] 2 8 4 [8 9 7 2] 4 1 0 3 [2 7] 2 0 3 [8 9 7 2] 0

Also other information would be interesting like:

*

*What is the probability that 7 comes after 2

*When each number has a timestamp assigned to it, what is the estimated time interval that 7 occurs after 2

The sequential pattern mining methods I found require multiple sequences, but I have one large sequence where I want to detect regularities.
Thanks for any help!

A: Calculate a histogram of N-grams and threshold at an appropriate level. In Python:
from scipy.stats import itemfreq
s = '36127389722027284897241032720389720'
N = 2 # bi-grams
grams = [s[i:i+N] for i in xrange(len(s)-N)]
print itemfreq(grams)

The N-gram calculation (lines three and four) are from this answer.
The example output is
[['02' '1']
 ['03' '2']
 ['10' '1']
 ['12' '1']
 ['20' '2']
 ['22' '1']
 ['24' '1']
 ['27' '3']
 ['28' '1']
 ['32' '1']
 ['36' '1']
 ['38' '2']
 ['41' '1']
 ['48' '1']
 ['61' '1']
 ['72' '5']
 ['73' '1']
 ['84' '1']
 ['89' '3']
 ['97' '3']]

So 72 is the most frequent two-digit subsequence in your example, occurring a total of five times. You can run the code for all $N$ you are interested about.

A: I think you can use the Apriori algorithm. Count the number each single element occurs in the sequence. If the count is greater than some threshold $\varepsilon$ then the item is frequent. Then count the number of pairs of frequent items. Continue with the number of frequent $4$-tuples, etc.

A: You could use something like the following. As far as I know SPADE uses something similar too for multiple sequences.
36127389722027284897241032720389720

First you need to gather the positions of every item in your sequence.
length: 1
{
    0: [11,23,28,34], //4
    1: [2,22], //2
    2: [3,9,10,12,14,20,25,27,33], //9
    3: [0,5,24,29], //4
    4: [16,21], //2
    5: [], //0
    6: [1], //1
    7: [4,8,13,19,26,32], //6
    8: [6,15,17,30], //4
    9: [7,18,31] //3
}

Then check the support of these items against the minimum support you choose for frequent sequences.
min_sup: 3
{
    0: [11,23,28,34], //4
    2: [3,9,10,12,14,20,25,27,33], //9
    3: [0,5,24,29], //4
    7: [4,8,13,19,26,32], //6
    8: [6,15,17,30], //4
    9: [7,18,31] //3
}

In your case you need to find the items with consecutive positions. You can use wildcards too, but in that case the position difference will be more than 1 and you will find a lot more candidates.
length: 2
{
    00: [], //0
    02: [[11,12]], //1
    03: [[23,24],[28,29]], //2
    07: [], //0
    08: [], //0
    09: [], //0
    20: [[33,34]], //1
    22: [[9,10]], //1
    23: [], //0
    27: [[3,4],[12,13],[25,26]], //3
    28: [], //0
    29: [], //0
    30: [], //0
    32: [[24,25]], //1
    33: [], //0
    37: [], //0
    38: [[5,6],[29,30]], //2
    39: [], //0
    70: [], //0
    72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5
    73: [[4,5]], //1
    77: [], //0
    78: [], //0
    79: [], //0
    80: [], //0
    82: [], //0
    83: [], //0
    87: [], //0
    88: [], //0
    89: [[6,7],[17,18],[30,31]], //3
    90: [], //0
    92: [], //0
    93: [], //0
    97: [[7,8],[18,19],[31,32]], //3
    98: [], //0
    99: [] //0
}

min_sup: 3
{
    27: [[3,4],[12,13],[25,26]], //3
    72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5
    89: [[6,7],[17,18],[30,31]], //3
    97: [[7,8],[18,19],[31,32]], //3
}

You can try to combine the upper sequences based on the ending, or you can just check the positions.
length: 3
{
    272: [[12,13,14],[25,26,27]], //2
    727: [], //0
    897: [[6,7,8],[17,18,19],[30,31,32]], //3
    972: [[7,8,9],[18,19,20],[31,32,33]] //3
}

min_sup: 3
{
    897: [[6,7,8],[17,18,19],[30,31,32]], //3
    972: [[7,8,9],[18,19,20],[31,32,33]] //3
}

length: 4
{
    8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3
}

min_sup: 3
{
    8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3
}

There is only one pattern and you cannot combine it with itself, so the mining is complete.
{
    27: [[3,4],[12,13],[25,26]], //3
    72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5
    89: [[6,7],[17,18],[30,31]], //3
    97: [[7,8],[18,19],[31,32]], //3
    897: [[6,7,8],[17,18,19],[30,31,32]], //3
    972: [[7,8,9],[18,19,20],[31,32,33]] //3
    8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3
}

If we exclude the sub-patterns of 8972.
{
    27: [[3,4],[12,13],[25,26]], //3
    72: [[13,14],[26,27]], //2
    8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3
}

min_sup: 3
{
    27: [[3,4],[12,13],[25,26]], //3
    8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3
}

I think it is the same as the patterns you have found.
361[27]3[8972]20[27]284[8972]4103[27]203[8972]0

Another option to keep the 72 too, because it occurs 3 times as a sub-sequence of 8972 and 2 other times independently from 8972. I think this should depend on whether you allow overlapping.
361[27]3[89(72)]202(72)84[89(72)]4103[2(7]2)03[89(72)]0

Note: I don't think sequential pattern mining is considered machine learning.

A: When it comes to a single sequence, episode mining fits the need.
When you want to know the probability of one element following another, sequential association analysis, such as lag-sequential analysis (Bakeman & Gottman, 1997: Observing interaction: An introduction to sequential analysis) serves the need.


text:
Q: Upload pdf file I want to upload Pdf file into my application
So I have ViewModel (I post only relevant code)
public class SubcategoryViewModel
{
    public HttpPostedFileBase PdfFile { get; set; }
    [DisplayName("PDF")]
    public string Pdf { get; set; }
}

Controller:
 public async Task<string> CreateSubcategory(SubcategoryViewModel model)
    {
              string pdf = null;
            if (model.Pdf != null)
            {
                pdf = Guid.NewGuid().ToString().Substring(0, 13) + "_" + model.File.FileName;
                model.Pdf = pdf;
                var path =    Path.Combine(HttpContext.Current.Server.MapPath("~/Content/pdf"), pdf);
                model.File.SaveAs(path);
            }

            var subcategory = new Subcategory
            {
                Pdf = pdf,
            };
            db.SubcategoriesList.Add(subcategory);
            await db.SaveChangesAsync();

View:
@model Models.ViewModels.SubcategoryViewModel
@using (Html.BeginForm("Create", "Subcategory", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

        @Html.LabelFor(model => model.Pdf, new { @class = "control-label col-md-2" })

            <input type="file" id="file" name="file" />

When I action post I don´t received nothing into model.Pdf, so into   if (model.Pdf != null) validation it comes null, and I don´t know why
Anyone have idea why it occurs? Thankyou in advance!

A: You have 2 main issues. First the name of your file input is name="file", but that does not match the property in your model. It needs to be
<input type="file" name="PdfFile" />

Second, you never generate an input for property string Pdf so in the POST method, it will always be null and therefore the code inside your if (model.Pdf != null) will never be executed. However, what you really want is to save the file if its not null, so the code needs to be
public async Task<string> CreateSubcategory(SubcategoryViewModel model)
{
   string fileName = null;
   if (model.PdfFile != null && model.PdfFile .ContentLength > 0)
   {
       fileName = Guid.NewGuid().ToString().Substring(0, 13) + "_" + model.PdfFile.FileName;
       string path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/pdf"), fileName);
       model.PdfFile.SaveAs(path);
    }
    var subcategory = new Subcategory
    {
        Pdf = fileName ,
    };
    db.SubcategoriesList.Add(subcategory);
    await db.SaveChangesAsync();

Side note: I would also recommend an additional property in your model for the files display name (i.e. the value of model.PdfFile.FileName) so that you can use that in your view rather than displaying the name prefixed with a Guid which would have little meaning to the user. Refer this answer for an example.

A: I think your problem is you are getting null value in PdfFile property of your model. This is because you have not given name attribute of file upload control same as you property. change name attribute of your file upload control to PdfFile.
<input type="file" id="file" name="PdfFile" />


text:
Q: Android / HTTP GET not reading REST API properly The content that is present in the URL

http://sspapi-dev.samsungrs.com/health

is
[{"dspName":"openrtb","status":[{"type":"BIDREQ","state":"UP","avgTime":37},{"type":"VIEWTRACK","state":"UP","avgTime":10}]}]

but when I am reading the URL from my Android application, the output is
    <title>MSG: Please wait while you are redirected</title>    <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">    <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">    <META HTTP-EQUIV="EXPIRES"CONTENT="0">  <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
Please wait while you are redirected to the login page

Please tell me what I am doing wrong.
Here is my code.
MainActivity.java
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity implements AsyncResponse {

    TextView t1;
    final String website = "http://sspapi-dev.samsungrs.com/health";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        t1 = findViewById(R.id.textview1);

        Viewdata v1 = new Viewdata();
        v1.delegate = this;
        v1.execute(website);
    }

    @Override
    public void processFinish(String output) {
        t1.setText(output);
    }
}

class Viewdata extends Urltask{
    public AsyncResponse delegate = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String dataModels) {
        super.onPostExecute(dataModels);

        delegate.processFinish(dataModels);
    }
}

JSONhelper.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JSONhelper{

    HttpURLConnection connection;
    String data;

    public String getdatafromurl(String url){
        String result = new String();
        try{
            URL url1 = new URL(url);

            connection = (HttpURLConnection) url1.openConnection();
            connection.connect();
            InputStream inputStream = connection.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            StringBuffer buffer = new StringBuffer();

            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }

            result = buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

AsyncResponse.java
public interface AsyncResponse {
    void processFinish(String output);
}

Urltask.java
import android.os.AsyncTask;

abstract class Urltask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {

        JSONhelper jsonhelper = new JSONhelper();
        String data = jsonhelper.getdatafromurl(params[0]);

        return data;
    }
}

By the way, it seems that the DefaultHttpClient package and its corresponding functions have been deprecated in API 22 (Android Lollipop) and removed from API 23 (Android Marshmallow). Making use of AsyncTask seems to be one of the alternative methods to it. But are there any other alternative methods that are available to it, that are closely related to the way of old DefaultHttpClient package and its corresponding functions themselves?

A: package com.example.sample;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadContent();
    }

    public static String GET(OkHttpClient client, String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    @SuppressLint("StaticFieldLeak")
    private void loadContent() {
        new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... params) {
                OkHttpClient client = new OkHttpClient();
                String response = "";
                try {
                    response = GET(client, "http://sspapi-dev.samsungrs.com/health");
                    //Parse the response string here

                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Log.e("Response", s);
            }
        }.execute();
    }
}

E/Response:
  [{"dspName":"openrtb","status":[{"type":"BIDREQ","state":"UP","avgTime":37},{"type":"VIEWTRACK","state":"UP","avgTime":10}]}]

add this depandancies in gradle
compile 'com.squareup.okhttp3:okhttp:3.12.0'


text:
Q: Latest Tapjoy adapter not compiling in Android I'm implementing Admob's mediation and I'm struggling to add the latest version of Tapjoy's adapter. The thing is, if I declare version 12.7.1.0 (old version), it works, but warns me there's a new version:

But if I change it to the latest version 12.8.0.0, it doesn't give any error while syncing. But it just doesn't launch the app with an error:

A: It is fixed by adding this to gradle repositories:
allprojects {
    repositories {
        ...
        maven {
            url "https://sdk.tapjoy.com/"
        }
    }
}

With only mavenCentral it seems to not throw any error but for version 12.8.0.0 or superior, tapjoy's maven repo is specifically needed


text:
Q: Find all possible pairs of digits $(a,b)$ such that the six-digit number $5a4bb2$ is divisible by $9$
Find all possible pairs of digits $(a,b)$ such that the six-digit number $5a4bb2$ is divisible by $9$

I tried to answer this question, but when I answered $(1,3)$, $(3,2)$, $(5,1)$, I got a 3/6 on the question. Can you kind people help me?

Okay so some of you guys helped me. Thank you. Now I have $(1,3)$, $(3,2)$, $(5,1)$, $(7,0)$, and $(0,8)$. I want to give my thanks to lulu and ty.

A: Use the fact that, in base $10,$ a number is divisible by $9$ if and only if the sum of its digits is divisible by $9.$ So our biconditional criterion is $$9+a+2b+2\equiv 0\pmod{9}$$ which is equivalent to $$a\equiv 7-2b\pmod{9}.$$ Substituting in $b=0,1,2,\ldots, 8$ yields the solutions:
$$(7,0),(5,1),(3,2),(1,3),(8,4),(6,5),(4,6),(2,7),(0,8).$$ But this is modulo $9,$ so we can also interchange $0$ and $9$ which yields the additional solutions $(7,9),(9,8).$ None of the other digits can be swapped with any other digits of base $10$ so this is the complete list of solutions.

A: If the sum of the digits of a number is divisible by $9$, the number is divisible by $n$. Formally speaking, if $n$ is a $d$ digit number in base $10$:
$$n=\sum_{k=0}^{d-1}{x_k \times 10^{k}}$$
Then $$\sum_{k=0}^{d-1}{x_k} \mod 9 = 0 \implies n \mod 9 =0$$
So then we need $5+a+4+b+b+2 = 11+a+2b \mod 9 = 0$ Thus
$$a+2b \mod 9 = 7$$
So $a+2b=7$ or $a+2b=16$ or $a+2b=25$ These are constrained Diophantine equations. Let's find all solutions for $(a,b)$. They are
$$(7,0);(5,1);(3,2);(1,3);(0,8);(2,7);(4,6);(6,5);(8,4);(7,9);(9,8)$$

A: divisibility test for 9 gives $$11+a+2b=9n$$ where $n \in N$
On rearranging , $b=\dfrac{9n-11-a}{2}$
Since, there's $2$ in denominator, numerator should be even.
Let's start with maximum value of $a$ , i.e. $a=9$
$$b=\dfrac{9n-20}{2} $$
$n$ will be even (why?)it can't be $2$,
and $$9n-20<20 \\ \implies n \le 4$$ (or else $b \text{ will be}>10$) , which infact, is the only possible value . Thus, $b=8$
If you choose $a=8$
$$b=\dfrac{9n-19}{2} \ $$  this time n will be odd (why?)
Similarly, you can work out all the cases, and each possible value of $a$ gives atmost 2 values of $b$ (that I know because I checked all possible values)
$(a, b)=(9,8), (8,4), (7,0), (7,9), (6,5), (5,1), (4,6), (3,2), (2,7), (1,3), (0,8)$


text:
Q: iText - Strange column- / page changing behaviour with ColumnText I am quite new to iText and trying to accomplish the following:

*

*read a list of text files from local hd

*arrange the texts of the files in a 2-column layout pdf file

*add a consecutively numbered index before each text

I started with the MovieColumns1 example (http://itextpdf.com/examples/iia.php?id=64) and ended up with the following code:
    final float[][] COLUMNS_COORDS = { { 36, 36, 296, 806 }, { 299, 36, 559, 806 } };

    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document, resultFile);
    document.open();

    ColumnText ct = new ColumnText(writer.getDirectContent());
    ct.setSimpleColumn(COLUMNS_COORDS[0][0], COLUMNS_COORDS[0][1],
        COLUMNS_COORDS[0][2], COLUMNS_COORDS[0][3]);

    File textDir = new File("c:/Users/raddatz/Desktop/123/texts/");
    File[] files = textDir.listFiles();

    int i = 1;
    int column = 0;
    for (File file : files) {
        String text = FileUtils.readFileToString(file, "UTF-8");
        float yLine = ct.getYLine();
        System.out.println("adding '" + file.getName() + "'");

        PdfPCell theText = new PdfPCell(new Phrase(text, new Font(Font.HELVETICA, 10)));
        theText.setBorder(Rectangle.NO_BORDER);
        theText.setPaddingBottom(10);
        PdfPCell runningNumber = new PdfPCell(new Phrase(new DecimalFormat("00").format(i++), new Font(
            Font.HELVETICA, 14, Font.BOLDITALIC,
            new Color(0.7f, 0.7f, 0.7f))));
        runningNumber.setBorder(Rectangle.NO_BORDER);
        runningNumber.setPaddingBottom(10);
        PdfPTable table = new PdfPTable(2);
        table.setWidths(new int[] { 12, 100 });
        table.addCell(runningNumber);
        table.addCell(theText);
        ct.addElement(table);
        int status = ct.go(true);
        if (ColumnText.hasMoreText(status)) {
            column = Math.abs(column - 1);
            if (column == 0) {
                document.newPage();
                System.out.println("inserting new page with size :" + document.getPageSize());
            }
            ct.setSimpleColumn(
                COLUMNS_COORDS[column][0], COLUMNS_COORDS[column][1],
                COLUMNS_COORDS[column][2], COLUMNS_COORDS[column][3]);
            yLine = COLUMNS_COORDS[column][3];
            System.out.println("correcting yLine to: " + yLine);
        } else {
            ct.addElement(table);
        }
        ct.setYLine(yLine);
        System.out.println("before adding: " + ct.getYLine());
        status = ct.go(false);
        System.out.println("after adding: " + ct.getYLine());
        System.out.println("--------------------------------");
    }

    document.close();

Here you can see the result:
http://d.pr/f/NEmx
Looking at the first page of the resulting PDF I assumed everything was working out fine.
But on second page you can see the problem(s):

*

*text #31 is not displayed completely (first line + index is cut / not in visible area)

*text #46 is not displayed completely (first three lines + index is cut / not in visible area)

On page 3 everything seems to be ok again. I am really lost here.
-- UPDATE (2013-03-14) --
I have analyzed the contents of the PDF now. The problem is not that content is show in non-visible areas but that the content is not present in the pdf at all. The missing part of the content is exactly the one which would have fit in the previous column / page. So it seems like ColumnText.go(true) is manipulating the object passed by addElement() before. Can someone confirm this? If so: what can I do about it?
-- end UPDATE (2013-03-14) --
Looking forward to your reply
regards,
sven

A: Solved! As soon as ColumnText indicates a table will not fit the current column I reinitialize ct with a new instance of ColumnText and add the table again.
In other words:
Each instance of ColumnText is exactly dealing one column of my document.
if (ColumnText.hasMoreText(status) || mediaPoolSwitch) {
  column = Math.abs(column - 1);
  if (mediaPoolSwitch) {
      currentMediaPool = mediapool;
      column = 0;
  }
  if (column == 0) {
      document.newPage();
      writeTitle(writer.getDirectContent(), mediapool.getName());
  }
  ct = new ColumnText(writer.getDirectContent());
  ct.addElement(table);
  ct.setSimpleColumn(
      COLUMNS_COORDS[column][0], COLUMNS_COORDS[column][1],
      COLUMNS_COORDS[column][2], COLUMNS_COORDS[column][3]);
  yLine = COLUMNS_COORDS[column][3];
  LOG.debug("correcting yLine to: " + yLine);
} else {
  ct.addElement(table);
}
ct.setYLine(yLine);
ct.go();


text:
Q: Integrating Associated Legendre Polynomials As part of a derivation for the question I asked here in Physics stackexchange, I am trying to calculate the following integral, but I am not sure how to proceed:
$\int_0^{2\pi}P_l^m(\cos\theta)P_{l-1}^m(\cos\theta) d\theta$,
where $P_l^m(\cos\theta)$ are the Associated Legendre Polynomials.
I believe that the answer is ultimately 0, but I am not quite sure of how reduce this integrable to a workable form, I have tried using recursion relations but have had no luck. I am sure that I am not trying to solve the integrand with an additional $\sin(\theta)$ factor, which would be easily solved using the change of variable $z = \cos(\theta)$ and applying the orthogonality of the Associated Legendre Polynomials. Does anyone have any advice?
Thanks.

A: We wish to evaluate:
$$\int_0^{2\pi} P_l^m(\cos\theta)P_{l-1}^m(\cos\theta)\,\text{d}\theta $$
We use the transformation:
$$x = \cos\theta\quad \frac{dx}{d\theta} = -\sin\theta \quad d\theta = \frac{-1}{\sqrt{1-x^2}}dx$$ to obtain$$\int_1^1 \frac{-P_l^m(x)P_{l-1}^m(x)}{\sqrt{1-x^2}}dx = 0$$
Since you're integrating from 1 to 1.
Weird? Yes I thought so too.  Seeing as the integral comes from spherical harmoics, I assume you are messing up your limits of integration (should be from $0$ to $\pi$, since that is how the zenith angle is normally defined).
Then, I think you should be working with:
$$\int_0^{\pi} P_l^m(\cos\theta)P_{l-1}^m(\cos\theta)\,\text{d}\theta $$
which after the transformation becomes:
$$I = \int_{-1}^1 \frac{P_l^m(x)P_{l-1}^m(x)}{\sqrt{1-x^2}}dx$$
The Legendre Polynomials satisfy the relationship:
$$P_l^m(-x) = (-1)^{l+m}P_l^m(x)$$
This means that if $l+m$ is even (odd), the Legendre Polynomial is also even (odd).  Here we have the two numbers:
$l+m$ and $l+m-1$  One of these two has to be even and the other odd.  So one of the polynomials is even and the other is odd. Since $\frac{1}{\sqrt{1-x^2}}$ is even, the integrand as a whole is odd.  Thus the integral is also zero.
$$I = 0$$
Reference for parity relationship.


text:
Q: Put multiple pragma directives into one preprocessor define I need to push/pop several gcc diagnostics in my code. If that was needed in a single file I would do the following:
#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wformat"
#pragma GCC diagnostic error "-Wuninitialized"

...some code...

#pragma GCC diagnostic push

But I need this in multiple locations. So I want to have a #define or something similar. I thought about the following but c preprocessor does not allow #pragmas in #define.
#define PushWarnings \
    #pragma GCC diagnostic push \
    #pragma GCC diagnostic error "-Wformat" \
    #pragma GCC diagnostic error "-Wuninitialized"

Is there a way of achieving this?

A: Yes, there is a way to do this. C99 introduced the _Pragma operator (also available in C++ since C++11).
A pragma such as
#pragma GCC diagnostic error "-Wformat"

can also be written as
_Pragma("GCC diagnostic error \"-Wformat\"")

The latter is not a # preprocessor directive, so it can be generated from macros:
#define PushWarnings \
    _Pragma("GCC diagnostic push") \
    _Pragma("GCC diagnostic error \"-Wformat\"") \
    _Pragma("GCC diagnostic error \"-Wuninitialized\"")


text:
Q: Drag and drop on HTML5 with Selenium I would like to know what is the script that I should driver.executeScript with Selenium to be able to drag and drop an element on html5 ?
I have a html5 page where I want drag and drop an element, for now I am  running this, but still not working:
JavascriptExecutor js = (JavascriptExecutor)driver;

js.executeAsyncScript("(function ($) {
$.fn.simulateDragDrop = function (options) {
    return this.each(function () {
        new $.simulateDragDrop(this, options);
    });
};
$.simulateDragDrop = function (elem, options) {
    this.options = options;
    this.simulateEvent(elem, options);
};
$.extend($.simulateDragDrop.prototype, {
    simulateEvent: function (elem, options) {
        /Simulating drag start/
        var type = 'dragstart';
        var event = this.createEvent(type);
        this.dispatchEvent(elem, type, event);

        /Simulating drop/
        type = 'drop';
        var dropEvent = this.createEvent(type, {});
        dropEvent.dataTransfer = event.dataTransfer;
        this.dispatchEvent($(options.dropTarget)[0], type, dropEvent);

        /Simulating drag end/
        type = 'dragend';
        var dragEndEvent = this.createEvent(type, {});
        dragEndEvent.dataTransfer = event.dataTransfer;
        this.dispatchEvent(elem, type, dragEndEvent);
    },
    createEvent: function (type) {
        var event = document.createEvent("CustomEvent");
        event.initCustomEvent(type, true, true, null);
        event.dataTransfer = {
            data: {
            },
            setData: function (type, val) {
                this.data[type] = val;
            },
            getData: function (type) {
                return this.data[type];
            }
        };
        return event;
    },
    dispatchEvent: function (elem, type, event) {
        if (elem.dispatchEvent) {
            elem.dispatchEvent(event);
        } else if (elem.fireEvent) {
            elem.fireEvent("on" + type, event);
        }
    }
});
})(jQuery);");

After this I

A: I had to run one script before this to make it work:
js.executeAsyncScript("(function(jqueryUrl, callback) {
if (typeof jqueryUrl != 'string') {
    jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
}
if (typeof jQuery == 'undefined') {
    var script = document.createElement('script');
    var head = document.getElementsByTagName('head')[0];
    var done = false;
    script.onload = script.onreadystatechange = (function() {
        if (!done && (!this.readyState || this.readyState == 'loaded'
                || this.readyState == 'complete')) {
            done = true;
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
            callback();
        }
    });
    script.src = jqueryUrl;
    head.appendChild(script);
}
else {
    callback();
}
})(arguments[0], arguments[arguments.length - 1]);
");

A: Try Using below code for doing so :
public static  void dragAndDropViaJQueryHelper(WebDriver driver, String dragSourceJQuerySelector, String dropTargetJQuerySelector) {
        String jqueryScript = "(function( jquery ) {\r\n" +
                "        jquery.fn.simulateDragDrop = function(options) {\r\n" +
                "                return this.each(function() {\r\n" +
                "                        new jquery.simulateDragDrop(this, options);\r\n" +
                "                });\r\n" +
                "        };\r\n" +
                "        jquery.simulateDragDrop = function(elem, options) {\r\n" +
                "                this.options = options;\r\n" +
                "                this.simulateEvent(elem, options);\r\n" +
                "        };\r\n" +
                "        jquery.extend(jquery.simulateDragDrop.prototype, {\r\n" +
                "                simulateEvent: function(elem, options) {\r\n" +
                "                        /*Simulating drag start*/\r\n" +
                "                        var type = 'dragstart';\r\n" +
                "                        var event = this.createEvent(type);\r\n" +
                "                        this.dispatchEvent(elem, type, event);\r\n" +
                "\r\n" +
                "                        /*Simulating drop*/\r\n" +
                "                        type = 'drop';\r\n" +
                "                        var dropEvent = this.createEvent(type, {});\r\n" +
                "                        dropEvent.dataTransfer = event.dataTransfer;\r\n" +
                "                        this.dispatchEvent(jquery(options.dropTarget)[0], type, dropEvent);\r\n" +
                "\r\n" +
                "                        /*Simulating drag end*/\r\n" +
                "                        type = 'dragend';\r\n" +
                "                        var dragEndEvent = this.createEvent(type, {});\r\n" +
                "                        dragEndEvent.dataTransfer = event.dataTransfer;\r\n" +
                "                        this.dispatchEvent(elem, type, dragEndEvent);\r\n" +
                "                },\r\n" +
                "                createEvent: function(type) {\r\n" +
                "                        var event = document.createEvent(\"CustomEvent\");\r\n" +
                "                        event.initCustomEvent(type, true, true, null);\r\n" +
                "                        event.dataTransfer = {\r\n" +
                "                                data: {\r\n" +
                "                                },\r\n" +
                "                                setData: function(type, val){\r\n" +
                "                                        this.data[type] = val;\r\n" +
                "                                },\r\n" +
                "                                getData: function(type){\r\n" +
                "                                        return this.data[type];\r\n" +
                "                                }\r\n" +
                "                        };\r\n" +
                "                        return event;\r\n" +
                "                },\r\n" +
                "                dispatchEvent: function(elem, type, event) {\r\n" +
                "                        if(elem.dispatchEvent) {\r\n" +
                "                                elem.dispatchEvent(event);\r\n" +
                "                        }else if( elem.fireEvent ) {\r\n" +
                "                                elem.fireEvent(\"on\"+type, event);\r\n" +
                "                        }\r\n" +
                "                }\r\n" +
                "        });\r\n" +
                "})(jQuery);";
        ((JavascriptExecutor) driver).executeScript(jqueryScript);
        String dragAndDropScript = "jQuery('" + dragSourceJQuerySelector + "').simulateDragDrop({ dropTarget: '" + dropTargetJQuerySelector + "'});";
        ((JavascriptExecutor) driver).executeScript(dragAndDropScript);
    }

Just pass your css or xpath selectors as parameters in method.
Hope that helps you.

A: This only works if you add these attributes to the Source and destination elements :
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].setAttribute('ondragstart','dragstart(event)')", source);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].setAttribute('ondrop','drop(event)')", dest);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].setAttribute('ondragover','dragend(event)')", dest);


text:
Q: Java GUI runs executable + Jar Packaging I am developing a GUI using swing that runs an executable. Currently the executable is being used via Runtime.getRuntime().exec().
I have both the executable and the source code. If I compile my GUI into a jar the executable will not be included into as it currently stands, correct?
I would like the whole thing to run as a single file, is it better then to use the source code or can I package it all as one jar when I'm done some how?
Though I'm writing all the code by hand I do have WindowBuilder for eclipse, I haven't really explored it thoroughly, is there anything in there that might help?
EDIT: Sorry, to clarify: The GUI I want to build uses an executable called src2srcml to take a source file (C, C++, Java) and convert it to an XML File. src2srcml is a separate executable I got from this website: http://www.sdml.info/projects/srcml/
I want to embed this executable into my GUI so that when I compile my GUI into a JAR it contains src2srcml inside it so that I don't need to send a client both my GUI and src2srcml separately.

A: If you include the executable within the Jar, the executable will not be runnable by the OS.
With that in mind, you have a number of choices...
You Could...
Design a build process that compiles and packages the jar file, takes that and the executable and copies it into an appropriate directory structure for distribution...possible even building installers...
This will mean that you can still access the executable at runtime by using a relative path
This does mean you will have at least two files you will need to distribute, but the over all process is relatively painless...
You Could...
Include the executable within the jar file.  At runtime, you would need to extract the executable to the filesystem and execute it.
This means that you will have at least one file you will need to distribute, but it complicates the development process as you will need to find the resources (executable) at run time and extract it to some location before you can execute it
You Could...
Just build an installer for your application.  Something like like izPack for example, or what ever installer you want to use.
This means that you can distribute a single file to the client, but when installed, it will unpack all the files into the installation location and you won't need to care...

A: I'm not sure if I understood your question, but if you want to export you application into jar file and you want it to include all dependecies just have a look at this SO question: How to create a jar with external libraries included in Eclipse?


text:
Q: How to display Zip Code or Postal Code using MapBox iOS SDK My goal is to display Zip Codes or Postal Codes using Mapbox's iOS SDK for USA only postal codes;
I am currently able to display the boundaries for Zip Codes and the international postal/zip code, for example "USP227518" when I actually want to display "27518"
I've tried using mapboxMap.queryRenderedFeatures() and was able to successfully display a modified string value as desired, however this doesn't solve my problem because I need to display the long zipcode with the prefix 'USP2' in order for it to find the Feature and display a map annotation without the prefix. This causes a visual overlap
I also tried 'mapboxMap.querySourceFeatures()' and was unable to retrieve any data at all from any of my sources
Here is the code I use to display the zip codes as given by MapBox
try mapboxMapView.mapboxMap.style.updateLayer(withId: MapConstants.symbolLayerIdentifier, type: SymbolLayer.self) { layer in

    layer.textField = .expression(Expression(.number) {
        Exp(.get) { "id" }
        zipCodes // Array of strings all with 'USP2' prefix
        Exp(.get) { "id" }
        ""
    })
}

Is there some way to drop the prefixes or to query the source features for zip code points from the source points_postal_2?
I also have no idea where Exp(.get) { "id" } comes from. My best guess is it comes from here https://docs.mapbox.com/data/boundaries/reference/feature-lookup-tables/ . unit_code from that doc didn't work for me in place of "id" even when I removed the 'USP2' prefix from the zipCodes string array values
How do I display the zip codes on a map?


text:
Q: How to avoid duplication of events in Android Calendar? I get a list of events (of a week) from server through an API call and my app needs to sync them to calendar in device. The events can be updated or deleted on server without any intercations from app. And I need to sync them to calendar on every refresh of screen.
To make my events on calendar up to date with my server, I'm performing following actions on refresh:

*

*Deleting all the events of a given week from calendar.

*Then inserting the events that I get from the server.
public static void deleteAllEventsInWeekOfCalendar(Activity activity, int calId, long weekStartTimeMillis, long weekEndTimeMillis) {
    try {
    Uri eventUri = Uri.parse("content://com.android.calendar/events");
    String[] projection = new String[]{Events._ID, Events.TITLE, Events.DTSTART, Events.DESCRIPTION};
    String whereClause = Events.CALENDAR_ID + "=" + calId +
            " AND " + Events.DTSTART + " >= " + weekStartTimeMillis +
            " AND " + Events.DTSTART + " <= " + weekEndTimeMillis +
            " AND " + Events.DESCRIPTION + " LIKE '% Added by MyApp'";

    Cursor cursor = activity.getContentResolver().query(eventUri, projection, whereClause, null, Events.DTSTART);
    if (cursor != null && cursor.moveToFirst()) {
        Log.v("HowMany", cursor.getCount() + " matching events Found");
        int numOfDeleted = 0;
        do {
            try {
                String event_id = cursor.getString(cursor.getColumnIndexOrThrow(projection[0]));
                int numOfRowsDeleted = activity.getContentResolver().delete(ContentUris.withAppendedId(eventUri, Long.parseLong(event_id)), null, null);
                if (numOfRowsDeleted == 1) {
                    ++numOfDeleted;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } while (cursor.moveToNext());
        cursor.close();
        Log.v("HowMany", numOfDeleted + " deleted");
    }
} catch (Exception e) {
    e.printStackTrace();
}
}

And here is my code to insert all events to calendar:
 public static void doAddCalendarEvent(MyEvent myEvent, Activity activity, int calendarId) {
    try {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        String desc = myEvent.getDesc();
        desc += "\n\n Added by MyApp";

        ContentResolver cr = activity.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(Events.DTSTART, myEvent.getEventStartTime());
        values.put(Events.DTEND, myEvent.getEventEndTime());
        values.put(Events.TITLE, myEvent.getTitle());
        values.put(Events.DESCRIPTION, desc);
        values.put(Events.CALENDAR_ID, calendarId);
        values.put(Events.EVENT_LOCATION, myEvent.getLocation());
        values.put(Events.STATUS, Events.STATUS_CONFIRMED);
        values.put(Events.AVAILABILITY, Events.AVAILABILITY_BUSY);
        if (hasAlarm) {
            values.put(Events.HAS_ALARM, true);
        }
        values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
        long eventId = 0;
        Uri uri = cr.insert(Events.CONTENT_URI, values);
        if (uri != null) {
            eventId = Long.parseLong(uri.getLastPathSegment());
            Log.v(TAG, "INSERTED EVENT ID=>" + eventId + "--->" + startDate);
        }
        if (hasAlarm) {
            setReminder(cr, reminderValue, eventId);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Issue : Sometimes The events are duplicating on calendar. How do I avoid the duplication? Where Am'I going wrong? Please suggest.

A: I am assuming that you are using a Sync Adapter to interface with the Calendar.
The Sync Adapter has two important methods:
onPerformSync(...), and
onSyncCanceled(...)
onPerformSync is called whenever you make a ContentResolver.requestSync call or if automatic sync is set to true.
While executing, onPerformSync can be interrupted by Android. This can happen if the device is running low on resources of if your app is not in the foreground anymore.
When interupted, the Sync Adapter will stop execution where it's at and will call onSyncCanceled. The default behavior of the Sync Adapter is to retry the failed sync messages the first chance it gets. So if your app manages to grab onto OS resources again, it will replay the interrupted sync message.
It is possible that some of your messages are being fully processed and, just before onPerformSync is about to complete, the Sync Adapter is interrupted. At this point you managed to save the event, however, the Sync Adapter believes that the sync failed, and therefore will replay the same message again the next time it tries to sync.
I am not sure if you are syncing one event at a time so I can't offer a definitive solution. However, what you can do is change the default behaviour of the Sync Adapter to stop it from replaying "failed" messages.
Bundle extras = new Bundle();
...
extras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true);
CalendarConstants.AUTHORITY, true);
ContentResolver.requestSync(mAccount, CalendarConstants.AUTHORITY, extras);
In OnSyncCanceled, you can do some light checks to make sure the message succeeded, i.e. is present in the calendar's events table. If not, then manually replay it. If it is present, the SyncAdapter will simply move on to the next message, and you won't get any duplicates.
Alternatively, you could make sure all operations within onPerformSync are atomic.


text:
Q: Extract data from website as separate fields I am trying to use excel to scrap some information from a website.
This is what shows on source:

    1
    Acrobatic Maneuver
    Instant
    2W
    Common
    Winona Nelson
     Kaladesh

So I want to get everything that has even, and extract the data between the
However, all I've found until now is this code
Sub getcards()
    Dim IE As Object
    Dim i As Long
    Dim objCollection As Object

    ' Create InternetExplorer Object
    Set IE = CreateObject("InternetExplorer.Application")

    ' You can uncoment Next line To see form results
    IE.Visible = False

    ' URL to get data from
    IE.Navigate "http://magiccards.info/query?q=%2B%2Be%3Akld/en&v=list&s=issue"

    ' Statusbar
    Application.StatusBar = "Loading, Please wait..."

    ' Wait while IE loading...
    Do While IE.Busy
        DoEvents
        Application.Wait DateAdd("s", 1, Now)
    Loop
    On Error GoTo abort
    Application.StatusBar = "Searching for value. Please wait..."
    Dim dd As String
    Set objCollection = IE.document.getElementsByClassName("even")
    For i = 0 To objCollection.Length

    dd = IE.document.getElementsByClassName("even")(i).innerText

    MsgBox dd
    Next i
abort:
    ' Show IE
    IE.Visible = True
    IE.Quit

    ' Clean up
    Set IE = Nothing

    Application.StatusBar = ""
End Sub

It works in such a way that it extracts the data, but the output is 1Acrobatic ManeuverInstant2WCommonWinona Nelson Kaladesh all together.
How can I do so it understands each  as a separate field, so I can extract it easily?

A: When you're looping through i within objCollection you're actually looping through all elements with the ClassName of "even" as opposed to the elements inside the specific element you want.
Try this:
For i = 0 To objCollection.Length - 1
    For c = 0 to IE.document.getElementsByClassName("even")(i).getElementsByTagName("td").Length - 1
        dd = IE.document.getElementsByClassName("even")(i).getElementsByTagName("td")(c).innerText
        MsgBox dd
    Next c
Next i


text:
Q: Error 424 when passing Range parameter I am new to VBA, and I am having an error with this very simple code:
Sub sub1()
    Dim myCell As Range
    Set myCell = Sheet1.Cells(2, 2)
    sub2 (myCell)      '<<<<------- Error 424
End Sub

Sub sub2(x As Range)
    'not doing anything yet
End Sub

I am receiving Error 424 when invoking the sub2 from sub1. In my mind, this should work, since myCell is a Range... any idea?

A: Ty removing either removing the brackets, or adding a Call ie:
Sub Opt1()
    Dim myCell As Range
    Set myCell = Sheet1.Cells(2, 2)
    sub2 myCell
End Sub

Sub sub2(x As Range)
MsgBox x.Address
End Sub

or
Sub Opt2()
    Dim myCell As Range
    Set myCell = Sheet1.Cells(2, 2)
    Call sub2(myCell)
End Sub

Sub sub2(x As Range)
MsgBox x.Address
End Sub


text:
Q: UISearchController not dismissed when View is pushed I know this is a long write-up, but it's just one issue I promise.
The Setup
I'm getting some very strange behavior with a UISearchController. Let me describe the hierarchy, then I'll explain step by step what happens in my video:
The first view you see is a regular ViewController, with a tableView and the UISearchController as completely separate entities. The UISearchController has its own searchResultsController that I set when I create it:
let searchResultsController = MyResultsControllerClass()
searchController = UISearchController(searchResultsController: searchResultsController)

That's the basic setup.
The Behavior
A link to a video of the behavior
The MyResultsControllerClass has a tableView, as well as a pointer back to the master view controller all these views are housed in.  When the searchController's searchBar begins searching, you see that tableView show up. Then I tap a result, Programming Club. The MyResultsControllerClass uses the pointer to the master view to push a new view controller (just details about that event) like so:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let activityDetail = ActivityDetailViewController(nibName: nil, bundle: nil, activity: searchResults[indexPath.row])
    parentController?.navigationController?.pushViewController(activityDetail, animated: true)
}

You can see this happen behind the searchBar, but the searchController is not "covered up" by the presented view! This is my issue. As you can see, I can still interact with it. When I press "Cancel", it finally disappears.
What I've tried
Now, I thought this might have to do with the fact that a UISearchController is in fact a UIViewController, if I understand correctly. So I attempted pushing from the UISearchController, nothing happens. I tried embedding the UISearchController in its own UINavigationController and pushing from searchController.navigationController, nothing happens. I can completely cancel the editing before pushing, but I want the editing to still exist when they navigate back.
What am I doing wrong? Is there a better way to do this?

A: I have the same exact issue, I have solved it by setting:
self.definesPresentationContext = YES;

on the view controller that presents the UISearchController. This is recommended by Apple in WWDC session 228, read about it here: http://asciiwwdc.com/2014/sessions/228.


text:
Q: Cannot start rails server I tried to rails server

= Could not find rake-12.0.0 in any of the sources
    Run bundle install to install missing gems.

I tried to bundle update/ install
It goes to the error msg below .

A: Try changing your Gemfile line from source 'https://rubygems.org' to source 'http://rubygems.org'

A: Follow this step:

*

*gem install rack

*Run bundle update rake for updating your Gemfile.lock file.

*Delete the Gemfile.lock and again bundle install.

A: Try following commands:
gem update --system

bundle install


text:
Q: For Loop Issues I am using Python Version 3.2.  Have the following code:
for row2 in reader2:
    for row1 in reader1:
        if row1['identification_column'] == row2['identification_column']:
            row2['updated_col'] = row1['updated_col']
    writer.writerow(row2)

reader1 is a csv.DictReader object that looks like the following:
    identification_column,type

    1, bike
    2, guitar
    3, drums
    4, airplane
    5, computer

reader2 is similar to reader1, except a much longer and more comprehensive file.
The problem is this:
I run through all of the inner loop, and, if the program doesn't find a match, it doesn't write the line, and then increment the outer loop like I thought it would. It just stops. Initially it threw me an error until I read a post here where someone suggested adding "extrasaction = 'ignore'" to the writer declaration statement.  But that didn't solve my problem.
I would greatly appreciate any feedback for fixing this logic. In my mind the following was what would be happening:
A) In the case where the inner loop does not find the value in question from the outer loop, the program outputs the line in the outer loop with no changes
B) In the case where the inner loop has the exact value that the outer loop is iterating over, change the values in one of the columns in the row and then output that row
I can see that as is, the program just stops after the first iteration of the inner loop, but I don't understand why this is the case.

A: reader1 and reader2 are file objects (wrapped in a csv DictReader). Those are iterators that can only be read once (until you're at the end of the file), so there's nothing for the next for loop to do.
Solution:
Read the file into a list and use that to refresh the DictReader:
read_1 = myfile1.readlines()
for row2 in reader2:
    reader1 = csv.DictReader(read_1)
    for row1 in reader1:
        # etc.

Even better, read that csv file into a list of dictionaries once - that should be faster:
reader1 = list(csv.DictReader(myfile))
for row2 in reader2:
    for row1 in reader1:
        # etc.

A: I'm not experienced with csv, but I'd guess that the reader is exhausted once you have iterated to the last line, and then you need to restart it to iterate again. So, maybe you should try to reassign reader1 before using it in the inner loop:
for row2 in reader2:
    reader1 = csv.DictReader(open('my.csv'), ...)
    for row1 in reader1:


text:
Q: Handling Buffer sent from Express to React to download an image I am trying to download an image from my s3 server. I successfully grab the file no problem in my express server as a Buffer. I then pipe it to the client and log it which results in the large binary file. The download in the browser shows up as well but it fails because it says there is no file. How do you get it to download the Buffer file that it sent as an attachment and have it save on the person's computer (either automatically in Downloads or allow people to choose what to use). I am using React js.
When it fails to download anything, in the download section on chrome, it will say Downloads Failed - No file
server
app.post('/download', (req, res) => {
  if (req.body.id) {
    User.findById(req.body.id)
    .then(user => {
      user.Images.filter(e => e.key === req.body.Images.key)
      .forEach(file => {
        res.setHeader('Content-Type', file.mimetype);
        res.setHeader('Content-Disposition', `attachment; filename=${file.originalname}`);
        res.setHeader('Content-Length', file.size)
        s3.getObject({ Bucket: 'bucket-name', Key: file.bucketKey })
        .createReadStream()
        .pipe(res)
      })
    })
    .catch(err => res.json({message: 'No user could be found.', err}));
  } else { res.json({message: 'You must be logged in to download these files.'}); };
});

client download button
<Button onClick={this.download} href='~/Downloads' download>Download Image</Button>

action
export const imageDownload = image => {
  return dispatch => {
    axios.post('http://localhost:8080/image-download', image)
    .then(res => {
      if (!res.data.message) {
        console.log(res.data);
        return dispatch({ type: 'DOWNLOAD', Download: res.data});
      } else { console.log(res.data); };
    })
    .catch(err => { console.log(err); });
  }
}

res.data is a massive binary/buffer/encode file like �<�˹���v���5�`���|�=�� but much longer. This means that I must have gotten the file however it does not download.I am also uncertain if the redux call is even necessary.
Edit: I no longer have access to this codebase so I cannot test it but I believe that the solution would be
    app.post('/download', (req, res) => {
      if (req.body.id) {
        User.findById(req.body.id)
        .then(user => {
          user.Images.filter(e => e.key === req.body.Images.key)
          .forEach(async file => {
            res.setHeader('Content-Type', file.mimetype);
            res.setHeader('Content-Disposition', `attachment; filename=${file.originalname}`);
            res.setHeader('Content-Length', file.size)
            const file = await s3.getObject({ Bucket: 'bucket-name', Key: file.bucketKey })
            fs.createReadStream(file).pipe(res)
          })
        })
        .catch(err => res.json({message: 'No user could be found.', err}));
      } else { res.json({message: 'You must be logged in to download these files.'}); };
    });


text:
Q: Backtrader problems in resampling to daily Using backtrader, I would like to retrieve quotes at a five minute scale and resample at a daily scale.
I am able to resample five minutes to sixty minutes, but can't do daily. Here is the code:
from __future__ import absolute_import, division, print_function, unicode_literals
import backtrader as bt
import backtrader.stores.ibstore as ibstore
import datetime
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

_CLIENTID = 100

class St(bt.Strategy):
    def __init__(self):
        self.sma = bt.indicators.SMA(self.data)

    def logdata(self):
        txt = []
        txt.append('{}'.format(len(self)))
        txt.append('{}'.format(self.data.datetime.datetime(0).isoformat()))
        txt.append('{:.2f}'.format(self.data.open[0]))
        txt.append('{:.2f}'.format(self.data.high[0]))
        txt.append('{:.2f}'.format(self.data.low[0]))
        txt.append('{:.2f}'.format(self.data.close[0]))
        txt.append('{:.2f}'.format(self.data.volume[0]))
        logger.debug(','.join(txt))

    data_live = False

    def notify_data(self, data, status, *args, **kwargs):
        print('*' * 5, 'DATA Notification:', data._getstatusname(status), *args)
        if status == data.LIVE:
            self.data_live = True

    def next(self):
        self.logdata()
        if not self.data_live:
            return

_TICKER = "TSLA-STK-SMART-USD"
_FROMDATE = datetime.datetime(2021,1,4)
_TODATE = datetime.datetime(2021,1,29)
_HAS_STATS = False

def run(args=None):
    cerebro = bt.Cerebro(stdstats=_HAS_STATS)

    store = ibstore.IBStore(host="127.0.0.1", port=7497, clientId= _CLIENTID )
    cerebro.broker = store.getbroker()
    stockkwargs = dict(
        timeframe=bt.TimeFrame.Minutes,
        compression=10,
        rtbar=False,
        historical=True,
        qcheck=0.5,
        fromdate=_FROMDATE,
        todate=_TODATE,
        latethrough=False,
        tradename=None
    )

    data0 = store.getdata(dataname=_TICKER, **stockkwargs)
    # cerebro.resampledata(data0, timeframe=bt.TimeFrame.Minutes, compression=60)
    cerebro.resampledata(data0, timeframe=bt.TimeFrame.Days, compression=1)

    cerebro.run()

if __name__ == "__main__":
    run()

I get a connection, but no days. Here is the output (with no bars printed):
Server Version: 76
TWS Time at connection:20210303 09:39:17 EST
***** DATA Notification: DELAYED
***** DATA Notification: DISCONNECTED

However, if I go on a 60-minute resample, all is well. The code
cerebro.resampledata(data0, timeframe=bt.TimeFrame.Minutes, compression=60)
# cerebro.resampledata(data0, timeframe=bt.TimeFrame.Days, compression=1)

results in
Server Version: 76
TWS Time at connection:20210303 09:36:27 EST
***** DATA Notification: DELAYED
DEBUG:__main__:30,2021-01-05T17:00:00,749.65,754.40,735.11,753.21,6011.00
DEBUG:__main__:31,2021-01-05T18:00:00,753.39,754.18,751.60,753.34,1126.00
DEBUG:__main__:32,2021-01-05T19:00:00,753.32,753.32,750.49,752.90,1179.00
DEBUG:__main__:33,2021-01-06T04:00:00,748.00,752.55,746.66,751.88,331.00
DEBUG:__main__:34,2021-01-06T05:00:00,751.60,753.00,749.26,750.50,137.00
(omitted)
DEBUG:__main__:286,2021-01-28T17:00:00,833.00,833.25,831.36,831.61,116.00
DEBUG:__main__:287,2021-01-28T18:00:00,831.60,833.96,830.11,831.00,175.00
DEBUG:__main__:288,2021-01-28T19:00:00,830.51,832.00,829.45,829.45,358.00
***** DATA Notification: DISCONNECTED

I am using these versions:
Python 3.7.4
ib                   0.8.0
IbPy2                0.8.0
numpy                1.19.2
pandas               1.1.3

TL;DR
I did several other experiments.

getData timeframe
getData compression
resample timeframe
resample compression
outcome

Minutes
5
Minutes
60
can see hourly, as expected

Minutes
5
Days
1
(empty)

(blank)
(blank)
Days
1
(empty)

Days
1
Days
1
(empty)

Days
1
(commented out)
(commented out)
(empty)

A: You are right there was a known issue a few years a back with this. There is an easy work-around though. Instead of using the backtrader resampling facility, use Interactive Brokers.
You can bypass resample and call the data directly from IB. Just remember that you must add the shortest timeframe first to Backtrader.

for tf_com in [(bt.TimeFrame.Minutes, 1), (bt.TimeFrame.Days, 1)]:
    stockkwargs = dict(
        timeframe=tf_com[0],
        compression=tf_com[1],
        rtbar=False,
        historical=True,
        qcheck=0.5,
        fromdate=_FROMDATE,
        todate=_TODATE,
        latethrough=False,
        tradename=None
    )

    data0 = store.getdata(dataname=_TICKER, **stockkwargs)

    cerebro.adddata(data0)

You can adjust your timeframe and compression in the tuples in the first line. I will adjust it to 5 and 15 minutes so you can see the output.
for tf_com in [(bt.TimeFrame.Minutes, 5), (bt.TimeFrame.Minutes, 15)]:

************ OUTPUT ************

2021-03-25 12:00:00 636.77 632.71
2021-03-25 12:05:00 634.69 632.71
2021-03-25 12:10:00 632.71 632.71
2021-03-25 12:15:00 640.39 643.00
2021-03-25 12:20:00 640.68 643.00
2021-03-25 12:25:00 643.00 643.00
2021-03-25 12:30:00 641.33 640.00
2021-03-25 12:35:00 637.84 640.00
2021-03-25 12:40:00 640.00 640.00
2021-03-25 12:45:00 640.34 633.95
2021-03-25 12:50:00 636.15 633.95
2021-03-25 12:55:00 633.95 633.95
2021-03-25 13:00:00 633.50 637.43
2021-03-25 13:05:00 634.95 637.43
2021-03-25 13:10:00 637.43 637.43

EDIT: IN RESPONSE TO OP COMMENT
I beg to differ. The days are sampled by Interactive Brokers so you will have daily information. You must be sure when using 5 minute data at the same time not to go back too far with your start date. IB is not a historical data provider.
Here is the entire code for your reference.
import backtrader as bt
import backtrader.stores.ibstore as ibstore
import datetime
import os
from dotenv import load_dotenv

load_dotenv()

class St(bt.Strategy):

    def __init__(self):
        self.data_live = False
        self.timeframes = {4: "minute", 5: "day"}

    def next(self):
        time = self.data.datetime.time()
        start_day = datetime.time(4, 20, 0)
        end_day = datetime.time(19, 40, 0)
        if time < start_day or time > end_day:
            print_date = True
        else:
            print_date = False

        if not self.data_live and print_date:
            print(
                f"{self.data.datetime.datetime()}   "

                f"data0: tf: {self.timeframes[self.datas[0]._timeframe]} "
                f"comp: {self.datas[0]._compression},   "
                f"{self.datas[0].close[0]:5.2f} "

                f"data1: tf: {self.timeframes[self.datas[1]._timeframe]} "
                f"comp: {self.datas[1]._compression} "
                f"{self.datas[1].close[0]:5.2f} "
            )
            return

_TICKER = "TSLA-STK-SMART-USD"
_FROMDATE = datetime.datetime(2021, 3, 10)
_TODATE = datetime.datetime(2021, 3, 24)
_HAS_STATS = False
_CLIENTID = os.getenv("CLIENTID")
_PORT = os.getenv("SOCKET_PORT")

def run():
    cerebro = bt.Cerebro(stdstats=_HAS_STATS)
    cerebro.addstrategy(St)

    store = ibstore.IBStore(host="127.0.0.1", port=int(_PORT), clientId=_CLIENTID)
    cerebro.broker = store.getbroker()

    for tf_com in [(bt.TimeFrame.Minutes, 5), (bt.TimeFrame.Days, 1)]:
        stockkwargs = dict(
            timeframe=tf_com[0],
            compression=tf_com[1],
            rtbar=False,
            historical=True,
            qcheck=0.5,
            fromdate=_FROMDATE,
            todate=_TODATE,
            latethrough=False,
            tradename=None,
        )

        data = store.getdata(dataname=_TICKER, **stockkwargs)

        cerebro.adddata(data)

    cerebro.run()

if __name__ == "__main__":
    run()

Here is the output with the middle of the days removed.
Please note that backtrader will set the next day value at the end of the last bar of the previous day.
2021-03-10 19:55:00   data0: tf: minute comp: 5,   664.56 data1: tf: day comp: 1 664.56
2021-03-11 04:00:00   data0: tf: minute comp: 5,   699.10 data1: tf: day comp: 1 664.56
2021-03-11 04:05:00   data0: tf: minute comp: 5,   701.50 data1: tf: day comp: 1 664.56
2021-03-11 04:10:00   data0: tf: minute comp: 5,   699.00 data1: tf: day comp: 1 664.56
2021-03-11 04:15:00   data0: tf: minute comp: 5,   701.00 data1: tf: day comp: 1 664.56
2021-03-11 19:45:00   data0: tf: minute comp: 5,   698.05 data1: tf: day comp: 1 664.56
2021-03-11 19:50:00   data0: tf: minute comp: 5,   698.09 data1: tf: day comp: 1 664.56
2021-03-11 19:55:00   data0: tf: minute comp: 5,   698.50 data1: tf: day comp: 1 664.56
2021-03-11 19:55:00   data0: tf: minute comp: 5,   698.50 data1: tf: day comp: 1 698.50
2021-03-12 04:00:00   data0: tf: minute comp: 5,   674.25 data1: tf: day comp: 1 698.50
2021-03-12 04:05:00   data0: tf: minute comp: 5,   676.00 data1: tf: day comp: 1 698.50
2021-03-12 04:10:00   data0: tf: minute comp: 5,   669.00 data1: tf: day comp: 1 698.50
2021-03-12 04:15:00   data0: tf: minute comp: 5,   669.46 data1: tf: day comp: 1 698.50
2021-03-12 19:45:00   data0: tf: minute comp: 5,   693.30 data1: tf: day comp: 1 698.50
2021-03-12 19:50:00   data0: tf: minute comp: 5,   692.80 data1: tf: day comp: 1 698.50
2021-03-12 19:55:00   data0: tf: minute comp: 5,   692.99 data1: tf: day comp: 1 698.50
2021-03-12 19:55:00   data0: tf: minute comp: 5,   692.99 data1: tf: day comp: 1 692.99
2021-03-15 04:00:00   data0: tf: minute comp: 5,   689.00 data1: tf: day comp: 1 692.99
2021-03-15 04:05:00   data0: tf: minute comp: 5,   692.13 data1: tf: day comp: 1 692.99
2021-03-15 04:10:00   data0: tf: minute comp: 5,   692.12 data1: tf: day comp: 1 692.99
2021-03-15 04:15:00   data0: tf: minute comp: 5,   692.31 data1: tf: day comp: 1 692.99
2021-03-15 19:45:00   data0: tf: minute comp: 5,   702.00 data1: tf: day comp: 1 692.99
2021-03-15 19:50:00   data0: tf: minute comp: 5,   702.00 data1: tf: day comp: 1 692.99
2021-03-15 19:55:00   data0: tf: minute comp: 5,   702.00 data1: tf: day comp: 1 692.99
2021-03-15 19:55:00   data0: tf: minute comp: 5,   702.00 data1: tf: day comp: 1 702.00
2021-03-16 04:00:00   data0: tf: minute comp: 5,   704.01 data1: tf: day comp: 1 702.00
2021-03-16 04:05:00   data0: tf: minute comp: 5,   704.98 data1: tf: day comp: 1 702.00
2021-03-16 04:10:00   data0: tf: minute comp: 5,   704.99 data1: tf: day comp: 1 702.00
2021-03-16 04:15:00   data0: tf: minute comp: 5,   706.20 data1: tf: day comp: 1 702.00
2021-03-16 19:45:00   data0: tf: minute comp: 5,   673.65 data1: tf: day comp: 1 702.00
2021-03-16 19:50:00   data0: tf: minute comp: 5,   674.00 data1: tf: day comp: 1 702.00
2021-03-16 19:55:00   data0: tf: minute comp: 5,   674.10 data1: tf: day comp: 1 702.00
2021-03-16 19:55:00   data0: tf: minute comp: 5,   674.10 data1: tf: day comp: 1 674.10
2021-03-17 04:00:00   data0: tf: minute comp: 5,   672.00 data1: tf: day comp: 1 674.10
2021-03-17 04:05:00   data0: tf: minute comp: 5,   675.80 data1: tf: day comp: 1 674.10
2021-03-17 04:10:00   data0: tf: minute comp: 5,   677.19 data1: tf: day comp: 1 674.10
2021-03-17 04:15:00   data0: tf: minute comp: 5,   676.03 data1: tf: day comp: 1 674.10
2021-03-17 19:45:00   data0: tf: minute comp: 5,   699.66 data1: tf: day comp: 1 674.10
2021-03-17 19:50:00   data0: tf: minute comp: 5,   699.90 data1: tf: day comp: 1 674.10
2021-03-17 19:55:00   data0: tf: minute comp: 5,   699.74 data1: tf: day comp: 1 674.10
2021-03-17 19:55:00   data0: tf: minute comp: 5,   699.74 data1: tf: day comp: 1 699.74
2021-03-18 04:00:00   data0: tf: minute comp: 5,   685.00 data1: tf: day comp: 1 699.74
2021-03-18 04:05:00   data0: tf: minute comp: 5,   686.35 data1: tf: day comp: 1 699.74
2021-03-18 04:10:00   data0: tf: minute comp: 5,   688.32 data1: tf: day comp: 1 699.74
2021-03-18 04:15:00   data0: tf: minute comp: 5,   692.50 data1: tf: day comp: 1 699.74
2021-03-18 19:45:00   data0: tf: minute comp: 5,   652.10 data1: tf: day comp: 1 699.74
2021-03-18 19:50:00   data0: tf: minute comp: 5,   651.00 data1: tf: day comp: 1 699.74
2021-03-18 19:55:00   data0: tf: minute comp: 5,   650.56 data1: tf: day comp: 1 699.74
2021-03-18 19:55:00   data0: tf: minute comp: 5,   650.56 data1: tf: day comp: 1 650.56
2021-03-19 04:00:00   data0: tf: minute comp: 5,   661.00 data1: tf: day comp: 1 650.56
2021-03-19 04:05:00   data0: tf: minute comp: 5,   663.00 data1: tf: day comp: 1 650.56
2021-03-19 04:10:00   data0: tf: minute comp: 5,   663.60 data1: tf: day comp: 1 650.56
2021-03-19 04:15:00   data0: tf: minute comp: 5,   666.48 data1: tf: day comp: 1 650.56
2021-03-19 19:45:00   data0: tf: minute comp: 5,   652.50 data1: tf: day comp: 1 650.56
2021-03-19 19:50:00   data0: tf: minute comp: 5,   652.02 data1: tf: day comp: 1 650.56
2021-03-19 19:55:00   data0: tf: minute comp: 5,   652.20 data1: tf: day comp: 1 650.56
2021-03-19 19:55:00   data0: tf: minute comp: 5,   652.20 data1: tf: day comp: 1 652.20
2021-03-22 04:00:00   data0: tf: minute comp: 5,   665.97 data1: tf: day comp: 1 652.20
2021-03-22 04:05:00   data0: tf: minute comp: 5,   664.00 data1: tf: day comp: 1 652.20
2021-03-22 04:10:00   data0: tf: minute comp: 5,   665.00 data1: tf: day comp: 1 652.20
2021-03-22 04:15:00   data0: tf: minute comp: 5,   663.94 data1: tf: day comp: 1 652.20
2021-03-22 19:45:00   data0: tf: minute comp: 5,   668.39 data1: tf: day comp: 1 652.20
2021-03-22 19:50:00   data0: tf: minute comp: 5,   668.56 data1: tf: day comp: 1 652.20
2021-03-22 19:55:00   data0: tf: minute comp: 5,   669.35 data1: tf: day comp: 1 652.20
2021-03-22 19:55:00   data0: tf: minute comp: 5,   669.35 data1: tf: day comp: 1 669.35
2021-03-23 04:00:00   data0: tf: minute comp: 5,   670.25 data1: tf: day comp: 1 669.35
2021-03-23 04:05:00   data0: tf: minute comp: 5,   665.33 data1: tf: day comp: 1 669.35
2021-03-23 04:10:00   data0: tf: minute comp: 5,   664.11 data1: tf: day comp: 1 669.35
2021-03-23 04:15:00   data0: tf: minute comp: 5,   662.93 data1: tf: day comp: 1 669.35
2021-03-23 19:45:00   data0: tf: minute comp: 5,   661.00 data1: tf: day comp: 1 669.35
2021-03-23 19:50:00   data0: tf: minute comp: 5,   661.08 data1: tf: day comp: 1 669.35
2021-03-23 19:55:00   data0: tf: minute comp: 5,   663.00 data1: tf: day comp: 1 669.35
2021-03-23 19:55:00   data0: tf: minute comp: 5,   663.00 data1: tf: day comp: 1 663.00

=== OP Verification ===
Here is what the data0 and data1 plot look like, adding a cerebro.plot() after the cerebro.run().

That's good looking daily data.


text:
Q: why jquery's ui.css files's font-sizes are bigger than normal? Im looking at jqueries tabs, datepicker etc and see that font-sizes of the classes added to elements are like 1.1em, 1em which seems big in the page. Why did they do this like that?
What is the purpose?
http://jquery-ui.googlecode.com/svn/tags/latest/themes/base/jquery.ui.theme.css

A: .ui-widget {
    font-size:75% !important;
}

That code will override the default font-size. Please note the !important attribute to make sure it works.

A: em is a relativ size and depends on the next fixed font-size up the dom tree. when there is no fixed font-size it defaults to 16px.
so when you change your own css like this
body {
    font-size: 12px;
}

1em means 12px, 2em means 24px and so on.

A: This is the default style that someone determined, you are free to change it though using ThemeRoller.  Just go under font settings on the left and adjust to what you want.

A: I usually set the class ui-widget in my css like this
.ui-widget {
    font-size:80%;
}


text:
Q: Akka (JVM): Serialize an actorref with protobuf within another message I have the following scala object that I would like to serialize with protobuf:
case class Worker(id: String, ref: ActorRef)

My understanding is that Akka comes with a ProtobufSerializer that I can use to serialize from/to ActorRef. Therefore I defined the following message in a proto file:
message Worker {
    string id = 1;
    bytes ref = 2;
}

However the static methods ProtobufSerializer take an ExtentendActorSystem that I do not have at hand when I need to serialize those messages (only an ActorSystem through the context.system attribute of my actor). I am not sure how to actually serialize my object to protobuf and the other way around.

A: I am not sure in which cases it is true, but I was able to simply cast my ActorSystem to an ExtendedActorSystem. In my specific case (I am using Akka Persistence with Akka Singleton) it seems to work fine.


text:
Q: Setting custom property in config.ini I want add a property that with a value that is a path to a local directory, for example, <property name="loc" value="C:\Program Files\myDir" />.
This works during the build, but when I retrieve this property I get C:Program FilesmyDir.
What is the right away to represent file references and URL references in config.ini?

A: Use forward slashes or replace each backslash with two backslashes:

*

*C:/Program Files/myDir or

*C:\\Program Files\\myDir


text:
Q: Software to clean windows junk file I'm looking for any free software or way around to clean junk files and make more space available in Windows drive.
Using Windows 10

A: In fact, you can use the built-tin Disk Cleanup tool to remove the temporary internet files, thumbnails,browser caches and others. If you do like software, you can use FileCleaner.

A: Many (hundreds) such free software. CCleaner is very good. If you're looking to clean up space, clean out the following two locations as well. None of the cleaning software clean these locations.
1) C:\Windows\Installer\$PatchCache$\Managed
2) C:\Windows\SoftwareDistribution\Download
Delete their contents only.


text:
Q: Is it possible to autocomplete user's text input in telegram? If there is a command-like text in the telegram chat room, it becomes clickable. (Please refer to below picture.)
Is there a way to make it so that if someone clicks on the telegram command-like text such as \set_something, the text of the command itself gets automatically entered into the user's input window where they type rather than the command itself being sent to the chatroom?

A: This sort of custom behaviour can be achieved only if you write a custom Telegram client.
You cannot do that using Telegram bot API alone.


text:
Q: How to disable Chrome/Safari notifications on multiple devices I have a macbook, iPad and two iPhones (one is mine, second - my wife's). All of them are connected to the same iCloud/apple account. Now, after last updates (starting from iOS 9), once my wife open some page at Chrome/Safari on her iPhone, I receive notifications at my macbook (some app icon at the left side of Dock menu). Moreover, after installing 9.0.3 on iPhone, once I open some page at Chrome/Safari on my macbook, she receives the notification at her iPhone..
The question is - how can I disable it? Is there some option that disables only this feature without disconnecting the whole device from apple/iCloud account?

A: This sounds like Handoff. Handoff lets you continue an action you start on one device on a different one (e.g. browsing a webpage).
If not already, you have to disable it on every device.
On OS X:

*

*Go to System Preferences > General

*Deselect Allow Handoff between this Mac and your iCloud devices
On iOS:

*

*Go to Settings > General > Handoff & Suggested Apps

*Turn off Handoff.


text:
Q: re.sub not working for a particular regex pattern I am using following code :
re.sub(inputpattern,outputpattern, currentline)
in the above code  , i am reading the value of outputpattern from csv , whose value is :
\\1-\\2-\\3-\\4

I am reading it like below :
outputpattern =  row['PREFIX_1_WRT_FMT']
I have also tried :
outputpattern =  "'"+ row['PREFIX_1_WRT_FMT'] +"'"
The problem is that it is not treating it as proper format , but if I hard code it like below it works fine :
re.sub(inputpattern,'\\1-\\2-\\3-\\4', currentline)

A: You only need to escape the backslashes if you have it as a literal string.
"\\1-\\2-\\3-\\4"

If you read it from an input you don't have to do that.  You need to change the pattern inside the CSV to be like \1-\2-\3-\4
You could also use the raw string if you dislike escaping every char when using literal string, by prefixing you string with the letter r.
r"\1-\2-\3-\4"


text:
Q: Certificate to read Digitally Signed Emails in EWS I am trying to read digitally signed emails in EWS. Specifically I am interested in the file attachments in the email. I am using the following code with no success:
SignedCms signedCms = new SignedCms();
signedCms.Decode(filebyte)

Where filebyte is the smime.p7m attachment.
I get the error "ASN1 bad tag value
met." on the second line of the code.
Can anybody help me figure out the issue? Am I missing a certificate on the machine that runs the code? Or is the certificate already in the smime.p7m? Am I not supposed to pass smime.p7m attachment to decode?


text:
Q: Custom infinite scrolling trigger many times I am new to angular was used to work with jquery.
I set a directive which listen scrolling to trigger an http.get request when the user is almost on the bottom of the document. Everything works fine but I cannot avoid the event to be trigger a lot of time at once.
here is some code if you have some suggestion that would be great !
html :
div(class="home-flex", ng-scroll, infinite-request="addMore()", ng-disabled)
    div(class="home-article", ng-repeat="article in articles", ng-cloak)
        img(class="home-article-image", ng-src="{{ article.imageUrl }}", ng-cloak)

directive :
nemi.directive('ngScroll', function($window, $document){
    return {
        link: function(scope, element, attrs){
            $document.on('scroll', function(element){
                var height = Math.max(
                    document.body.scrollHeight, document.documentElement.scrollHeight,
                    document.body.offsetHeight, document.documentElement.offsetHeight,
                    document.body.clientHeight, document.documentElement.clientHeight
                );
                // console.log("window height : " + $window.innerHeight)
                // console.log("scroll from top : " + $window.pageYOffset);
                // console.log("scroll from top + window height : " + ($window.innerHeight + $window.pageYOffset))
                // console.log("doc height : " + height);
                // console.log("scroll/doc : " +  $window.pageYOffset/height);

                if ((($window.pageYOffset + $window.innerHeight)/height) > 0.6) {
                    console.log("trigger");
                    scope.$apply(attrs.infiniteRequest);
                }

            })
        }
    }
})

annnnd my controller :
nemi.controller('homeController', [ '$scope', '$http', '$window', function($scope, $http){
    $http.get('/articles').success(function(res){
        $scope.articles = res;
    }).error(function(data){
        console.log(data);
    });

    var wait = true;
    $scope.addMore = function() {
        if (wait === true) {
            wait = false;
            console.log("trigger");
            $http.get('/articles').success(function(res) {
                res.forEach(function(elem){
                    $scope.articles.push(elem);

                })
            wait = true;
            }).error(function(){
                console.log("scroll failed");
            })
        }
    }
}]);

my miserable attempte to block the function with my "wait boolean" works but doesnt save me from the many request at once.
I tried different things with ng-disabled but nothing worked for me so far

A: You can get a help from promise returned by $http which is happening from addMore & then do check that does request already in process or not. If no then make a call again. This way code will ensure unless one call gets completed, other will not happen.
Controller
nemi.controller('homeController', ['$scope', '$http', '$window', function($scope, $http, $window) {
  $http.get('/articles').success(function(res) {
    $scope.articles = res;
  }).error(function(data) {
    console.log(data);
  });

  var addMorePromise = null;
  $scope.addMore = function() {
    console.log("trigger");
    if (!addMorePromise) { //if no request is in progress then do it again
      addMorePromise = $http.get('/articles').then(function(response) {
        var data = response.data;
        data.forEach(function(elem) {
          $scope.articles.push(elem);
        });
      }).finally(function() {
        addMorePromise = null; //after request complete, make promise object to null
      });
    }
  }
}]);


text:
Q: Почему падает приложение Android? Не могу понять, в чем причина падения приложения?
Стектрейс:
03-24 01:25:00.701 2998-2998/com.navesilli.sergey.galleryapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.navesilli.sergey.galleryapp, PID: 2998
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.navesilli.sergey.galleryapp/com.navesilli.sergey.galleryapp.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.v7.app.AlertController.RecycleListView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.v7.app.AlertController.RecycleListView
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.v7.app.AlertController.RecycleListView
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.app.AlertController.RecycleListView" on path: DexPathList[[zip file "/data/app/com.navesilli.sergey.galleryapp-2/base.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_dependencies_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_0_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_1_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_2_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_3_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_4_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_5_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_6_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_7_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_8_apk.apk", zip file "/data/app/com.navesilli.sergey.galleryapp-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.navesilli.sergey.galleryapp-2/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.view.LayoutInflater.createView(LayoutInflater.java:609)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.navesilli.sergey.galleryapp.MainActivity.onCreate(MainActivity.java:33)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)

Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical"
        >

<include
    layout="@layout/toolbar_layout"></include>

<android.support.v7.app.AlertController.RecycleListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/recyclerView"
    android:scrollbars="vertical">

    </android.support.v7.app.AlertController.RecycleListView>

</LinearLayout>

A: В xml вместо android.support.v7.app.AlertController.RecycleListView напишите android.support.v7.widget.RecyclerView:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <include
        layout="@layout/toolbar_layout">
    </include>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/recyclerView"
        android:scrollbars="vertical">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>


text:
Q: How to get less-than-equal-to to show in iTextRenderer conversion I've tried everything I know but still cannot get the ≥ and ≤ characters to show up in my PDF generated by Flying Saucer's iTextRenderer from xHTML.  They display fine in my browser as HTML of course.  I've tried different xml encoding types, doctypes, and using the decimal and hex values instead of the shortcut names.  Still, no errors display, but I get a blank space where the characters should be.
Has anyone successfully converted an xhtml to pdf using iTextRenderer with the ≤ and ≥ special symbols, and if so, how?
SOLUTION:  Okay, I got this one solved.  Turns out I did need to embed the Verdana font into the PDF using the follow lines of Java code:
renderer.getFontResolver().addFont("/Library/Fonts/Verdana.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("/Library/Fonts/Verdana Bold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("/Library/Fonts/Verdana Italic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("/Library/Fonts/Verdana Bold Italic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

A: SOLUTION: Okay, I got this one solved. Turns out I did need to embed the Verdana font into the PDF using the follow lines of Java code:
renderer.getFontResolver().addFont("/Library/Fonts/Verdana.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("/Library/Fonts/Verdana Bold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("/Library/Fonts/Verdana Italic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("/Library/Fonts/Verdana Bold Italic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);


text:
Q: Genymotion 2.1.1 API 18 VM gives AOSP Stopped error after GAPPS flash After flashing ARM Transalation and GAPPS from this tutorial : http://forum.xda-developers.com/showthread.php?t=2528952, "Unfortunately AOSP Stopped" message flashes every time. As a result Keyboard input is stopped, I cannot type anything. Signed into Google Play with great difficulty after copy pasting username password from a txt file. But still the problem persists after repeated reboots. Also I have tried fresh install numerous times, but still the same issue.
Also, back button doesn't work after Gapps flash. I have downloaded and tried both Gapps from mirrors too (gapps-jb-20130813-signed.zip and *gapps-jb-20130813-signed_0.zip*, both 97MB files).
Need to mention though, only drag and drop just copies the files in Download directory in this new version of Genymotion, so had to flash both zips via adb. (adb push ./system /system)
Please help!


text:
Q: Sending Email to multiple addresses from multiselect option using codeigniter-PHP I have a multiselect dropdown, which allows me to select more than one user at a time. I want to be able to select more than one user and when I click on the "Send code" button, the application will snow send email to these users using the email addresses. Currently when I select and click "Send Code", the application will only send email to only one user leaving other once. Please I will like to know to be sending email to all selected users at a time. I'm using CodeIgniter and  below is my code:
Below is the view section of my code, which enable user to select users and send code:

     <meta charset="UTF-8">
     <title>Member Invite</title>

    <form class="form-horizontal" method="post" action="<?php echo site_url('root/administrator/sendinvite'); ?>">
        <fieldset>

                Select Set

                    <select id="select01" class="chzn-select" name="set_code" title="Select the set this student(s) will belong to">
                        <option value="">Select set</option>
                        <?php foreach ($sets as $set) { ?>
                        <option <?php echo set_select('set_code', $set->group_id); ?> value="<?php echo $set->group_id; ?>"><?php echo $set->group_name; ?></option>
                        <?php } ?>
                    </select>
                    <?php echo form_error('set_code'); ?>

                Select student(s)

                    <select multiple="multiple" id="multiSelect" name="student_email" class="chzn-select span4" title="Select student(s) for this set">
                        <option value="">Select Student</option>
                        <?php foreach ($students as $student) { ?>
                        <option <?php echo set_select('student_email', $student->uacc_email); ?> value="<?php echo $student->uacc_email; ?>"><?php echo $student->uacc_username; ?></option>
                        <?php } ?>
                    </select>

Start typing to activate auto complete!

                    <?php echo form_error('student_email'); ?>

                <input type="hidden" name="student_id" value="<?php echo $student->upro_uacc_fk; ?>" class="span6 m-wrap"/>

                <button type="submit" class="btn btn-primary">Send code</button>
                <button type="reset" class="btn">Cancel</button>

        </fieldset>
    </form>

Below is my Controller, which accepts the selected users and used same to send email:
public function sendinvite() {
    if ($this->input->post()) {

        $this->form_validation->set_rules('student_email', 'Student name', 'required');
        $this->form_validation->set_rules('set_code', 'Set name', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->data['students'] = $this->super_model->get_members_with_out_group();
            $this->data['sets'] = $this->super_model->get_group_list_for_code_invite();
            $this->data['content'] = 'root/invitestudent';
            $this->load->view('layout/root/template', $this->data);
        } else {
            $config = Array(
                'protocol' => 'smtp',
                'smtp_host' => 'mail.mydomain.com',
                'smtp_port' => 25,
                'smtp_user' => 'root',
                'smtp_pass' => '347y6Z45Rwlfub020',
                'mailtype' => 'html',
                'charset' => 'iso-8859-1',
                'wordwrap' => TRUE
            );

            $this->load->library('email', $config);
            $len = 8;
            $type = 'HhJjKkMmNnPpQqRrSsTt';
            $set = $this->input->post('set_code');
            //$new_password = rand(34546, 89757);
            $this->email->from('admin@passwordmanager.com', "Admin Manager");
            $this->email->to($this->input->post('student_email'));
            //$this->email->cc($this->input->post('student_email'));
            $this->email->subject('BSN-Set Code');
            //$this->flexi_auth->forgotten_password($identity);
            $this->email->message("You are invited to join the group. Your set code is: $set");

            $data['message'] = "Sorry Unable to send email...";
            if ($this->email->send()) {
                $data['message'] = "Mail sent...";
            }
            redirect('root/administrator/invitesuccess');
        }
    } else {
        $this->data['students'] = $this->super_model->get_members_with_out_group();
        $this->data['sets'] = $this->super_model->get_group_list_for_code_invite();
        $this->data['content'] = 'root/invitestudent';
        $this->load->view('layout/root/template', $this->data);
    }
}

Image is here

A: you can use like this
// Array ( [0] => c@gmail.com [1] => a@gmail.com [2] => b@gamil.com )

$addresses = implode(',',$this->input->post('student_email');

// c@gmail.com,a@gmail.com,b@gamil.com

$this->email->to($addresses);