问:
Select only latest record for every employees and for specific employee in MySQL
I have a MySQL DB and in it there's a table with activity logs of employees.

```<code>+-------------------------------------------------+
| log_id | employee_id | date_time  | action_type |
+-------------------------------------------------+
|   1    |      1      | 2015/02/03 |   action1   |
|   2    |      2      | 2015/02/01 |   action1   |
|   3    |      2      | 2017/01/02 |   action2   |
|   4    |      3      | 2016/02/12 |   action1   |
|   5    |      1      | 2016/10/12 |   action2   |
+-------------------------------------------------+
</code>```

And I would need 2 queries. First, to get for every employee his last action. So from this example table I would need to get row 3,4 and 5 with all columns. And second, get the latest action only for specified employee.

Any ideas how to achieve this? I'm using Spring Data JPA, but raw SQL Query would be also great.

Thank you in advance.

答:
You can get the expected output by doing a self join

```<code>select a.*
from demo a
left join demo b on a.employee_id = b.employee_id
and a.date_time < b.date_time
where b.employee_id is null
</code>```

Note it may return multiple rows for single employee if there are rows with same date_time you might need a CASE statement and another attribute to decide which row should be picked to handle this kind of situation

Demo

Body:
I have a MySQL DB and in it there's a table with activity logs of employees.

+-------------------------------------------------+
| log_id | employee_id | date_time  | action_type |
+-------------------------------------------------+
|   1    |      1      | 2015/02/03 |   action1   |
|   2    |      2      | 2015/02/01 |   action1   |
|   3    |      2      | 2017/01/02 |   action2   |
|   4    |      3      | 2016/02/12 |   action1   |
|   5    |      1      | 2016/10/12 |   action2   |
+-------------------------------------------------+

And I would need 2 queries. First, to get for every employee his last action. So from this example table I would need to get row 3,4 and 5 with all columns. And second, get the latest action only for specified employee.

Any ideas how to achieve this? I'm using Spring Data JPA, but raw SQL Query would be also great.

Thank you in advance.

Body:
You can get the expected output by doing a self join

select a.*
from demo a
left join demo b on a.employee_id = b.employee_id
and a.date_time < b.date_time
where b.employee_id is null

Note it may return multiple rows for single employee if there are rows with same date_time you might need a CASE statement and another attribute to decide which row should be picked to handle this kind of situation

Demo


来源: stackexchange

问:
VueJS/VueX Maximum call stack size exceeded
I'm currently working on a Vue project, I'm using Vuex for state management. But when I bind the two actions below in my component with mapactions and mapgetters I get Maximum call stack size exceeded error in my console.

I don't know what I'm doing wrong.

```<code>import Vue from 'vue'
import Vuex from 'vuex'
import service from "../services/statisticsService"
import moment from 'moment'

Vue.use(Vuex)

const state = {
    customersAndServicesOverTime:[],
    counters:{}
}
const actions = {
    actGetAllData(context){
        context.dispatch('actGetCustomersAndServicesOverTime')
        context.dispatch('actGetCounters')
    },

    actGetCustomersAndServicesOverTime(context){
        service.getCustomerAndServicesOverTime(context.getters.getJWT)
            .then(response =>{
                context.commit('mutCustomersAndServicesOverTime', response.body)
            })
    },
    actGetCounters(context){
        service.getCounts(context.getters.getJWT)
            .then(response =>{
                context.commit('mutCounts', response.body)
            })
    }
}
const mutations = {
    mutCustomersAndServicesOverTime(state,payload){
        state.customersAndServicesOverTime ={
            labels:payload.map(x => moment(x.created).format("DD-MM-YYYY")),
            datasets:[{
                data:payload.map(x => x.customersCount),
                backgroundColor:"rgba(52, 73, 94,0.5)",
                label:"customers",lineTension:0
            },{
                data:payload.map(x => x.servicesCount),
                backgroundColor:"rgba(230, 126, 34,0.5)",
                label:"services",lineTension:0
            }]}
    },
    mutCounts(state,payload){
        state.counters = payload
    },
}
const getters = {
    getCustomersAndServicesOverTime:state=>state.customersAndServicesOverTime,
    getCounts:state=>state.counters,
}

export default {
    state,
    getters,
    actions,
    mutations
}
</code>```

In my service I declared Two function that connect with my API.

```<code>import Vue from 'vue'
import VueResource from 'vue-resource'
import CONFIG from "../config"

export default {
    getCounts(jwt) {
        return Vue.http.get(CONFIG.API + "statistics/counts", {
            headers: {
                'Content-Type': 'application/json'
                ,'Authorization': 'Bearer ' + jwt
            }
        })
    },
    getCustomerAndServicesOverTime(jwt) {
        return Vue.http.get(CONFIG.API + "statistics/customersandservicesovertime", {
            headers: {
                'Content-Type': 'application/json'
                ,'Authorization': 'Bearer ' + jwt
            }
        })
    }
}
</code>```

答:
It wasn't a vuex problem. I use vue-chartjs and I didn't hard copy my object instance but used it as a reference. Which causes the Maximum call stack size exceeded error.

https://github.com/apertureless/vue-chartjs/issues/197

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on a Vue project, I'm using Vuex for state management. But when I bind the two actions below in my component with mapactions and mapgetters I get Maximum call stack size exceeded error in my console.

I don't know what I'm doing wrong.

import Vue from 'vue'
import Vuex from 'vuex'
import service from "../services/statisticsService"
import moment from 'moment'

Vue.use(Vuex)

const state = {
    customersAndServicesOverTime:[],
    counters:{}
}
const actions = {
    actGetAllData(context){
        context.dispatch('actGetCustomersAndServicesOverTime')
        context.dispatch('actGetCounters')
    },

    actGetCustomersAndServicesOverTime(context){
        service.getCustomerAndServicesOverTime(context.getters.getJWT)
            .then(response =>{
                context.commit('mutCustomersAndServicesOverTime', response.body)
            })
    },
    actGetCounters(context){
        service.getCounts(context.getters.getJWT)
            .then(response =>{
                context.commit('mutCounts', response.body)
            })
    }
}
const mutations = {
    mutCustomersAndServicesOverTime(state,payload){
        state.customersAndServicesOverTime ={
            labels:payload.map(x => moment(x.created).format("DD-MM-YYYY")),
            datasets:[{
                data:payload.map(x => x.customersCount),
                backgroundColor:"rgba(52, 73, 94,0.5)",
                label:"customers",lineTension:0
            },{
                data:payload.map(x => x.servicesCount),
                backgroundColor:"rgba(230, 126, 34,0.5)",
                label:"services",lineTension:0
            }]}
    },
    mutCounts(state,payload){
        state.counters = payload
    },
}
const getters = {
    getCustomersAndServicesOverTime:state=>state.customersAndServicesOverTime,
    getCounts:state=>state.counters,
}

export default {
    state,
    getters,
    actions,
    mutations
}

In my service I declared Two function that connect with my API.

import Vue from 'vue'
import VueResource from 'vue-resource'
import CONFIG from "../config"

export default {
    getCounts(jwt) {
        return Vue.http.get(CONFIG.API + "statistics/counts", {
            headers: {
                'Content-Type': 'application/json'
                ,'Authorization': 'Bearer ' + jwt
            }
        })
    },
    getCustomerAndServicesOverTime(jwt) {
        return Vue.http.get(CONFIG.API + "statistics/customersandservicesovertime", {
            headers: {
                'Content-Type': 'application/json'
                ,'Authorization': 'Bearer ' + jwt
            }
        })
    }
}


问:
Concurrency problem
We got an old system here in .NET 4.0 using an Oracle DB.
At some point, some calculus are made and the system "locks" that register in the table using the following command: "SELECT [the registry that will be update by the calculus] FOR UPDATE NOWAIT". So if anyone tries to calculate or update the registry with that ID it won't work.
After calculating, the system connects to the DB again and then "releases" the registry by simply executing a Rollback command.

