问:
Xamarin.forms ImageSource.FromFile doesn't work
I'm using Xam.Plugin.Media to take a picture .

```<code> var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions()
        {
            Directory = "attachments",
            Name = fileName,
            CompressionQuality = 35
        });
        cam.Source = ImageSource.FromFile(file.Path);
</code>```

above code does work !

file path is (file.Path):

```<code>/var/mobile/Containers/Data/Application/F3997E36-78EB-41AF-A37F-FC794BAF30EC/Documents/attachments/13c8ac4e57734a36bded2c2694e27495.jpg
</code>```

but this code does not show picture in an Image control

```<code>var q = "/var/mobile/Containers/Data/Application/F3997E36-78EB-41AF-A37F-FC794BAF30EC/Documents/attachments/13c8ac4e57734a36bded2c2694e27495.jpg"

 cam.Source = ImageSource.FromFile(q);
</code>```

答:
You need to save photo in gallery. When your user takes a photo it will still store temporary data, but also if needed make a copy to the public gallery

```<code>var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    SaveToAlbum = true
});
</code>```

Get the public album path

```<code>var aPpath = file.AlbumPath;
</code>```

Get private path

```<code>var path = file.Path;
</code>```

Body:
I'm using Xam.Plugin.Media to take a picture .

 var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions()
        {
            Directory = "attachments",
            Name = fileName,
            CompressionQuality = 35
        });
        cam.Source = ImageSource.FromFile(file.Path);

above code does work !

file path is (file.Path):

/var/mobile/Containers/Data/Application/F3997E36-78EB-41AF-A37F-FC794BAF30EC/Documents/attachments/13c8ac4e57734a36bded2c2694e27495.jpg

but this code does not show picture in an Image control

var q = "/var/mobile/Containers/Data/Application/F3997E36-78EB-41AF-A37F-FC794BAF30EC/Documents/attachments/13c8ac4e57734a36bded2c2694e27495.jpg"

 cam.Source = ImageSource.FromFile(q);

Body:
You need to save photo in gallery. When your user takes a photo it will still store temporary data, but also if needed make a copy to the public gallery

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    SaveToAlbum = true
});

Get the public album path

var aPpath = file.AlbumPath;

Get private path

var path = file.Path;


来源: stackexchange

问:
Checking to see if a MySQL row is populated
I have a page that writes to a MySQL table. The table has a set amount of rows (24).

I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.

My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.

Here's my code:

```<code>    mysql_select_db("delives0_booklet", $con);

    $query = "SELECT * FROM booklet WHERE id = '$id'";

    $res = mysql_query($query,$con);

    $newId = $id;

    while($row = mysql_fetch_array($res))
    {
        if($row['price'] != 0)
        {
            do{
                $newId = rand(1, 24);
            }while($newId == $id);
        }
    }
    $id = $newId;
    mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
</code>```

Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.

```<code>        mysql_select_db("delives0_booklet", $con);

    $query = "SELECT * FROM booklet";

    $res = mysql_query($query,$con);
    $i = 0;
    $isEmpty = array();

    while($row = mysql_fetch_array($res))
    {

            if($row['price'] == 0)
            {
                $isEmpty[i] = $row['id'];
                $i = $i + 1;
            }
    }
    echo $i . " unfilled spots.";
    $n = 0;
    while($n<$i)
    {
        echo $isEmpty[$n];
        $n = $n + 1;
    }
    if($i > 0)
    {
        $id = $isEmpty[rand(0, $i)];
    }
    if($i == 0)
    {
        echo 'All spots have been filled.';
    }
</code>```

答:
I think it is a top level logic problem.  Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.

I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go.  A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.

ContentLicense: CC BY-SA 2.5

Body:
I have a page that writes to a MySQL table. The table has a set amount of rows (24).

I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.

My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.

Here's my code:

    mysql_select_db("delives0_booklet", $con);

    $query = "SELECT * FROM booklet WHERE id = '$id'";

    $res = mysql_query($query,$con);

    $newId = $id;

    while($row = mysql_fetch_array($res))
    {
        if($row['price'] != 0)
        {
            do{
                $newId = rand(1, 24);
            }while($newId == $id);
        }
    }
    $id = $newId;
    mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");

Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.

        mysql_select_db("delives0_booklet", $con);

    $query = "SELECT * FROM booklet";

    $res = mysql_query($query,$con);
    $i = 0;
    $isEmpty = array();

    while($row = mysql_fetch_array($res))
    {

            if($row['price'] == 0)
            {
                $isEmpty[i] = $row['id'];
                $i = $i + 1;
            }
    }
    echo $i . " unfilled spots.";
    $n = 0;
    while($n<$i)
    {
        echo $isEmpty[$n];
        $n = $n + 1;
    }
    if($i > 0)
    {
        $id = $isEmpty[rand(0, $i)];
    }
    if($i == 0)
    {
        echo 'All spots have been filled.';
    }


问:
how to rotate a "triangle down" to a "triangle up" using css and jquery
i have the following triangle

created by the following css:

```<code>.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
</code>```

html:

```<code><div class=triangle></div>
</code>```

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

```<code>.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}
</code>```

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

答:
One way of achieving this is by using .hasClass() and .addClass() method in jQuery

