问:
Using IP address to find location in python
I'm using this python code to get the users ip address:

```<code>import socket
print socket.gethostbyname(socket.gethostname())
</code>```

and using this to find their location:

```<code>import socket
print socket.gethostbyname(socket.gethostname())
import urllib
response = urllib.urlopen('http://api.hostip.info/get_html.php?   ip=xxx&position=true').read()
print(response)
</code>```

Could someone please help me find a way to get the ip and then put it into the second part of the code.
The program should find the users ip without them doing anything and then show the location.

Thanks.

答:
I would suggest looking into the Geoip library.
it has a pretty straight forward module called geolite2.
example:

```<code>from geoip import geolite2

match = geolite2.lookup('10.10.10.10')
print('Country: '+match.country)
print('timezone: '+match.timezone)
...
</code>```

there are functions for you to use if you want too look for the host ip without user input !
it is pretty well documented here http://pythonhosted.org/python-geoip/
Hope this helps you out !

Body:
I'm using this python code to get the users ip address:

import socket
print socket.gethostbyname(socket.gethostname())

and using this to find their location:

import socket
print socket.gethostbyname(socket.gethostname())
import urllib
response = urllib.urlopen('http://api.hostip.info/get_html.php?   ip=xxx&position=true').read()
print(response)

Could someone please help me find a way to get the ip and then put it into the second part of the code.
The program should find the users ip without them doing anything and then show the location.

Thanks.

Body:
I would suggest looking into the Geoip library.
it has a pretty straight forward module called geolite2.
example:

from geoip import geolite2

match = geolite2.lookup('10.10.10.10')
print('Country: '+match.country)
print('timezone: '+match.timezone)
...

there are functions for you to use if you want too look for the host ip without user input !
it is pretty well documented here http://pythonhosted.org/python-geoip/
Hope this helps you out !


来源: stackexchange

问:
Adding lines in AWK?
Can you please help me? I need help coding the AWK, I can't get through this. Can also be a BASH solution.
Code:

```<code>1
4
7
5
5
1
4
8
3
6
</code>```

My desired output is
Code:

```<code>1 5 .2
4 5 .8
7 12 .58
5 12 .41
5 6  .83
1 6  .16
4 12 .33
8 12 .66
3 9 .5
6 9  .5
</code>```

As you can see I need to add the even and odd lines together to generate the second column. This value is kept for the 2 lines because I need to do some searching and add results up to get a percent.

After that I need to divide the value in the first column with the value of the same spot in the second column. to get the per cent.

I just can't get it done efficiently. What I'm doing right now is just getting the odd lines in a separate file from the even ones and then attaching the columns and proceeding to create an array for both files and then do the algebra. Must be a simple way with AWK that does not involve temporary files or anything like that.

Upon using dudiboy's advised piece of code on the following text file, these are the incorrect results I'm getting:

This is the list.txt file contents:

```<code>1
2
6
6
8
1
2
3
5

root@debian:/home/l0l/Documents/awk# awk 'a[NR]=$1; END {for (ln=2; ln<=NR; ln+=2){ print(a[ln], a[ln]+a[ln-1], a[ln]/a[ln-1]); print(a[ln], a[ln]+a[ln-1], a[ln-1]/a[ln]);}}' list.txt
1
2
6
6
8
1
2
3
5
2 3 2
2 3 0.5
6 12 1
6 12 1
1 9 0.125
1 9 8
3 5 1.5
3 5 0.666667
</code>```

The percent's are way off and the way that it prints it out is way off as well, will keep trying however I'd really appreciate any help with this. Please guide me step by step about the advised command?

UPDATE:
    $ awk -v fmt="%-2i %-2i %.2f\n" 'NR%2{x=$1;next} {printf fmt,     x,x+$1,x/(x+$1); printf fmt,$1,x+$1,$1/(x+$1)}' file

Is the PERFECT solution !!!! THANKS A ZILLION!! so happy! However when I try to get the output of the command into a file I get a zero divide error

```<code>root@debian:/home/l0l/Documents/bash# awk -v fmt="%-2i %-2i %.2f\n" 'NR%2{x=$1;next} {printf fmt, x,x+$1,x/(x+$1); printf fmt,$1,x+$1,$1/(x+$1)}'     results >> RESULTS2.txt
awk: cmd. line:1: (FILENAME=results FNR=648) fatal: division by zero attempted
</code>```

I'm using it on a 2000 part list of numbers and there is sometimes 2 zeros in a  row so. so it produces the second column with also a 0 and then since we are dividing by zero we get this zero divide issue. How do we prevent this? I have to keep the 0's in the file, its super important. Maybe a different way to calculate percentage?
How to get a nice output without that zero divide?
For example if the list file is now:

```<code>0
0
1
5
5
6
0
0
0
1
0
0
</code>```

We get zero divides all over. Any insight of how to prevent this?

答:
Here is a simple oneline awk example;

```<code>awk 'a[NR]=$1; END {for (ln=2; ln<=NR; ln+=2){ print(a[ln], a[ln]+a[ln-1], a[ln]/a[ln-1]); print(a[ln], a[ln]+a[ln-1], a[ln-1]/a[ln]);}}' list.1.txt
</code>```

Hope this helps, the quest was not clear.

ContentLicense: CC BY-SA 3.0

Title: Adding lines in AWK?

Body:
Can you please help me? I need help coding the AWK, I can't get through this. Can also be a BASH solution.
Code:

1
4
7
5
5
1
4
8
3
6

My desired output is
Code:

1 5 .2
4 5 .8
7 12 .58
5 12 .41
5 6  .83
1 6  .16
4 12 .33
8 12 .66
3 9 .5
6 9  .5

As you can see I need to add the even and odd lines together to generate the second column. This value is kept for the 2 lines because I need to do some searching and add results up to get a percent.

After that I need to divide the value in the first column with the value of the same spot in the second column. to get the per cent.

I just can't get it done efficiently. What I'm doing right now is just getting the odd lines in a separate file from the even ones and then attaching the columns and proceeding to create an array for both files and then do the algebra. Must be a simple way with AWK that does not involve temporary files or anything like that.

Upon using dudiboy's advised piece of code on the following text file, these are the incorrect results I'm getting:

This is the list.txt file contents:

1
2
6
6
8
1
2
3
5

root@debian:/home/l0l/Documents/awk# awk 'a[NR]=$1; END {for (ln=2; ln<=NR; ln+=2){ print(a[ln], a[ln]+a[ln-1], a[ln]/a[ln-1]); print(a[ln], a[ln]+a[ln-1], a[ln-1]/a[ln]);}}' list.txt
1
2
6
6
8
1
2
3
5
2 3 2
2 3 0.5
6 12 1
6 12 1
1 9 0.125
1 9 8
3 5 1.5
3 5 0.666667

The percent's are way off and the way that it prints it out is way off as well, will keep trying however I'd really appreciate any help with this. Please guide me step by step about the advised command?

UPDATE:
    $ awk -v fmt="%-2i %-2i %.2f\n" 'NR%2{x=$1;next} {printf fmt,     x,x+$1,x/(x+$1); printf fmt,$1,x+$1,$1/(x+$1)}' file

Is the PERFECT solution !!!! THANKS A ZILLION!! so happy! However when I try to get the output of the command into a file I get a zero divide error

root@debian:/home/l0l/Documents/bash# awk -v fmt="%-2i %-2i %.2f\n" 'NR%2{x=$1;next} {printf fmt, x,x+$1,x/(x+$1); printf fmt,$1,x+$1,$1/(x+$1)}'     results >> RESULTS2.txt
awk: cmd. line:1: (FILENAME=results FNR=648) fatal: division by zero attempted

I'm using it on a 2000 part list of numbers and there is sometimes 2 zeros in a  row so. so it produces the second column with also a 0 and then since we are dividing by zero we get this zero divide issue. How do we prevent this? I have to keep the 0's in the file, its super important. Maybe a different way to calculate percentage?
How to get a nice output without that zero divide?
For example if the list file is now:

0
0
1
5
5
6
0
0
0
1
0
0

We get zero divides all over. Any insight of how to prevent this?

Body:
Here is a simple oneline awk example;

awk 'a[NR]=$1; END {for (ln=2; ln<=NR; ln+=2){ print(a[ln], a[ln]+a[ln-1], a[ln]/a[ln-1]); print(a[ln], a[ln]+a[ln-1], a[ln-1]/a[ln]);}}' list.1.txt

Hope this helps, the quest was not clear.


问:
Create new column using condition on another existing column
I have data like this

```<code>Time    chamber
9       1
10      2
11      3
12      4
13      5
14      6
15      7
16      8
17      9
18      10
19      11
20      12
21      1
22      2
23      3
24      4
</code>```

I want to create a new column using conditions on another existing column (chamber).

It should look something like this

```<code>Time    chamber treatment
9       1       c2t2
10      2       c2t2
11      3       c0t0r
12      4       c2t2r
13      5       c2t2r
14      6       c0t0
15      7       c0t0r
16      8       c0t0r
17      9       c2t2
18      10      c2t2r
19      11      c0t0
20      12      c0t0
21      1       c2t2
22      2       c2t2
23      3       c0t0r
24      4       c2t2r
</code>```

For chambers 1,2,9:   Treatment is c2t2

For chambers 3,7,8:   Treatment is c0t0r.

For chambers 4,5,10:  Treatment is c2t2r

For chambers 6,11,12: Treatment is c0t0.

I have also made a lookup table, but I don't know how to use it:

```<code>lookup_table <- data.frame(row.names = c("1", "2", "3","4", "5", "6","7", "8", "9","10", "11", "12"),
                           new_col = c("C2T2", "C2T2", "C0T0R","C2T2R", "C2T2R", "C0T0","C0T0R", "C0T0R", "C2T2","C2T2R", "C0T0", "C0T0"),
                           stringsAsFactors = FALSE)
</code>```

答:
Assuming "dt" is your dataframe name, then you can use dplyr with case_when

```<code>library(tidyverse)
dt %>%
  mutate(newcol = case_when(dt$chamber %in% c(1, 2, 9) ~ "c2t2",
                            dt$chamber %in% c(3, 7, 8) ~ "c0t0r",
                            dt$chamber %in% c(4, 5, 10) ~ "c2t2r",
                            dt$chamber %in% c(6, 11, 12) ~ "c0t0"))
</code>```