Theoretically, this is correct for the system(altought I don't like it).

Anyway, here is the thing: if something is being calculated(and these calculous take like 5 minutes to finish) and in the middle of the calculous I close the browser, the registry will still be "locked", only being unlocked when IIS restarts(actually I dunno if it's released first, I forced IIS restart 'cause it was taking too long).

Could anybody give me a light about how to deal with that?
Or if you guys have a better approach to deal with this tipe of concurrency, I'll be greatful.

Thanks!
Gabriel.

Adding some code.
Before starting the calculus, this method is called:

```<code>Public Shared Sub LockAndUnlock(ByVal pTable As String, ByVal pWhere As String, ByVal pConnectionString As String, ByVal pLock As Boolean)

    Dim vConnection As OleDbConnection = New OleDbConnection(pConnectionString)
    Dim vCommand As OleDbCommand = New OleDbCommand

    Try
        vCommand.Connection = vConnection
        If (pLock) Then
            vCommand.CommandText = "SELECT * " &
                                   "  FROM   " & pTable &
                                   " WHERE   " & pWhere &
                                   " FOR UPDATE NOWAIT"

            vConnection.Open()
            vCommand.ExecuteNonQuery()
        Else
            vCommand.CommandText = "ROLLBACK"

            If (vConnection.State = ConnectionState.Closed) Then
                vConnection.Open()
            End If

            vCommand.ExecuteNonQuery()
            vConnection.Close()
        End If

    Catch ex As Exception
        Throw ex
    End Try
End Sub
</code>```

If the parameter pLock is True then the method locks. Otherwise, it unlocks.

答: I'd use an Oracle Profile with a maximum IDLE_TIME of about 10 minutes.</p>

ContentLicense: CC BY-SA 2.5

Title: Concurrency problem

Body:
We got an old system here in .NET 4.0 using an Oracle DB.
At some point, some calculus are made and the system "locks" that register in the table using the following command: "SELECT [the registry that will be update by the calculus] FOR UPDATE NOWAIT". So if anyone tries to calculate or update the registry with that ID it won't work.
After calculating, the system connects to the DB again and then "releases" the registry by simply executing a Rollback command.

Theoretically, this is correct for the system(altought I don't like it).

Anyway, here is the thing: if something is being calculated(and these calculous take like 5 minutes to finish) and in the middle of the calculous I close the browser, the registry will still be "locked", only being unlocked when IIS restarts(actually I dunno if it's released first, I forced IIS restart 'cause it was taking too long).

Could anybody give me a light about how to deal with that?
Or if you guys have a better approach to deal with this tipe of concurrency, I'll be greatful.

Thanks!
Gabriel.

Adding some code.
Before starting the calculus, this method is called:

Public Shared Sub LockAndUnlock(ByVal pTable As String, ByVal pWhere As String, ByVal pConnectionString As String, ByVal pLock As Boolean)

    Dim vConnection As OleDbConnection = New OleDbConnection(pConnectionString)
    Dim vCommand As OleDbCommand = New OleDbCommand

    Try
        vCommand.Connection = vConnection
        If (pLock) Then
            vCommand.CommandText = "SELECT * " &
                                   "  FROM   " & pTable &
                                   " WHERE   " & pWhere &
                                   " FOR UPDATE NOWAIT"

            vConnection.Open()
            vCommand.ExecuteNonQuery()
        Else
            vCommand.CommandText = "ROLLBACK"

            If (vConnection.State = ConnectionState.Closed) Then
                vConnection.Open()
            End If

            vCommand.ExecuteNonQuery()
            vConnection.Close()
        End If

    Catch ex As Exception
        Throw ex
    End Try
End Sub

If the parameter pLock is True then the method locks. Otherwise, it unlocks.


问:
Quick way to list all files in Amazon S3 bucket?
I have an amazon s3 bucket that has tens of thousands of filenames in it. What's the easiest way to get a text file that lists all the filenames in the bucket?</p>

答:
```<code># find like file listing for s3 files
aws s3api --profile <<profile-name>> \
--endpoint-url=<<end-point-url>> list-objects \
--bucket <<bucket-name>> --query 'Contents[].{Key: Key}'
</code>```


问:
Expression of Type Scala.Predef.String doesn't conform to expected type String
I have a function, validateCell, that takes a function, func, as one of its input parameters. It is as follows:

```<code>def validateCell[String](cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {
  cell match {
    case Some(cellContents)  => (func(cellContents), s"$cellContents is not valid.")
    case None => (false, s"$cellKey, not found.")
  }
}
</code>```

I call the function as follows:

```<code>val map = Map("Well" -> "A110")
validateCell("Well", map.get("Well"), BarcodeWell.isValidWell)
</code>```

The function that is passed in this case is as follows, though I don't think it's related to the problem:

```<code>def isValidWell(w: String): Boolean = {
  val row: String = w.replaceAll("[^A-Za-z]", "")
  val col: Int = w.replaceAll("[^0-9]+", "").toInt
  isValidRow(row) && isValidColumn(col)
}
</code>```

I am expecting validateCell to return a Tuple(Boolean, String), but I get the following error:

```<code>Error:(5, 55) type mismatch;
 found   : java.lang.String
 required: String(in method validateCell)
    case Some(cellContents)  => (func(cellContents), s"$cellContents is not valid.")
</code>```

I can make this error go away by converting the java strings in each tuple that are returned by the case statements to Scala strings like so:

```<code>s"$cellContents is not valid.".asInstanceOf[String]
s"$cellKey, not found.".asInstanceOf[String]
</code>```

This seems really silly. What am I missing here? Shouldn't this conversion be handled by Scala automatically and why are my strings being cast as Java strings in the first place?

答:
There is no difference between Scala strings and Java strings. In fact, Predef.String aliases to java.lang.String. However, you're working with neither of these things; you're working with a type parameter.

```<code>def validateCell[String](cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {
</code>```

This is a generic function which takes a type argument whose name is String. When you call validateCell, this type argument is being inferred and filled in for you, by something that definitely isn't a string. My guess is that you're misunderstanding the point of the brackets and that you meant to write

```<code>def validateCell(cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {
</code>```

Body:
I have a function, validateCell, that takes a function, func, as one of its input parameters. It is as follows:

def validateCell[String](cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {
  cell match {
    case Some(cellContents)  => (func(cellContents), s"$cellContents is not valid.")
    case None => (false, s"$cellKey, not found.")
  }
}

I call the function as follows:

val map = Map("Well" -> "A110")
validateCell("Well", map.get("Well"), BarcodeWell.isValidWell)

The function that is passed in this case is as follows, though I don't think it's related to the problem:

def isValidWell(w: String): Boolean = {
  val row: String = w.replaceAll("[^A-Za-z]", "")
  val col: Int = w.replaceAll("[^0-9]+", "").toInt
  isValidRow(row) && isValidColumn(col)
}

I am expecting validateCell to return a Tuple(Boolean, String), but I get the following error:

Error:(5, 55) type mismatch;
 found   : java.lang.String
 required: String(in method validateCell)
    case Some(cellContents)  => (func(cellContents), s"$cellContents is not valid.")

I can make this error go away by converting the java strings in each tuple that are returned by the case statements to Scala strings like so:

s"$cellContents is not valid.".asInstanceOf[String]
s"$cellKey, not found.".asInstanceOf[String]

This seems really silly. What am I missing here? Shouldn't this conversion be handled by Scala automatically and why are my strings being cast as Java strings in the first place?

Body:
There is no difference between Scala strings and Java strings. In fact, Predef.String aliases to java.lang.String. However, you're working with neither of these things; you're working with a type parameter.

def validateCell[String](cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {

This is a generic function which takes a type argument whose name is String. When you call validateCell, this type argument is being inferred and filled in for you, by something that definitely isn't a string. My guess is that you're misunderstanding the point of the brackets and that you meant to write

def validateCell(cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {


问:
jquery validation plugin on blur
Friends i am new to javascripting & jQuery and need your your help to solve 2 problems. I am using jquery validation plugin https://jqueryvalidation.org for a project which contains multiple forms on different pages.

PROBLEM #1

I included a custom JS file which already has the

```<code>$(document).ready(function() {
  //some codes
});
</code>```

To execute this plugin with different properties on different pages it is required to initialize it in document.ready i.e.

```<code>$(document).ready(function() {
  $("#theForm").validate();
});
</code>```

so is it ok to have document ready 2 times this way?

PROBLEM #2

This plugin works after the submit button is clicked. I want it to also validate onblur for input fields. It do have the property to validate on onfocusout also but that also works to handle errors after the submit button is clicked.
So is there anyway to make the validations to also work on blur or focusout before the submit button is clicked?

Any help will be highly appreciated. Thank you friends in advance.

答:
Yes, and yes. You can have any $(document).ready(); on your page. It is need when you define your methods, functions before elements are rendered in DOM.

If you put your javascript at very bottom of your page (after your html element has rendered) you can leave that.

For example, in this case it needs:

```<code><script>
   //before create the element
   $(function() { //same as document ready
       $('#element').on('click', function () {
          alert('Hi');
       });
   });
</script>

<div id="element">some text</div>
</code>```

but in this case not:

```<code><div id="element"></div>
<script>
   //Your element has already rendered
   $('#element').on('click', function () {
      alert('Hi');
   });
</script>
</code>```

and you can use your validation on blur.

```<code>$('#myInput').on('blur', function() {
   $("#theForm").validate();
});
</code>```

These are the basics, when you manipulate DOM by javascript, that is another story.

Title: jquery validation plugin on blur

Body:
Friends i am new to javascripting & jQuery and need your your help to solve 2 problems. I am using jquery validation plugin https://jqueryvalidation.org for a project which contains multiple forms on different pages.

PROBLEM #1

I included a custom JS file which already has the

$(document).ready(function() {
  //some codes
});

To execute this plugin with different properties on different pages it is required to initialize it in document.ready i.e.

$(document).ready(function() {
  $("#theForm").validate();
});

so is it ok to have document ready 2 times this way?

PROBLEM #2

This plugin works after the submit button is clicked. I want it to also validate onblur for input fields. It do have the property to validate on onfocusout also but that also works to handle errors after the submit button is clicked.
So is there anyway to make the validations to also work on blur or focusout before the submit button is clicked?

Any help will be highly appreciated. Thank you friends in advance.

Body:
Yes, and yes. You can have any $(document).ready(); on your page. It is need when you define your methods, functions before elements are rendered in DOM.

If you put your javascript at very bottom of your page (after your html element has rendered) you can leave that.

For example, in this case it needs:

<script>
   //before create the element
   $(function() { //same as document ready
       $('#element').on('click', function () {
          alert('Hi');
       });
   });
</script>

<div id="element">some text</div>

but in this case not:

<div id="element"></div>
<script>
   //Your element has already rendered
   $('#element').on('click', function () {
      alert('Hi');
   });
</script>

and you can use your validation on blur.

$('#myInput').on('blur', function() {
   $("#theForm").validate();
});

These are the basics, when you manipulate DOM by javascript, that is another story.


问:
Scrollbar overlaps content on IE/Edge
I would like to have an horizontal scrollbar and no vertical scroll on a root container and vertical scrollbar on sub-containers and no horizontal scrollbar.
Compatibility needed : IE, Edge, Chrome, FF. (Latest versions)

```<code><rootcontainer> => horizontal scroll
 <subcontainer1> => vertical scroll
  <data></data>
 </subcontainer1>
 <subcontainer2> => vertical scroll
   <data></data>
 </subcontainer2>
</rootcontainer>
</code>```

No problem with the scroll on Chrome and FF, but on IE11 and Edge, the scroll of the root container is overlapping with the content of the sub container.

Note: each subcontainer must have a width equals to 50% of the subcontainer.

Here is my problem in a fiddle.

What did I missed to make it work ?

EDIT :

Windows 10 Edge

Windows 10 IE

Please note that on IE11, the borders are not visibles.
The bug is more visible on Edge

答: Be sure to check the list of Flex bugs that IE has; especially since you're using box-sizing: border-box, a property known to have compatibility issues in IE: https://github.com/philipwalton/flexbugs#flexbug-7

Title: Scrollbar overlaps content on IE/Edge

Body:
I would like to have an horizontal scrollbar and no vertical scroll on a root container and vertical scrollbar on sub-containers and no horizontal scrollbar.
Compatibility needed : IE, Edge, Chrome, FF. (Latest versions)

<rootcontainer> => horizontal scroll
 <subcontainer1> => vertical scroll
  <data></data>
 </subcontainer1>
 <subcontainer2> => vertical scroll
   <data></data>
 </subcontainer2>
</rootcontainer>

No problem with the scroll on Chrome and FF, but on IE11 and Edge, the scroll of the root container is overlapping with the content of the sub container.

Note: each subcontainer must have a width equals to 50% of the subcontainer.

Here is my problem in a fiddle.

What did I missed to make it work ?

EDIT :

Windows 10 Edge

Windows 10 IE

Please note that on IE11, the borders are not visibles.
The bug is more visible on Edge


问:
Embedding password in and Internal Console App
I'm about to release a console application onto one of our servers to be run by the task scheduler on a daily basis. Based on certain conditions, the application will email selected users through Office 365. In order to email users, of course, I'll need to use the credentials for an email account.

Given that this is an internal application on one of our servers, is embedding the username and password in the code safe? If not, what is the best practice to securely get around this?

If it helps, this is my code for the email function (written in C#):

```<code>String userName = "my.email@organization.ca";
String password = "myPassword";

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(user.getEmail()));
msg.From = new MailAddress(userName);
msg.Subject = "My Subject";
msg.Body = "My message";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "mail.office365.com";
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Port = 587;
client.EnableSsl = true;
client.Send(msg);
</code>```

Edit: I should add that only administrators have access to this specific server.

答:
It's not safe in that anyone with access to that code or the application can get the password to the account with ease.

It's about risk vs reward. If a malicious player has access to the code or server then surely you have bigger issues to worry about than someone being able to access a mail account that can easily be recovered or shut down.

Is it worth going through extra trouble to prevent this outcome? It's up to you.

Arguably the configuration details should at least be in App.config so that they can be easily changed if a password expires, otherwise you'd have to recompile and redeploy the entire solution.

Ideally you should look into the various means available to you to perform encryption of your configuration file if you want to be as safe as possible. A simple search for c# encrypt configuration has enough material to get you started.

Body:
I'm about to release a console application onto one of our servers to be run by the task scheduler on a daily basis. Based on certain conditions, the application will email selected users through Office 365. In order to email users, of course, I'll need to use the credentials for an email account.

Given that this is an internal application on one of our servers, is embedding the username and password in the code safe? If not, what is the best practice to securely get around this?

If it helps, this is my code for the email function (written in C#):

String userName = "my.email@organization.ca";
String password = "myPassword";

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(user.getEmail()));
msg.From = new MailAddress(userName);
msg.Subject = "My Subject";
msg.Body = "My message";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "mail.office365.com";
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Port = 587;
client.EnableSsl = true;
client.Send(msg);

Edit: I should add that only administrators have access to this specific server.


问:
Picasso won't load image (Android)
I'm trying to load image to ImageView using Picasso. The most basic stuff.

I know it's straightforward and I'm pretty sure I did it properly but it wouldn't work for some reason. No photo is shown in my app. I have found someone having the same issue (this, for example, Android - Picasso in Android Studio doesn't load) and my code is almost exactly the same as the fixed version of theirs, but it still wouldn't work.

Here is my code.

In MainActivity.java, I have

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

    if(savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new MyFragment())
                .commit();
    }
</code>```

And in MyFragment.java, I have

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    ImageView image = (ImageView) rootView.findViewById(R.id.movie_image);
    Picasso.with(getActivity()).load(Uri.parse("http://i.imgur.com/DvpvklR.png")).into(image);

    return rootView;
}
</code>```

fragment_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/movie_image" />

</FrameLayout>
</code>```

Manifest file

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.popmovies">

   <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

    <user-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>
</code>```

build.gradle (module:app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.admin.popmovies"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

repositories {
    mavenCentral();
}
</code>```

Any suggestion would be appreciated!

EDIT: Logcat
I got some messages in Logcat from Picasso previously, but I checked again and now there is no log from Picasso.
It looked exactly like in the other thread that has the same issue which looks like this..

```<code>02-23 16:41:36.857  28865-28865/com.example.enrico.prova D/Picasso﹕ Main        created      [R1] Request{http://www.online-image-editor.com//styles/2014/images/example_image.png}
02-23 16:41:36.858  28865-28884/com.example.enrico.prova D/Picasso﹕ Dispatcher  enqueued     [R1]+0ms
02-23 16:41:36.876  28865-29238/com.example.enrico.prova D/Picasso﹕ Hunter      executing    [R1]+16ms
02-23 16:41:36.883  28865-28884/com.example.enrico.prova D/Picasso﹕ Dispatcher  batched      [R1]+25ms for error
02-23 16:41:37.112  28865-28884/com.example.enrico.prova D/Picasso﹕ Dispatcher  delivered    [R1]+254ms
02-23 16:41:37.112  28865-28865/com.example.enrico.prova D/Picasso﹕ Main        errored      [R1]+255ms
</code>```

UPDATE:

I figured it out! It was because target sdk version in my app was 23, while my phone is using KitKat. When I changed dependency in gradle to  compile 'com.android.support:appcompat-v7:21.0.2'instead of compile 'com.android.support:appcompat-v7:23.1.1', it works.

Thanks again for all suggestion!

答:
The main error is in your manifest file.

You should correct :

<user-permission android:name="android.permission.INTERNET" />

To:

<uses-permission android:name="android.permission.INTERNET" />

And all the pictures will work!

Title: Picasso won't load image (Android)

Body:
I'm trying to load image to ImageView using Picasso. The most basic stuff.

I know it's straightforward and I'm pretty sure I did it properly but it wouldn't work for some reason. No photo is shown in my app. I have found someone having the same issue (this, for example, Android - Picasso in Android Studio doesn't load) and my code is almost exactly the same as the fixed version of theirs, but it still wouldn't work.

Here is my code.

In MainActivity.java, I have

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

    if(savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new MyFragment())
                .commit();
    }

And in MyFragment.java, I have

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    ImageView image = (ImageView) rootView.findViewById(R.id.movie_image);
    Picasso.with(getActivity()).load(Uri.parse("http://i.imgur.com/DvpvklR.png")).into(image);

    return rootView;
}

fragment_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/movie_image" />

</FrameLayout>

Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.popmovies">

   <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

    <user-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>

build.gradle (module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.admin.popmovies"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

repositories {
    mavenCentral();
}

Any suggestion would be appreciated!

EDIT: Logcat
I got some messages in Logcat from Picasso previously, but I checked again and now there is no log from Picasso.
It looked exactly like in the other thread that has the same issue which looks like this..

02-23 16:41:36.857  28865-28865/com.example.enrico.prova D/Picasso﹕ Main        created      [R1] Request{http://www.online-image-editor.com//styles/2014/images/example_image.png}
02-23 16:41:36.858  28865-28884/com.example.enrico.prova D/Picasso﹕ Dispatcher  enqueued     [R1]+0ms
02-23 16:41:36.876  28865-29238/com.example.enrico.prova D/Picasso﹕ Hunter      executing    [R1]+16ms
02-23 16:41:36.883  28865-28884/com.example.enrico.prova D/Picasso﹕ Dispatcher  batched      [R1]+25ms for error
02-23 16:41:37.112  28865-28884/com.example.enrico.prova D/Picasso﹕ Dispatcher  delivered    [R1]+254ms
02-23 16:41:37.112  28865-28865/com.example.enrico.prova D/Picasso﹕ Main        errored      [R1]+255ms

UPDATE:

I figured it out! It was because target sdk version in my app was 23, while my phone is using KitKat. When I changed dependency in gradle to  compile 'com.android.support:appcompat-v7:21.0.2'instead of compile 'com.android.support:appcompat-v7:23.1.1', it works.

Thanks again for all suggestion!

ContentLicense: CC BY-SA 4.0


问:
How to create Start menu items for all users when running installer with PrivilegesRequired=lowest as Administrator
Inno Setup documentation says the following:

{group}
      The path to the Start Menu folder, as selected by the user on Setup's Select Start Menu Folder wizard page. This folder is created under the All Users profile unless the user installing the application does not have administrative privileges, in which case it is created in the user's profile.*

When I use PrivilegesRequired=admin (i.e. the default), Start menu items are created for all users in C:\ProgramData\Microsoft\Windows\Start Menu\Programs.

When I use PrivilegesRequired=lowest, but run setup with right-click run-as-administrator, Start menu items are created for just the admin user in C:\Users\admin-user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs.  This happens even if the current user is an admin.

How can I make start menu items be for all users when using right-click elevation?  In this situation, Setup installs program files for all users in C:\Program Files\.  So I would like start menu items also to be for all users.

答:
Use a scripted constant to dynamically change Start menu root path, based on an elevation status of the installer.

You have to use WinAPI (e.g. SHGetFolderPath) to retrieve the path to common Start menu folder, as {commonprograms} actually return {userprograms}, if PrivilegesRequired=lowest, even when the installer is actually running elevated.

[Icons]
Name: "{code:GetMenuRootPath}\{groupname}\My Program"; Filename: "{app}\MyProg.exe"
```

<pre class="lang-pascal prettyprint-override"><code>[Code]

const
  CSIDL_COMMON_PROGRAMS = $0017;
  SHGFP_TYPE_CURRENT = 0;
  MAX_PATH = 260;
  S_OK = 0;

function SHGetFolderPath(
  hwnd: HWND; csidl: Integer; hToken: THandle; dwFlags: DWORD;
  pszPath: string): HResult;
  external 'SHGetFolderPathW@shell32.dll stdcall';

function GetMenuRootPath(Param: string): string;
var
  R, I: Integer;
begin
  if IsAdminLoggedOn then
  begin
    SetLength(Result, MAX_PATH);
    R := SHGetFolderPath(0, CSIDL_COMMON_PROGRAMS, 0, SHGFP_TYPE_CURRENT, Result);
    if R <> S_OK then
    begin
      Log('Failed to resolve path to common Start menu folder');
    end
      else
    begin
      SetLength(Result, Pos(#0, Result) - 1);

      Log(Format('Resolved path to common Start menu folder: %s', [Result]));
    end;
  end
    else
  begin
    Result := ExpandConstant('{userprograms}');
    Log(Format('Using user''s Start menu folder: %s', [Result]))
  end;
end;
</code>```

The code is for Unicode version of Inno Setup (the only version as of Inno Setup 6).

Though note that using groups in Start menu is against Windows guidelines for Windows 8 and newer.

Body:
Use a scripted constant to dynamically change Start menu root path, based on an elevation status of the installer.

You have to use WinAPI (e.g. SHGetFolderPath) to retrieve the path to common Start menu folder, as {commonprograms} actually return {userprograms}, if PrivilegesRequired=lowest, even when the installer is actually running elevated.

[Icons]
Name: "{code:GetMenuRootPath}\{groupname}\My Program"; Filename: "{app}\MyProg.exe"

[Code]

const
  CSIDL_COMMON_PROGRAMS = $0017;
  SHGFP_TYPE_CURRENT = 0;
  MAX_PATH = 260;
  S_OK = 0;

function SHGetFolderPath(
  hwnd: HWND; csidl: Integer; hToken: THandle; dwFlags: DWORD;
  pszPath: string): HResult;
  external 'SHGetFolderPathW@shell32.dll stdcall';

function GetMenuRootPath(Param: string): string;
var
  R, I: Integer;
begin
  if IsAdminLoggedOn then
  begin
    SetLength(Result, MAX_PATH);
    R := SHGetFolderPath(0, CSIDL_COMMON_PROGRAMS, 0, SHGFP_TYPE_CURRENT, Result);
    if R <> S_OK then
    begin
      Log('Failed to resolve path to common Start menu folder');
    end
      else
    begin
      SetLength(Result, Pos(#0, Result) - 1);

      Log(Format('Resolved path to common Start menu folder: %s', [Result]));
    end;
  end
    else
  begin
    Result := ExpandConstant('{userprograms}');
    Log(Format('Using user''s Start menu folder: %s', [Result]))
  end;
end;

The code is for Unicode version of Inno Setup (the only version as of Inno Setup 6).

Though note that using groups in Start menu is against Windows guidelines for Windows 8 and newer.


问:
What are current recommended settings for a Microsoft app used with Janrain Single Sign On?
I am trying to configure a new Microsoft Account for use with Janrain (RPX) Single Sign On.  I have Google, Twitter and Yahoo working.  I mention that because it indicates that most of my configuration is valid.

The Janrain docs for the Microsoft provider do not match the current Microsoft screens at all.

I was wondering whether anyone who got the Microsoft provider working some time ago, when the docs must have matched, would be able/willing to log in to their Microsoft dev apps account, and provide a brief guide to the old/new way of referring to the details that are critical to integration with Janrain.

As one example, on the Microsoft apps page, Microsoft has a heading "App ID / Client Id".  I assume that mean that the item listed just below must be filled in for the ClientID requested by Janrain.  Probably.

Is Implicit Flow required? recommended? for use with Janrain ?

For the Client Secret required by Janrain when configuring the Microsoft Provider, do you go under Application Secrets on the Microsoft app page, click [Generate New Password], and use that password which is given once right then?

The error message that I am getting is "Token exchange error for Microsoft Account."

Is a sign OUT page required for use with Microsoft? What did you use for the Sign OUT Url?  A static html page, containing what? I expected this to be a URL that Janrain would tell us to use, not a static page on our site as the little Microsoft help tip indicates.

Screenshots of the application as configured on my Microsoft panel follow.

答:
Looks like Microsoft has changed the UI once again.  I'll open a ticket to have our documentation updated.

The current URL for setting up the Microsoft Login is:
https://apps.dev.microsoft.com/?mkt=en-us&referrer=https%3a%2f%2faccount.live.com#/appList

Here are the steps to create a new login application:

Login to the url above

Under "Live SDK applications" click the "Add an app" button

Give your app an obvious name.

Check the "Allow Implicit Flow" checkbox

Check the "Restrict token issuing to this app" checkbox

Uncheck the "Enhanced redirection security" checkbox

Target domain should be something like: "YOUR_ENGAGE_APP_NAME.rpxnow.com"

Redirect URL should be something
like: "https://YOUR_ENGAGE_APP_NAME.rpxnow.com"

I think the Logo, Terms of Service URL and Privacy Statement URL might be optional but if you want to be "professional" then go ahead and fill them in with valid URL's for you web site.

Once you save you changes, the site should give you an Application Id and Application Secret that you can use in the Engage application provider configuration for Microsoft Login.


问:
How to assign values to more than one variable from set of files using batch for loop?
I am trying to call a batch script with parameter, from another script. I have two txt files containing list of PC IP addresses and list of services to check running on those PCs. I am planning this will remotely check service status or file exists on bulk of PCs. What I have tried, main.bat contains:

```<code>for /f %%i %%j in (PCList.txt FileList.txt) do call anotherscript.bat %%i %%j
</code>```

definitely it should not work as there is nothing like this in for man page, I know. what I am trying, use two variables that will hold two values from two files respectively  and call anotherscript.bat with two parameters. I am able to play with one variable and one file. anotherscript.bat contains:

```<code>psexec.exe \\%1 -s IF EXIST "%2" ( echo File exist : %2 >>"%~dp0\logs.txt" )
</code>```

FileList.txt contains

```<code>"C:\Program Files\Java\jre1.8.0_144"
"C:\Program Files\Java\jre1.8.0_144\bin"
</code>```

PCList.txt contains

```<code>LANS14118815
LANS14118816
</code>```

Is there any workaround? Please support. Thanks

答:
You need a method to read from two files in parallel. This is possible by using two methods at the same time (<file1 set /p and for /f ... in (file2)):

```<code>@echo off
setlocal enabledelayedexpansion

<pclist.txt (
  for /f "delims=" %%a in (filelist.txt) do (
    set /p out=
    ECHO call anotherscript.bat "!out!" "%%~a"
  )
)
</code>```

Remove the ECHO, if the output is what you need.

Body:
I am trying to call a batch script with parameter, from another script. I have two txt files containing list of PC IP addresses and list of services to check running on those PCs. I am planning this will remotely check service status or file exists on bulk of PCs. What I have tried, main.bat contains:

for /f %%i %%j in (PCList.txt FileList.txt) do call anotherscript.bat %%i %%j

definitely it should not work as there is nothing like this in for man page, I know. what I am trying, use two variables that will hold two values from two files respectively  and call anotherscript.bat with two parameters. I am able to play with one variable and one file. anotherscript.bat contains:

psexec.exe \\%1 -s IF EXIST "%2" ( echo File exist : %2 >>"%~dp0\logs.txt" )

FileList.txt contains

"C:\Program Files\Java\jre1.8.0_144"
"C:\Program Files\Java\jre1.8.0_144\bin"

PCList.txt contains

LANS14118815
LANS14118816

Is there any workaround? Please support. Thanks

Body:
You need a method to read from two files in parallel. This is possible by using two methods at the same time (<file1 set /p and for /f ... in (file2)):

@echo off
setlocal enabledelayedexpansion

<pclist.txt (
  for /f "delims=" %%a in (filelist.txt) do (
    set /p out=
    ECHO call anotherscript.bat "!out!" "%%~a"
  )
)

Remove the ECHO, if the output is what you need.


问:
Zooming in & out an image by clicking zoom buttons (Javascript)
I'm trying to get an image zoomed in & out by two zoom buttons (+) & (-). The problem is that "zooming in" stops when the image is full screen size (width 100%). I need to zoom the image much bigger than the screen size. Just can't figure it out how to o that. I'm beginner with Javascript so I hope someone have motivation to help me this little Javascript problem.

I wonder is there any simple zoom in/out/reset plugins that works with zoom buttons? Image grab would be more than cool also.

Thanks again!

function zoomin(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        if(currWidth == 2500) return false;
         else{
            myImg.style.width = (currWidth + 100) + "px";
        }
    }
    function zoomout(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        if(currWidth == 100) return false;
   else{
            myImg.style.width = (currWidth - 100) + "px";
        }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*body {
  margin: 0;
}
#navbar {
 overflow: hidden;
 background-color: #099;
 position: fixed;
 top: 0;
 width: 100%;
 padding-top: 3px;
 padding-bottom: 3px;
 padding-left: 20px;
}
#navbar a {
  float: left;
  display: block;
  color: #666;
  text-align: center;
  padding-right: 20px;
  text-decoration: none;
  font-size: 17px;
}
#navbar a:hover {
  background-color: #ddd;
  color: black;
}
#navbar a.active {
  background-color: #4CAF50;
  color: white;
}
.main {
  padding: 16px;
  margin-top: 30px;
}
.main img {
 max-width: 100%;
 height: auto;
}
.button {
  width: 300px;
  height: 60px;
}</code>```

<button type="button" onclick="zoomin()"> Zoom In</button>
<button type="button" onclick="zoomout()"> Zoom Out</button>

```

" />

答: Remove max-width: 100%; from .main img css</p>

Body:
I'm trying to get an image zoomed in & out by two zoom buttons (+) & (-). The problem is that "zooming in" stops when the image is full screen size (width 100%). I need to zoom the image much bigger than the screen size. Just can't figure it out how to o that. I'm beginner with Javascript so I hope someone have motivation to help me this little Javascript problem.

I wonder is there any simple zoom in/out/reset plugins that works with zoom buttons? Image grab would be more than cool also.

Thanks again!

function zoomin(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        if(currWidth == 2500) return false;
         else{
            myImg.style.width = (currWidth + 100) + "px";
        }
    }
    function zoomout(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        if(currWidth == 100) return false;
   else{
            myImg.style.width = (currWidth - 100) + "px";
        }
    }

*body {
  margin: 0;
}
#navbar {
 overflow: hidden;
 background-color: #099;
 position: fixed;
 top: 0;
 width: 100%;
 padding-top: 3px;
 padding-bottom: 3px;
 padding-left: 20px;
}
#navbar a {
  float: left;
  display: block;
  color: #666;
  text-align: center;
  padding-right: 20px;
  text-decoration: none;
  font-size: 17px;
}
#navbar a:hover {
  background-color: #ddd;
  color: black;
}
#navbar a.active {
  background-color: #4CAF50;
  color: white;
}
.main {
  padding: 16px;
  margin-top: 30px;
}
.main img {
 max-width: 100%;
 height: auto;
}
.button {
  width: 300px;
  height: 60px;
}

<button type="button" onclick="zoomin()"> Zoom In</button>
<button type="button" onclick="zoomout()"> Zoom Out</button>

" />


问:
create-react-app + Visual Studio + F5 = "Unexpected token import"
React newbie here. How can I enable Visual Studio 2017 to run (via F5) a react.js app that's been created by create-react-app?  Here's the steps I've followed so far:

npm install -g create-react-app

create-react-app my-app

In Visual Studio 2016 RC (5.0.26206.0 D15REL) with Node.js Tools( 1.3.41102.00) I created a node.js project using the "from existing code" option.

I set the startup file to src/index.js

F5

I get this error:

```<code>Debugger listening on port 5858
 H:\dev\XXXXXX\src\index.js:1
(function (exports, require, module, __filename, __dirname) { import React from 'react';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:404:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.runMain [as _onTimeout] (module.js:429:10)
    at Timer.listOnTimeout (timers.js:92:15)
 Press any key to continue...
</code>```

npm start works fine. I assume that I need to instruct Visual Studio to either execute npm start or to duplicate what npm start is doing. I'm sure I'm not the first person that's tried this. What's the recommended solution?

答:
A bit late in the game but I had a simliar error in a project using angular and .net in visual studio 2017. I fixed it by giong to tools -> project and solutions -> Web Package Management -> External Web Tools

and moving the Path variable up in the order. see image

Body:
React newbie here. How can I enable Visual Studio 2017 to run (via F5) a react.js app that's been created by create-react-app?  Here's the steps I've followed so far:

npm install -g create-react-app

create-react-app my-app

In Visual Studio 2016 RC (5.0.26206.0 D15REL) with Node.js Tools( 1.3.41102.00) I created a node.js project using the "from existing code" option.

I set the startup file to src/index.js

F5

I get this error:

Debugger listening on port 5858
 H:\dev\XXXXXX\src\index.js:1
(function (exports, require, module, __filename, __dirname) { import React from 'react';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:404:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.runMain [as _onTimeout] (module.js:429:10)
    at Timer.listOnTimeout (timers.js:92:15)
 Press any key to continue...

npm start works fine. I assume that I need to instruct Visual Studio to either execute npm start or to duplicate what npm start is doing. I'm sure I'm not the first person that's tried this. What's the recommended solution?


问:
How to make a div clickable and redirect to an url Angular JS
This might seem like a stupid question but I am learning Angular JS these days and came across a problem. I want to make a div clickable and once you click on it, it should go to another page, but I can't seem to make it work....

```

答:
This is what [ng-href][1] directive is for. Compiled acts as a simple html href attribute.

```<code><a class="test" ng-href="/url?language={{$control.lang}}"></a>
</code>```

If you wanted to use [ng-click][1] because of some reason, you would actually need to call a function from within your controller. Inside the function you'd have to manually change the location using [$location][1] or $window module preferably.

```<code>$scope.GoTo = function(url){
   $location.path(url);
}
</code>```

Then your div would become

```<code><div class="test" ng-click="GoTo('/url?language='+$control.lang)"></div>
</code>```

Make sure you inject the $location module into your controller too.

Body:
This is what [ng-href][1] directive is for. Compiled acts as a simple html href attribute.

<a class="test" ng-href="/url?language={{$control.lang}}"></a>

If you wanted to use [ng-click][1] because of some reason, you would actually need to call a function from within your controller. Inside the function you'd have to manually change the location using [$location][1] or $window module preferably.

$scope.GoTo = function(url){
   $location.path(url);
}

Then your div would become

<div class="test" ng-click="GoTo('/url?language='+$control.lang)"></div>

Make sure you inject the $location module into your controller too.


答:
For your first query. Simply

```<code>SELECT t1.*
FROM tableName t1
WHERE t1.log_id = (SELECT MAX(t2.log_id)
                 FROM tableName t2
                 WHERE t2.employee_id = t1.employee_id)
</code>```

For the second one

```<code>SELECT t1.*
FROM tableName  t1
WHERE t1.employee_id=X and t1.log_id = (SELECT MAX(t2.log_id)
                 FROM tableName t2
                 WHERE t2.employee_id = t1.employee_id);
</code>```

Title: Select only latest record for every employees and for specific employee in MySQL

Body:
I have a MySQL DB and in it there's a table with activity logs of employees.

+-------------------------------------------------+
| log_id | employee_id | date_time  | action_type |
+-------------------------------------------------+
|   1    |      1      | 2015/02/03 |   action1   |
|   2    |      2      | 2015/02/01 |   action1   |
|   3    |      2      | 2017/01/02 |   action2   |
|   4    |      3      | 2016/02/12 |   action1   |
|   5    |      1      | 2016/10/12 |   action2   |
+-------------------------------------------------+

And I would need 2 queries. First, to get for every employee his last action. So from this example table I would need to get row 3,4 and 5 with all columns. And second, get the latest action only for specified employee.

Any ideas how to achieve this? I'm using Spring Data JPA, but raw SQL Query would be also great.

Thank you in advance.

Body:
For your first query. Simply

SELECT t1.*
FROM tableName t1
WHERE t1.log_id = (SELECT MAX(t2.log_id)
                 FROM tableName t2
                 WHERE t2.employee_id = t1.employee_id)

For the second one

SELECT t1.*
FROM tableName  t1
WHERE t1.employee_id=X and t1.log_id = (SELECT MAX(t2.log_id)
                 FROM tableName t2
                 WHERE t2.employee_id = t1.employee_id);


问:
Firestore: Get subcollection of document found with where
I am trying to get the documents inside an subcollection which is part of an document found with the .where function

Example:

RootColl/

Doc A/

SubColl 1

Doc 1

Doc 2

Doc 3

SubColl 2

Docs

Doc A/

SubColl 1

Doc 1

Doc 2

Doc 3

SubColl 2

Docs

I want to get all the documents under SubColl 1 from the doc with the field level == 1

I am trying to do it like:

```<code>db.collection("RootColl").where("field", "==", "1").collection("SubColl 1").get()
</code>```

But by doing that I get the error

Uncaught TypeError: db.collection(...).where(...).collection is not a function

EDIT 1:
By following Frank van Puffelen suggestion, i get the same error, "collection" is not a function

Current Code

Error

答:
A sub-collection lives under a specific document. A query as you've shared now points to a number of documents. You'll need to execute the query to determine what documents it points to, then loop over the results, and get the sub-collection for each document.

In code:

```<code>var query = db.collection("RootColl").where("field", "==", "1");
query.get().then((querySnapshot) => {
  querySnapshot.forEach((document) => {
    document.ref.collection("SubColl 1").get().then((querySnapshot) => {
      ...
    });
  });
});
</code>```

Body:
I am trying to get the documents inside an subcollection which is part of an document found with the .where function

Example:

RootColl/

Doc A/

SubColl 1

Doc 1

Doc 2

Doc 3

SubColl 2

Docs

Doc A/

SubColl 1

Doc 1

Doc 2

Doc 3

SubColl 2

Docs

I want to get all the documents under SubColl 1 from the doc with the field level == 1

I am trying to do it like:

db.collection("RootColl").where("field", "==", "1").collection("SubColl 1").get()

But by doing that I get the error

Uncaught TypeError: db.collection(...).where(...).collection is not a function

EDIT 1:
By following Frank van Puffelen suggestion, i get the same error, "collection" is not a function

Current Code

Error

Body:
A sub-collection lives under a specific document. A query as you've shared now points to a number of documents. You'll need to execute the query to determine what documents it points to, then loop over the results, and get the sub-collection for each document.

In code:

var query = db.collection("RootColl").where("field", "==", "1");
query.get().then((querySnapshot) => {
  querySnapshot.forEach((document) => {
    document.ref.collection("SubColl 1").get().then((querySnapshot) => {
      ...
    });
  });
});


问:
How come .sh shell scripts work in Concourse tutorial but NOT in my actual codebase?
Very much a newbie to CI system setup, so please be gentle :)

I'm following a Stark And Wayne tutorial & trying to get a Concourse CI task yml to run a shell script that it finds via the input folder:

task.yml

```<code>---
platform: linux

image_resource:
  type: docker-image
  source: {repository: busybox}

inputs:
- name: my-input-folder

run:
  path: ./my-input-folder/my-shell-script.sh
</code>```

So when i run:

fly --target team-name execute --config task.yml -i my-input-folder=my-input-folder

It should go into that folder, action my-shell-script.sh and echo the this is working that's in there.

Instead i get:

```<code>hijack: Backend error: Exit status: 500, message: {"Type":"","Message":"runc exec: exit status 1: exec failed: container_linux.go:264: starting container process caused \"exec: \\\"./__tests__/this-is-my-shell-script.sh\\\": permission denied\"\n","Handle":""}
</code>```

I get this is something to do with the docker/busybox image, from this other thread.

But...

a) why does it work with the same .sh extension and busybox image on their tutorial? (but then not when i use it on my actual project?)

b) how can i resolve this so that my project is running shell scripts? Which docker image would work?

答:
I found out through colleagues this error was due to:

a) needing to chmod +x folder/name-of-file.sh so it's an executable file.

and

b) Adding in the #!/bin/sh to the beginning of my .sh file (as i'm using oh-my-zsh). Though i gather if i were using bash, this would be #!/bin/bash.

Now the shell script links fine.

Body:
Very much a newbie to CI system setup, so please be gentle :)

I'm following a Stark And Wayne tutorial & trying to get a Concourse CI task yml to run a shell script that it finds via the input folder:

task.yml

---
platform: linux

image_resource:
  type: docker-image
  source: {repository: busybox}

inputs:
- name: my-input-folder

run:
  path: ./my-input-folder/my-shell-script.sh

So when i run:

fly --target team-name execute --config task.yml -i my-input-folder=my-input-folder

It should go into that folder, action my-shell-script.sh and echo the this is working that's in there.

Instead i get:

hijack: Backend error: Exit status: 500, message: {"Type":"","Message":"runc exec: exit status 1: exec failed: container_linux.go:264: starting container process caused \"exec: \\\"./__tests__/this-is-my-shell-script.sh\\\": permission denied\"\n","Handle":""}

I get this is something to do with the docker/busybox image, from this other thread.

But...

a) why does it work with the same .sh extension and busybox image on their tutorial? (but then not when i use it on my actual project?)

b) how can i resolve this so that my project is running shell scripts? Which docker image would work?


问:
Is it worth creating an interface for a trivial return type?
Consider the following interfaces:

```<code>public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

and the associated implementations:

```<code>public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?

答: PlayerInfo is just a simple data-storage-structure, and does not have much of a contract to formalize in a form of an interface. I avoid creating interfaces for classes that don't really DO anything.

Body:
Consider the following interfaces:

public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

and the associated implementations:

public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?


问:
Image is not visible in android project with XAML forms - Xamarin even though provided solutions applied
I tried solutions from the following links but none worked.

where-to-put-images-for-xamarin-froms-application

developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Local_Images

image-not-showing-in-xamarin-forms-app.html

I used below syntax

```<code><Image Source="lock.png" HeightRequest="20" WidthRequest="20" HorizontalOptions="Center" VerticalOptions="Center"  Grid.Row="0" Grid.Column="0"></Image>
</code>```

Here is the image for where i've kept image

No image displays

Edit

These are the only things in my XAML page.

答: In my case I need to use method Forms.Init(Context activity, Bundle bundle), in my SplashScreen OnCreate method and Activity class OnCreate method. But it also important that images build action properties is set on AndroidResource.

Body:
I tried solutions from the following links but none worked.

where-to-put-images-for-xamarin-froms-application

developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Local_Images

image-not-showing-in-xamarin-forms-app.html

I used below syntax

<Image Source="lock.png" HeightRequest="20" WidthRequest="20" HorizontalOptions="Center" VerticalOptions="Center"  Grid.Row="0" Grid.Column="0"></Image>

Here is the image for where i've kept image

No image displays

Edit

These are the only things in my XAML page.


答:
Your zoom method is working good just remove the css max width, and change your js validation to allow the image, get bigger.

function zoomin(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        //if(currWidth == 2500) return false;
        // else{
        //    myImg.style.width = (currWidth + 100) + "px";
        //}
        myImg.style.width = (currWidth + 100) + "px";
    }
    function zoomout(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        if(currWidth == 100) return false;
   else{
            myImg.style.width = (currWidth - 100) + "px";
        }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*body {
  margin: 0;
}
#navbar {
 overflow: hidden;
 background-color: #099;
 position: fixed;
 top: 0;
 width: 100%;
 padding-top: 3px;
 padding-bottom: 3px;
 padding-left: 20px;
}
#navbar a {
  float: left;
  display: block;
  color: #666;
  text-align: center;
  padding-right: 20px;
  text-decoration: none;
  font-size: 17px;
}
#navbar a:hover {
  background-color: #ddd;
  color: black;
}
#navbar a.active {
  background-color: #4CAF50;
  color: white;
}
.main {
  padding: 16px;
  margin-top: 30px;
}
.main img {
 /* max-width: 100%; */
 height: auto;
}
.button {
  width: 300px;
  height: 60px;
}</code>```

<button type="button" onclick="zoomin()"> Zoom In</button>
<button type="button" onclick="zoomout()"> Zoom Out</button>

```

On the other hand I would recommend magic zoom as a zoom library

Title: Zooming in & out an image by clicking zoom buttons (Javascript)

Body:
Your zoom method is working good just remove the css max width, and change your js validation to allow the image, get bigger.

function zoomin(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        //if(currWidth == 2500) return false;
        // else{
        //    myImg.style.width = (currWidth + 100) + "px";
        //}
        myImg.style.width = (currWidth + 100) + "px";
    }
    function zoomout(){
        var myImg = document.getElementById("map");
        var currWidth = myImg.clientWidth;
        if(currWidth == 100) return false;
   else{
            myImg.style.width = (currWidth - 100) + "px";
        }
    }

*body {
  margin: 0;
}
#navbar {
 overflow: hidden;
 background-color: #099;
 position: fixed;
 top: 0;
 width: 100%;
 padding-top: 3px;
 padding-bottom: 3px;
 padding-left: 20px;
}
#navbar a {
  float: left;
  display: block;
  color: #666;
  text-align: center;
  padding-right: 20px;
  text-decoration: none;
  font-size: 17px;
}
#navbar a:hover {
  background-color: #ddd;
  color: black;
}
#navbar a.active {
  background-color: #4CAF50;
  color: white;
}
.main {
  padding: 16px;
  margin-top: 30px;
}
.main img {
 /* max-width: 100%; */
 height: auto;
}
.button {
  width: 300px;
  height: 60px;
}