jQuery(document).ready(function(){
  jQuery('.triangle').click(function(){
   if(jQuery(this).hasClass('triangle-up')){
    jQuery(this).removeClass('triangle-up');
   }else{
    jQuery(this).addClass('triangle-up');
   }

  });
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    }

    .triangle-up{
     -webkit-transform: rotate(180deg);
     -moz-transform: rotate(180deg);
     transform: rotate(180deg);
    }
    </code>```

```

ContentLicense: CC BY-SA 3.0

Body:
i have the following triangle

created by the following css:

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

html:

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

Body:
One way of achieving this is by using .hasClass() and .addClass() method in jQuery

jQuery(document).ready(function(){
  jQuery('.triangle').click(function(){
   if(jQuery(this).hasClass('triangle-up')){
    jQuery(this).removeClass('triangle-up');
   }else{
    jQuery(this).addClass('triangle-up');
   }

  });
 });

    .triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    }

    .triangle-up{
     -webkit-transform: rotate(180deg);
     -moz-transform: rotate(180deg);
     transform: rotate(180deg);
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class=triangle></div>


问:
Linux/gcc: Is there a way to check if a build is identical to a previous one on a different machine?
Scenario:
A build of a C++ project (under Linux with gcc) is supposed to be repeated on a new machine.

If the very same gcc version is used for the build:
Is the build output (binaries) identical? Or are time stamps, path, or other information contained in the binary that makes them different?
If the output is not identical: Can the output be compared in a way to see if the binaries are "functional" identical? I.e. can a tool be called that just compares the actual code inside the binary (without meta data like e.g. debug info)?

Motivation:
I have to prepare a clean new Linux system on which a software system (that was developed by someone else, let's call them X) has to be built.
In order to build the software I will get a source tree with build scripts, makefiles etc.
Now I have to check that the build output is the same as the last build that was provided by X (and built on their system). I need to do this to make sure that the source that will be handed over is the same that was used to build the last version that we got in binary form from X.

答:
If the very same gcc version is used for the build: Is the build output (binaries) identical?

What changes is the CPU more than the version of GCC and the static linking it does. I believe the answer you are looking for lies here.

It basically boils dow to "it depends".
Quoting the linked answer by Rici :

the binaries are likely to differ unless the CPUs are similar (and even then, it's possible)

And like Oliv said, objdump is also a good way to compare the differences.


问:
mean-before-after imputation in R
I'm new in R. My question is how to impute missing value using mean of before and after of the missing data point?

example;

using the mean from the upper and lower of each NA as the impute value.

-mean for row number 3 is 38.5

-mean for row number 7 is 32.5

```<code>age
52.0
27.0
NA
23.0
39.0
32.0
NA
33.0
43.0
</code>```

Thank you.

答:
You are looking for Moving Average Imputation - you can use the na_ma function of imputeTS for this.

```<code>library(imputeTS)
x <- c(52, 27, NA, 23, 39, NA, NA, 33, 43)
na_ma(x, k=1, weighting = "simple")
</code>```

[1] 52.00000 27.00000 25.00000 23.00000 39.00000 31.66667 38.33333
33.00000 43.00000

This produces exactly the required result.
With the k parameter you specify how many neighbors on each side are taken into account for the calculation.

Title: mean-before-after imputation in R

Body:
I'm new in R. My question is how to impute missing value using mean of before and after of the missing data point?

example;

using the mean from the upper and lower of each NA as the impute value.

-mean for row number 3 is 38.5

-mean for row number 7 is 32.5

age
52.0
27.0
NA
23.0
39.0
32.0
NA
33.0
43.0

Thank you.

Body:
You are looking for Moving Average Imputation - you can use the na_ma function of imputeTS for this.

library(imputeTS)
x <- c(52, 27, NA, 23, 39, NA, NA, 33, 43)
na_ma(x, k=1, weighting = "simple")

[1] 52.00000 27.00000 25.00000 23.00000 39.00000 31.66667 38.33333
33.00000 43.00000

This produces exactly the required result.
With the k parameter you specify how many neighbors on each side are taken into account for the calculation.

ContentLicense: CC BY-SA 4.0


问:
Send param in URL using OFBiz
I want to end a param in URL in OFBiz, but I get this error
from security

```<code>org.apache.ofbiz.webapp.event.EventHandlerException: Found URL parameter [twCompagneDeRecrutementId]
passed to secure (https) request-map with uri [showCompagne] with an event that calls service [showCompagne];
this is not allowed for security reasons! The data should be encrypted by making it part of the request body (a form field) instead of the request URL.
Moreover it would be kind if you could create a Jira sub-task of https://issues.apache.org/jira/browse/OFBIZ-2330 (check before if a sub-task for this error does not exist). If you are not sure how to create a Jira issue please have a look before at http://cwiki.apache.org/confluence/x/JIB2
</code>```

This is my ftl

```<code><#if listCompagne??>

            <#list listCompagne as newCompagne>

            <div style="display:flex; width:100%;">
                         <div style="padding:6px; width:24%;"><label>${newCompagne.nom}</label></div>
                         <div style="padding:6px; width:24%;"><label>${newCompagne.dateDebut ?date}</label></div>
                         <div style="padding:6px; width:24%;"><label>${newCompagne.dateFin ?date}</label></div>
                         <input type="hidden" value="${newCompagne.twCompagneDeRecrutementId}"/>
     <div style="padding:6px; width:20%;"> <a class="btn btn-outline-danger btn-block " href="<@ofbizUrl>showCompagne?twCompagneDeRecrutementId=${newCompagne.twCompagneDeRecrutementId}</@ofbizUrl>">afficher</a>
</div>

           </div>
           </#list>
</code>```

答: the solution is to go to url.properties and change parameters.url.encrypt to no </p>

Title: Send param in URL using OFBiz

Body:
I want to end a param in URL in OFBiz, but I get this error
from security

org.apache.ofbiz.webapp.event.EventHandlerException: Found URL parameter [twCompagneDeRecrutementId]
passed to secure (https) request-map with uri [showCompagne] with an event that calls service [showCompagne];
this is not allowed for security reasons! The data should be encrypted by making it part of the request body (a form field) instead of the request URL.
Moreover it would be kind if you could create a Jira sub-task of https://issues.apache.org/jira/browse/OFBIZ-2330 (check before if a sub-task for this error does not exist). If you are not sure how to create a Jira issue please have a look before at http://cwiki.apache.org/confluence/x/JIB2

This is my ftl

<#if listCompagne??>

            <#list listCompagne as newCompagne>

${newCompagne.nom}

${newCompagne.dateDebut ?date}

${newCompagne.dateFin ?date}

                         <input type="hidden" value="${newCompagne.twCompagneDeRecrutementId}"/>

 <a class="btn btn-outline-danger btn-block " href="<@ofbizUrl>showCompagne?twCompagneDeRecrutementId=${newCompagne.twCompagneDeRecrutementId}</@ofbizUrl>">afficher

           </#list>


问:
Oracle SQL - Sum up and show text if > 0
I'm totally new with Oracle SQL and my question may seem stupid but I have some difficulties to solve my problem.

Current situation:
I have following tables: Supplier, Debtor, Invoice

Every Supplier has various Debtors and every Debtor has various Invoices.
I want to create an evaluation which shows me the following scenario:

A list of all Debtors from a Supplier. I also want to see in that list if the Debtor once haven't payed his invoice. I have this information within the table Invoice as the attribute called "payed" and possible values are 0 (payed) and 1 (not payed). I just want to see the debtor ONCE in the list so if there is only ONE invoice which is 1, it should show me "1" or "Not Payed" in the list. Right now when a debtor has 100 invoices it shows me 100 times the debtor with the info "0" or "1".

Currently:

```<code>     SELECT company.company_id,
         company.companyname_1,
         supplier.supplier_id,
         supplier.suppliername_1,
         debtor.debtor_id_from_supplier,
         debtor_ext.debtorname_1,
         debtor_ext.street,
         debtor_ext.street_number,
         debtor_ext.postcode,
         debtor_ext.city,
         debtor.approved_limit,
         debitor.limit_left,
         debitor.limit_status,
         debitor.limit_type,
         debitor.prosecution,
         CASE
            WHEN invoice.payed = 0 THEN 'Yes'
            ELSE 'No'
         END as deb_payment
    FROM debtor,
         debtor_ext,
         company,
         supplier,
         invoice
   WHERE ( company.company_id = supplier.company_id ) and
         ( supplier.supplier_id = debtor.supplier_id ) and
         ( debtor.debtor_id = debtor_ext.debtor_id ) and
         ( debtor.supplier_id = invoice.supplier_id ) and
         ( debtor.debtor_id_from_supplier = invoice.debtor_id_from_supplier )
</code>```

CODE CORRECTED!
Hope you guys can help me

答:
First of all, In your query, you're doing cross join which is not required and also affects on the performance. I'll advice you to use Inner Join here.

Also,as the schema is not provided in question,I am giving solution for the below schema:

Supplier:

```<code>Supplier_Id (PK) | Supplier_Name
</code>```

Debtor:

```<code>Debtor_Id (PK) | Debtor_Name | Supplier_Id (FK)
</code>```

Invoice:

```<code>Invoice_Id (PK) | Supplier_Id (FK) | Debtor_Id (FK) | Amount | Payed
</code>```

Query:

```<code>Select company.company_id,
        company.companyname_1,
        s.supplier_id,
        s.suppliername_1,
        d.debtor_id_from_supplier,
        d.debtorname_1,
        d.street,
        d.street_number,
        d.postcode,
        d.city,
        d.approved_limit,
        d.limit_left,
        d.limit_status,
        d.limit_type,
        d.prosecution,
        tmp.deb_payment
 From
 (
 SELECT d.supplier_id,
        d.debtor_id,
    (
     CASE
        WHEN min(i.payed) <> max(i.payed) Then 'Not Payed'
        ELSE 'Payed'
     END
    )as deb_payment
FROM supplier s
inner join debtor d
on s.supplier_id = d.supplier_id
inner join invoice i
on i.supplier_id = d.supplier_id
and i.debtor_id = d.debtor_id
Group by d.supplier_id,d.debtor_id
) tmp
inner join supplier s
on s.supplier_id = tmp.supplier_id
inner join company
on company.company_id = s.company_id
inner join debtor d
on s.supplier_id = d.supplier_id
inner join debtor_ext de
d.debtor_id = de.debtor_id
;
</code>```

Hope it helps!

Body:
I'm totally new with Oracle SQL and my question may seem stupid but I have some difficulties to solve my problem.

Current situation:
I have following tables: Supplier, Debtor, Invoice

Every Supplier has various Debtors and every Debtor has various Invoices.
I want to create an evaluation which shows me the following scenario:

A list of all Debtors from a Supplier. I also want to see in that list if the Debtor once haven't payed his invoice. I have this information within the table Invoice as the attribute called "payed" and possible values are 0 (payed) and 1 (not payed). I just want to see the debtor ONCE in the list so if there is only ONE invoice which is 1, it should show me "1" or "Not Payed" in the list. Right now when a debtor has 100 invoices it shows me 100 times the debtor with the info "0" or "1".

Currently:

     SELECT company.company_id,
         company.companyname_1,
         supplier.supplier_id,
         supplier.suppliername_1,
         debtor.debtor_id_from_supplier,
         debtor_ext.debtorname_1,
         debtor_ext.street,
         debtor_ext.street_number,
         debtor_ext.postcode,
         debtor_ext.city,
         debtor.approved_limit,
         debitor.limit_left,
         debitor.limit_status,
         debitor.limit_type,
         debitor.prosecution,
         CASE
            WHEN invoice.payed = 0 THEN 'Yes'
            ELSE 'No'
         END as deb_payment
    FROM debtor,
         debtor_ext,
         company,
         supplier,
         invoice
   WHERE ( company.company_id = supplier.company_id ) and
         ( supplier.supplier_id = debtor.supplier_id ) and
         ( debtor.debtor_id = debtor_ext.debtor_id ) and
         ( debtor.supplier_id = invoice.supplier_id ) and
         ( debtor.debtor_id_from_supplier = invoice.debtor_id_from_supplier )

CODE CORRECTED!
Hope you guys can help me

Body:
First of all, In your query, you're doing cross join which is not required and also affects on the performance. I'll advice you to use Inner Join here.

Also,as the schema is not provided in question,I am giving solution for the below schema:

Supplier:

Supplier_Id (PK) | Supplier_Name

Debtor:

Debtor_Id (PK) | Debtor_Name | Supplier_Id (FK)

Invoice:

Invoice_Id (PK) | Supplier_Id (FK) | Debtor_Id (FK) | Amount | Payed

Query:

Select company.company_id,
        company.companyname_1,
        s.supplier_id,
        s.suppliername_1,
        d.debtor_id_from_supplier,
        d.debtorname_1,
        d.street,
        d.street_number,
        d.postcode,
        d.city,
        d.approved_limit,
        d.limit_left,
        d.limit_status,
        d.limit_type,
        d.prosecution,
        tmp.deb_payment
 From
 (
 SELECT d.supplier_id,
        d.debtor_id,
    (
     CASE
        WHEN min(i.payed) <> max(i.payed) Then 'Not Payed'
        ELSE 'Payed'
     END
    )as deb_payment
FROM supplier s
inner join debtor d
on s.supplier_id = d.supplier_id
inner join invoice i
on i.supplier_id = d.supplier_id
and i.debtor_id = d.debtor_id
Group by d.supplier_id,d.debtor_id
) tmp
inner join supplier s
on s.supplier_id = tmp.supplier_id
inner join company
on company.company_id = s.company_id
inner join debtor d
on s.supplier_id = d.supplier_id
inner join debtor_ext de
d.debtor_id = de.debtor_id
;

Hope it helps!


问:
Understanding event listeners in java
I'm new to java and I'm still trying to understand the language, so I apologize if this question might sound noobish.

There's something I don't understand about listeners, sometime you can see a listener declared in such a fashion:

```<code>    private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {

// Some code

}

};
</code>```

or:

```<code>javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
</code>```

The thing that perplex me the most is that semicolon and parenthesis after the end of the method.

I understand inner classes for the purpose of having multiple listeners, but I don't understand this mixed declaration of variables and method.

Which purpose it has?

How is it declared?

WTF? :P

cheers :)

答: That is an anonymous inner class. It's a very common and handy construct. Read the tutorial I linked to!</p>

Title: Understanding event listeners in java

Body:
I'm new to java and I'm still trying to understand the language, so I apologize if this question might sound noobish.

There's something I don't understand about listeners, sometime you can see a listener declared in such a fashion:

    private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {

// Some code

}

};

or:

javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });

The thing that perplex me the most is that semicolon and parenthesis after the end of the method.

I understand inner classes for the purpose of having multiple listeners, but I don't understand this mixed declaration of variables and method.

Which purpose it has?

How is it declared?

WTF? :P

cheers :)


问:
How to secure web services when authentication is done at client side (frontend)
I have web application which structure is as-

webapi : django web services [NOT REST] no security implemented

frontend : Angular2. authentication implemented via SAML

Database : Mongodb

Can you please suggest best way to secure webapi, as currently anyone can access web services who has server[api] url

It will be big help if you suggest the authentication and authorization flow because I am totally stuck.
Thanks in advance.

答:
Implement an /authentication on your API which accepts Basic authentication. Make sure you do that over HTTPS. Username and password will be collected by your Angular app and sent back to /authentication. If the user authenticates, return a session token, for example JWT (check pyjwt).

All the following communications between the front and back should contain the token, which is issued only if the user authenticated. The token is inclued in the request headers and specifically in Authororization header using the Bearer schema:

```<code>Authorization: Bearer <token>
</code>```

A JWT contains the username so you can use that on each future request. Furthermore, you are not required to keep record of the issued JWT since each one is self-contained and can have predetermined expiration data.

Body:
Implement an /authentication on your API which accepts Basic authentication. Make sure you do that over HTTPS. Username and password will be collected by your Angular app and sent back to /authentication. If the user authenticates, return a session token, for example JWT (check pyjwt).

All the following communications between the front and back should contain the token, which is issued only if the user authenticated. The token is inclued in the request headers and specifically in Authororization header using the Bearer schema:

Authorization: Bearer <token>

A JWT contains the username so you can use that on each future request. Furthermore, you are not required to keep record of the issued JWT since each one is self-contained and can have predetermined expiration data.


问:
jQuery: Conflict with removeData() executing at inadequate times
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

```<code><div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
</code>```

Html of the modal:

```<code>@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>
</code>```

GET Method:

```<code>    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }
</code>```

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

```<code><script type="text/javascript">

    var wasclicked = 0;
    var $this = this;

    $(document).ready(function () {

        document.getElementById("modalbutton").onclick = function () {
            //is AddNew Store button is hitted, this var = 1
            wasclicked = 1;
        };

        $('#modal-action-store').on('hidden.bs.modal', function () {
            //global.wasclicked = 0;
            wasclicked = 0;
            $(this).removeData('bs.modal');
        });

        $('#modal-action-store').on('shown.bs.modal', function (e) {
            console.log($('#DistrictID').length);
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            };
        });
    });
</script>
</code>```

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

```<code>  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
</code>```

And this line is lost:

```<code>var items = "<option value='0'>-- Seleccione Distrito --</option>";
</code>```

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

答:
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.

```<code>    @model Application.Models.ApplicationviewModels.StoreIndexData
    @using Application.Models

    <form asp-action="Create" role="form">
            @await Html.PartialAsync("_ModalHeader", new ModalHeader
        { Heading = String.Format("Actualización de Modelo: Tiendas") })

            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="modal-body form-horizontal">
                <div class="form-group">
                    <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                    <div class="col-md-10">
                        <select asp-for="DepartmentID" class="form-control"
                                asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">Distrito</label>
                    <div class="col-md-10">
                        <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                                asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                    </div>
                </div>
                {... more elements}
           </div>
    </form>

<script type="text/javascript">

    $(document).ready(function () {
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            }
    });

</script>
</code>```

PS: Default option can be also be used. refer the below code.

```<code><div class="form-group">
 <label class="col-md-2 control-label">Distrito</label>
  <div class="col-md-10">
   <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
     <option value='0'>-- Seleccione Distrito --</option>
  </select>
 </div>
</div>
</code>```

Body:
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

              NEW STORE

Html of the modal:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>

                Distrito

                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>

            {... more elements}

</form>

GET Method:

    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"

And this line is lost:

var items = "<option value='0'>-- Seleccione Distrito --</option>";

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

Body:
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.

    @model Application.Models.ApplicationviewModels.StoreIndexData
    @using Application.Models

    <form asp-action="Create" role="form">
            @await Html.PartialAsync("_ModalHeader", new ModalHeader
        { Heading = String.Format("Actualización de Modelo: Tiendas") })

            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="modal-body form-horizontal">
                <div class="form-group">
                    <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                    <div class="col-md-10">
                        <select asp-for="DepartmentID" class="form-control"
                                asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">Distrito</label>
                    <div class="col-md-10">
                        <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                                asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                    </div>
                </div>
                {... more elements}
           </div>
    </form>

<script type="text/javascript">

    $(document).ready(function () {
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            }
    });

</script>

PS: Default option can be also be used. refer the below code.

<div class="form-group">
 <label class="col-md-2 control-label">Distrito</label>
  <div class="col-md-10">
   <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
     <option value='0'>-- Seleccione Distrito --</option>
  </select>
 </div>
</div>


问:
t-sql how to subtract two records from table
I have such a query:

```<code>SELECT Stamp_date , Stamp_Action FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)
</code>```

And I have such a results from query:

```<code>2017-12-04 12:56:37.293 5

2017-12-04 15:40:02.593 15
</code>```

What is the best way to subtract two records? Also how can I define them as a variables, if I would like to maintain with them easily?

答:
It's good example for applying LAG function:

```<code>declare @x table([date] datetime, [value] int)
insert into @x values ('2017-12-04 12:56:37.293', 5), ('2017-12-04 15:40:02.593', 15)

select *,LAG([date], 1) over (order by [date]) [DateLag],
       LAG([value], 1) over (order by [date]) [ValueLag],
       DATEDIFF(minute, [date],LAG([value], 1) over (order by [date])) [DateDifference],
       [value] - LAG([value], 1) over (order by [date]) [ValueDifference]
from @x
</code>```

I included as much examples as I could, so you can decide what you need and could see how it works :)

Body:
I have such a query:

SELECT Stamp_date , Stamp_Action FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)

And I have such a results from query:

2017-12-04 12:56:37.293 5

2017-12-04 15:40:02.593 15

What is the best way to subtract two records? Also how can I define them as a variables, if I would like to maintain with them easily?

Body:
It's good example for applying LAG function:

declare @x table([date] datetime, [value] int)
insert into @x values ('2017-12-04 12:56:37.293', 5), ('2017-12-04 15:40:02.593', 15)

select *,LAG([date], 1) over (order by [date]) [DateLag],
       LAG([value], 1) over (order by [date]) [ValueLag],
       DATEDIFF(minute, [date],LAG([value], 1) over (order by [date])) [DateDifference],
       [value] - LAG([value], 1) over (order by [date]) [ValueDifference]
from @x

I included as much examples as I could, so you can decide what you need and could see how it works :)


问:
Why is "using getString() to get device identifiers" not recommended?
I'm trying to get my device ID to Logcat but Android Studio is giving me this warning.

using getstring to get device identifiers is not recommended

```<code>String deviceID = Settings.Secure.getString(getApplicationContext().getContentResolver(),
        Settings.Secure.ANDROID_ID);
</code>```

Why is it not recommended?

答:
The full warning says:

Using these device identifiers is not recommended other
than for high value fraud prevention and advanced telephony use-cases.
For advertising use-cases, use AdvertisingIdClient$Info#getId and for
analytics, use InstanceId#getId.

More info:
https://developer.android.com/training/articles/user-data-ids.html