Output:

```<code>   Time chamber newcol
1     9       1   c2t2
2    10       2   c2t2
3    11       3  c0t0r
4    12       4  c2t2r
5    13       5  c2t2r
6    14       6   c0t0
7    15       7  c0t0r
8    16       8  c0t0r
9    17       9   c2t2
10   18      10  c2t2r
11   19      11   c0t0
12   20      12   c0t0
13   21       1   c2t2
14   22       2   c2t2
15   23       3  c0t0r
16   24       4  c2t2r
>
</code>```

Body:
I have data like this

Time    chamber
9       1
10      2
11      3
12      4
13      5
14      6
15      7
16      8
17      9
18      10
19      11
20      12
21      1
22      2
23      3
24      4

I want to create a new column using conditions on another existing column (chamber).

It should look something like this

Time    chamber treatment
9       1       c2t2
10      2       c2t2
11      3       c0t0r
12      4       c2t2r
13      5       c2t2r
14      6       c0t0
15      7       c0t0r
16      8       c0t0r
17      9       c2t2
18      10      c2t2r
19      11      c0t0
20      12      c0t0
21      1       c2t2
22      2       c2t2
23      3       c0t0r
24      4       c2t2r

For chambers 1,2,9:   Treatment is c2t2

For chambers 3,7,8:   Treatment is c0t0r.

For chambers 4,5,10:  Treatment is c2t2r

For chambers 6,11,12: Treatment is c0t0.

I have also made a lookup table, but I don't know how to use it:

lookup_table <- data.frame(row.names = c("1", "2", "3","4", "5", "6","7", "8", "9","10", "11", "12"),
                           new_col = c("C2T2", "C2T2", "C0T0R","C2T2R", "C2T2R", "C0T0","C0T0R", "C0T0R", "C2T2","C2T2R", "C0T0", "C0T0"),
                           stringsAsFactors = FALSE)

Body:
Assuming "dt" is your dataframe name, then you can use dplyr with case_when

library(tidyverse)
dt %>%
  mutate(newcol = case_when(dt$chamber %in% c(1, 2, 9) ~ "c2t2",
                            dt$chamber %in% c(3, 7, 8) ~ "c0t0r",
                            dt$chamber %in% c(4, 5, 10) ~ "c2t2r",
                            dt$chamber %in% c(6, 11, 12) ~ "c0t0"))

Output:

   Time chamber newcol
1     9       1   c2t2
2    10       2   c2t2
3    11       3  c0t0r
4    12       4  c2t2r
5    13       5  c2t2r
6    14       6   c0t0
7    15       7  c0t0r
8    16       8  c0t0r
9    17       9   c2t2
10   18      10  c2t2r
11   19      11   c0t0
12   20      12   c0t0
13   21       1   c2t2
14   22       2   c2t2
15   23       3  c0t0r
16   24       4  c2t2r
>


问:
Why VueJs introduce .native Event modifier ? What are the use case of this? - Vue.js
I din't get any docs for native event modifiers. I have seen some where like this:

```<code><router-link @click.native="pressThis()"> Press here </router-link>
</code>```

what is the use of native modifier on router-link click event.
and what other use case native modifier can have ?

答:
You can override Vue events in custom components. For instance, you might have a list component that once you click an item you call this.$emit('click', selectedItemData), and that will emit the click event to the parent component that is watching that.

However, sometimes you really want to bind to the native HTML/DOM event listener element.addEventListener('click', callThisMethod), and that's the use of .native. Also, make a note that it will handle cleaning the event listener once your component gets destroyed just like a non-native event.

In sum: use .native when you need the 'raw' event from DOM.

ContentLicense: CC BY-SA 4.0

Body:
I din't get any docs for native event modifiers. I have seen some where like this:

<router-link @click.native="pressThis()"> Press here </router-link>

what is the use of native modifier on router-link click event.
and what other use case native modifier can have ?


问:
Web service to return image from SQL Server database
Firstly let me tell you that I am a DBA who is trying to cross skill into the world of web development and I'm pretty new to all this and learning as I go.

I have a SQL Server database which has a table that stores images of staff members.

I am currently updating some sales reports in SSRS and on each report will be an image of the sales manager.

What I want to do is create a web service which will accept a staff ID integer as a parameter and return a resized version of the image.

So the image url on the report will be something like http://photoserver.com/getphoto?id=123456

So some sort of . Net C# code to do this.

I know there are other ways to achieve this, but I really want to learn how to develop these kind of simple Web services.

Thanks

答:
I did this recently for PowerBI using an Azure Function.  Using IIS on-prem and SSRS would be largely the same code:

```<code>#r "System.Configuration"
#r "System.Data"

using System.Net;
using System.Net.Http.Headers;
using System.Data.SqlClient;
using System.IO;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string productStr = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "ProductId", true) == 0)
        .Value;

    int productId = int.Parse(productStr);

    string constr = "server=someserver.database.windows.net;database=databasename;user id=imageViererUser;Password=password";

    using (var con = new SqlConnection(constr))
    {

        await con.OpenAsync();
        log.Info("Connection Open.");

        var sql = @"
        select ThumbnailPhoto
        from SalesLT.Product
        where ProductId = @productId
        ";

        var cmd = new SqlCommand(sql, con);

        cmd.Parameters.Add(new SqlParameter("@productId", productId));

        var buf = new MemoryStream();

        using (var rdr = await cmd.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess))
        {
            if (!rdr.Read())
            {
                return req.CreateResponse(HttpStatusCode.NotFound);
            }
            var stream = rdr.GetStream(0);

            var resp = req.CreateResponse(HttpStatusCode.OK);

            await stream.CopyToAsync(buf);
            buf.Position = 0;

            log.Info($"Image Read {buf.Length} bytes");

            resp.Content = new StreamContent(buf);

            resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");

            return resp;

        }
    }

}
</code>```

Then you’ll get a url for image retrieval like this:

https://yourfunction.azurewebsites.net/api/HttpTriggerCSharp1?code=E0Xw32IKcJadkr6OmhzUVoEaLXpQLDgsA0WerH3EcaOL7yKhDKiyg==&ProductId=952

Then you can add a calculated column to the Product table in your PowerBI model like thise:

ProductImageUrl = "https://yourfunction.azurewebsites.net/api/HttpTriggerCSharp1?code=E0Xw32IKcJadkr6OmhzUVoEaLXpQLDgsA0WerH3EcaOL7yKhDKiyg==&ProductId=" & 'SalesLT Product'[ProductID]

Body:
I did this recently for PowerBI using an Azure Function.  Using IIS on-prem and SSRS would be largely the same code:

#r "System.Configuration"
#r "System.Data"

using System.Net;
using System.Net.Http.Headers;
using System.Data.SqlClient;
using System.IO;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string productStr = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "ProductId", true) == 0)
        .Value;

    int productId = int.Parse(productStr);

    string constr = "server=someserver.database.windows.net;database=databasename;user id=imageViererUser;Password=password";

    using (var con = new SqlConnection(constr))
    {

        await con.OpenAsync();
        log.Info("Connection Open.");

        var sql = @"
        select ThumbnailPhoto
        from SalesLT.Product
        where ProductId = @productId
        ";

        var cmd = new SqlCommand(sql, con);

        cmd.Parameters.Add(new SqlParameter("@productId", productId));

        var buf = new MemoryStream();

        using (var rdr = await cmd.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess))
        {
            if (!rdr.Read())
            {
                return req.CreateResponse(HttpStatusCode.NotFound);
            }
            var stream = rdr.GetStream(0);

            var resp = req.CreateResponse(HttpStatusCode.OK);

            await stream.CopyToAsync(buf);
            buf.Position = 0;

            log.Info($"Image Read {buf.Length} bytes");

            resp.Content = new StreamContent(buf);

            resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");

            return resp;

        }
    }

}

Then you’ll get a url for image retrieval like this:

https://yourfunction.azurewebsites.net/api/HttpTriggerCSharp1?code=E0Xw32IKcJadkr6OmhzUVoEaLXpQLDgsA0WerH3EcaOL7yKhDKiyg==&ProductId=952

Then you can add a calculated column to the Product table in your PowerBI model like thise:

ProductImageUrl = "https://yourfunction.azurewebsites.net/api/HttpTriggerCSharp1?code=E0Xw32IKcJadkr6OmhzUVoEaLXpQLDgsA0WerH3EcaOL7yKhDKiyg==&ProductId=" & 'SalesLT Product'[ProductID]


问:
Where to start debugging, when you get the "Activity is not responding, Force Close, Wait"?
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

```<code>//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
</code>```

答:
Are you doing network connections on the main thread? Or Time.sleep()'s. Or extremely long running calculations?

Something in your app's main thread is taking more than 5 (or is it 10?) seconds to complete.

Body:
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}

ContentLicense: CC BY-SA 2.5


问:
Issue forEach JS array
Here is my code JS :

```<code>var items = [255, 255, 255, 255];
items.forEach(function(item) {
    if (item = 255) {
        item = 0;
    };
});
console.log(items)
</code>```

In console.log I get [255, 255, 255, 255], why it doesn't change to [0, 0, 0, 0]? What am I doing wrong?

答:
You could take the reference to the array for changing the value inside of the callback for Array#forEach.

BTW, after a block statement, there is no need for a semicolon.

var items = [255, 255, 255, 255];

items.forEach(function(item, index, array) {
//                                  ^^^^^
    if (item = 255) {
        array[index] = 0;
    }
//   ^ no semicolon needed
});