</head>
<body>

<div id="navbar">
<button type="button" onclick="zoomin()"> Zoom In</button>
<button type="button" onclick="zoomout()"> Zoom Out</button>
</div>

<div class="main">
<img id="map" src="http://www.worldatlas.com/webimage/countrys/europelargesm.jpg" />
</div>

On the other hand I would recommend magic zoom as a zoom library


问:
gRPC client do not dispose Channel
I'm developing .net core 2.0 application with gRPC and find out a problem: after delete reference to instance of my gRPC client class, there still channel that use resourses (memory and processor).
Example code:

```<code>public class MyClient : ClientBase
    {
        public MyClient(Channel channel) : base(channel)
        {
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var list = new List<MyClient>();
            for (var i = 0; i < 10000; i++)
            {
                Console.WriteLine($"Creating {i} instance");
                list.Add(new MyClient(new Channel("127.0.0.1:61783", ChannelCredentials.Insecure)));
            }

            Console.WriteLine("press enter to list = null");
            Console.ReadLine();
            list = null;

            Console.WriteLine("press enter to GC.Collect();");
            Console.ReadLine();
            GC.Collect();

            Console.WriteLine("press enter to exit");
            Console.ReadLine();
        }
    }
</code>```

If u run example, u'll see that 10% (on my PC) used by this application. Even after list = null and GC.Collect()