I think Android does not recommend using this value, since it's a permanent unique id, which can be used to track your user, and he or she can't change this id or prevent you to read it. The other options given in the warning respects your user's wishes. That's why Android recommend you to use that.

It really depends on what you are going to do with that id. Privacy is a sensitive thing these days.

Also check this:

...you must abide by a user’s ‘Opt out of interest-based advertising’
or 'Opt out of Ads Personalization' setting. If a user has enabled
this setting, you may not use the advertising identifier for creating
user profiles for advertising purposes or for targeting users with
personalized advertising. Allowed activities include contextual
advertising, frequency capping, conversion tracking, reporting and
security and fraud detection.

Source: https://developer.android.com/training/articles/user-data-ids.html

Body:
I'm trying to get my device ID to Logcat but Android Studio is giving me this warning.

using getstring to get device identifiers is not recommended

String deviceID = Settings.Secure.getString(getApplicationContext().getContentResolver(),
        Settings.Secure.ANDROID_ID);

Why is it not recommended?


问:
jQuery to Vanilla JS - querySelector issues
I'm going through some code and working to change all of the jQuery to vanilla JS. However there is one section and I keep getting an error in my console that says either:

TypeError: document.querySelectorAll(...).toggle is not a function pr
  TypeError: document.querySelectorAll(...) is null

Below is my code, the top part you can see is where I am trying to change the jquery to vanilla js (I have commented out the jquery) :

```<code>console.log(shipmentNumbers);
            for (let i = 0; i < shipmentNumbers.length; i += 1) {
                let sNumber = shipmentNumbers[i];

                function getHistory(event) {
                    console.log(event);
                    document.querySelectorAll('#shipment' + sNumber + 'tr.show-history' + sNumber).toggle();
                    // $('#shipment' + sNumber + ' tr.show-history' + sNumber).toggle();
                    document.getElementsByClassName('overlay-line' + sNumber).style.display = 'table-row';
                    // $('.overlay-line' + sNumber).css({
                    //  "display": "table-row"
                    // });
                    if (flag == false) {
                        let shipmentNumber = event.currentTarget.id.replace('status', '');
                        console.log('shipmentNumber=', shipmentNumber);
                        callHistoryApi(clientId, shipmentNumber);
                        $(this).find('.expand' + sNumber).html("▼");
                        flag = true;
                    } else {
                        $(this).find('.expand' + sNumber).html("►");
                        $('.overlay-line' + sNumber).css({
                            "display": "none"
                        });
                        flag = false;
                    }
                }
</code>```

Can someone explain why this isn't working, and how I can get it working using vanilla js?

答:
I find that writing these two functions can really help when moving from jQuery to native JS.

```<code>function domEach(selector, handler, context) {
    return Array.from(document.querySelectorAll(selector), handler, context);
}

// If you get a TypeError "Array.from" is not a function, use the polyfill
// found on MPN.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
</code>```

This gets you around issues where you relied on implicit loops that jQuery uses.

```<code>// Instead of these:

document.querySelectorAll('#shipment' + sNumber + 'tr.show-history' + sNumber).toggle();
document.getElementsByClassName('overlay-line' + sNumber).style.display = 'table-row';

// Use these:

domEach('#shipment' + sNumber + 'tr.show-history' + sNumber, function (tr) {

    tr.style.display = tr.style.display === "none"
        ? ""
        : "none";

});

domEach('.overlay-line' + sNumber, function (el) {
    el.style.display = 'table-row';
});
</code>```

For a list of techniques to use instead of the jQuery functions, you can check You Might Not Need jQuery

Edit: more information about the code above

jQuery uses implicit loops. That is, when you do this:

```<code>$("#one").addClass("two");
</code>```

jQuery does this behind the scenes:

```<code>var elements = document.querySelectorAll("#one");
var i = 0;
var il = elements.length;
while (i < il) {
    elements[i].classList.add("two");
    i += 1;
}
</code>```

This leads to some confusion when going from jQuery to vanilla JavaScript since you have to manually loop over the results of querySelectorAll.

Array.from will loop over an array or array-like structure. querySelectorAll will return a NodeList - this is an array-like structure (it has numerical indicies and a length property). The domEach function allows us to pass a CSS selector to the function and will loop over the results of finding matching elements.

The ? : syntax is called a ternary operator. It's a short-cut for if ... else.

```<code>// Ternary operator
tr.style.display = tr.style.display === "none"
    ? ""
    : "none";

// Equivalent if/else statements
if (tr.style.display === "none") {
    tr.style.display = "";
} else {
    tr.style.display = "none";
}
</code>```

I hope that helps clarify things.

Body:
I'm going through some code and working to change all of the jQuery to vanilla JS. However there is one section and I keep getting an error in my console that says either:

TypeError: document.querySelectorAll(...).toggle is not a function pr
  TypeError: document.querySelectorAll(...) is null

Below is my code, the top part you can see is where I am trying to change the jquery to vanilla js (I have commented out the jquery) :

console.log(shipmentNumbers);
            for (let i = 0; i < shipmentNumbers.length; i += 1) {
                let sNumber = shipmentNumbers[i];

                function getHistory(event) {
                    console.log(event);
                    document.querySelectorAll('#shipment' + sNumber + 'tr.show-history' + sNumber).toggle();
                    // $('#shipment' + sNumber + ' tr.show-history' + sNumber).toggle();
                    document.getElementsByClassName('overlay-line' + sNumber).style.display = 'table-row';
                    // $('.overlay-line' + sNumber).css({
                    //  "display": "table-row"
                    // });
                    if (flag == false) {
                        let shipmentNumber = event.currentTarget.id.replace('status', '');
                        console.log('shipmentNumber=', shipmentNumber);
                        callHistoryApi(clientId, shipmentNumber);
                        $(this).find('.expand' + sNumber).html("▼");
                        flag = true;
                    } else {
                        $(this).find('.expand' + sNumber).html("►");
                        $('.overlay-line' + sNumber).css({
                            "display": "none"
                        });
                        flag = false;
                    }
                }

Can someone explain why this isn't working, and how I can get it working using vanilla js?

Body:
I find that writing these two functions can really help when moving from jQuery to native JS.

function domEach(selector, handler, context) {
    return Array.from(document.querySelectorAll(selector), handler, context);
}

// If you get a TypeError "Array.from" is not a function, use the polyfill
// found on MPN.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

This gets you around issues where you relied on implicit loops that jQuery uses.

// Instead of these:

document.querySelectorAll('#shipment' + sNumber + 'tr.show-history' + sNumber).toggle();
document.getElementsByClassName('overlay-line' + sNumber).style.display = 'table-row';

// Use these:

domEach('#shipment' + sNumber + 'tr.show-history' + sNumber, function (tr) {

    tr.style.display = tr.style.display === "none"
        ? ""
        : "none";

});

domEach('.overlay-line' + sNumber, function (el) {
    el.style.display = 'table-row';
});

For a list of techniques to use instead of the jQuery functions, you can check You Might Not Need jQuery

Edit: more information about the code above

jQuery uses implicit loops. That is, when you do this:

$("#one").addClass("two");

jQuery does this behind the scenes:

var elements = document.querySelectorAll("#one");
var i = 0;
var il = elements.length;
while (i < il) {
    elements[i].classList.add("two");
    i += 1;
}

This leads to some confusion when going from jQuery to vanilla JavaScript since you have to manually loop over the results of querySelectorAll.

Array.from will loop over an array or array-like structure. querySelectorAll will return a NodeList - this is an array-like structure (it has numerical indicies and a length property). The domEach function allows us to pass a CSS selector to the function and will loop over the results of finding matching elements.

The ? : syntax is called a ternary operator. It's a short-cut for if ... else.

// Ternary operator
tr.style.display = tr.style.display === "none"
    ? ""
    : "none";

// Equivalent if/else statements
if (tr.style.display === "none") {
    tr.style.display = "";
} else {
    tr.style.display = "none";
}

I hope that helps clarify things.


问:
PHP Carbon get toDay date by formatting date
Simply I can format PHP date such as:

```<code>$current_date_time = new DateTime("now");
$user_current_date = $current_date_time->format("Y-m-d");
</code>```

to get toDay date. how to do this action by using Carbon without time in date?

```<code>$now = Carbon::now();
echo $now;    // 2015-11-11 12:38:36
</code>```

答:
You can add the static method today() at the end of the Carbon Object:

```<code>$today = Carbon::today()->toDateString();
</code>```

Then ->toDateString() to convert the carbon object to a date string.

This will take the Carbon Object of: date: 2023-01-27 00:00:00.0 UTC (+00:00), and modify it to a string 2023-01-27 without time stamp.

Body:
Simply I can format PHP date such as:

$current_date_time = new DateTime("now");
$user_current_date = $current_date_time->format("Y-m-d");

to get toDay date. how to do this action by using Carbon without time in date?

$now = Carbon::now();
echo $now;    // 2015-11-11 12:38:36

Body:
You can add the static method today() at the end of the Carbon Object:

$today = Carbon::today()->toDateString();

Then ->toDateString() to convert the carbon object to a date string.

This will take the Carbon Object of: date: 2023-01-27 00:00:00.0 UTC (+00:00), and modify it to a string 2023-01-27 without time stamp.


答:
Break it down...

```<code>javax.swing.SwingUtilities.invokeLater(Runnable runnable);
</code>```

invokeLater() is a static method on SwingUtilities that takes a Runnable as a parameter.

Note the right parenthesis and semi-colon at the end; it's just a standard method, right?

The stuff in the middle is just creating a new instance of a Runnable to pass to the method.  You're recognize it better if I assigned it to a reference:

```<code>Runnable parameter = new Runnable()
{
    public void run()
    {
        createAndShowGUI();
        }
    }
};
</code>```

Title: Understanding event listeners in java

Body:
Break it down...

javax.swing.SwingUtilities.invokeLater(Runnable runnable);

invokeLater() is a static method on SwingUtilities that takes a Runnable as a parameter.

Note the right parenthesis and semi-colon at the end; it's just a standard method, right?

The stuff in the middle is just creating a new instance of a Runnable to pass to the method.  You're recognize it better if I assigned it to a reference:

Runnable parameter = new Runnable()
{
    public void run()
    {
        createAndShowGUI();
        }
    }
};