console.log(items);```

Title: Issue forEach JS array

Body:
Here is my code JS :

var items = [255, 255, 255, 255];
items.forEach(function(item) {
    if (item = 255) {
        item = 0;
    };
});
console.log(items)

In console.log I get [255, 255, 255, 255], why it doesn't change to [0, 0, 0, 0]? What am I doing wrong?


问:
View HTML content after Login
I have an index.php page.
The user just connects to the page has a form to login.
Once logged in, always display on the same page "Welcome User234, you are logged in. Logout?"

```<code><?php if(isset($_SESSION['user_info']) && is_array($_SESSION['user_info'])) { ?>

    <form id="login-form" class="login-form" name="form1">

        <div id="form-content">
            <div class="welcome">
                <?php echo $_SESSION['user_info']['name']  ?>, you are logged in.
                <br /><br />
                <?php echo $_SESSION['user_info']['content']  ?>
                <br /><br />
                <a href="index.php?ac=logout" style="color:#3ec038">Logout</a>
            </div>
        </div>

    </form>
</code>```

You can see here: http://demo.phpjabbers.com/freescripts/php-user-login/index.php (email: demo1@demo.com, password: pass)

Okay, now I want add my table (http://vulpinelab.online/TabellaExcel/) after the login of the User (each user will see a different table, for example user1 can view only /TabellaExcel, user2 can view only /TabellaExcel2..)

Is there a method to insert the table file in the index.php?

Or there is a method to make the page /TabellaExcel protected by the previous login for each user?

What is the best method and how canI do it?

答:
You can make a tableID session variable which is extracted at the time of login from the database for each registered user in an auto_increment manner or however you prefer. According to that unique id variable, you can add the view of different tables for different users.

Suppose, the tableID for user1 is '1', then he will see "/TabellaExcel1" or whatever and for user2 with tableID '2', he can view "/TabellaExcel".$_SESSION['tableID'] (which is 2) thus /TabellaExcel2.You can make use of this method and remember that it isn't necessary to use alternate integers as tableID, for protection they should be unique but random.

Title: View HTML content after Login

Body:
I have an index.php page.
The user just connects to the page has a form to login.
Once logged in, always display on the same page "Welcome User234, you are logged in. Logout?"

<?php if(isset($_SESSION['user_info']) && is_array($_SESSION['user_info'])) { ?>

    <form id="login-form" class="login-form" name="form1">

                <?php echo $_SESSION['user_info']['name']  ?>, you are logged in.

                <?php echo $_SESSION['user_info']['content']  ?>

                Logout

    </form>

You can see here: http://demo.phpjabbers.com/freescripts/php-user-login/index.php (email: demo1@demo.com, password: pass)

Okay, now I want add my table (http://vulpinelab.online/TabellaExcel/) after the login of the User (each user will see a different table, for example user1 can view only /TabellaExcel, user2 can view only /TabellaExcel2..)

Is there a method to insert the table file in the index.php?

Or there is a method to make the page /TabellaExcel protected by the previous login for each user?

What is the best method and how canI do it?


问:
How to share code between TypeScript projects?
Let's say I have two projects with following file structure

```<code>/my-projects/

  /project-a/
    lib.ts
    app.ts
    tsconfig.json

  /project-b/
    app.ts         // import '../project-a/lib.ts'
    tsconfig.json
</code>```

I want to consume lib.ts located in project-a also from project-b. How to do that?

Release it as NPM module - absolutely don't want that, it's an overkill for such a simple use case. I just
want to share one file between two projects.

Use import '../project-a/lib.ts' - doesn't work, TypeScript complains

'lib.ts' is not under 'rootDir'. 'rootDir' is expected to contain all source files.

Put tsconfig.json one level up so it would cover both project-a and project-b - can't do that, the TypeScript config is slightly different for those projects. Also it's not very convenient, don't want to do that.

Any other ways?

答:
In a similar scenario, where I also wanted to avoid the overhead of having to perform an NPM release, I went for the following structure (after lots of trial and error and failed attempts):

```<code>/my-projects/

  /node_modules/
    /my-lib/
      lib.ts
      tsconfig.json
      package.json

  /project-a/
    app.ts
    tsconfig.json

  /project-b/
    app.ts
    tsconfig.json
</code>```

The central idea is to move the shared stuff to a node_modules directory above the individual projects (this exploits NPMs loading mechanism, which would start looking for dependencies in the current directory and then move upwards).

So, project-a and project-b can now access the lib simply via import { Whatever } from 'my-lib'.

Notes:

In my case, my-lib is actually only for shared typings (i.e. .d.ts files within a lib subdirectory). This means, I do not explicitly need to build my-lib and my my-lib/package.json looks as follows:

```<code>{
  "name": "my-types",
  "version": "0.0.0",
  "private": true,
  "types": "lib/index"
}
</code>```

In case my-lib contains runnable code, you’ll obviously need to build my-lib, so that .js files are generated, and add a "main" property to the package.json which exposes the main .js file.

Most important: Despite its name, /my-projects/node_modules only contains custom code, no installed dependencies (they are actually in the individual projects project-a/node_modules and project-b/node_modules). This means, there’s an explicit git ignore setting, which un-ignores the /node_modules directory from being committed.

Is this a clean solution? Probably not not. Did it solve my issue? Yes. Am I happy to hear about improvement suggestions? Absolutely!

Body:
Let's say I have two projects with following file structure

/my-projects/

  /project-a/
    lib.ts
    app.ts
    tsconfig.json

  /project-b/
    app.ts         // import '../project-a/lib.ts'
    tsconfig.json

I want to consume lib.ts located in project-a also from project-b. How to do that?

Release it as NPM module - absolutely don't want that, it's an overkill for such a simple use case. I just
want to share one file between two projects.

Use import '../project-a/lib.ts' - doesn't work, TypeScript complains

'lib.ts' is not under 'rootDir'. 'rootDir' is expected to contain all source files.

Put tsconfig.json one level up so it would cover both project-a and project-b - can't do that, the TypeScript config is slightly different for those projects. Also it's not very convenient, don't want to do that.

Any other ways?

Body:
In a similar scenario, where I also wanted to avoid the overhead of having to perform an NPM release, I went for the following structure (after lots of trial and error and failed attempts):

/my-projects/

  /node_modules/
    /my-lib/
      lib.ts
      tsconfig.json
      package.json

  /project-a/
    app.ts
    tsconfig.json

  /project-b/
    app.ts
    tsconfig.json

The central idea is to move the shared stuff to a node_modules directory above the individual projects (this exploits NPMs loading mechanism, which would start looking for dependencies in the current directory and then move upwards).

So, project-a and project-b can now access the lib simply via import { Whatever } from 'my-lib'.

Notes:

In my case, my-lib is actually only for shared typings (i.e. .d.ts files within a lib subdirectory). This means, I do not explicitly need to build my-lib and my my-lib/package.json looks as follows:

{
  "name": "my-types",
  "version": "0.0.0",
  "private": true,
  "types": "lib/index"
}

In case my-lib contains runnable code, you’ll obviously need to build my-lib, so that .js files are generated, and add a "main" property to the package.json which exposes the main .js file.

Most important: Despite its name, /my-projects/node_modules only contains custom code, no installed dependencies (they are actually in the individual projects project-a/node_modules and project-b/node_modules). This means, there’s an explicit git ignore setting, which un-ignores the /node_modules directory from being committed.

Is this a clean solution? Probably not not. Did it solve my issue? Yes. Am I happy to hear about improvement suggestions? Absolutely!


问:
Unable to fetch data by checking if one list is equal to other list in django
I am new to Django and I am trying to fetch records from the table UserBookmark where tag is equal to category.

My code is as follows:

views.py:

```<code>def home(request):

    category=Category.objects.values_list('category',flat = True).filter(user=request.user.pk)
    category = list(category)
    print category
    bookmarks = UserBookmark.objects.filter(tag__name__in = category)
    print bookmarks
    return render(request,'home.html',{'bookmarks':bookmarks})
</code>```

models.py:

```<code>class Category(models.Model):

    user = models.ForeignKey(User)
    category= models.CharField(max_length=100)

    def __str__(self):
        return '%s %s'%(self.user,self.category)

class UserBookmark(models.Model):

    user = models.ForeignKey(User)
    bookmark = models.URLField()
    tag = TaggableManager()

    def __str__(self):
        return '%i %s %s'%(self.id,self.user,self.bookmark)
</code>```

But when I print bookmarks in views.py , I get an empty set.I tried printing category as well , it gives :

```<code>u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"]
</code>```

And when I try this in shell:

```<code>UserBookmark.objects.filter(tag__name__in = [u'Data Science', u'Python', u'Android', u'Data Analytics'])
</code>```

I do get a resultset

```<code><QuerySet [<UserBookmark: 24 user12 https://github.com/shreyag12?tab=stars>, <UserBookmark: 24 user12 https://github.com/swapnil?tab=stars>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 27 user14 https://github.com/sunny2krGupta/Bigquery-series>, <UserBookmark: 28 user14 https://github.com/ctfs/write-ups-2017>]>
</code>```

Can someone guide me in this?

答:
I solved this issue by converting category which looked like this

```<code> u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"]
</code>```

category2=ast.literal_eval(category[0])

category2 [u'Data Science', u'Python', u'Android', u'Data Analytics']and

then using bookmarks = UserBookmark.objects.filter(tag__name__in = category2)

It worked!

Body:
I am new to Django and I am trying to fetch records from the table UserBookmark where tag is equal to category.

My code is as follows:

views.py:

def home(request):

    category=Category.objects.values_list('category',flat = True).filter(user=request.user.pk)
    category = list(category)
    print category
    bookmarks = UserBookmark.objects.filter(tag__name__in = category)
    print bookmarks
    return render(request,'home.html',{'bookmarks':bookmarks})

models.py:

class Category(models.Model):

    user = models.ForeignKey(User)
    category= models.CharField(max_length=100)

    def __str__(self):
        return '%s %s'%(self.user,self.category)

class UserBookmark(models.Model):

    user = models.ForeignKey(User)
    bookmark = models.URLField()
    tag = TaggableManager()

    def __str__(self):
        return '%i %s %s'%(self.id,self.user,self.bookmark)

But when I print bookmarks in views.py , I get an empty set.I tried printing category as well , it gives :

u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"]

And when I try this in shell:

UserBookmark.objects.filter(tag__name__in = [u'Data Science', u'Python', u'Android', u'Data Analytics'])

I do get a resultset

<QuerySet [<UserBookmark: 24 user12 https://github.com/shreyag12?tab=stars>, <UserBookmark: 24 user12 https://github.com/swapnil?tab=stars>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 27 user14 https://github.com/sunny2krGupta/Bigquery-series>, <UserBookmark: 28 user14 https://github.com/ctfs/write-ups-2017>]>

Can someone guide me in this?

Body:
I solved this issue by converting category which looked like this

 u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"]

category2=ast.literal_eval(category[0])

category2 [u'Data Science', u'Python', u'Android', u'Data Analytics']and

then using bookmarks = UserBookmark.objects.filter(tag__name__in = category2)

It worked!


问:
can we use couchdb for web application development?
I was wondering whether we can use java script for application development and use couchdb to serve it. I was also imagining jquery as the java script library. Do you think this is possible?</p>

答:
Check out using CouchApp. CouchApp allows you to build your application in JavaScript and host it out of CouchDB. Its a great way to learn CouchDB and its a very rapid development environment.

CouchApp


问:
Mistake in like SQL Server with Arabic language
There is a database and in it a data table contains lots of values in Arabic language. When I use like, I get a wrong answer.

Code that I used

```<code>Select *
From customers
Where cusname like ''%جديد%
</code>```

But kindly note the data already contains the values

答:
Use the Unicode prefix (N)</p>

```<code>Select * from customer where cusname like N'%جديد٪'
</code>```

Body:
There is a database and in it a data table contains lots of values in Arabic language. When I use like, I get a wrong answer.

Code that I used

Select *
From customers
Where cusname like ''%جديد%

But kindly note the data already contains the values

Body:
Use the Unicode prefix (N)

Select * from customer where cusname like N'%جديد٪'


问:
Cannot download file in R - status 503
I'm trying to download file:

```<code>> URL <- "https://www.bitmarket.pl/graphs/BTCPLN/90m.json"
> download.file(URL, destfile = "res.json", method = "curl")
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  4676    0  4676    0     0  56930          0 --:--:-- --:--:-- --:--:-- 57024
</code>```

but it returns 503 status. Whole output:

```<code><!DOCTYPE HTML>
<html lang="en-US">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
  <meta name="robots" content="noindex, nofollow" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>Just a moment...</title>
  <style type="text/css">
    html, body {width: 100%; height: 100%; margin: 0; padding: 0;}
    body {background-color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 100%;}
    h1 {font-size: 1.5em; color: #404040; text-align: center;}
    p {font-size: 1em; color: #404040; text-align: center; margin: 10px 0 0 0;}
    #spinner {margin: 0 auto 30px auto; display: block;}
    .attribution {margin-top: 20px;}
    @-webkit-keyframes bubbles { 33%: { -webkit-transform: translateY(10px); transform: translateY(10px); } 66% { -webkit-transform: translateY(-10px); transform: translateY(-10px); } 100% { -webkit-transform: translateY(0); transform: translateY(0); } }
    @keyframes bubbles { 33%: { -webkit-transform: translateY(10px); transform: translateY(10px); } 66% { -webkit-transform: translateY(-10px); transform: translateY(-10px); } 100% { -webkit-transform: translateY(0); transform: translateY(0); } }
    .bubbles { background-color: #404040; width:15px; height: 15px; margin:2px; border-radius:100%; -webkit-animation:bubbles 0.6s 0.07s infinite ease-in-out; animation:bubbles 0.6s 0.07s infinite ease-in-out; -webkit-animation-fill-mode:both; animation-fill-mode:both; display:inline-block; }
  </style>

    <script type="text/javascript">
  //<![CDATA[
  (function(){
    var a = function() {try{return !!window.addEventListener} catch(e) {return !1} },
    b = function(b, c) {a() ? document.addEventListener("DOMContentLoaded", b, c) : document.attachEvent("onreadystatechange", b)};
    b(function(){
      var a = document.getElementById('cf-content');a.style.display = 'block';
      setTimeout(function(){
        var s,t,o,p,b,r,e,a,k,i,n,g,f, eoQNdpG={"GwwAAtfX":+((+!![]+[])+(+!![]))};
        t = document.createElement('div');
        t.innerHTML="<a href='/'>x</a>";
        t = t.firstChild.href;r = t.match(/https?:\/\//)[0];
        t = t.substr(r.length); t = t.substr(0,t.length-1);
        a = document.getElementById('jschl-answer');
        f = document.getElementById('challenge-form');
        ;eoQNdpG.GwwAAtfX+=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]));eoQNdpG.GwwAAtfX*=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));eoQNdpG.GwwAAtfX-=+((!+[]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));eoQNdpG.GwwAAtfX-=+((+!![]+[])+(+[]));eoQNdpG.GwwAAtfX-=+((+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));eoQNdpG.GwwAAtfX+=+((!+[]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));eoQNdpG.GwwAAtfX+=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));eoQNdpG.GwwAAtfX*=+((!+[]+!![]+!![]+[])+(!+[]+!![]+!![]));a.value = parseInt(eoQNdpG.GwwAAtfX, 10) + t.length; '; 121'
        f.action += location.hash;
        f.submit();
      }, 4000);
    }, false);
  })();
  //]]>