The reason i suppose is  ClientBase do not call Channel.ShutdownAsync().

So the question is:

What is the better way to resolve problem?

p.s. actually i use a "generated by the protocol buffer compiler" Client

```<code>Client: Grpc.Core.ClientBase<TDto>
</code>```

and i can't explicitly change finalizer in generated class

答:
Possible suggestion would be to make the client implement IDisposable and in the Dispose method call the Channel.ShutdownAsync().

```<code>public class MyClass : Client, IDisposable {
    Channel channel;
    private bool _isDisposed = false;
    private readonly object _lock = new object();

    public MyClass(Channel channel)
        : base(channel) {
        this.channel = channel;
        this.channelDisposing += onDisposing;
    }

    public Channel Channel { get { return channel; } }

    private event EventHandler channelDisposing = delegate { };

    async void onDisposing(object sender, EventArgs e) {
        await channel.ShutdownAsync();
        channel = null;
    }

    public void Dispose() {
        if (!_isDisposed) {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

    void Dispose(bool disposing) {
        // No exception should ever be thrown except in critical scenarios.
        // Unhandled exceptions during finalization will tear down the process.
        if (!_isDisposed) {
            try {
                if (disposing) {
                    // Acquire a lock on the object while disposing.
                    if (channel != null) {
                        lock (_lock) {
                            if (channel != null) {
                                channelDisposing(this, EventArgs.Empty);
                            }
                        }
                    }
                }
            } finally {
                // Ensure that the flag is set
                _isDisposed = true;
            }
        }
    }
}
</code>```