问:
C - RSA Cryptosystem Decryption Issue (unsigned long long not big enough?)
I'm working on an assignment where I have to build an RSA Cryptosystem. I was able to encrypt the cipher key no problem however I'm having trouble decrypting it due to the result of the exponent being so large. I've tried using unsigned long long int but I'm still getting an output of 0.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//Unsigned long long int power function
unsigned long long getPower(unsigned long long int base, int exponent){
    unsigned long long result = 1;
    int count = 0;

    while(count != exponent){
        result *= base;
        count++;
    }

    return result;
}

int decryptFile(int cipherInt, int n, int d){
    int plainInt;
    unsigned long long int cipherIntLong = cipherInt;
    unsigned long long int power = getPower(cipherIntLong, d);

    printf("%llu\n", power);

    return (int) plainInt;
}

int main(){
    decryptFile(1394, 3127, 2011);
}
</code>```

I should add that the professor made no mention of using a big number library so I'm sure we are most likely not supposed to use one for this assignment.

答:
The maximum value of an unsigned 64-bit integer is 18,446,744,073,709,551,615

However, 1394^2011 is more around 1.296 x 10^6323.  That is 7.02 x 10^6303 times larger than the maximum value of an unsigned 64-bit integer.

TL;DR: Use a BigInteger library, a really big one.

Seriously though, the main reason RSA can compute such large powers is because RSA operates under a modulus, so if we use Modular Exponentiation, we require far less computational power to reach the result.  Calculating the result by raising the plaintext to the exponent and then applying the modulus at the end isn't computationally feasible.

Body:
I'm working on an assignment where I have to build an RSA Cryptosystem. I was able to encrypt the cipher key no problem however I'm having trouble decrypting it due to the result of the exponent being so large. I've tried using unsigned long long int but I'm still getting an output of 0.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//Unsigned long long int power function
unsigned long long getPower(unsigned long long int base, int exponent){
    unsigned long long result = 1;
    int count = 0;

    while(count != exponent){
        result *= base;
        count++;
    }

    return result;
}

int decryptFile(int cipherInt, int n, int d){
    int plainInt;
    unsigned long long int cipherIntLong = cipherInt;
    unsigned long long int power = getPower(cipherIntLong, d);

    printf("%llu\n", power);

    return (int) plainInt;
}

int main(){
    decryptFile(1394, 3127, 2011);
}

I should add that the professor made no mention of using a big number library so I'm sure we are most likely not supposed to use one for this assignment.


问:
writing cgi code by C language
Is this possible to write CGI code by C or C++ ? please give me a "hello World !!!" Example . </p>

答:
Have a look at kcgi

kcgi is an open source CGI and FastCGI library for C web applications. It is minimal, secure, and auditable

```<code>#include <sys/types.h> /* size_t, ssize_t */
#include <stdarg.h> /* va_list */
#include <stddef.h> /* NULL */
#include <stdint.h> /* int64_t */
#include <stdlib.h> /* EXIT_SUCCESS, etc. */
#include <kcgi.h>

int main(void) {
  struct kreq r;
  const char *page = "index";
  if (KCGI_OK != khttp_parse(&r, NULL, 0, &page, 1, 0))
    return(EXIT_FAILURE);
  khttp_head(&r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
  khttp_head(&r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME__MAX == r.mime ?
      KMIME_APP_OCTET_STREAM : r.mime]);
  khttp_body(&r);
  khttp_puts(&r, "Hello, world!");
  khttp_free(&r);
  return(EXIT_SUCCESS);
}
</code>```

Title: writing cgi code by C language

Body:
Have a look at kcgi

kcgi is an open source CGI and FastCGI library for C web applications. It is minimal, secure, and auditable

#include <sys/types.h> /* size_t, ssize_t */
#include <stdarg.h> /* va_list */
#include <stddef.h> /* NULL */
#include <stdint.h> /* int64_t */
#include <stdlib.h> /* EXIT_SUCCESS, etc. */
#include <kcgi.h>

int main(void) {
  struct kreq r;
  const char *page = "index";
  if (KCGI_OK != khttp_parse(&r, NULL, 0, &page, 1, 0))
    return(EXIT_FAILURE);
  khttp_head(&r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
  khttp_head(&r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME__MAX == r.mime ?
      KMIME_APP_OCTET_STREAM : r.mime]);
  khttp_body(&r);
  khttp_puts(&r, "Hello, world!");
  khttp_free(&r);
  return(EXIT_SUCCESS);
}


问:
Ensure that a consumer group's offset is behind another group's
I have two services, A and B, processing stuff from a Kafka topic. However, B must not process stuff from the topic before A is done doing so. Is there any way to ensure that B's poll() will only return records that have been committed by A?

答: In this case, you need to create a pipeline and push messages committed by A to a new topic which B should subscribe.</p>


问:
Iterate through ObservableCollection of class
I'm assigning values to a class by using ObservableCollection.Class contains MainItems and it's SubItems. Now how can I read all SubItems for each input of MainItem?</p>

```<code> public class MainItems
   {
    public string ItemName { get; set; }
    public ObservableCollection<SubItems> SubItemsList { get; set; }
   }
   public class SubItems
   {
    public string SubItemName { get; set; }
   }

  ObservableCollection<MainItems> _data = new   ObservableCollection<MainItems>();
        for (int i = 1; i <= 5; i++)
        {
            MainItems _mainItems = new MainItems();
            _mainItems.ItemName = "Main" + i.ToString();
            _mainItems.SubItemsList = new ObservableCollection<SubItems>();
            for (int j = 1; j <= 3; j++)
            {
                SubItems _subItems = new SubItems()
                {
                    SubItemName = "SubItem" + i.ToString()
                };
                _mainItems.SubItemsList.Add(_subItems);
            }
            _data.Add(_mainItems);
        }
</code>```

答:
// For Enumerator version

// get the input main item

```<code>string input = "Main1";

    IEnumerable<ObservableCollection<SubItems>> ItemsforSelectedMainIem = _data.Where(x => x.ItemName == input).Select(x => x.SubItemsList);
    var e = ItemsforSelectedMainIem.GetEnumerator();
    while (e.MoveNext())
    {
        var v = e.Current.Select(x=>x.SubItemName).ToList();
        foreach (var item in v)
        {
            Console.WriteLine(item);
        }
    }
</code>```

Body:
I'm assigning values to a class by using ObservableCollection.Class contains MainItems and it's SubItems. Now how can I read all SubItems for each input of MainItem?

 public class MainItems
   {
    public string ItemName { get; set; }
    public ObservableCollection<SubItems> SubItemsList { get; set; }
   }
   public class SubItems
   {
    public string SubItemName { get; set; }
   }

  ObservableCollection<MainItems> _data = new   ObservableCollection<MainItems>();
        for (int i = 1; i <= 5; i++)
        {
            MainItems _mainItems = new MainItems();
            _mainItems.ItemName = "Main" + i.ToString();
            _mainItems.SubItemsList = new ObservableCollection<SubItems>();
            for (int j = 1; j <= 3; j++)
            {
                SubItems _subItems = new SubItems()
                {
                    SubItemName = "SubItem" + i.ToString()
                };
                _mainItems.SubItemsList.Add(_subItems);
            }
            _data.Add(_mainItems);
        }

Body:
// For Enumerator version

// get the input main item

string input = "Main1";

    IEnumerable<ObservableCollection<SubItems>> ItemsforSelectedMainIem = _data.Where(x => x.ItemName == input).Select(x => x.SubItemsList);
    var e = ItemsforSelectedMainIem.GetEnumerator();
    while (e.MoveNext())
    {
        var v = e.Current.Select(x=>x.SubItemName).ToList();
        foreach (var item in v)
        {
            Console.WriteLine(item);
        }
    }


问:
Angular 4 Image Upload
I want to upload image through HTTP post API. My input is like this.

```<code><input type="file" (change)="changedata($event)" name="file"/>
</code>```

And Changedata() function .

```<code>let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      let formData: FormData = new FormData();
          formData.append('File', file, file.name);
            this.mainservice.updateIcon(formData).subscribe(responseData=>{
            console.log(' Reposnce Data ',responseData)
   })
}
</code>```

When I check Request Payload its not send image .. see  https://www.screencast.com/t/vKFKj0S3

How I can send image in base64 ?

答:
```<code><input id="profile" type="file" name="profile" required (change)="uploadImage()">
</code>```

and Uploadimage Function

```<code>    public uploadImage(): void {
    let files = this.element.nativeElement.querySelector('#profile').files;
    let formData = new FormData();
    let file = files[0];
    formData.append( 'userID', this.userID); // if you want pass other value
    formData.append('profile', file, file.name); // add image  in FormData
    // pass image to service
     this.fileUpload.uploadFile(formData).subscribe( res => res);
}
</code>```

in uploadFile ->>Service

```<code>    public uploadFile(formdata: any ) {

      return this.http.post('ApiURL here', formdata).catch(this.errorHandler);
      // return this.apiUrl;
    }