</script>

</head>
<body>
  <table width="100%" height="100%" cellpadding="20">
    <tr>
      <td align="center" valign="middle">
          <div class="cf-browser-verification cf-im-under-attack">
  <noscript><h1 data-translate="turn_on_js" style="color:#bd2426;">Please turn JavaScript on and reload the page.</h1></noscript>
  <div id="cf-content" style="display:none">

    <div>
      <div class="bubbles"></div>
      <div class="bubbles"></div>
      <div class="bubbles"></div>
    </div>
    <h1><span data-translate="checking_browser">Checking your browser before accessing</span> bitmarket.pl.</h1>

    <p data-translate="process_is_automatic">This process is automatic. Your browser will redirect to your requested content shortly.</p>
    <p data-translate="allow_5_secs">Please allow up to 5 seconds…</p>
  </div>

  <form id="challenge-form" action="/cdn-cgi/l/chk_jschl" method="get">
    <input type="hidden" name="jschl_vc" value="51a7cb71596dbf54fdd307c1e65de941"/>
    <input type="hidden" name="pass" value="1512824604.589-Uwtm9TfzWe"/>
    <input type="hidden" id="jschl-answer" name="jschl_answer"/>
  </form>
</div>

          <div class="attribution">
            <a href="https://www.cloudflare.com/5xx-error-landing?utm_source=iuam" target="_blank" style="font-size: 12px;">DDoS protection by Cloudflare</a>
            <br>
            Ray ID: 3ca829f9aed06afb
          </div>
      </td>

    </tr>
  </table>
</body>
</html>
</code>```

wget does not work too:

```<code>--2017-12-09 14:01:29--  https://www.bitmarket.pl/graphs/BTCPLN/90m.json
Resolving www.bitmarket.pl... 104.20.67.184, 104.20.68.184
Connecting to www.bitmarket.pl|104.20.67.184|:443... connected.
HTTP request sent, awaiting response... 503 Service Temporarily Unavailable
2017-12-09 14:01:29 ERROR 503: Service Temporarily Unavailable.
</code>```

But when you go to this link: https://www.bitmarket.pl/graphs/BTCPLN/90m.json your web browser will return correct json file. Any ideas why it does not work?

答:
That's because the page is using a DDoS protection service. On the first load, the page itself does a JavaScript-initiated redirect after 5 seconds to fetch the final content so the process fails with tools like wget/curl which do not interpret JavaScript. If you think that it is justifiable to do so, then one option would be to use for example phantomjs and supply a custom script (say, save.js):

```<code>var system = require('system');
var page = require('webpage').create();

page.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5';