This will allow you to now call Dispose on the clients and release resources or wrap them in using so that it will be done for you when they go out of scope.

```<code>public class Program {
    public static void Main(string[] args) {
        var list = new List<MyClient>();
        for (var i = 0; i < 10000; i++) {
            Console.WriteLine($"Creating {i} instance");
            list.Add(new MyClient(new Channel("127.0.0.1:61783", ChannelCredentials.Insecure)));
        }

        Console.WriteLine("press enter to dispose clients");
        Console.ReadLine();
        list.ForEach(c => c.Dispose());

        Console.WriteLine("press enter to list = null");
        Console.ReadLine();
        list = null;

        Console.WriteLine("press enter to GC.Collect();");
        Console.ReadLine();
        GC.Collect();

        Console.WriteLine("press enter to exit");
        Console.ReadLine();
    }
}
</code>```

Title: gRPC client do not dispose Channel

Body:
I'm developing .net core 2.0 application with gRPC and find out a problem: after delete reference to instance of my gRPC client class, there still channel that use resourses (memory and processor).
Example code:

public class MyClient : ClientBase
    {
        public MyClient(Channel channel) : base(channel)
        {
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var list = new List<MyClient>();
            for (var i = 0; i < 10000; i++)
            {
                Console.WriteLine($"Creating {i} instance");
                list.Add(new MyClient(new Channel("127.0.0.1:61783", ChannelCredentials.Insecure)));
            }

            Console.WriteLine("press enter to list = null");
            Console.ReadLine();
            list = null;

            Console.WriteLine("press enter to GC.Collect();");
            Console.ReadLine();
            GC.Collect();

            Console.WriteLine("press enter to exit");
            Console.ReadLine();
        }
    }