private errorHandler(error: Response) {
      console.error('Error Occured: ' + error);
      return Observable.throw(error || 'Some Error on Server Occured');
    }
</code>```

Title: Angular 4 Image Upload

Body:
I want to upload image through HTTP post API. My input is like this.

<input type="file" (change)="changedata($event)" name="file"/>

And Changedata() function .

let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      let formData: FormData = new FormData();
          formData.append('File', file, file.name);
            this.mainservice.updateIcon(formData).subscribe(responseData=>{
            console.log(' Reposnce Data ',responseData)
   })
}

When I check Request Payload its not send image .. see  https://www.screencast.com/t/vKFKj0S3

How I can send image in base64 ?

Body:
<input id="profile" type="file" name="profile" required (change)="uploadImage()">

and Uploadimage Function

    public uploadImage(): void {
    let files = this.element.nativeElement.querySelector('#profile').files;
    let formData = new FormData();
    let file = files[0];
    formData.append( 'userID', this.userID); // if you want pass other value
    formData.append('profile', file, file.name); // add image  in FormData
    // pass image to service
     this.fileUpload.uploadFile(formData).subscribe( res => res);
}

in uploadFile ->>Service

    public uploadFile(formdata: any ) {

      return this.http.post('ApiURL here', formdata).catch(this.errorHandler);
      // return this.apiUrl;
    }

private errorHandler(error: Response) {
      console.error('Error Occured: ' + error);
      return Observable.throw(error || 'Some Error on Server Occured');
    }


问:
Search abbreviation from sentence in mysql
I want to list the words that match the abbreviation. For an example, if I'm searching for AI or Artificial Intelligence then it should list for any record that contains 'Artificial Intelligence' as a part of the sentence. Similarly when I search for MCA or Master of Computer Application then it would list all the records which contain Master of Computer Application as a part of a sentence.

Assuming that my MySQL table is 'topics' with columns TopicID, TopicName, TopicDesc.
Sample data: http://sqlfiddle.com/#!9/77f8df

Note: I was asked to achieve it without additional table or column.

Please let me know if more information is required.

答:
To search for abbreviations, use RLIKE with a regular expression. For instance, when searching for "MCA":

```<code>SELECT * FROM TOPICS WHERE
    TOPICNAME RLIKE '[[:<:]]M.*[[:<:]]C.*[[:<:]]A.*'
    OR
    TOPICDESC RLIKE '[[:<:]]M.*[[:<:]]C.*[[:<:]]A.*'
</code>```

Where [[:<:]] denotes the start of a word and .* matches any text character.

Note that there are some restrictions for Unicode characters as stated in the documentation, but as long as your text are in English you should be fine.

For a regular text search, use LIKE like with the text to be searched like this:

```<code>SELECT * FROM TOPICS WHERE
    TOPICNAME LIKE '%Master of Computer Application%'
    OR
    TOPICDESC LIKE '%Master of Computer Application%'
</code>```

Body:
To search for abbreviations, use RLIKE with a regular expression. For instance, when searching for "MCA":

SELECT * FROM TOPICS WHERE
    TOPICNAME RLIKE '[[:<:]]M.*[[:<:]]C.*[[:<:]]A.*'
    OR
    TOPICDESC RLIKE '[[:<:]]M.*[[:<:]]C.*[[:<:]]A.*'

Where [[:<:]] denotes the start of a word and .* matches any text character.

Note that there are some restrictions for Unicode characters as stated in the documentation, but as long as your text are in English you should be fine.

For a regular text search, use LIKE like with the text to be searched like this:

SELECT * FROM TOPICS WHERE
    TOPICNAME LIKE '%Master of Computer Application%'
    OR
    TOPICDESC LIKE '%Master of Computer Application%'


问:
Not able to install codedeploy-agent.msi using Cloudformation
I am trying to deploy codedeploy-agent.msi to an ec2 instance (win 2012).  Its behind a private subnet with NO NAT gateway, but with S3 endpoint, i tested this powershell.exe -Command Read-S3Object -BucketName aws-codedeploy-us-west-2 -Key latest/codedeploy-agent.msi -File codedeploy-agent.msi is working. agent is being downloaded through powershell from the ec2 instance.

However, with below cloudfromation script the instance gets created without the agent installed.  There is no c:\cfn folder and cfn-init.log files are missing.  What could be the issue???

```<code>"WorkerInstance": {
            "Type": "AWS::EC2::Instance",
            "Metadata": {
                "AWS::CloudFormation::Init": {
                    "config": {
                        "commands": {
                            "00-download-host-agent": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "powershell.exe -Command \"Read-S3Object ",
                                            "-BucketName aws-codedeploy-us-west-2 ",
                                            "-Key latest/codedeploy-agent.msi ",
                                            "-File codedeploy-agent.msi\""
                                        ]
                                    ]
                                },
                                "cwd": "C:/cfn",
                                "waitAfterCompletion" : 0
                            },
                            "01-install-host-agent": {
                                "command": "C:\\cfn\\codedeploy-agent.msi /quiet /l C:\\cfn\\host-agent-install-log.txt",
                                "ignoreErrors": "true",
                                "waitAfterCompletion" : 0
                            },
                            "02-signal-ready": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "\"C:\\Program Files\\Amazon\\cfn-bootstrap\\cfn-signal\"",
                                            " -e 0 \"",
                                            "\""
                                        ]
                                    ]
                                }
                            }
                        },
                        "services": {
                            "windows": {
                                "codedeploy-agent": {
                                    "enabled": "true",
                                    "ensureRunning": "true",
                                    "commands": [
                                        "01-install-host-agent"
                                    ]
                                }
                            }
                        }
                    }
                }
            },
            "Properties": {
                "DisableApiTermination": "false",
                "InstanceInitiatedShutdownBehavior": "stop",
                "IamInstanceProfile": {
                            "Ref": "IAMRole"
                        },
                "ImageId": "ami-c55089bd",
                "InstanceType": "t2.medium",
                "KeyName": "mykey",
                "Monitoring": "true",
                "Tags": [{
                        "Key": "CodeDeployGroup",
                        "Value": {
                            "Fn::Join": ["-", ["app", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "CodeDeployGroup"
                                ]]
                        }
                    }, {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": ["-", ["App", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "Worker"
                                ]]
                        }
                    }
                ],
                        "NetworkInterfaces": [{
                        "DeleteOnTermination": "true",
                        "Description": "Primary network interface",
                        "DeviceIndex": 0,
                        "SubnetId": "subnet-70234568",
                        "GroupSet": ["sg-8affd7", "sg-fdffsfsd4"]
                    }
                ]
            }
        }
</code>```

答:
Im not sure, why it dint work.  I finally got it to work by putting it as  userdata script.

```<code>"UserData": {
                    "Fn::Base64": {
                            "Fn::Join": ["", ["<script>\n", "mkdir c:\\cfn\n", "mkdir c:\\cfn\\log\n",
                                "powershell.exe Read-S3Object -BucketName aws-codedeploy-us-west-2/latest -Key codedeploy-agent.msi -File c:\\cfn\\codedeploy-agent.msi\n",
                                "c:\\cfn\\codedeploy-agent.msi /quiet /l c:\\cfn\\host-agent-install-log.txt\n",
                                "c:\\\"Program Files\"\\Amazon\\cfn-bootstrap\\cfn-init.exe -s ", {
                                    "Ref": "AWS::StackName"
                                }, " --region ", {
                                    "Ref": "AWS::Region"
                                }, " > c:\\cfn\\log\\cfn-call-log 2>&1", "</script>"]]
                    }
                },