page.open(system.args[1], function(){
    setTimeout(function(){
        console.log(page.evaluate(function(){
            //gets the JSON from the first ``` element rendered on the page
            return document.getElementsByTagName('pre')[0].textContent;
        }));
        phantom.exit();
    }, 6000); //waits 6 seconds for the page to reload
});
```

<p>and then use it instead of <code>wget</code> as:</p>

```phantomjs save.js https://www.bitmarket.pl/graphs/BTCPLN/90m.json
```

Title: Cannot download file in R - status 503

Body:
I'm trying to download file:

> URL <- "https://www.bitmarket.pl/graphs/BTCPLN/90m.json"
> download.file(URL, destfile = "res.json", method = "curl")
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  4676    0  4676    0     0  56930          0 --:--:-- --:--:-- --:--:-- 57024

but it returns 503 status. Whole output:

<!DOCTYPE HTML>

  <meta charset="UTF-8" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
  <meta name="robots" content="noindex, nofollow" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>Just a moment...</title>

Please turn JavaScript on and reload the page.

Checking your browser before accessing bitmarket.pl.

This process is automatic. Your browser will redirect to your requested content shortly.

Please allow up to 5 seconds…

  <form id="challenge-form" action="/cdn-cgi/l/chk_jschl" method="get">
    <input type="hidden" name="jschl_vc" value="51a7cb71596dbf54fdd307c1e65de941"/>
    <input type="hidden" name="pass" value="1512824604.589-Uwtm9TfzWe"/>
    <input type="hidden" id="jschl-answer" name="jschl_answer"/>
  </form>

            DDoS protection by Cloudflare

            Ray ID: 3ca829f9aed06afb

wget does not work too:

--2017-12-09 14:01:29--  https://www.bitmarket.pl/graphs/BTCPLN/90m.json
Resolving www.bitmarket.pl... 104.20.67.184, 104.20.68.184
Connecting to www.bitmarket.pl|104.20.67.184|:443... connected.
HTTP request sent, awaiting response... 503 Service Temporarily Unavailable
2017-12-09 14:01:29 ERROR 503: Service Temporarily Unavailable.

But when you go to this link: https://www.bitmarket.pl/graphs/BTCPLN/90m.json your web browser will return correct json file. Any ideas why it does not work?

Body:
That's because the page is using a DDoS protection service. On the first load, the page itself does a JavaScript-initiated redirect after 5 seconds to fetch the final content so the process fails with tools like wget/curl which do not interpret JavaScript. If you think that it is justifiable to do so, then one option would be to use for example phantomjs and supply a custom script (say, save.js):

var system = require('system');
var page = require('webpage').create();

page.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5';

page.open(system.args[1], function(){
    setTimeout(function(){
        console.log(page.evaluate(function(){
            //gets the JSON from the first <pre> element rendered on the page
            return document.getElementsByTagName('pre')[0].textContent;
        }));
        phantom.exit();
    }, 6000); //waits 6 seconds for the page to reload
});

and then use it instead of wget as:

phantomjs save.js https://www.bitmarket.pl/graphs/BTCPLN/90m.json


问:
Running program with asan does not use rpath
I am compiling my application which consist of a binary and some dynamic libraries. My makefile uses

```<code>LDFLAGS=-Wl,-rpath='$$ORIGIN/../lib',-rpath=/opt/suse/lib64,--disable-new-dtags
</code>```

For my normal build without asan this works so that all libraries (directly linked and dynamically loaded) are first searched in ../lib during runtime.

When I use asan with -fsanitize=address for both CXXFLAGS and LDFLAGS, ld does not use rpath anymore for searching the dynamically loaded (dlopen) libraries.

```<code>echo $LD_LIBRARY_PATH
:/EDI_TOOLS/ORACLE/client:/home1/conic/Trafo/program/UmsetzerV19
</code>```

strace output:

```<code>open("tls/x86_64/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("tls/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("x86_64/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/EDI_TOOLS/ORACLE/client/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/home1/conic/Trafo/program/UmsetzerV19/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/lib64/gcc/x86_64-suse-linux/5/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY)      = 4
fstat(4, {st_mode=S_IFREG|0644, st_size=83482, ...}) = 0
</code>```

objdump -x gives this output (amongst much more, but rpath is set correctly). All libs in NEEDED are found correctly.

```<code>Dynamic Section:
  NEEDED               libasan.so.2
  NEEDED               libKernel.so
  NEEDED               libCUtil.so
  NEEDED               libApi.so
  NEEDED               libactivemq-cpp.so.19
  NEEDED               libnorm.so
  NEEDED               libcurl.so.4
  NEEDED               libcurlpp.so.0
  NEEDED               libutilspp.so.0
  NEEDED               libtdsodbc.so.0
  NEEDED               libicuuc.so.58
  NEEDED               libicui18n.so.58
  NEEDED               libxerces-c-3.1.so
  NEEDED               libxalan-c.so.111
  NEEDED               libldap60.so
  NEEDED               libclntsh.so.12.1
  NEEDED               libuuid.so.1
  NEEDED               libz.so.1
  NEEDED               libdl.so.2
  NEEDED               libstdc++.so.6
  NEEDED               libm.so.6
  NEEDED               libgcc_s.so.1
  NEEDED               libpthread.so.0
  NEEDED               libc.so.6
  RPATH                $ORIGIN/../lib:/opt/suse/lib64
</code>```

I am using SLES 11 with

```<code>g++-5 (SUSE Linux) 5.3.1 20160301 [gcc-5-branch revision 233849]
GNU ld (GNU Binutils; SUSE Linux Enterprise 11) 2.25.0
ld.so-1.7.0
</code>```

Am I missing something?

答: It seems that the ASAN wrapper around dlopen() changes its behaviour. Looks like the following bug: https://bugzilla.redhat.com/show_bug.cgi?id=1449604

Body:
I am compiling my application which consist of a binary and some dynamic libraries. My makefile uses

LDFLAGS=-Wl,-rpath='$$ORIGIN/../lib',-rpath=/opt/suse/lib64,--disable-new-dtags

For my normal build without asan this works so that all libraries (directly linked and dynamically loaded) are first searched in ../lib during runtime.

When I use asan with -fsanitize=address for both CXXFLAGS and LDFLAGS, ld does not use rpath anymore for searching the dynamically loaded (dlopen) libraries.

echo $LD_LIBRARY_PATH
:/EDI_TOOLS/ORACLE/client:/home1/conic/Trafo/program/UmsetzerV19

strace output:

open("tls/x86_64/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("tls/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("x86_64/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/EDI_TOOLS/ORACLE/client/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/home1/conic/Trafo/program/UmsetzerV19/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/lib64/gcc/x86_64-suse-linux/5/Consumer_EndTransaction.so", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY)      = 4
fstat(4, {st_mode=S_IFREG|0644, st_size=83482, ...}) = 0

objdump -x gives this output (amongst much more, but rpath is set correctly). All libs in NEEDED are found correctly.

Dynamic Section:
  NEEDED               libasan.so.2
  NEEDED               libKernel.so
  NEEDED               libCUtil.so
  NEEDED               libApi.so
  NEEDED               libactivemq-cpp.so.19
  NEEDED               libnorm.so
  NEEDED               libcurl.so.4
  NEEDED               libcurlpp.so.0
  NEEDED               libutilspp.so.0
  NEEDED               libtdsodbc.so.0
  NEEDED               libicuuc.so.58
  NEEDED               libicui18n.so.58
  NEEDED               libxerces-c-3.1.so
  NEEDED               libxalan-c.so.111
  NEEDED               libldap60.so
  NEEDED               libclntsh.so.12.1
  NEEDED               libuuid.so.1
  NEEDED               libz.so.1
  NEEDED               libdl.so.2
  NEEDED               libstdc++.so.6
  NEEDED               libm.so.6
  NEEDED               libgcc_s.so.1
  NEEDED               libpthread.so.0
  NEEDED               libc.so.6
  RPATH                $ORIGIN/../lib:/opt/suse/lib64

I am using SLES 11 with

g++-5 (SUSE Linux) 5.3.1 20160301 [gcc-5-branch revision 233849]
GNU ld (GNU Binutils; SUSE Linux Enterprise 11) 2.25.0
ld.so-1.7.0

Am I missing something?


问:
Show pdf inside silverlight application. PDF to XAML
I need to create silverlight application where customer will see some pdf files.
PDF files have to be inside silverlight control and not rendered as images (customer wants to select text)

For this purposes i need some free libriaries or code to convert pdf file to xaml (or just open pdf so i can convert it to xaml).

Which library can read pdf and help me to convert data to xaml?
Can I read somehow pdf file and write custom convertation tool?

I saw iTextSharp. Is this library can read pdf and help me with my issue?

I will be thankfull for any ideas or links.

答:
I make use of the Acrobat Reader plugin to do the displaying for me.  It does require a different method depending on whether your application is running inside or outside the browser (I check if the application is running inside the browser and change the means of display accordingly). If running inside the browser, I overlay the application with an IFrame, as I describe in this article: http://www.silverlightshow.net/items/Building-a-Silverlight-Line-Of-Business-Application-Part-6.aspx. Otherwise, I use the WebBrowser control. I have a control which does this all for you in the source code that accompanies my book, which is downloadable from the Apress website here: http://www.apress.com/9781430272076/.

Hope this helps...

Chris


问:
Using awk to extract lines between patterns
I am trying to use awk to extract lines between two patterns, but as the second pattern involves multiple $$$$ sign I do not manage to protect properly the $

input is:

```<code>Name1
iii
iii
$$$$

Name2
ii
ooo
ppp
$$$$

Name3
pp
oo
ii
uu
$$$$
</code>```

desired output

```<code>Name2
ii
ooo
ppp
$$$$
</code>```

I tried something like this:

```<code>awk 'BEGIN {RS="\\$\\$\\$\\$\n"; FS="\n"} $1==Name2 {print $0; print "$$$$"}' inputfile
</code>```

I also tried something like

```<code>awk '/^Name2/,/\\$\\$\\$\\$\\/' input
</code>```

I tried many different protection of $ but i do it wrong, either nothing is printed or it prints the entire file

Many thanks for suggestions

答:
you don't have to use patterns if you're looking for a literal match

```<code>awk '$0=="Name2",$0=="$$$$"' file
</code>```

will extract the lines between the two literals.  Or a combination if the first match is a pattern

```<code>awk '/Name2/,$0=="$$$$"' file
</code>```

Body:
I am trying to use awk to extract lines between two patterns, but as the second pattern involves multiple $$$$ sign I do not manage to protect properly the $

input is:

Name1
iii
iii
$$$$

Name2
ii
ooo
ppp
$$$$

Name3
pp
oo
ii
uu
$$$$

desired output

Name2
ii
ooo
ppp
$$$$

I tried something like this:

awk 'BEGIN {RS="\\$\\$\\$\\$\n"; FS="\n"} $1==Name2 {print $0; print "$$$$"}' inputfile

I also tried something like

awk '/^Name2/,/\\$\\$\\$\\$\\/' input

I tried many different protection of $ but i do it wrong, either nothing is printed or it prints the entire file

Many thanks for suggestions

Body:
you don't have to use patterns if you're looking for a literal match

awk '$0=="Name2",$0=="$$$$"' file

will extract the lines between the two literals.  Or a combination if the first match is a pattern

awk '/Name2/,$0=="$$$$"' file


问:
How to address multidimensional json array in Python
I have a following context received from a query in Python script (an example):

{
    "active": false,
    "owner": "user1",
    "content": [
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]
      }
    ]
  }

making this to json array works without errors:

```<code>data = json.loads(*string_above*)
</code>```

as a result this works ok:

```<code>print data["owner"]
</code>```

user1

also this is ok:

```<code>print data["content"]
</code>```

[
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]}

Now my problem is how can I make this a multidimensional array?

E.g. command

```<code>print data["content"]["record"]
</code>```

gives an error:

TypeError: list indices must be integers, not str

what I was hoping to get is:

{
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }

Found many different comments on this kind of problem with Google but is there no a simple solution - what am I missing?

答:
Simple answer - data["content"] is a list with one element. You could use

```<code>print data["content"][0]["record"]
</code>```

You could use online json fromatters (for example this) to explore your json data.

Body:
I have a following context received from a query in Python script (an example):

{
    "active": false,
    "owner": "user1",
    "content": [
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]
      }
    ]
  }

making this to json array works without errors:

data = json.loads(*string_above*)

as a result this works ok:

print data["owner"]

user1

also this is ok:

print data["content"]

[
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]}

Now my problem is how can I make this a multidimensional array?

E.g. command

print data["content"]["record"]

gives an error:

TypeError: list indices must be integers, not str

what I was hoping to get is:

{
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }

Found many different comments on this kind of problem with Google but is there no a simple solution - what am I missing?

Body:
Simple answer - data["content"] is a list with one element. You could use

print data["content"][0]["record"]

You could use online json fromatters (for example this) to explore your json data.


问:
Delete duplicate records from table where id is duplicate
I have a little problem, my table 'furniture' contains records where the ID is the same. I'll show you.

Title

id : public_name

1 : 'desk'

1 : 'desk'

1 : 'desk'

2 : 'comp'

2 : 'comp'

3 : 'rug'

3 : 'rug'

3 : 'rug'

3 : 'rug'

I don't know how it happened, but the record for id 2 has been duplicated, and some of them has even been tripled.
I've tried this script to solve it.

```<code><?php

$con = mysql_connect("localhost","root","pass");
Mysql_Select_db("db", $con);

for($i = 0; $i < 52752; $i++) {
$find = mysql_query("SELECT * FROM furniture WHERE id = '".$i."'");
$count = mysql_num_rows($find);

mysql_query("DELETE FROM furniture WHERE id = '$i' LIMIT ($i - $count)");
echo "'.$i.' fixed";
}
</code>```

But it is not working, it deletes all off the ids, I want it to leave one record per id.

Is there any easy query or script to solve this?

答:
The simplest method in MySQL is to empty and re-populate the table:

```<code>create table temp_furniture as
    select distinct id, public_name
    from furniture;

truncate table temp_furniture;

insert into temp_furniture(id, public_name)
    select id, public_name
    from temp_furniture;
</code>```

Then, to prevent this happening in the future, add unique indexes/constraints:

```<code>create unique index unq_furniture_id on furniture(id);
</code>```

And you probably want on on the name as well:

```<code>create unique index unq_furniture_public_name on furniture(public_name);
</code>```

Body:
I have a little problem, my table 'furniture' contains records where the ID is the same. I'll show you.

Title

id : public_name

1 : 'desk'

1 : 'desk'

1 : 'desk'

2 : 'comp'

2 : 'comp'

3 : 'rug'

3 : 'rug'

3 : 'rug'

3 : 'rug'

I don't know how it happened, but the record for id 2 has been duplicated, and some of them has even been tripled.
I've tried this script to solve it.

<?php

$con = mysql_connect("localhost","root","pass");
Mysql_Select_db("db", $con);

for($i = 0; $i < 52752; $i++) {
$find = mysql_query("SELECT * FROM furniture WHERE id = '".$i."'");
$count = mysql_num_rows($find);

mysql_query("DELETE FROM furniture WHERE id = '$i' LIMIT ($i - $count)");
echo "'.$i.' fixed";
}

But it is not working, it deletes all off the ids, I want it to leave one record per id.

Is there any easy query or script to solve this?

Body:
The simplest method in MySQL is to empty and re-populate the table:

create table temp_furniture as
    select distinct id, public_name
    from furniture;

truncate table temp_furniture;

insert into temp_furniture(id, public_name)
    select id, public_name
    from temp_furniture;

Then, to prevent this happening in the future, add unique indexes/constraints:

create unique index unq_furniture_id on furniture(id);

And you probably want on on the name as well:

create unique index unq_furniture_public_name on furniture(public_name);


问:
Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric in KNN classification
I have the follow code to try to use the knn in a classification model:

```<code>library(dplyr)
library(e1071)
library(ggplot2)
library(nnet)
library(DMwR)
library(rpart.plot)
library(class)

dat         <- read.csv("C:/Users/Ze/Desktop/HallowSet/train.csv",header = T,stringsAsFactors = F)

needToSolve <- read.csv("C:/Users/Ze/Desktop/HallowSet/test.csv",header = T,stringsAsFactors = F)

dat$color <- factor(dat$color)
dat$type  <- factor(dat$type)

sp    <- sample(1:nrow(dat),0.7*nrow(dat))
train <- dat[sp,]
test  <- dat[-sp,]
full  <- rbind(train,test)

pre <-kNN(type ~ .,train ,test,k=3,norm=TRUE,type='class')
</code>```

But when the code reach the next line I get an colMeans(x, na.rm = TRUE) : 'x' must be numeric, I don't know why is that happening and how to solve it someone can tell me it?
Thaks in the advance.

str(full):

```<code>'data.frame':   259 obs. of  12 variables:
$ id           : int  62 699 23 172 701 70 809 393 465 839 ...
$ bone_length  : num  0.304 0.417 0.585 0.498 0.477 ...
$ rotting_flesh: num  0.267 0.625 0.593 0.374 0.479 ...
$ hair_length  : num  0.527 0.329 0.681 0.58 0.404 ...
$ has_soul     : num  0.387 0.28 0.936 0.512 0.545 ...
$ color        : Factor w/ 6 levels "black","blood",..: 4 2 4 4 3 5 6 4 6 2 ...
$ type         : Factor w/ 3 levels "Ghost","Ghoul",..: 3 1 2 3 2 1 1 2 1 3 ...
$ bone_flesh   : num  0.0812 0.2608 0.3467 0.1866 0.2282 ...
$ bone_hair    : num  0.16 0.137 0.398 0.289 0.192 ...
$ bone_soul    : num  0.118 0.117 0.547 0.255 0.26 ...
$ flesh_hair   : num  0.141 0.205 0.404 0.217 0.193 ...
$ flesh_soul   : num  0.103 0.175 0.555 0.192 0.261 ...
</code>```

答:
'Color' is a factor. kNN only takes numeric inputs. You can turn your Color variable into a numeric variable or just remove Color entirely.</p>

```<code>dat$color = as.numeric(dat$color)
</code>```

Body:
I have the follow code to try to use the knn in a classification model:

library(dplyr)
library(e1071)
library(ggplot2)
library(nnet)
library(DMwR)
library(rpart.plot)
library(class)

dat         <- read.csv("C:/Users/Ze/Desktop/HallowSet/train.csv",header = T,stringsAsFactors = F)

needToSolve <- read.csv("C:/Users/Ze/Desktop/HallowSet/test.csv",header = T,stringsAsFactors = F)

dat$color <- factor(dat$color)
dat$type  <- factor(dat$type)

sp    <- sample(1:nrow(dat),0.7*nrow(dat))
train <- dat[sp,]
test  <- dat[-sp,]
full  <- rbind(train,test)

pre <-kNN(type ~ .,train ,test,k=3,norm=TRUE,type='class')

But when the code reach the next line I get an colMeans(x, na.rm = TRUE) : 'x' must be numeric, I don't know why is that happening and how to solve it someone can tell me it?
Thaks in the advance.

str(full):

'data.frame':   259 obs. of  12 variables:
$ id           : int  62 699 23 172 701 70 809 393 465 839 ...
$ bone_length  : num  0.304 0.417 0.585 0.498 0.477 ...
$ rotting_flesh: num  0.267 0.625 0.593 0.374 0.479 ...
$ hair_length  : num  0.527 0.329 0.681 0.58 0.404 ...
$ has_soul     : num  0.387 0.28 0.936 0.512 0.545 ...
$ color        : Factor w/ 6 levels "black","blood",..: 4 2 4 4 3 5 6 4 6 2 ...
$ type         : Factor w/ 3 levels "Ghost","Ghoul",..: 3 1 2 3 2 1 1 2 1 3 ...
$ bone_flesh   : num  0.0812 0.2608 0.3467 0.1866 0.2282 ...
$ bone_hair    : num  0.16 0.137 0.398 0.289 0.192 ...
$ bone_soul    : num  0.118 0.117 0.547 0.255 0.26 ...
$ flesh_hair   : num  0.141 0.205 0.404 0.217 0.193 ...
$ flesh_soul   : num  0.103 0.175 0.555 0.192 0.261 ...

Body:
'Color' is a factor. kNN only takes numeric inputs. You can turn your Color variable into a numeric variable or just remove Color entirely.

dat$color = as.numeric(dat$color)


问:
call javascript function on div with same class
I have a javascript function i would like to call on multiple div with same class but when i call the function and hover over the first div the function is called on the other div with same class

```<code>function flip() {
    $('.front').css("display", "none");
    $('.back').fadeIn();
}
function flipBack() {
    $('.front').fadeIn();
    $('.back').css("display", "none");
}
</code>```

html

```<code><div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-globe"></i>
                    <h3>Nigeriaeexport</h3>
                    <p>Your one stop export solution platform for everything export.</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div>
            <div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-location-arrow"></i>
                    <h3>XPT Logistics</h3>
                    <p>The top Company in terms of Export Logistics in Nigeria</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div>
</code>```

What I want is when mouseenter the .subMainSlate the .front fadeOut() and .back fadeIn().

Thanks.

答:
Instead of binding event on class , bind event on element which is whithin the root node. You can use find selector to select only nodes which are part of root node.

function flip(el) {
    $(el).find('.front').css("display", "none");
    $(el).find('.back').fadeIn();
}
function flipBack(el) {
    $(el).find('.front').fadeIn();
    $(el).find('.back').css("display", "none");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-globe"></i>
                    <h3>Nigeriaeexport</h3>
                    <p>Your one stop export solution platform for everything export.</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div>
            <div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-location-arrow"></i>
                    <h3>XPT Logistics</h3>
                    <p>The top Company in terms of Export Logistics in Nigeria</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div></code>```

Body:
I have a javascript function i would like to call on multiple div with same class but when i call the function and hover over the first div the function is called on the other div with same class

function flip() {
    $('.front').css("display", "none");
    $('.back').fadeIn();
}
function flipBack() {
    $('.front').fadeIn();
    $('.back').css("display", "none");
}

html

Nigeriaeexport

Your one stop export solution platform for everything export.

                    Want to work

XPT Logistics

The top Company in terms of Export Logistics in Nigeria

                    Want to work

What I want is when mouseenter the .subMainSlate the .front fadeOut() and .back fadeIn().

Thanks.

Body:
Instead of binding event on class , bind event on element which is whithin the root node. You can use find selector to select only nodes which are part of root node.

function flip(el) {
    $(el).find('.front').css("display", "none");
    $(el).find('.back').fadeIn();
}
function flipBack(el) {
    $(el).find('.front').fadeIn();
    $(el).find('.back').css("display", "none");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-globe"></i>
                    <h3>Nigeriaeexport</h3>
                    <p>Your one stop export solution platform for everything export.</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div>
            <div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-location-arrow"></i>
                    <h3>XPT Logistics</h3>
                    <p>The top Company in terms of Export Logistics in Nigeria</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div>


问:
Writing a big text file fast
How can I write a big text file very fast on Android?

I made some tests using a PrintWriter, a BufferedWriter and a FileWriter, but there are no significative time difference, and writing takes about three times the time of reading.

答: Give Okio a spin. Not sure if it's actually faster though.</p>

Title: Writing a big text file fast


问:
Method links do not exist - Laravel 5.5
I'm getting the following error:

Method links do not exist

I also tried render function which gives me the same result.

This is my code:

```<code>public function welcome() {
    $products = DB::table('products')->paginate(12);
    return view('welcome', compact('products', $products));
}
</code>```

When I call {{ $products->links() }}, it shows an error but if I remove {{ $products->links() }} I can see the results.

This is my view:

```<code>    @foreach($products as $product)
    <div class="col-sm-6 col-md-4 col-lg-3">
        <!-- Product item -->
        <div class="product-item hover-img">
            <a href="product_detail.html" class="product-img">
                <img src="images/default.png" alt="image">
            </a>
            <div class="product-caption">
                <h4 class="product-name"><a href="#">{!! $product->name !!}</a></h4>
                <div class="product-price-group">
                    <span class="product-price">{!! $product->price !!} KM</span>
                </div>
            </div>
            <div class="absolute-caption">
                <form action="{!! route('store') !!}" method="POST">
                    {!! csrf_field() !!}
                    <input type="hidden" name="id" value="{{ $product->id }}">
                    <input type="hidden" name="name" value="{{ $product->name }}">
                    <input type="hidden" name="price" value="{{ $product->price }}">
                    <input type="submit" class="btn btn-success btn-lg" value="Dodaj u korpu">
                </form>
            </div>
        </div>
    </div>
    @endforeach

   {{ $products->links() }}
</code>```

答:
You should use Eloquent instead of query builder.

Use:

```<code>$products = \App\Product::paginate(12);
</code>```

instead of

```<code>$products = DB::table('products')->paginate(12);
</code>```

to make it work.

(Of course you need to have created Product model first extending Eloquent model)

Title: Method links do not exist - Laravel 5.5

Body:
I'm getting the following error:

Method links do not exist

I also tried render function which gives me the same result.

This is my code:

public function welcome() {
    $products = DB::table('products')->paginate(12);
    return view('welcome', compact('products', $products));
}

When I call {{ $products->links() }}, it shows an error but if I remove {{ $products->links() }} I can see the results.

This is my view:

    @foreach($products as $product)

{!! $product->name !!}

                    {!! $product->price !!} KM

                <form action="{!! route('store') !!}" method="POST">
                    {!! csrf_field() !!}
                    <input type="hidden" name="id" value="{{ $product->id }}">
                    <input type="hidden" name="name" value="{{ $product->name }}">
                    <input type="hidden" name="price" value="{{ $product->price }}">
                    <input type="submit" class="btn btn-success btn-lg" value="Dodaj u korpu">
                </form>

    @endforeach

   {{ $products->links() }}

Body:
You should use Eloquent instead of query builder.

Use:

$products = \App\Product::paginate(12);

instead of

$products = DB::table('products')->paginate(12);

to make it work.

(Of course you need to have created Product model first extending Eloquent model)


问:
how to write user input in whatsapp sharing message
In my website I have a whatsapp sharing button, so i want to send my website link with a parameter,

For e.g.

abcd.com/?name=userinput

This is the code of whatsapp sharing button.

```<code><script type="text/javascript">
var userinput=prompt("Please Enter Your Name");
</script>
<script><a href="whatsapp://send?text= Link abcd.html?name="><b>share on whatsapp</b></script>
</code>```

答:
You can do this:

JS:

```<code><script>
    //Ask the user for name and store it on name variable
    var name = prompt("Please Enter Your Name");

    //This will be called when the link is clicked
    function sendWhatsapp(){
        var url     = "www.abcd.com/?name=" + name;
        var sMsg    = encodeURIComponent( "hi this is " + name + " and my link is " + url );
        var whatsapp_url = "whatsapp://send?text=" + sMsg;
        window.location.href = whatsapp_url;
    }
</script>
</code>```

HTML:

```<code><a onclick="sendWhatsapp()">share on whatsapp</a>
</code>```

FULL HTML CODE:

```<code><html>
<head>
<script>
    //Ask the user for name and store it on name variable
    var name = prompt("Please Enter Your Name");

    //This will be called when the link is clicked
    function sendWhatsapp(){
        var url     = "www.abcd.com/?name=" + name;
        var sMsg    = encodeURIComponent( "hi this is " + name + " and my link is " + url );
        var whatsapp_url = "whatsapp://send?text=" + sMsg;
        window.location.href = whatsapp_url;
    }
</script>
</head>
<body>
    <a onclick="sendWhatsapp()">share on whatsapp</a>
</body>
</html>
</code>```

Body:
You can do this:

JS:

<script>
    //Ask the user for name and store it on name variable
    var name = prompt("Please Enter Your Name");

    //This will be called when the link is clicked
    function sendWhatsapp(){
        var url     = "www.abcd.com/?name=" + name;
        var sMsg    = encodeURIComponent( "hi this is " + name + " and my link is " + url );
        var whatsapp_url = "whatsapp://send?text=" + sMsg;
        window.location.href = whatsapp_url;
    }
</script>

HTML:

<a onclick="sendWhatsapp()">share on whatsapp</a>

FULL HTML CODE:

<html>
<head>
<script>
    //Ask the user for name and store it on name variable
    var name = prompt("Please Enter Your Name");

    //This will be called when the link is clicked
    function sendWhatsapp(){
        var url     = "www.abcd.com/?name=" + name;
        var sMsg    = encodeURIComponent( "hi this is " + name + " and my link is " + url );
        var whatsapp_url = "whatsapp://send?text=" + sMsg;
        window.location.href = whatsapp_url;
    }
</script>
</head>
<body>
    <a onclick="sendWhatsapp()">share on whatsapp</a>
</body>
</html>


问:
How do you play ogg files in Python in Linux?
Could someone provide a short code or pseudocode example of how to play ogg files in Python 2.7.1 or Python 3.1.3 in Linux (along with a list of any dependencies from the Synaptic Package Manager, or elsewhere)?</p>

答:
Sometime ago I tried to write some game prototype in python and i used pygame.
http://www.pygame.org/news.html
You should be able to find it in synaptic, and it should install all needed dependencies, if ogg would not work you would probably need libvorbis, but you most likely have it installed already. Anyway, probably best thing to do is to read pygame. Otho if it's not a game that your making you might need another library. But then all I can suggest is try searching.</p>


问:
I have a task to find bugs in this code and I just can't find any
I study in school c programming and I have this assignment to find 3 bugs in this code. I just can't find any! It all seems to work just fine...
maybe I should also mention that I have been studying for about only 2 months.

This is the code:

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

#define LOWER 0
#define UPPER 172486
/*
Bug Report:
1.
2.
3.
*/
void welcome(void);
void useage(void);
void getNumber(void);
void printTwice(int number);

int main(void)
{
    welcome();
    return 0;
}

/*
This function prints "welcome".
input: none
output: none
*/
void welcome(void)
{
    printf("Welcome to my cool program!\n");
    useage();
}

/*
This function prints what the program is for.
input: none
output: none
*/
void useage(void)
{
    printf("My program gets a number from you - and prints it twice in a row!\n");
    getNumber();
}

/*
The function gets a number.
input: none
output: none
*/
void getNumber(void)
{
    printf("Please enter a number between 0 - 172,486: \n");
    int number = 0;
    scanf("%d", &number);
    while(number < LOWER || number > UPPER)
    {
        printf("Invalid choice!\n");
        scanf("%d", &number);
    }
    printTwice(number);
}

/*
Prints the number twice.
input: the number we got from the user.
output: none
*/
void printTwice(int number)
{
    printf("The number twice in a row: %d%d", number, number);
}
</code>```

答:
Issues:

1.

No warning for entering strings instead of numbers. 00 will be printed.

2.

```<code>   printf("The number twice in a row: %d%d", number, number);
</code>```

No space between numbers, no line termination
Proposed change:

```<code>   printf("The number twice in a row: %d %d\n", number, number);
</code>```

Body:
I study in school c programming and I have this assignment to find 3 bugs in this code. I just can't find any! It all seems to work just fine...
maybe I should also mention that I have been studying for about only 2 months.

This is the code:

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

#define LOWER 0
#define UPPER 172486
/*
Bug Report:
1.
2.
3.
*/
void welcome(void);
void useage(void);
void getNumber(void);
void printTwice(int number);

int main(void)
{
    welcome();
    return 0;
}

/*
This function prints "welcome".
input: none
output: none
*/
void welcome(void)
{
    printf("Welcome to my cool program!\n");
    useage();
}

/*
This function prints what the program is for.
input: none
output: none
*/
void useage(void)
{
    printf("My program gets a number from you - and prints it twice in a row!\n");
    getNumber();
}

/*
The function gets a number.
input: none
output: none
*/
void getNumber(void)
{
    printf("Please enter a number between 0 - 172,486: \n");
    int number = 0;
    scanf("%d", &number);
    while(number < LOWER || number > UPPER)
    {
        printf("Invalid choice!\n");
        scanf("%d", &number);
    }
    printTwice(number);
}

/*
Prints the number twice.
input: the number we got from the user.
output: none
*/
void printTwice(int number)
{
    printf("The number twice in a row: %d%d", number, number);
}

Body:
Issues:

1.

No warning for entering strings instead of numbers. 00 will be printed.

2.

   printf("The number twice in a row: %d%d", number, number);

No space between numbers, no line termination
Proposed change:

   printf("The number twice in a row: %d %d\n", number, number);


问:
Dissecting a simple Javascript Closure
When looking at the code for the addSuffix function

```<code>const addSuffix = (x) => {
    const concat = (y) => {
        return y + x
    }
return concat;
}

let add_ful = addSuffix("ful");
</code>```

If I were to console.log(add_ful);  why do I get

```<code>(y) => {
    return y + x
}
</code>```

instead of

```<code>(y) => {
    return y + "ful"
}
</code>```

?

This is the most confusing point about closures for me, I understand that I can return a function, but I'm not sure where the reference to "ful" is being stored in the function.

Where is the value of x being stored in the add_ful function?

答:
console.log logs a string representation of the function itself. It doesn't enquire into the state of the function and display the current values that are being referenced. It's just showing the syntax you used to create the function.

However, if you set a breakpoint and walk through the execution, you can see the state of the variables in scope using your debugging tools.

Title: Dissecting a simple Javascript Closure

Body:
When looking at the code for the addSuffix function

const addSuffix = (x) => {
    const concat = (y) => {
        return y + x
    }
return concat;
}

let add_ful = addSuffix("ful");

If I were to console.log(add_ful);  why do I get

(y) => {
    return y + x
}

instead of

(y) => {
    return y + "ful"
}

?

This is the most confusing point about closures for me, I understand that I can return a function, but I'm not sure where the reference to "ful" is being stored in the function.

Where is the value of x being stored in the add_ful function?


答:
Use the find() on the targeted element like the following:

function flip(that) {
  $(that).find('.fornt').css("display", "none");
  $(that).find('.back').fadeIn();
}
function flipBack(that) {
  $(that).find('.front').fadeIn();
  $(that).find('.back').css("display", "none");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
    <div class="front">
        <i class="typcn typcn-globe"></i>
        <h3>Nigeriaeexport</h3>
        <p>Your one stop export solution platform for everything export.</p>
    </div>
    <div class="back">
        Want to work
    </div>
</div>
<div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
    <div class="front">
        <i class="typcn typcn-location-arrow"></i>
        <h3>XPT Logistics</h3>
        <p>The top Company in terms of Export Logistics in Nigeria</p>
    </div>
    <div class="back">
        Want to work
    </div>
</div></code>```

Title: call javascript function on div with same class

Body:
Use the find() on the targeted element like the following:

function flip(that) {
  $(that).find('.fornt').css("display", "none");
  $(that).find('.back').fadeIn();
}
function flipBack(that) {
  $(that).find('.front').fadeIn();
  $(that).find('.back').css("display", "none");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
    <div class="front">
        <i class="typcn typcn-globe"></i>
        <h3>Nigeriaeexport</h3>
        <p>Your one stop export solution platform for everything export.</p>
    </div>
    <div class="back">
        Want to work
    </div>
</div>
<div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
    <div class="front">
        <i class="typcn typcn-location-arrow"></i>
        <h3>XPT Logistics</h3>
        <p>The top Company in terms of Export Logistics in Nigeria</p>
    </div>
    <div class="back">
        Want to work
    </div>
</div>


问:
How Do I Use The CSS Background Property?
```<code>body {
  background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;
}
</code>```

That's my CSS for my body, yet, it won't load the image, but somehow,

```<code>body {
  background-color: #fff;
  background-image: url("milkshakeonthewindowsill.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
</code>```

this code does. What am I missing or doing wrong?

答:
When using the shorthand property the order of the property values is:

```<code>background-color
background-image
background-repeat
background-attachment
background-position
</code>```

It does not matter if one of the property values is missing, as long as the other ones are in this order.

```<code>background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;
</code>```

You are making use of background-size which isn't supported in the shorthand syntax and it should be in that order to work as given above. So, the correct syntax would be:

```<code>background: #fff url("milkshakeonthewindowsill.jpg") no-repeat fixed;
background-size:cover;
</code>```

Body:
body {
  background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;
}

That's my CSS for my body, yet, it won't load the image, but somehow,

body {
  background-color: #fff;
  background-image: url("milkshakeonthewindowsill.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

this code does. What am I missing or doing wrong?

Body:
When using the shorthand property the order of the property values is:

background-color
background-image
background-repeat
background-attachment
background-position

It does not matter if one of the property values is missing, as long as the other ones are in this order.

background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;

You are making use of background-size which isn't supported in the shorthand syntax and it should be in that order to work as given above. So, the correct syntax would be:

background: #fff url("milkshakeonthewindowsill.jpg") no-repeat fixed;
background-size:cover;


问:
Different virtualenv's on one Jupyter notebook
I am working on a setup where several developers, working on different projects, all execute their code on a remote machine, using Jupyter notebook.

Since every projects requires a different virtualenv what happens now is that every developer for every projects, sets up a project specific virtualenv, installs notebook to it, runs it on a different port and connects to the remote machine through that port.

Is there a way to have 1 Jupyter notebook running on the remote machine, but be able to choose which virtualenv to use as kernel?

My main consideration is being able to expose only one port on the remote machine, but be able to use different virtual python environment for running the notebooks

答:
I am working on a setup where several developers

If you have many dev working on a remote machine you must use JupyterHub, JupyterHub is made for that, and JupyterHub is the first step toward easing your pain; if you do not use JupyterHub, things will go wrong.

Once you have JupyterHub installed, your devs will be able to login with their credential wit exposing a single port, and will be able to start/stop notebook servers without sshing in.

Once this is done, you can investigate multiple venv.

In each environment you want to install ipykernel. It is the module that knows how to talk to the notebook. And in each environment you need to issue the python -m ipykernel install --user --name=my-env-name as said in the comments below your posts. This register each env with Jupyter, telling it "Hey I exist expose me to your users". You may also decide to install this that does part of this automatically for you, but have some caveats.

As other commenters have pointed out you likely want to read Jake's post, and if you have several users you should absolutely always almost without questions use JupyterHub.


问:
writing a text file in line by line from the speech recognition method using audio
I am trying to produce a text file from the speech recognition using audio in .wav format. this is to get the subtitle. I already got the text file but the problem right now is the text is produced in a longgggg line.

I want them to be in line by line (maybe after 5 words it will go to the next line) because i want to show up the subtitle in the tkinter windows. as i said I got them already to show up on tkinter windows, only the problem is the text file not producing in lines by lines. pls help me. this is for my final year project as i am still a student of degree.

```<code>    AUDIO_FILE = path.get()

    r= sr.Recognizer()
    with sr.AudioFile(AUDIO_FILE) as source:
        audio = r.record(source)

    try:
        filename = ".txt"
        f = open( filename , "w+")

        a = f.writelines(r.recognize_google(audio))
        b = a.split("\n\n")
        b[:] = (value for value in b if value is not '\t')
        f.close()

    except sr.UnknownValueError:
        print("Google could not understand audio")
    except sr.RequestError as e:
        print("Google error; {0}".format(e))

    return filename
</code>```

maybe u guys know how to write an array to produce / writing the text file from audio in line by line. i repeat i want "LINE by LINE".

These are the error that i got. please help me.

```<code>b = a.split("\n\n")
AttributeError: 'NoneType' object has no attribute 'split'
</code>```

答:
Your error on b = a.split("\n\n") is because you seem to think that f.writelines() will return something. It doesn't, so a has the value None and can't be split.

The documentation says this about what writelines() does:

writelines(lines)

Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line
  separator at the end.

So, if you want there to be linefeeds in your output file, you have to put them there before you call writelines().

But you should not be calling writelines()at all, because it expects a list of strings, and recognize_google() returns a string.

Since you are getting one long string of words, and you want 5 per line, you need to break the text up into lines with 5 words and call write() for each line. Something like this:

```<code>recognized_text = r.recognize_google(audio)
remainder = recognized_text.split()
while remainder:
    line, remainder = remainder[:5], remainder[5:]
    f.write(' '.join(line) + "\n")
</code>```

Body:
I am trying to produce a text file from the speech recognition using audio in .wav format. this is to get the subtitle. I already got the text file but the problem right now is the text is produced in a longgggg line.

I want them to be in line by line (maybe after 5 words it will go to the next line) because i want to show up the subtitle in the tkinter windows. as i said I got them already to show up on tkinter windows, only the problem is the text file not producing in lines by lines. pls help me. this is for my final year project as i am still a student of degree.

    AUDIO_FILE = path.get()

    r= sr.Recognizer()
    with sr.AudioFile(AUDIO_FILE) as source:
        audio = r.record(source)

    try:
        filename = ".txt"
        f = open( filename , "w+")

        a = f.writelines(r.recognize_google(audio))
        b = a.split("\n\n")
        b[:] = (value for value in b if value is not '\t')
        f.close()

    except sr.UnknownValueError:
        print("Google could not understand audio")
    except sr.RequestError as e:
        print("Google error; {0}".format(e))

    return filename

maybe u guys know how to write an array to produce / writing the text file from audio in line by line. i repeat i want "LINE by LINE".

These are the error that i got. please help me.

b = a.split("\n\n")
AttributeError: 'NoneType' object has no attribute 'split'

Body:
Your error on b = a.split("\n\n") is because you seem to think that f.writelines() will return something. It doesn't, so a has the value None and can't be split.

The documentation says this about what writelines() does:

writelines(lines)

Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line
  separator at the end.

So, if you want there to be linefeeds in your output file, you have to put them there before you call writelines().

But you should not be calling writelines()at all, because it expects a list of strings, and recognize_google() returns a string.

Since you are getting one long string of words, and you want 5 per line, you need to break the text up into lines with 5 words and call write() for each line. Something like this:

recognized_text = r.recognize_google(audio)
remainder = recognized_text.split()
while remainder:
    line, remainder = remainder[:5], remainder[5:]
    f.write(' '.join(line) + "\n")


问:
ASP.net: ClientScript.RegisterClientScriptBlock fires before jQuery is loaded
Interesting problem here from some inherited code I recently looked at. I'm trying to add a compression module to a project. It is loading all the JS and CSS files, combining them, minifying them, and compressing them. I've tried a number of solutions, but all of them have one fatal problem.

I have some javascript that is being loaded via Page.ClientScript.RegisterClientScriptBlock in the PreRender of the MasterPage. The compression module is loading as a Script Tag link in the MasterPage, but when I run the page... the code from the PreRender is lopped on top and is giving me a '$ is undefined' error, telling me jQuery isn't loaded yet.

Furthermore, I can't seem to get past the same problem when it comes to inline javascript on content pages.

Any ideas as to what is causing this? Enlighten me as I have no clue.

答: If have done this before with RegisterStartupScript (instead of RegisterClientScriptBlock)  and called the $(document).ready(function() from WITHIN that script.