If u run example, u'll see that 10% (on my PC) used by this application. Even after list = null and GC.Collect()

The reason i suppose is  ClientBase do not call Channel.ShutdownAsync().

So the question is:

What is the better way to resolve problem?

p.s. actually i use a "generated by the protocol buffer compiler" Client

Client: Grpc.Core.ClientBase<TDto>

and i can't explicitly change finalizer in generated class

Body:
Possible suggestion would be to make the client implement IDisposable and in the Dispose method call the Channel.ShutdownAsync().

public class MyClass : Client, IDisposable {
    Channel channel;
    private bool _isDisposed = false;
    private readonly object _lock = new object();

    public MyClass(Channel channel)
        : base(channel) {
        this.channel = channel;
        this.channelDisposing += onDisposing;
    }

    public Channel Channel { get { return channel; } }

    private event EventHandler channelDisposing = delegate { };

    async void onDisposing(object sender, EventArgs e) {
        await channel.ShutdownAsync();
        channel = null;
    }

    public void Dispose() {
        if (!_isDisposed) {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

    void Dispose(bool disposing) {
        // No exception should ever be thrown except in critical scenarios.
        // Unhandled exceptions during finalization will tear down the process.
        if (!_isDisposed) {
            try {
                if (disposing) {
                    // Acquire a lock on the object while disposing.
                    if (channel != null) {
                        lock (_lock) {
                            if (channel != null) {
                                channelDisposing(this, EventArgs.Empty);
                            }
                        }
                    }
                }
            } finally {
                // Ensure that the flag is set
                _isDisposed = true;
            }
        }
    }
}

This will allow you to now call Dispose on the clients and release resources or wrap them in using so that it will be done for you when they go out of scope.

public class Program {
    public static void Main(string[] args) {
        var list = new List<MyClient>();
        for (var i = 0; i < 10000; i++) {
            Console.WriteLine($"Creating {i} instance");
            list.Add(new MyClient(new Channel("127.0.0.1:61783", ChannelCredentials.Insecure)));
        }

        Console.WriteLine("press enter to dispose clients");
        Console.ReadLine();
        list.ForEach(c => c.Dispose());

        Console.WriteLine("press enter to list = null");
        Console.ReadLine();
        list = null;

        Console.WriteLine("press enter to GC.Collect();");
        Console.ReadLine();
        GC.Collect();

        Console.WriteLine("press enter to exit");
        Console.ReadLine();
    }
}


问:
MongoDB & NodeJS Insert If Not Exists Else Throw Error
First, I'd like to start by saying I know there are several other posts out there somewhat related to inserting/updating if not exists; however, my case is a bit different and doesn't fit other posts.

I'm trying to insert a new user registration record if the user's email doesn't exist.  All I'm doing right now is inserting the record.

One problem is that duplication checking with upsert:true doesn't really work because of all the unique values that get generated when a record is going to be inserted like the JSON Web Token, and Created Date, etc.  Here is my current code:

```<code>MongoClient.connect('mongodb://localhost:27017/norad', function(err, db){
if (err) return router.error( Error(err) );
db.collection('users', function(err, coll){
    if (err) return router.error( Error(err) );

    coll.insert({
                 'email'    : useremail
                ,'pass'     : userpass
                ,'total_req': 0
                ,'threshold_req': 0
                ,'threshold_start_time': 0
                ,'ak'       : activation_key
                ,'activated': false
                ,'adm'      : false
                ,'iat'      : iat
                ,'created'  : iat
                ,'modified' : iat
            }
            ,function(err, writeResults){
                console.log( writeResults );
                if ( err && err.code == 11000 ) return router.error( ErrorHandler('User already exists.', 'Conflict', 409) )
                if ( err ) return router.error( Error(err) );
                var r = {'email': writeResults.ops[0].email
                        ,'Response':'Your activation code has been emailed to the address used in registration. Please check your email and follow the instructions for account activation.'
                        }

                    ,scallback = function(){ return router.submit(r) }
                    // send the activation email to the user
                    ,res = ActivationEmail(activation_key, useremail, scallback, router)
                    ;
                if ( res instanceof Error ) router.error( Error(err) );
            }
);

});
});
</code>```

I'm not getting any error from this.  Instead, this works fine and inserts a new record with every call, even if the user's email is already present in the table.

I'm trying to add functionality to check if the user's email is present in the table already, and throw an error if so, otherwise, create a new record.

答:
You need to create unique index on email field. E.g. in mongo shell:

```<code>db.users.createIndex(
   { email: 1},
   { unique: true }
);
</code>```

Body:
First, I'd like to start by saying I know there are several other posts out there somewhat related to inserting/updating if not exists; however, my case is a bit different and doesn't fit other posts.

I'm trying to insert a new user registration record if the user's email doesn't exist.  All I'm doing right now is inserting the record.

One problem is that duplication checking with upsert:true doesn't really work because of all the unique values that get generated when a record is going to be inserted like the JSON Web Token, and Created Date, etc.  Here is my current code:

MongoClient.connect('mongodb://localhost:27017/norad', function(err, db){
if (err) return router.error( Error(err) );
db.collection('users', function(err, coll){
    if (err) return router.error( Error(err) );

    coll.insert({
                 'email'    : useremail
                ,'pass'     : userpass
                ,'total_req': 0
                ,'threshold_req': 0
                ,'threshold_start_time': 0
                ,'ak'       : activation_key
                ,'activated': false
                ,'adm'      : false
                ,'iat'      : iat
                ,'created'  : iat
                ,'modified' : iat
            }
            ,function(err, writeResults){
                console.log( writeResults );
                if ( err && err.code == 11000 ) return router.error( ErrorHandler('User already exists.', 'Conflict', 409) )
                if ( err ) return router.error( Error(err) );
                var r = {'email': writeResults.ops[0].email
                        ,'Response':'Your activation code has been emailed to the address used in registration. Please check your email and follow the instructions for account activation.'
                        }

                    ,scallback = function(){ return router.submit(r) }
                    // send the activation email to the user
                    ,res = ActivationEmail(activation_key, useremail, scallback, router)
                    ;
                if ( res instanceof Error ) router.error( Error(err) );
            }
);

});
});

I'm not getting any error from this.  Instead, this works fine and inserts a new record with every call, even if the user's email is already present in the table.

I'm trying to add functionality to check if the user's email is present in the table already, and throw an error if so, otherwise, create a new record.

Body:
You need to create unique index on email field. E.g. in mongo shell:

db.users.createIndex(
   { email: 1},
   { unique: true }
);


问:
Protocol Buffers: How to parse a .proto file in Java
I am trying to dynamically parse a given .proto file in Java to decode a Protobuf-encoded binary.

I have the following parsing method, in which the "proto" string contains the content of the .proto file:

```<code>public static Descriptors.FileDescriptor parseProto (String proto) throws InvalidProtocolBufferException, Descriptors.DescriptorValidationException {
        DescriptorProtos.FileDescriptorProto descriptorProto = DescriptorProtos.FileDescriptorProto.parseFrom(proto.getBytes());
        return Descriptors.FileDescriptor.buildFrom(descriptorProto, null);
}
</code>```

Though, on execution the previous method throws an exception with the message "Protocol message tag had invalid wire type.". I use the example .proto file from Google so I guess it is valid: https://github.com/google/protobuf/blob/master/examples/addressbook.proto

Here is the stack trace:

```<code>15:43:24.707 [pool-1-thread-1] ERROR com.github.whiver.nifi.processor.ProtobufDecoderProcessor - ProtobufDecoderProcessor[id=42c8ab94-2d8a-491b-bd99-b4451d127ae0] Protocol message tag had invalid wire type.
com.google.protobuf.InvalidProtocolBufferException$InvalidWireTypeException: Protocol message tag had invalid wire type.
    at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:115)
    at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:551)
    at com.google.protobuf.GeneratedMessageV3.parseUnknownField(GeneratedMessageV3.java:293)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:88)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:53)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:773)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:768)
    at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:163)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:197)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:209)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:214)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.parseFrom(DescriptorProtos.java:260)
    at com.github.whiver.nifi.parser.SchemaParser.parseProto(SchemaParser.java:9)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.lambda$onTrigger$0(ProtobufDecoderProcessor.java:103)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:895)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:62)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.onTrigger(ProtobufDecoderProcessor.java:100)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:251)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:245)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Any idea?
Thank you!

答:
It looks like you're trying to use FileDescriptorSet.parseFrom to populate a FileDescriptorSet. This will only work if the bytes you're providing are the binary protobuf contents - which is to say: a compiled schema. You can get a compiled schema by using the protoc command-line-tool with the --descriptor_set_out option. What you're actually passing it right now is the text bytes that make up the text schema, which is not what parseFrom expects.

Without a compiled schema, you would need a runtime .proto parser. I'm not aware of one for Java; protobuf-net includes one (protobuf-net.Reflection), but that is C#/.NET. Without an available runtime .proto parser, you'd need to shell-execute protoc instead.

Body:
I am trying to dynamically parse a given .proto file in Java to decode a Protobuf-encoded binary.

I have the following parsing method, in which the "proto" string contains the content of the .proto file:

public static Descriptors.FileDescriptor parseProto (String proto) throws InvalidProtocolBufferException, Descriptors.DescriptorValidationException {
        DescriptorProtos.FileDescriptorProto descriptorProto = DescriptorProtos.FileDescriptorProto.parseFrom(proto.getBytes());
        return Descriptors.FileDescriptor.buildFrom(descriptorProto, null);
}

Though, on execution the previous method throws an exception with the message "Protocol message tag had invalid wire type.". I use the example .proto file from Google so I guess it is valid: https://github.com/google/protobuf/blob/master/examples/addressbook.proto

Here is the stack trace:

15:43:24.707 [pool-1-thread-1] ERROR com.github.whiver.nifi.processor.ProtobufDecoderProcessor - ProtobufDecoderProcessor[id=42c8ab94-2d8a-491b-bd99-b4451d127ae0] Protocol message tag had invalid wire type.
com.google.protobuf.InvalidProtocolBufferException$InvalidWireTypeException: Protocol message tag had invalid wire type.
    at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:115)
    at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:551)
    at com.google.protobuf.GeneratedMessageV3.parseUnknownField(GeneratedMessageV3.java:293)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:88)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:53)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:773)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:768)
    at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:163)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:197)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:209)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:214)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.parseFrom(DescriptorProtos.java:260)
    at com.github.whiver.nifi.parser.SchemaParser.parseProto(SchemaParser.java:9)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.lambda$onTrigger$0(ProtobufDecoderProcessor.java:103)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:895)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:62)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.onTrigger(ProtobufDecoderProcessor.java:100)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:251)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:245)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Any idea?
Thank you!


答:
As the previous answers stated your code is absolutely fine with the exception of, you have limited the max-width of your image with max-width: 100%. If you remove that, it will give you the desired output.

function zoomin() {
  var myImg = document.getElementById("map");
  var currWidth = myImg.clientWidth;
  if (currWidth == 2500) return false;
  else {
    myImg.style.width = (currWidth + 100) + "px";
  }
}

function zoomout() {
  var myImg = document.getElementById("map");
  var currWidth = myImg.clientWidth;
  if (currWidth == 100) return false;
  else {
    myImg.style.width = (currWidth - 100) + "px";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*body {
  margin: 0;
}

#navbar {
  overflow: hidden;
  background-color: #099;
  position: fixed;
  top: 0;
  width: 100%;
  padding-top: 3px;
  padding-bottom: 3px;
  padding-left: 20px;
}

#navbar a {
  float: left;
  display: block;
  color: #666;
  text-align: center;
  padding-right: 20px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.main {
  padding: 16px;
  margin-top: 30px;
  width: 100%;
  height: 100vh;
  overflow: auto;
  cursor: grab;
  cursor: -o-grab;
  cursor: -moz-grab;
  cursor: -webkit-grab;
}

.main img {
  height: auto;
  width: 100%;
}

.button {
  width: 300px;
  height: 60px;
}</code>```

    <button type="button" onclick="zoomin()"> Zoom In</button>
    <button type="button" onclick="zoomout()"> Zoom Out</button>

```

Edits:

Since you wanted the initial width to be 100% (full size), instead of max-width, just set width to 100% like done in the last edit.

For implementing the drag feature to scroll the image, another CSS class has been added to the main container called dragscroll and it's js is imported as needed.

Body:
As the previous answers stated your code is absolutely fine with the exception of, you have limited the max-width of your image with max-width: 100%. If you remove that, it will give you the desired output.

function zoomin() {
  var myImg = document.getElementById("map");
  var currWidth = myImg.clientWidth;
  if (currWidth == 2500) return false;
  else {
    myImg.style.width = (currWidth + 100) + "px";
  }
}

function zoomout() {
  var myImg = document.getElementById("map");
  var currWidth = myImg.clientWidth;
  if (currWidth == 100) return false;
  else {
    myImg.style.width = (currWidth - 100) + "px";
  }
}

*body {
  margin: 0;
}

#navbar {
  overflow: hidden;
  background-color: #099;
  position: fixed;
  top: 0;
  width: 100%;
  padding-top: 3px;
  padding-bottom: 3px;
  padding-left: 20px;
}

#navbar a {
  float: left;
  display: block;
  color: #666;
  text-align: center;
  padding-right: 20px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.main {
  padding: 16px;
  margin-top: 30px;
  width: 100%;
  height: 100vh;
  overflow: auto;
  cursor: grab;
  cursor: -o-grab;
  cursor: -moz-grab;
  cursor: -webkit-grab;
}

.main img {
  height: auto;
  width: 100%;
}

.button {
  width: 300px;
  height: 60px;
}

<script type="text/javascript" src="https://cdn.rawgit.com/asvd/dragscroll/master/dragscroll.js"></script>

<body>

  <div id="navbar">
    <button type="button" onclick="zoomin()"> Zoom In</button>
    <button type="button" onclick="zoomout()"> Zoom Out</button>
  </div>

  <div class="main dragscroll">
    <img id="map" src="http://www.worldatlas.com/webimage/countrys/europelargesm.jpg" />
  </div>

Edits:

Since you wanted the initial width to be 100% (full size), instead of max-width, just set width to 100% like done in the last edit.

For implementing the drag feature to scroll the image, another CSS class has been added to the main container called dragscroll and it's js is imported as needed.