</code>```

This installs the agent as well as enables and starts the service.

Body:
I am trying to deploy codedeploy-agent.msi to an ec2 instance (win 2012).  Its behind a private subnet with NO NAT gateway, but with S3 endpoint, i tested this powershell.exe -Command Read-S3Object -BucketName aws-codedeploy-us-west-2 -Key latest/codedeploy-agent.msi -File codedeploy-agent.msi is working. agent is being downloaded through powershell from the ec2 instance.

However, with below cloudfromation script the instance gets created without the agent installed.  There is no c:\cfn folder and cfn-init.log files are missing.  What could be the issue???

"WorkerInstance": {
            "Type": "AWS::EC2::Instance",
            "Metadata": {
                "AWS::CloudFormation::Init": {
                    "config": {
                        "commands": {
                            "00-download-host-agent": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "powershell.exe -Command \"Read-S3Object ",
                                            "-BucketName aws-codedeploy-us-west-2 ",
                                            "-Key latest/codedeploy-agent.msi ",
                                            "-File codedeploy-agent.msi\""
                                        ]
                                    ]
                                },
                                "cwd": "C:/cfn",
                                "waitAfterCompletion" : 0
                            },
                            "01-install-host-agent": {
                                "command": "C:\\cfn\\codedeploy-agent.msi /quiet /l C:\\cfn\\host-agent-install-log.txt",
                                "ignoreErrors": "true",
                                "waitAfterCompletion" : 0
                            },
                            "02-signal-ready": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "\"C:\\Program Files\\Amazon\\cfn-bootstrap\\cfn-signal\"",
                                            " -e 0 \"",
                                            "\""
                                        ]
                                    ]
                                }
                            }
                        },
                        "services": {
                            "windows": {
                                "codedeploy-agent": {
                                    "enabled": "true",
                                    "ensureRunning": "true",
                                    "commands": [
                                        "01-install-host-agent"
                                    ]
                                }
                            }
                        }
                    }
                }
            },
            "Properties": {
                "DisableApiTermination": "false",
                "InstanceInitiatedShutdownBehavior": "stop",
                "IamInstanceProfile": {
                            "Ref": "IAMRole"
                        },
                "ImageId": "ami-c55089bd",
                "InstanceType": "t2.medium",
                "KeyName": "mykey",
                "Monitoring": "true",
                "Tags": [{
                        "Key": "CodeDeployGroup",
                        "Value": {
                            "Fn::Join": ["-", ["app", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "CodeDeployGroup"
                                ]]
                        }
                    }, {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": ["-", ["App", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "Worker"
                                ]]
                        }
                    }
                ],
                        "NetworkInterfaces": [{
                        "DeleteOnTermination": "true",
                        "Description": "Primary network interface",
                        "DeviceIndex": 0,
                        "SubnetId": "subnet-70234568",
                        "GroupSet": ["sg-8affd7", "sg-fdffsfsd4"]
                    }
                ]
            }
        }

Body:
Im not sure, why it dint work.  I finally got it to work by putting it as  userdata script.

"UserData": {
                    "Fn::Base64": {
                            "Fn::Join": ["", ["<script>\n", "mkdir c:\\cfn\n", "mkdir c:\\cfn\\log\n",
                                "powershell.exe Read-S3Object -BucketName aws-codedeploy-us-west-2/latest -Key codedeploy-agent.msi -File c:\\cfn\\codedeploy-agent.msi\n",
                                "c:\\cfn\\codedeploy-agent.msi /quiet /l c:\\cfn\\host-agent-install-log.txt\n",
                                "c:\\\"Program Files\"\\Amazon\\cfn-bootstrap\\cfn-init.exe -s ", {
                                    "Ref": "AWS::StackName"
                                }, " --region ", {
                                    "Ref": "AWS::Region"
                                }, " > c:\\cfn\\log\\cfn-call-log 2>&1", "</script>"]]
                    }
                },

This installs the agent as well as enables and starts the service.


问:
swift3，my timer can't stop. why?
this is i seting a timer function, the code like this:

```<code>@IBAction func start(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
}

@objc func action() {

    hoursMinutesSeconds()
    if stop == true{
        start = false
        timer.invalidate()
        timer.invalidate()
        time = 0
    }
}

@IBAction func stop(_ sender: UIButton){

    start = false
    timer.invalidate()
    timer.invalidate()
    time = 0
}
</code>```

but, when i click the stop func,  this function not work. mean is the timer not stop. timer stil working……  why？ thank you  for your time!!

答:
you are confusing between variable stop and func stop.

also you dont need 2 parameter to manage stop/start status

--
for your question,
you should retain the timer variable to able to use it in other func
declare a global timer

var timer: Timer!

then

timer = Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)

now you can invalidate it anywhere

Title: swift3，my timer can't stop. why?

Body:
this is i seting a timer function, the code like this:

@IBAction func start(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
}

@objc func action() {

    hoursMinutesSeconds()
    if stop == true{
        start = false
        timer.invalidate()
        timer.invalidate()
        time = 0
    }
}

@IBAction func stop(_ sender: UIButton){

    start = false
    timer.invalidate()
    timer.invalidate()
    time = 0
}

but, when i click the stop func,  this function not work. mean is the timer not stop. timer stil working……  why？ thank you  for your time!!


问:
Ejb application server in Eclipse development
I want to develop an EJB project using Eclipse. In the Eclipse development environment, which application server is lightest, easiest and fastest ?

Thanks.

答:
Glassfish V3 is probably the lightest one at the moment. It supports the full Java EE 6 platform, yet it starts up in a second or two.

JBoss AS 6 starts noticeable slower, on my 2.93 Ghz i7 a good 12 seconds in non-debug mode and takes a little longer when starting it in debug mode.

If you're only interested in the web profile of Java EE 6 (which includes EJB lite), then Caucho Resin might be a candidate worth looking into. They will officially support only EJB lite, but will nevertheless also implement some of the features from 'normal' EJB, like the extremely handy @Asynchronous annotation as well as message driven beans. See http://blog.caucho.com/?p=384. I haven't used Resin personally, but being 'light' seems to be their first and foremost design choice. At the time of writing, Resin is not yet Java EE 6 Web Profile certified, but this could happen any moment now.


问:
parse IOS FBSDKGraphRequest result using Swift4 JSONDecoder
the result of FBSDKGraphRequest is of type any and could be casting to NSDictionary, but how to convert it to Data object to be able to use this SWIFT4 feature

```<code>let jsonDecoder = JSONDecoder.init()
let fbModel = try? jsonDecoder.decode(FBModel.self, from: dataFromResult)
</code>```

i'm try this but the result was nil as code comments

```<code>    FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"email,name,id"]).start{ (connection, results, error) -> Void in
           let dataFromResult = NSKeyedArchiver.archivedData(withRootObject: results)
           let stringFromData = String.init(data: dataFromResult, encoding: String.Encoding.utf8)//return nil
           let jsonDecoder = JSONDecoder.init()
           let fbModel = try? jsonDecoder.decode(FBModel.self, from: dataFromResult)//fbModel nil
}
</code>```

答:
it worked for me but i'm not sure if it is the optimal solution </p>

```<code>let resDataFromDic = try? JSONSerialization.data(withJSONObject: resDict, options: JSONSerialization.WritingOptions.prettyPrinted)
</code>```

Body:
the result of FBSDKGraphRequest is of type any and could be casting to NSDictionary, but how to convert it to Data object to be able to use this SWIFT4 feature

let jsonDecoder = JSONDecoder.init()
let fbModel = try? jsonDecoder.decode(FBModel.self, from: dataFromResult)

i'm try this but the result was nil as code comments

    FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"email,name,id"]).start{ (connection, results, error) -> Void in
           let dataFromResult = NSKeyedArchiver.archivedData(withRootObject: results)
           let stringFromData = String.init(data: dataFromResult, encoding: String.Encoding.utf8)//return nil
           let jsonDecoder = JSONDecoder.init()
           let fbModel = try? jsonDecoder.decode(FBModel.self, from: dataFromResult)//fbModel nil
}

Body:
it worked for me but i'm not sure if it is the optimal solution

let resDataFromDic = try? JSONSerialization.data(withJSONObject: resDict, options: JSONSerialization.WritingOptions.prettyPrinted)


问:
Arrow link used as page scroll down
I made a simpel arrow in css:

```<code>.arrow {
border: solid black;
border-width: 0 4px 4px 0;
display: inline-block;
padding: 3px;
}
</code>```

But how do I insert it as a link. I'm using Joomla. I tried this:

```<code><a class="arrow" href="#info"></a>
</code>```

But Joomla just cut that line out. So is it not possible in Joomla or am I doing it wrong? :)

答:
Click button "Run code snippet" to see arrow or output.

.arrow {
  border: solid black;
  border-width: 0 3px 3px 0;
  display: inline-block;
  padding: 3px;
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  font-size:0 !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>

</head>
<body>

v

</body>
</html></code>```

Title: Arrow link used as page scroll down

Body:
I made a simpel arrow in css:

.arrow {
border: solid black;
border-width: 0 4px 4px 0;
display: inline-block;
padding: 3px;
}

But how do I insert it as a link. I'm using Joomla. I tried this:

But Joomla just cut that line out. So is it not possible in Joomla or am I doing it wrong? :)

Body:
Click button "Run code snippet" to see arrow or output.

.arrow {
  border: solid black;
  border-width: 0 3px 3px 0;
  display: inline-block;
  padding: 3px;
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  font-size:0 !important;
}

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<a class="arrow" href="#info">v</a>

</body>
</html>


问:
import pyodbc not working in eclipse
I am new to python..
I am not able to import pyodbc
I am getting an error in eclipse (just for this import)
i install pyodbc

```<code>C:\Users\app_rahavm>pip install pyodbc
Requirement already satisfied: pyodbc in c:\users\app_rahavm\appdata\local\programs\python\python36-32\lib\site-packages
</code>```

python interpeter is also updated with the path:

and still i am getting

```<code>Unresolved import: pyodbc
</code>```

when i write this:

```<code>import pyodbc
</code>```

i also see this package under packages

click here to see

any ideas?

another thing i notice is that each install package has it's own .dist-info lib but i have only dist-info file which does not hav python files inside
see image here see content of lib here

答:
just to update (if some else might need it... ) after spending alot of time on this ... the error is just a displayed error !! the code is running even with this error , this is very wierd but this is the case... also it is possible to press cntl + 1 and in the pop up screen choose "UnresolvedImport"

or just add at the end of the import - this will remove the red error and will do the import...

import pyodbc  # @UnresolvedImport

Title: import pyodbc not working in eclipse

Body:
I am new to python..
I am not able to import pyodbc
I am getting an error in eclipse (just for this import)
i install pyodbc

C:\Users\app_rahavm>pip install pyodbc
Requirement already satisfied: pyodbc in c:\users\app_rahavm\appdata\local\programs\python\python36-32\lib\site-packages

python interpeter is also updated with the path:

and still i am getting

Unresolved import: pyodbc

when i write this:

import pyodbc

i also see this package under packages

click here to see

any ideas?

another thing i notice is that each install package has it's own .dist-info lib but i have only dist-info file which does not hav python files inside
see image here see content of lib here


问:
Cannot implicitly convert type '.List<AnonymousType#1>' to '.List<WebApplication2.Customer>'
In the following code that returns a list:

```<code>public List<Customer> GeAllCust()
{
    var results = db.Customers
        .Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo })
        .ToList()
    return results;
}
</code>```

I get an error reporting that C# can't convert the list:

Error: Cannot implicitly convert type System.Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.List<WebApplication2.Customer>

Why is that?

Here's a screenshot showing some additional information that Visual Studio provides in a tooltip for the error:

Is it right way to return some columns instead of whole table....?

```<code>public object GeAllCust()
{
       var results = db.Customers.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo }).ToList();
        return results;
}
</code>```

答:
Basically whatever u got in var type, loop on that and store it in list<> object then loop and achieve ur target.Here I m posting code for Master details.
List obj = new List();</p>

```<code>        var orderlist = (from a in db.Order_Master
                         join b in db.UserAccounts on a.User_Id equals b.Id into abc
                         from b in abc.DefaultIfEmpty()
                         select new
                         {
                             Order_Id = a.Order_Id,
                             User_Name = b.FirstName,
                             Order_Date = a.Order_Date,
                             Tot_Qty = a.Tot_Qty,
                             Tot_Price = a.Tot_Price,
                             Order_Status = a.Order_Status,
                             Payment_Mode = a.Payment_Mode,
                             Address_Id = a.Address_Id

                         });

        List<MasterOrder> ob = new List<MasterOrder>();

        foreach (var item in orderlist)
        {

            MasterOrder clr = new MasterOrder();
            clr.Order_Id = item.Order_Id;
            clr.User_Name = item.User_Name;
            clr.Order_Date = item.Order_Date;
            clr.Tot_Qty = item.Tot_Qty;
            clr.Tot_Price = item.Tot_Price;
            clr.Order_Status = item.Order_Status;
            clr.Payment_Mode = item.Payment_Mode;
            clr.Address_Id = item.Address_Id;
            ob.Add(clr);

        }

        using(ecom_storeEntities en=new ecom_storeEntities())
        {
            var Masterlist = en.Order_Master.OrderByDescending(a => a.Order_Id).ToList();

            foreach (var i in ob)
            {
                var Child = en.Order_Child.Where(a => a.Order_Id==i.Order_Id).ToList();
                obj.Add(new OrderMasterChild
                {
                    Master = i,
                    Childs = Child
                });
            }

        }
</code>```

Body:
In the following code that returns a list:

public List<Customer> GeAllCust()
{
    var results = db.Customers
        .Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo })
        .ToList()
    return results;
}

I get an error reporting that C# can't convert the list:

Error: Cannot implicitly convert type System.Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.List<WebApplication2.Customer>

Why is that?

Here's a screenshot showing some additional information that Visual Studio provides in a tooltip for the error:

Is it right way to return some columns instead of whole table....?

public object GeAllCust()
{
       var results = db.Customers.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo }).ToList();
        return results;
}

Body:
Basically whatever u got in var type, loop on that and store it in list<> object then loop and achieve ur target.Here I m posting code for Master details.
List obj = new List();

        var orderlist = (from a in db.Order_Master
                         join b in db.UserAccounts on a.User_Id equals b.Id into abc
                         from b in abc.DefaultIfEmpty()
                         select new
                         {
                             Order_Id = a.Order_Id,
                             User_Name = b.FirstName,
                             Order_Date = a.Order_Date,
                             Tot_Qty = a.Tot_Qty,
                             Tot_Price = a.Tot_Price,
                             Order_Status = a.Order_Status,
                             Payment_Mode = a.Payment_Mode,
                             Address_Id = a.Address_Id

                         });

        List<MasterOrder> ob = new List<MasterOrder>();

        foreach (var item in orderlist)
        {

            MasterOrder clr = new MasterOrder();
            clr.Order_Id = item.Order_Id;
            clr.User_Name = item.User_Name;
            clr.Order_Date = item.Order_Date;
            clr.Tot_Qty = item.Tot_Qty;
            clr.Tot_Price = item.Tot_Price;
            clr.Order_Status = item.Order_Status;
            clr.Payment_Mode = item.Payment_Mode;
            clr.Address_Id = item.Address_Id;
            ob.Add(clr);

        }

        using(ecom_storeEntities en=new ecom_storeEntities())
        {
            var Masterlist = en.Order_Master.OrderByDescending(a => a.Order_Id).ToList();

            foreach (var i in ob)
            {
                var Child = en.Order_Child.Where(a => a.Order_Id==i.Order_Id).ToList();
                obj.Add(new OrderMasterChild
                {
                    Master = i,
                    Childs = Child
                });
            }

        }


问:
robots.txt: user-agent: Googlebot disallow: / Google still indexing
Look at the robots.txt of this site:

fr2.dk/robots.txt

The content is:

```<code>User-Agent: Googlebot
Disallow: /
</code>```

That ought to tell google not to index the site, no?

If true, why does the site appear in google searches?

答:
If you just added this, then you'll have to wait - it's not instantaenous - until Googlebot comes back to respider the site and sees the robots.txt, the site'll still be in their database.

I doubt it's relevant, but you might want to change your "Agent" to "agent" - Google's most likely not case sensitive for this, but can't hurt to follow the standard exactly.

Body:
Look at the robots.txt of this site:

fr2.dk/robots.txt

The content is:

User-Agent: Googlebot
Disallow: /

That ought to tell google not to index the site, no?

If true, why does the site appear in google searches?


问:
Is there a simple way to create user/group in alfresco at startup?
Here is alfresco-demo-data, they create user, group and some pieces of repository. But if you look a little deeper into code and examine PeopleUsersGroupAcpExporter, you see that to create some users you need:

acp archive with xml file with about 10-15 properties for one user

every user must have password hash, passwprd2 hash and salt, e.g. it is unclear how to create user with test 123 password.

create several classes: PeopleUsersGroupAcpExporter,
DynamicBootstrapPatchPostProcessor, ResourcesResolver,
UsersImporterPatch, GroupsImporterPatch with a lot of code.

And finally this classes wrap (put) some data into spring bean definition.

Definitely there are must much simpler way to create/import user and group at alfresco start up.

Note 1

Here is very similar question, but they used authenticationService, whithout telling what type it is. There is org.jbpm.security.AuthenticationService and org.alfresco.service.cmr.security.AuthenticationService but both do not have any *create* methods

Note 2

Alfresco already has a feature csv import/expport user, but it is about users only. It do not provides attaching imported users to group automatically.

答:
Yes you can here is the code</p>

```<code>if (this.authenticationService.authenticationExists(userName) == false)
{
   this.authenticationService.createAuthentication(userName, password.toCharArray());

   PropertyMap ppOne = new PropertyMap(4);
   ppOne.put(ContentModel.PROP_USERNAME, userName);
   ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
   ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
   ppOne.put(ContentModel.PROP_EMAIL, userName+"@example.com");
   ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");

   this.personService.createPerson(ppOne);
}
</code>```

Body:
Yes you can here is the code

if (this.authenticationService.authenticationExists(userName) == false)
{
   this.authenticationService.createAuthentication(userName, password.toCharArray());

   PropertyMap ppOne = new PropertyMap(4);
   ppOne.put(ContentModel.PROP_USERNAME, userName);
   ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
   ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
   ppOne.put(ContentModel.PROP_EMAIL, userName+"@example.com");
   ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");

   this.personService.createPerson(ppOne);
}