问:
react with Rails 5, getting CSRF error for post with axios
I'm trying to use react_on_rails to build my first example with react and rails. I'm trying to save some data to the rails backend, using axios for the ajax.

here's my code:

```<code>import store from "../store/helloWorld";
import axios from "axios";

export const SAVE_NAME = "SAVE_NAME";

export function saveNameAction(name) {
  return {
    type: SAVE_NAME,
    name
  };
}

export function saveName(name) {
  axios
    .post("/hello_world", saveNameAction(name))
    .then(function(response) {
      console.log(response);
    })
    .catch(function(error) {
      console.log(error);
    });
}
</code>```

and the component:

```<code>import PropTypes from "prop-types";
import React from "react";
import * as actions from "../actions/helloWorld";

export default class HelloWorld extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired // this is passed from the Rails view
  };

  /**
   * @param props - Comes from your rails view.
   */
  constructor(props) {
    super(props);
    this.state = { name: this.props.name };
  }

  updateName(name) {
    this.setState({ name: name });
  }

  handleSubmit(event) {
    event.preventDefault();
    actions.saveName(this.state.name);
  }

  render() {
    return (
      <div>
        <h3>
          Hellopp, {this.state.name}!
        </h3>
        <hr />
        <form>
          <label htmlFor="name">Say hello to:</label>
          <input
            id="name"
            type="text"
            value={this.state.name}
            onChange={e => this.updateName(e.target.value)}
          />

          <input
            type="submit"
            value="Submit"
            onClick={event => this.handleSubmit(event)}
          />
        </form>
      </div>
    );
  }
}
</code>```

The problem is that when I click the submit, my backend reports

```<code>Started POST "/hello_world" for ::1 at 2017-07-07 15:30:44 +0200
Processing by HelloWorldController#create as HTML
  Parameters: {"type"=>"SAVE_NAME", "name"=>"Stranger", "hello_world"=>{"type"=>"SAVE_NAME", "name"=>"Stranger"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
</code>```

For one, I don't understand why the parameters seem to be passed twice, but that's not even generating a warning, so don't care for now.

The problem is that I don't see a way to obtain the CSRF tokens in my react code to use in the post requests

should I just disable CSRF? or is there a better way?

答:
I found that react_on_rails has a helper system to handle CSRF tokens,

it basically uses:

```<code>  <%= csrf_meta_tags %>
</code>```

to add the csrf_token to the headers in the page as a meta

and then you can use:

```<code>import ReactOnRails from "react-on-rails";

export function saveNameAction(name) {
  console.log("creating action " + name);
  return {
    authenticity_token: ReactOnRails.authenticityToken(),
    type: SAVE_NAME,
    name
  };
}
</code>```

to fetch it and use it.

Body:
I'm trying to use react_on_rails to build my first example with react and rails. I'm trying to save some data to the rails backend, using axios for the ajax.

here's my code:

import store from "../store/helloWorld";
import axios from "axios";

export const SAVE_NAME = "SAVE_NAME";

export function saveNameAction(name) {
  return {
    type: SAVE_NAME,
    name
  };
}

export function saveName(name) {
  axios
    .post("/hello_world", saveNameAction(name))
    .then(function(response) {
      console.log(response);
    })
    .catch(function(error) {
      console.log(error);
    });
}

and the component:

import PropTypes from "prop-types";
import React from "react";
import * as actions from "../actions/helloWorld";

export default class HelloWorld extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired // this is passed from the Rails view
  };

  /**
   * @param props - Comes from your rails view.
   */
  constructor(props) {
    super(props);
    this.state = { name: this.props.name };
  }

  updateName(name) {
    this.setState({ name: name });
  }

  handleSubmit(event) {
    event.preventDefault();
    actions.saveName(this.state.name);
  }

  render() {
    return (

          Hellopp, {this.state.name}!

        <form>
          Say hello to:
          <input
            id="name"
            type="text"
            value={this.state.name}
            onChange={e => this.updateName(e.target.value)}
          />

          <input
            type="submit"
            value="Submit"
            onClick={event => this.handleSubmit(event)}
          />
        </form>

    );
  }
}

The problem is that when I click the submit, my backend reports

Started POST "/hello_world" for ::1 at 2017-07-07 15:30:44 +0200
Processing by HelloWorldController#create as HTML
  Parameters: {"type"=>"SAVE_NAME", "name"=>"Stranger", "hello_world"=>{"type"=>"SAVE_NAME", "name"=>"Stranger"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

For one, I don't understand why the parameters seem to be passed twice, but that's not even generating a warning, so don't care for now.

The problem is that I don't see a way to obtain the CSRF tokens in my react code to use in the post requests

should I just disable CSRF? or is there a better way?

Body:
I found that react_on_rails has a helper system to handle CSRF tokens,

it basically uses:

  <%= csrf_meta_tags %>

to add the csrf_token to the headers in the page as a meta

and then you can use:

import ReactOnRails from "react-on-rails";

export function saveNameAction(name) {
  console.log("creating action " + name);
  return {
    authenticity_token: ReactOnRails.authenticityToken(),
    type: SAVE_NAME,
    name
  };
}

to fetch it and use it.


来源: stackexchange

问:
Programatically triggering event into the $timeout cause infinite loop
I have template that looks like this (with many instances in template like this):

```<code><span>
  <button type="button" ng-click="uploadPdf($event)">
    <i class="fa fa-file"></i>
    <input type="file" class="pdfDoc" ng-show="false">
  </button>
</span>
</code>```

The idea is when user click on button, the input[type="file"] should be triggered (clicked).

I tried firstly to make It like this:

```<code>$scope.uploadPdf = function(e) {
  e.currentTarget.lastElementChild.click();
};
</code>```

And It works, but console yell on me that $apply is still in progress, so I found solution where usage of $timeout is suggested, so I wrapped code above to $timeout

```<code>$scope.uploadPdf = function(e) {
  $timeout(function() {
    e.currentTarget.lastElementChild.click();
  }, 0, false);
};
</code>```

And this for some reason runs infinitely.

Does anyone why is that happening and any another possible solution ?

Thanks.

答:
You can just check what element was clicked, and if it was input - do nothing</p>

```<code>$scope.uploadPdf = function(e) {
  if(e.target.tagName.toLowerCase() == 'input'){
    return false;
  }
  e.currentTarget.lastElementChild.click();
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have template that looks like this (with many instances in template like this):

  <button type="button" ng-click="uploadPdf($event)">

    <input type="file" class="pdfDoc" ng-show="false">
  </button>

The idea is when user click on button, the input[type="file"] should be triggered (clicked).

I tried firstly to make It like this:

$scope.uploadPdf = function(e) {
  e.currentTarget.lastElementChild.click();
};

And It works, but console yell on me that $apply is still in progress, so I found solution where usage of $timeout is suggested, so I wrapped code above to $timeout

$scope.uploadPdf = function(e) {
  $timeout(function() {
    e.currentTarget.lastElementChild.click();
  }, 0, false);
};

And this for some reason runs infinitely.

Does anyone why is that happening and any another possible solution ?

Thanks.

Body:
You can just check what element was clicked, and if it was input - do nothing

$scope.uploadPdf = function(e) {
  if(e.target.tagName.toLowerCase() == 'input'){
    return false;
  }
  e.currentTarget.lastElementChild.click();
};


问:
Updating the contents of a kml file, using libxml2 library in C
I am trying to extract particular data set using libxml2 header file using C. Every other part is working except for the change of contents of the node. This is very crucial since I dont want the program to read the same set of data points. The program works without error but the content wont change.

Here is the part of the code :

```<code>int parseName (xmlDocPtr doc,xmlNodePtr cur) {
    xmlChar *key;
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"Placemark"))) {
            cur = cur ->xmlChildrenNode;
            while(cur != NULL){
                if((!xmlStrcmp(cur->name, (const xmlChar *)"name"))) {
                    key = xmlNodeListGetString(doc,cur->xmlChildrenNode,1);
                    if((!xmlStrcmp(key,(const xmlChar *)"Untitled Polygon"))){
                        xmlNodeSetContent(cur->content,(const xmlChar *)"Done");
                        return 1;
                    }
                    else if((!xmlStrcmp(key,(const xmlChar *)"Out")))
                        return -1;

                }
                cur=cur->next;
            }

    }
    cur=cur->next;
    }
return 0;
}
</code>```

Here xmlNodeSetContent does not work. But the function still returns 1.

Edit : The kml file goes like this :

```<code><?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<Placemark>
        <name>Untitled Polygon</name>
        <styleUrl>#m_ylw-pushpin</styleUrl>
        <Polygon>
            <tessellate>1</tessellate>
            <outerBoundaryIs>
                <LinearRing>
                    <coordinates>
                        77.58482071603055,12.86858949944241,0 77.60057575684357,12.86642619038822,0 77.60374633781389,12.88004602175216,0 77.5844101227442,12.88296731261186,0 77.58482071603055,12.86858949944241,0
                    </coordinates>
                </LinearRing>
            </outerBoundaryIs>
        </Polygon>
    </Placemark>
</Document>
</kml>
</code>```

I can succesfully extract the coordinates but cannot change the name to something else. It just sticks to "Untitled Polygon".

Update answer : One line changed, xmlNodeSetContent(cur->xmlChildrenNode,(const xmlChar *)"Done"); and one more line is to be added to save the changes made to the content of the file : xmlSaveFormatFile ("NOW1.kml", doc, 0);
Thank you.

答:
cur's content member is unused, which is why you don't see an effect when you set it.  Element nodes like cur never use their "content" member, instead they have children nodes of type "text" that have content.

Notice that when looking for "Untitled Polygon", you're using xmlNodeListGetString on cur->xmlChildrenNode, not on cur itself.  That xmlChildrenNode is the text node.

It's designed this way so if you had a situation like <name>Untitled Polygon</name>, you would see 2 child text nodes (with contnet of Untitled and gon), with a  element node between them, which itself has a text node child (with content Poly).

Use xmlNodeSetContent on cur->xmlChildrenNode and you should see the result.

Body:
I am trying to extract particular data set using libxml2 header file using C. Every other part is working except for the change of contents of the node. This is very crucial since I dont want the program to read the same set of data points. The program works without error but the content wont change.

Here is the part of the code :

int parseName (xmlDocPtr doc,xmlNodePtr cur) {
    xmlChar *key;
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"Placemark"))) {
            cur = cur ->xmlChildrenNode;
            while(cur != NULL){
                if((!xmlStrcmp(cur->name, (const xmlChar *)"name"))) {
                    key = xmlNodeListGetString(doc,cur->xmlChildrenNode,1);
                    if((!xmlStrcmp(key,(const xmlChar *)"Untitled Polygon"))){
                        xmlNodeSetContent(cur->content,(const xmlChar *)"Done");
                        return 1;
                    }
                    else if((!xmlStrcmp(key,(const xmlChar *)"Out")))
                        return -1;

                }
                cur=cur->next;
            }

    }
    cur=cur->next;
    }
return 0;
}

Here xmlNodeSetContent does not work. But the function still returns 1.

Edit : The kml file goes like this :

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<Placemark>
        <name>Untitled Polygon</name>

        <Polygon>
            <tessellate>1</tessellate>
            <outerBoundaryIs>
                <LinearRing>
                    <coordinates>
                        77.58482071603055,12.86858949944241,0 77.60057575684357,12.86642619038822,0 77.60374633781389,12.88004602175216,0 77.5844101227442,12.88296731261186,0 77.58482071603055,12.86858949944241,0
                    </coordinates>
                </LinearRing>
            </outerBoundaryIs>
        </Polygon>
    </Placemark>
</Document>
</kml>

I can succesfully extract the coordinates but cannot change the name to something else. It just sticks to "Untitled Polygon".

Update answer : One line changed, xmlNodeSetContent(cur->xmlChildrenNode,(const xmlChar *)"Done"); and one more line is to be added to save the changes made to the content of the file : xmlSaveFormatFile ("NOW1.kml", doc, 0);
Thank you.

Body:
cur's content member is unused, which is why you don't see an effect when you set it.  Element nodes like cur never use their "content" member, instead they have children nodes of type "text" that have content.

Notice that when looking for "Untitled Polygon", you're using xmlNodeListGetString on cur->xmlChildrenNode, not on cur itself.  That xmlChildrenNode is the text node.

It's designed this way so if you had a situation like <name>Untitled <b>Poly</b>gon</name>, you would see 2 child text nodes (with contnet of Untitled and gon), with a <b> element node between them, which itself has a text node child (with content Poly).

Use xmlNodeSetContent on cur->xmlChildrenNode and you should see the result.


问:
How reconnect clients sockets to my server if my server restarts
I'm trying to make a client-server connection using sockets.

It basically works pretty well; only one problem is when I close and re-open my server on server computer the clients won't reconnect

This is my client code :

```<code>Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
        Public Delegate Sub MessageReceivedEventHandler(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
        Public Delegate Sub ClientConnectedEventHandler(ByVal sender As Object, ByVal e As ClientConnectedEventArgs)
        Public Event MessageReceived As MessageReceivedEventHandler
        Public Event ClientConnected As ClientConnectedEventHandler
        Public Buffer As Byte()
        Public Shared Client As TcpClient
        Dim Port As Integer = 5050
    Dim host As String = "computer name"
    Dim KEY As String = "mykey"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim T As New Thread(AddressOf run)
        T.Start()
    End Sub

    Private Sub run()
        ' Connect to the server'
        Client = New TcpClient(host, Port)
        Dim T As New Thread(AddressOf Receiver, 10)
        T.Start()
    End Sub

    Public Shared Function StringToByte(ByVal STR As String) As Byte()
        Return System.Text.Encoding.Default.GetBytes(STR)
    End Function
    Public Shared Function ByteToString(ByVal BYS As Byte()) As String
        Return System.Text.Encoding.Default.GetString(BYS)
    End Function
    Public Sub Data(ByVal Sender As Object, ByVal Data As MessageReceivedEventArgs) Handles Me.MessageReceived
        Dim info As Byte() = Data.Message
        Dim Client As Socket = Data.clientSocket
        Dim ID As String = Data.Sender
        Dim Arr As String() = Split(System.Text.Encoding.Default.GetString(info), "mykey")
        Try
            Select Case Arr(0)

                Case "MSG"
                MsgBox(Arr(1))
                           End Select
        Catch ex As Exception
            MsgBox("Error Detected in Data Client :" & ex.Message)
        End Try
    End Sub

    Sub Receiver()
        Dim M As New MemoryStream
        Try
                If Client.Available > 0 Then
                    ReDim Buffer(Client.Available - 1)
                    Client.Client.Receive(Buffer, 0, Buffer.Length, SocketFlags.None)
                    M.Write(Buffer, 0, Buffer.Length)
                    If System.Text.Encoding.Default.GetString(M.ToArray).Contains("EOF") Then
                        Dim Data As Byte() = (M.ToArray).Remove(ConfigTcp.ENDOFPACKET)
                        Dim Msg As New MessageReceivedEventArgs
                        Msg.Message = Data
                        Msg.clientSocket = Client.Client
                        Msg.Sender = Client.Client.Handle.ToString()
                        RaiseEvent MessageReceived(Me, Msg)
                        M.Dispose()
                        M = New MemoryStream
                    End If
                End If
                Thread.Sleep(1)
        Catch ex As Exception
            MsgBox("Error Detected :" & ex.Message)
        End Try
    End Sub
    Public Shared Sub Send(ByVal sock As Socket, ByVal s As String)
            Send(sock, System.Text.Encoding.UTF8.GetBytes(s))
        End Sub
        Private Shared Sub Send(ByVal sock As Socket, ByVal b As Byte())
            Try
                Dim Memory As MemoryStream = New MemoryStream
                Dim CB As Byte() = b
                Memory.Write(CB, 0, CB.Length)
                Memory.Write(ConfigTcp.ENDOFPACKET, 0, ConfigTcp.ENDOFPACKET.Length)
                sock.Send(Memory.ToArray, 0, Memory.Length, SocketFlags.None)
                Memory.Dispose()
            Catch x As Exception
            End Try
        End Sub
    End Class
    Public Class MessageReceivedEventArgs
        Inherits EventArgs
        Public Sender As String
        Public clientSocket As Socket
        Public Message As Byte()
    End Class
    Public Class ClientConnectedEventArgs
        Inherits EventArgs
        Public clientID As String
        Public clientSocket As Socket
    End Class
</code>```

答:
@Alexander Higgins
I tried something like this but seems that  SocketException happens only before opening the server for the first time.If I close the server it and re-open it, it doesn't catch SocketException

```<code>   Public Sub DoReconnect()
    re:
            Thread.Sleep(1000)
            Try
                Client = New TcpClient(host, Port)
                Dim T As New Thread(AddressOf Receiver, 10)
                T.IsBackground = True
                T.Start()
            Catch SockEx As SocketException
                MsgBox("SocketException " + SockEx.Message)
                GoTo re

            Catch Ex As Exception
                MsgBox("Exception " + Ex.Message)

            End Try

        End Sub
        Private Sub run()
            DoReconnect()
        End Sub
</code>```

Body:
I'm trying to make a client-server connection using sockets.

It basically works pretty well; only one problem is when I close and re-open my server on server computer the clients won't reconnect

This is my client code :

Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
        Public Delegate Sub MessageReceivedEventHandler(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
        Public Delegate Sub ClientConnectedEventHandler(ByVal sender As Object, ByVal e As ClientConnectedEventArgs)
        Public Event MessageReceived As MessageReceivedEventHandler
        Public Event ClientConnected As ClientConnectedEventHandler
        Public Buffer As Byte()
        Public Shared Client As TcpClient
        Dim Port As Integer = 5050
    Dim host As String = "computer name"
    Dim KEY As String = "mykey"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim T As New Thread(AddressOf run)
        T.Start()
    End Sub

    Private Sub run()
        ' Connect to the server'
        Client = New TcpClient(host, Port)
        Dim T As New Thread(AddressOf Receiver, 10)
        T.Start()
    End Sub

    Public Shared Function StringToByte(ByVal STR As String) As Byte()
        Return System.Text.Encoding.Default.GetBytes(STR)
    End Function
    Public Shared Function ByteToString(ByVal BYS As Byte()) As String
        Return System.Text.Encoding.Default.GetString(BYS)
    End Function
    Public Sub Data(ByVal Sender As Object, ByVal Data As MessageReceivedEventArgs) Handles Me.MessageReceived
        Dim info As Byte() = Data.Message
        Dim Client As Socket = Data.clientSocket
        Dim ID As String = Data.Sender
        Dim Arr As String() = Split(System.Text.Encoding.Default.GetString(info), "mykey")
        Try
            Select Case Arr(0)

                Case "MSG"
                MsgBox(Arr(1))
                           End Select
        Catch ex As Exception
            MsgBox("Error Detected in Data Client :" & ex.Message)
        End Try
    End Sub

    Sub Receiver()
        Dim M As New MemoryStream
        Try
                If Client.Available > 0 Then
                    ReDim Buffer(Client.Available - 1)
                    Client.Client.Receive(Buffer, 0, Buffer.Length, SocketFlags.None)
                    M.Write(Buffer, 0, Buffer.Length)
                    If System.Text.Encoding.Default.GetString(M.ToArray).Contains("EOF") Then
                        Dim Data As Byte() = (M.ToArray).Remove(ConfigTcp.ENDOFPACKET)
                        Dim Msg As New MessageReceivedEventArgs
                        Msg.Message = Data
                        Msg.clientSocket = Client.Client
                        Msg.Sender = Client.Client.Handle.ToString()
                        RaiseEvent MessageReceived(Me, Msg)
                        M.Dispose()
                        M = New MemoryStream
                    End If
                End If
                Thread.Sleep(1)
        Catch ex As Exception
            MsgBox("Error Detected :" & ex.Message)
        End Try
    End Sub
    Public Shared Sub Send(ByVal sock As Socket, ByVal s As String)
            Send(sock, System.Text.Encoding.UTF8.GetBytes(s))
        End Sub
        Private Shared Sub Send(ByVal sock As Socket, ByVal b As Byte())
            Try
                Dim Memory As MemoryStream = New MemoryStream
                Dim CB As Byte() = b
                Memory.Write(CB, 0, CB.Length)
                Memory.Write(ConfigTcp.ENDOFPACKET, 0, ConfigTcp.ENDOFPACKET.Length)
                sock.Send(Memory.ToArray, 0, Memory.Length, SocketFlags.None)
                Memory.Dispose()
            Catch x As Exception
            End Try
        End Sub
    End Class
    Public Class MessageReceivedEventArgs
        Inherits EventArgs
        Public Sender As String
        Public clientSocket As Socket
        Public Message As Byte()
    End Class
    Public Class ClientConnectedEventArgs
        Inherits EventArgs
        Public clientID As String
        Public clientSocket As Socket
    End Class

Body:
@Alexander Higgins
I tried something like this but seems that  SocketException happens only before opening the server for the first time.If I close the server it and re-open it, it doesn't catch SocketException

   Public Sub DoReconnect()
    re:
            Thread.Sleep(1000)
            Try
                Client = New TcpClient(host, Port)
                Dim T As New Thread(AddressOf Receiver, 10)
                T.IsBackground = True
                T.Start()
            Catch SockEx As SocketException
                MsgBox("SocketException " + SockEx.Message)
                GoTo re

            Catch Ex As Exception
                MsgBox("Exception " + Ex.Message)

            End Try

        End Sub
        Private Sub run()
            DoReconnect()
        End Sub


问:
Why do we do a POST to confirm deletion in asp.net MVC?
The following is a note from Professional ASP.NET MVC 2 by Scott Hanselman ++

You might ask — why did we go through
  the effort of creating a <form> within
  our Delete Confi rmation screen? Why
  not just use a standard hyperlink to
  link to an action method that does the
  actual delete operation? The reason is
  because we want to be careful to guard
  against Web-crawlers and search
  engines discovering our URLs and
  inadvertently causing data to be
  deleted when they follow the links.
  HTTP-GET-based URLs are considered
  safe for them to access/crawl, and
  they are supposed to not follow
  HTTP-POST ones. A good rule is to make
  sure that you always put destructive
  or data-modifying operations behind
  HTTP-POST requests.

If web-crawlers and search engine have no access to the page containing deletion button, is it safe to use a standard hyperlink to link to an action method doing the actual delete operation?

答:
A good rule of thumb is that GET shouldn't change data.  If you want to change some data you use POST.

That is why ScottHa etc used a form to submit the delete.  If it doesn't work for your app you can use GET if needed.

Alternatively you could use JavaScript to submit the form whe the user clicks link.

ContentLicense: CC BY-SA 2.5


问:
Reverse Dependency Service
I have a Xamarin Forms Project. I have used Dependency Service to call the Platform specific method to fire a local notification on Android and a Alert on iOS.

My problem is now, how to handle an action on both notification(android) and alert(iOS). Is it possible to call a method of the shared project from the android or iOS project?

Do I need another approach? Does someone know what I have to do?

Just for clarification, I know how the ordinary dependency services works i.e. Call a method on android or iOS from the shared project!

答: Have you tried just calling the method from your native project...? No special patterns necessary. The native iOS and Android projects have a direct reference to your shared project, so it can call the method directly.</p>

ContentLicense: CC BY-SA 4.0

Title: Reverse Dependency Service


问:
REST json api with symfony 2.7, form not validating even when filled
I'm trying to figure out why the form is not validating when I create one with a pre-populated entity with values coming from a json request.

Here is the controller in Symfony with the FosRestBundle already configured:

```<code>public function createAction(Request $request)
{
    $house = new House();
    $house->setTitle($request->get('title'));
    $house->setDescription($request->get('description'));
    $house->setPostcode($request->get('postCode'));
    $house->setPhoneNumber((int) $request->get('phoneNumber'));
    $availability = $request->get('available') ? true : false;
    $house->setAvailability($availability);

    $form = $this->createCreateForm($house);

    $form->handleRequest($request);

    $response = new JsonResponse();

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($house);
        $em->flush();

        return $response->setData(array(
            'success' => true
        ));
    }

    return $response->setData(array(
        'success' => false,
        'errors' => $this->getFormErrors($form)
    ));
}

private function createCreateForm(House $entity)
{
    $form = $this->createForm(new HouseType(), $entity, array(
        'action' => $this->generateUrl('houses_create'),
        'method' => 'POST',
        'csrf_protection' => false
    ));

    return $form;
}
</code>```

the yaml config file:

```<code># app/config/config.yml
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    routing_loader:
        default_format: json
    exception:
        enabled: true
    # configure the view handler
    view:
        force_redirects:
            html: true
        formats:
            json: true
            xml: true
        templating_formats:
            html: true
    # add a content negotiation rule, enabling support for json/xml for the entire website
    format_listener:
        enabled: true
        rules:
            - { path: ^/, priorities: [ json, xml, html ], fallback_format: html, prefer_extension: false }
</code>```

If I execute $form->get('title')->getData() for example I can see that the form is filled correctly but still doesn't pass the validation and when I execute $this->getFormErrors($form) I just get an empty array.

Any idea on how I could debug this issue?

答:
I noticed a typo when you initiate the $form: "createCreateForm" -> it should be just "createForm".

If that doesn't work check the values from $form->getData() after the "if ($form->isValid()) { " part. I suspect the framework doesn't know how to handle the request (not coming from a standard form). It that's the case then you can set manually the values on the entity and save it.

```<code>$house->setStuff($request->request->get('stuff');
...
$em->persist($house);`$em->flush();`
</code>```

Body:
I'm trying to figure out why the form is not validating when I create one with a pre-populated entity with values coming from a json request.

Here is the controller in Symfony with the FosRestBundle already configured:

public function createAction(Request $request)
{
    $house = new House();
    $house->setTitle($request->get('title'));
    $house->setDescription($request->get('description'));
    $house->setPostcode($request->get('postCode'));
    $house->setPhoneNumber((int) $request->get('phoneNumber'));
    $availability = $request->get('available') ? true : false;
    $house->setAvailability($availability);

    $form = $this->createCreateForm($house);

    $form->handleRequest($request);

    $response = new JsonResponse();

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($house);
        $em->flush();

        return $response->setData(array(
            'success' => true
        ));
    }

    return $response->setData(array(
        'success' => false,
        'errors' => $this->getFormErrors($form)
    ));
}

private function createCreateForm(House $entity)
{
    $form = $this->createForm(new HouseType(), $entity, array(
        'action' => $this->generateUrl('houses_create'),
        'method' => 'POST',
        'csrf_protection' => false
    ));

    return $form;
}

the yaml config file:

# app/config/config.yml
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    routing_loader:
        default_format: json
    exception:
        enabled: true
    # configure the view handler
    view:
        force_redirects:
            html: true
        formats:
            json: true
            xml: true
        templating_formats:
            html: true
    # add a content negotiation rule, enabling support for json/xml for the entire website
    format_listener:
        enabled: true
        rules:
            - { path: ^/, priorities: [ json, xml, html ], fallback_format: html, prefer_extension: false }

If I execute $form->get('title')->getData() for example I can see that the form is filled correctly but still doesn't pass the validation and when I execute $this->getFormErrors($form) I just get an empty array.

Any idea on how I could debug this issue?

Body:
I noticed a typo when you initiate the $form: "createCreateForm" -> it should be just "createForm".

If that doesn't work check the values from $form->getData() after the "if ($form->isValid()) { " part. I suspect the framework doesn't know how to handle the request (not coming from a standard form). It that's the case then you can set manually the values on the entity and save it.

$house->setStuff($request->request->get('stuff');
...
$em->persist($house);`$em->flush();`


问:
Tooltip over small image
I am currently about to setup our forum and already made a verification system, but wondering how to make a tooltip just like Facebook have. Once you mouse over the check image, you will see some sort of text.

I already tried some way to achieve it but did not work.

GoDaddy's Facebook Page

HTML

The img tag contains these:

```<code>data="BroHosting confirmed that this profile is an authentic for person, media, brand or company." class="tip"
</code>```

CSS /Style

```<code>img:hover {
  color: red;
  position: relative;
}

img[data]:hover:after {
  content: attr(data);
  padding: 4px 8px;
  color: rgba(0,0,0,0.5);
  position: absolute;
  left: 0;
  top: 100%;
  white-space: nowrap;
  z-index: 2;
  border-radius: 5px ;
  background: rgba(0,0,0,0.5);
}
</code>```

Do you have a possible fix or other idea or suggestion maybe?

答:
.check {
  position: relative;
  display: inline-block;
  background-color: #5890ff;
  width: 12px;
  height: 12px;
  border-radius: 100%;
  color: #000;
  text-decoration: none;
}
.check:after {
  content: attr(data-tooltip);
  position: absolute;
  top: 0;
  left: 14px;
  width: 100px;
  background-color: #000;
  color: #FFF;
  font-family: Arial, sans-serif;
  font-size: 14px;
  padding: 5px;
  opacity: 0;
  pointer-events: none;
  transition: opacity .3s ease-in-out;
  will-change: opacity;
}

.check:hover:after {
  opacity: 1;
  pointer-events: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></code>```

Title: Tooltip over small image

Body:
I am currently about to setup our forum and already made a verification system, but wondering how to make a tooltip just like Facebook have. Once you mouse over the check image, you will see some sort of text.

I already tried some way to achieve it but did not work.

GoDaddy's Facebook Page

HTML

The img tag contains these:

data="BroHosting confirmed that this profile is an authentic for person, media, brand or company." class="tip"

CSS /Style

img:hover {
  color: red;
  position: relative;
}

img[data]:hover:after {
  content: attr(data);
  padding: 4px 8px;
  color: rgba(0,0,0,0.5);
  position: absolute;
  left: 0;
  top: 100%;
  white-space: nowrap;
  z-index: 2;
  border-radius: 5px ;
  background: rgba(0,0,0,0.5);
}

Do you have a possible fix or other idea or suggestion maybe?

Body:
.check {
  position: relative;
  display: inline-block;
  background-color: #5890ff;
  width: 12px;
  height: 12px;
  border-radius: 100%;
  color: #000;
  text-decoration: none;
}
.check:after {
  content: attr(data-tooltip);
  position: absolute;
  top: 0;
  left: 14px;
  width: 100px;
  background-color: #000;
  color: #FFF;
  font-family: Arial, sans-serif;
  font-size: 14px;
  padding: 5px;
  opacity: 0;
  pointer-events: none;
  transition: opacity .3s ease-in-out;
  will-change: opacity;
}

.check:hover:after {
  opacity: 1;
  pointer-events: auto;
}

<a href="#" class="check" data-tooltip="Lorem ipsum dolor sit amet"></a>


问:
Subscript out of range (Error 9): Loop through a folder of Excel files, copy cells and paste in the current worksheet
I'm a beginner in VBA and have to work on some task to open a folder consists of scientific results in Excel files, select some cells based on a specific key from each Excel file and retrieve these data to the current workbook/worksheet in a sort of final table.

I'm getting this error

Subscript out of range (Error 9)

and I know the reason because it can't find the current worksheet to paste the data as required.

The current workbook named Task and current worksheet Output

Here's the edited code:

```<code>Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            sht.Cells(i, 6).Copy 'BW
            sht.Cells(i, 8).Copy 'Spec_symbol

       ' copy to the final sheet
        erow = current.Worksheets("Output").Cells(85, 1)

       ActiveSheet.Cells(erow, 1).Select
       ActiveSheet.Paste
       ActiveWorkbook.Save
       ActiveWorkbook.Close
       Application.CutCopyMode = False
        End If

Next i
Next element

  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

I guess the problem now is that this line returns Nothing, however it opens the right worksheet and both myPath & myFile are correct!

```<code>Set wb = Workbooks.Open(Filename:=myPath & myFile)
</code>```

答:
The code would to be like this.  It is more easy to accumulate your data to array vR().  And in your current sheet to get it.</p>

```<code>Sub LoopAllExcelFilesInFolder()

    Dim wb As Workbook, current As Workbook
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim FldrPicker As FileDialog
    Dim sht As Worksheet
    Dim curWs As Worksheet, rngT As Range
    Dim vR() As Variant, n As Long

      'set source workbook
    Set current = ThisWorkbook
    Set curWs = current.Sheets("Output")
    Set rngT = curWs.Range("a85")

     'Optimize Macro Speed
      Application.ScreenUpdating = False
      Application.EnableEvents = False
      Application.Calculation = xlCalculationManual

    'Retrieve Target Folder Path From User
      Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

        With FldrPicker
          .Title = "Select A Target Folder"
          .AllowMultiSelect = False
            If .Show <> -1 Then GoTo NextCode
            myPath = .SelectedItems(1) & "\"
        End With

       'In Case of Cancel
NextCode:
      myPath = myPath
      If myPath = "" Then GoTo ResetSettings

    'Target File Extension (must include wildcard "*")
      myExtension = "*.xls*"

    'Target Path with Ending Extention
      myFile = Dir(myPath & myExtension)

    Dim arr(3) As String
    Dim element As Variant

    arr(0) = "aclr_utra1"
    arr(1) = "aclr_utra2"
    arr(2) = "aclr_eutra"

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
     ' DoEvents

      Set sht = wb.Worksheets(1)
      Dim LastRow As Long
      LastRow = sht.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
        For Each element In arr
          ' Retrieve and copy the matched results
            For i = 35 To LastRow
                If sht.Cells(i, 9).Value = CStr(element) Then
                    n = n + 2
                    ReDim Preserve vR(1 To n)
                    vR(n - 1) = sht.Cells(i, 6)
                    vR(n) = sht.Cells(i, 8)
                    'sht.Cells(i, 6).Copy 'BW
                    'sht.Cells(i, 8).Copy 'Spec_symbol
                   ' copy to the final sheet
                    'erow = current.Worksheets("Output").Cells(85, 1)

                   'ActiveSheet.Cells(erow, 1).Select
                   'ActiveSheet.Paste
                   'ActiveWorkbook.Save
                   'ActiveWorkbook.Close
                   'Application.CutCopyMode = False
                End If

            Next i
        Next element
        wb.Close (0)

  'Ensure Workbook has closed before moving on to next line of code
      'DoEvents

    'Get next file name
      myFile = Dir
    Loop
    If n > 0 Then
        rngT.Resize(n) = WorksheetFunction.Transpose(vR)
    End If
ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

Body:
I'm a beginner in VBA and have to work on some task to open a folder consists of scientific results in Excel files, select some cells based on a specific key from each Excel file and retrieve these data to the current workbook/worksheet in a sort of final table.

I'm getting this error

Subscript out of range (Error 9)

and I know the reason because it can't find the current worksheet to paste the data as required.

The current workbook named Task and current worksheet Output

Here's the edited code:

Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            sht.Cells(i, 6).Copy 'BW
            sht.Cells(i, 8).Copy 'Spec_symbol

       ' copy to the final sheet
        erow = current.Worksheets("Output").Cells(85, 1)

       ActiveSheet.Cells(erow, 1).Select
       ActiveSheet.Paste
       ActiveWorkbook.Save
       ActiveWorkbook.Close
       Application.CutCopyMode = False
        End If

Next i
Next element

  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

I guess the problem now is that this line returns Nothing, however it opens the right worksheet and both myPath & myFile are correct!

Set wb = Workbooks.Open(Filename:=myPath & myFile)

Body:
The code would to be like this.  It is more easy to accumulate your data to array vR().  And in your current sheet to get it.

Sub LoopAllExcelFilesInFolder()

    Dim wb As Workbook, current As Workbook
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim FldrPicker As FileDialog
    Dim sht As Worksheet
    Dim curWs As Worksheet, rngT As Range
    Dim vR() As Variant, n As Long

      'set source workbook
    Set current = ThisWorkbook
    Set curWs = current.Sheets("Output")
    Set rngT = curWs.Range("a85")

     'Optimize Macro Speed
      Application.ScreenUpdating = False
      Application.EnableEvents = False
      Application.Calculation = xlCalculationManual

    'Retrieve Target Folder Path From User
      Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

        With FldrPicker
          .Title = "Select A Target Folder"
          .AllowMultiSelect = False
            If .Show <> -1 Then GoTo NextCode
            myPath = .SelectedItems(1) & "\"
        End With

       'In Case of Cancel
NextCode:
      myPath = myPath
      If myPath = "" Then GoTo ResetSettings

    'Target File Extension (must include wildcard "*")
      myExtension = "*.xls*"

    'Target Path with Ending Extention
      myFile = Dir(myPath & myExtension)

    Dim arr(3) As String
    Dim element As Variant

    arr(0) = "aclr_utra1"
    arr(1) = "aclr_utra2"
    arr(2) = "aclr_eutra"

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
     ' DoEvents

      Set sht = wb.Worksheets(1)
      Dim LastRow As Long
      LastRow = sht.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
        For Each element In arr
          ' Retrieve and copy the matched results
            For i = 35 To LastRow
                If sht.Cells(i, 9).Value = CStr(element) Then
                    n = n + 2
                    ReDim Preserve vR(1 To n)
                    vR(n - 1) = sht.Cells(i, 6)
                    vR(n) = sht.Cells(i, 8)
                    'sht.Cells(i, 6).Copy 'BW
                    'sht.Cells(i, 8).Copy 'Spec_symbol
                   ' copy to the final sheet
                    'erow = current.Worksheets("Output").Cells(85, 1)

                   'ActiveSheet.Cells(erow, 1).Select
                   'ActiveSheet.Paste
                   'ActiveWorkbook.Save
                   'ActiveWorkbook.Close
                   'Application.CutCopyMode = False
                End If

            Next i
        Next element
        wb.Close (0)

  'Ensure Workbook has closed before moving on to next line of code
      'DoEvents

    'Get next file name
      myFile = Dir
    Loop
    If n > 0 Then
        rngT.Resize(n) = WorksheetFunction.Transpose(vR)
    End If
ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub


问:
Order of OK, APPLY, CANCEL buttons
An extenstion of this question:
https://stackoverflow.com/questions/50335/ok-cancel-or-cancel-ok

Where should the APPLY button go (clicking the APPLY button has the same effect as clicking OK, except the dialog remains open)?

Windows typically uses OK-CANCEL-APPLY, but my inclination is to use OK-APPLY-CANCEL.

Also, if the APPLY button is clicked, should the CANCEL button text be changed to CLOSE until another change is made in the dialog?  I'm assuming the APPLY button will be disabled if there are no changes to apply.

答:
In Windows:

OK Cancel

Prev Next

Agree Disagree

In Mac OS:

Cancel OK

Prev Next

Disagree Agree

P.S.
I prefer always set the next action closer to the right. It's like reading text (from left to right). So the next step is always closer to right, the previous step is always closer to left.

For me, it's make more sense that something previous or past should be on the left and the next or future should be on the right.
But polls show it's 50%/50%... So the final decision is up to you.

Offtop:
I'm using Microsoft from Windows 3.11 and pretty sure nobody in Microsoft ever thought about this so deeply... and about a lot other things in UI also...

Title: Order of OK, APPLY, CANCEL buttons


问:
Java:how to group similar strings (items) to respective array (group)?
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

```<code>[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]
</code>```

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

```<code>String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }
</code>```

答:
```<code>//Create a map for storing groups
Map<String, Collection<String>> groupMap = new HashMap<String, Collection<String>>();

String[] parts = yourString.split("[, ]+"); //Split by each word
for (String part : parts) {   //Go over all words
    String[] subparts = part.split("#"); //Split to index and value

    String groupKey;
    String value;
    if (subparts.length == 1) { //There is no '#' sign
        groupKey = null;
        value = subparts[0];
    } else if (subparts.length == 2) { //There is one '#'sign
        groupKey = subparts[0];
        value = subparts[1];
    } else {
        throw new IllegalArgumentException("Can not parse string");
    }

    Collection<String> groupContents = groupMap.get(groupKey); //Extract list of items in this group
    if (groupContents == null) { //If there was no such group yet - create one
        groupMap.put(groupKey, groupContents = new ArrayList<String>());
    }
    groupContents.add(value); //Add item to group
}
</code>```

Body:
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }


问:
Website shows data from Android App - Like WhatsApp Web
Does anyone know how WhatsApp Web have done this?

They show the messages/data from the Android phone connected to the Internet.

So it seems there is no database on the server site. They get all messages directly from the mobile app and sends also the changes directly.

How can this be done?

With Firebase or any other Library?

答:
WhatsApp created an API which is used both for mobile and web end to communicate to each other and to the main database where all the messages and user information are stored.
The fact that your phone needs to be turned on and have internet connection still doesn't really show that the website pulls the information out of the phone itself.
What it is happening, more likely, is that the web extension communicates with the mobile phone linked to it to make sure that the account is still active on the mobile device and then proceeds to pull messages and information out of the database using the API.
I'm not excluding that the web extension retrieves some information form the device but it probably constantly keeps in sync with it to make sure the account is still active and there is no ambiguity between the account on the web extension and the account currently logged in to the mobile device.
Hope this clarifies a bit but there's no public documentation that I could find online so I'm going by what I believe is the most likely scenario.
:)
P.S. You can have a look here if you haven't already tried:
WhatApp website FAQ</p>


问:
csv to avro without apache spark in scala
Is there a way I can convert a scv file to Avro without using Apache Spark. I see most of the post suggests using spark which I cannot in my case. I have a schema in a separate file. I was thinking of some custom serializer and deserializer that will use the Schema and convert csv to avro. Any kind of reference would work for me.
Thanks</p>

答:
Avro is an open format, there are many languages which support it.

Just pick one, like python for example which also support csv. But Go would do, and Java also.


问:
Asterisk Playback with no answer on dahdi channel?
Here is my sample dialplan

```<code>        exten => _X.,1,Progress()
        exten => _X.,n,Playback(welcome,noanswer)
        exten => _X.,n,Hangup()
</code>```

When I tried to call through dhadi channel. I am getting the below logs in asterisk console.

```<code>-- Accepting call from '9042394773' to '33468550' on channel 0/8, span 1
-- Executing [33468550@test:1] Progress("DAHDI/i1/9042394773-8", "") in new stack
-- Executing [33468550@test:2] Playback("DAHDI/i1/9042394773-8", "welcome,noanswer") in new stack
-- <DAHDI/i1/9042394773-8> Playing 'welcome.slin' (language 'en')
-- Executing [33468550@test:3] Hangup("DAHDI/i1/9042394773-8", "") in new stack
-- Hungup 'DAHDI/i1/9042394773-8'
</code>```

But the welcome voice is not audio able.. How do I play weclome voice before atten the call??? Whether I have to change any configuration in asterisk????

Am using asterisk 13.5.

答:
I found this example where a Wait(1) is used between Progress and Playback.

Maybe you can give it a try.

```<code>exten => 500,1,Progress()
exten => 500,n,Wait(1)
exten => 500,n,Playback(WeAreClosedGoAway,noanswer)
exten => 500,n,Hangup()
</code>```

Body:
Here is my sample dialplan

        exten => _X.,1,Progress()
        exten => _X.,n,Playback(welcome,noanswer)
        exten => _X.,n,Hangup()

When I tried to call through dhadi channel. I am getting the below logs in asterisk console.

-- Accepting call from '9042394773' to '33468550' on channel 0/8, span 1
-- Executing [33468550@test:1] Progress("DAHDI/i1/9042394773-8", "") in new stack
-- Executing [33468550@test:2] Playback("DAHDI/i1/9042394773-8", "welcome,noanswer") in new stack
-- <DAHDI/i1/9042394773-8> Playing 'welcome.slin' (language 'en')
-- Executing [33468550@test:3] Hangup("DAHDI/i1/9042394773-8", "") in new stack
-- Hungup 'DAHDI/i1/9042394773-8'

But the welcome voice is not audio able.. How do I play weclome voice before atten the call??? Whether I have to change any configuration in asterisk????

Am using asterisk 13.5.

Body:
I found this example where a Wait(1) is used between Progress and Playback.

Maybe you can give it a try.

exten => 500,1,Progress()
exten => 500,n,Wait(1)
exten => 500,n,Playback(WeAreClosedGoAway,noanswer)
exten => 500,n,Hangup()


问:
Why cannot I return values from two functions in Java?
Error description here

I can return either getMonth() or getYear() from the following code.

When both are called, an error is displayed.

I have tried giving the value of m and y separately in the calculate date function and that works perfectly !!
Any suggestions?

I am a beginner, apologies if there is a trivial mistake, though there shouldn't be according to me.

```<code>import java.util.Scanner;

public class Second_Java {

public static int getMonth() {

    int a;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the input for the required month: ");
    a = sc.nextInt(); // stored in 'a' locally

    while (a < 1 || a > 12) {

        a = -1;
        System.out.println(a);

    }
    sc.close();
    return a;
}

public static int getYear() {

    int b;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the input for the required year: ");
    b = input.nextInt(); // stored in 'a' locally

    while (b < 1) {

        b = -2;
        System.out.println(b);

    }
    input.close();
    return b;
}

public static void calculateDays(int m, int y) {

    switch (m) {
    case 4:
    case 6:
    case 9:
    case 11:
        m = 30;
        System.out.println(m);
        break;
    case 2:
        if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
            m = 29;
            System.out.println(m);
        } else {
            m = 28;
            System.out.println(m);
        }
        break;
    default: {
        m = 31;
        System.out.println(m);
    }

    }

}

public static void main(String[] args) {

    int m = getMonth();
    int y = getYear();
    calculateDays(m, y);
}
</code>```

}

答:
You can do this, simply by defining an object with both values as fields e.g. for the above.

```<code>class MonthAndYear {
   public int month;
   public int year;
}
</code>```

and your function can execute both your methods above, and return an instance of MonthAndYear populated with the month and year values.

In the above case, your month and year are obviously closely tied together, and you're on your way to (re)defining some sort of Date class.

Note that lots of codebases have a Pair object (or similar) for this sort of things. If you're using Scala, you can couple the two values together trivially using a tuple (e.g. like this (month, year) )

Body:
Error description here

I can return either getMonth() or getYear() from the following code.

When both are called, an error is displayed.

I have tried giving the value of m and y separately in the calculate date function and that works perfectly !!
Any suggestions?

I am a beginner, apologies if there is a trivial mistake, though there shouldn't be according to me.

import java.util.Scanner;

public class Second_Java {

public static int getMonth() {

    int a;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the input for the required month: ");
    a = sc.nextInt(); // stored in 'a' locally

    while (a < 1 || a > 12) {

        a = -1;
        System.out.println(a);

    }
    sc.close();
    return a;
}

public static int getYear() {

    int b;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the input for the required year: ");
    b = input.nextInt(); // stored in 'a' locally

    while (b < 1) {

        b = -2;
        System.out.println(b);

    }
    input.close();
    return b;
}

public static void calculateDays(int m, int y) {

    switch (m) {
    case 4:
    case 6:
    case 9:
    case 11:
        m = 30;
        System.out.println(m);
        break;
    case 2:
        if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
            m = 29;
            System.out.println(m);
        } else {
            m = 28;
            System.out.println(m);
        }
        break;
    default: {
        m = 31;
        System.out.println(m);
    }

    }

}

public static void main(String[] args) {

    int m = getMonth();
    int y = getYear();
    calculateDays(m, y);
}

}

Body:
You can do this, simply by defining an object with both values as fields e.g. for the above.

class MonthAndYear {
   public int month;
   public int year;
}

and your function can execute both your methods above, and return an instance of MonthAndYear populated with the month and year values.

In the above case, your month and year are obviously closely tied together, and you're on your way to (re)defining some sort of Date class.

Note that lots of codebases have a Pair object (or similar) for this sort of things. If you're using Scala, you can couple the two values together trivially using a tuple (e.g. like this (month, year) )


问:
Python Decorators & Nested Functions return statement. Proper usage with parenthesis?
What's the difference including/not including the parentheses on the return statement for inner function for decorators (and any nested functions)? Are the parenthesis only required if the function returns more than 1 variable?

In the example below I know this won't work unless I use return inner(), but I see other examples that don't use the () on the return and they work fine.

Terminology behind the reason would great so help me fully understand. Thanks.

```<code>def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner()

@stars
def func():
    print('Decorate this message.')
</code>```

It initially prints my message, decorated. But if I call func() again, it will not print anything.

Another working example, but return inner works fine in this case, long as I have set up my function to support a callable variable, being msg for my example:

```<code>def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

@star
def func(msg):
    print(msg)
func("Another message to be decorated")
</code>```

And I can call func('my new message') each time to print my message, decorated. Why is this compared to the previous example when I don't use a callable function?

答:
In a decorator you should not do return inner()

That would mean you are replacing the decorated func with the result of calling the wrapped func

Your code will immediately print the modified message, without you even trying to call func()!!

```<code>**************************************************
Decorate this message.
**************************************************
</code>```

But that is not what is intended when you decorate a function.

You intend to modify the behaviour of the function, but you still expect to have to call the function manually.

That is why the code should be:

```<code>def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner

@stars
def func():
    print('Decorate this message.')

func()
**************************************************
Decorate this message.
**************************************************
</code>```

To explain further:

When you use the decorator syntax

```<code>@stars
def func():
</code>```

You are telling python to do the following:

```<code>func = stars(func)
</code>```

In other words, def func but replace the function with the result of calling stars(func)

You might find it less confusing if you don't reuse the name func in the code. For example:

```<code>def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner

@stars
def print_a_message():
    print('Decorate this message.')

print_a_message()
**************************************************
Decorate this message.
**************************************************
</code>```

Maybe it's clearer now that when we do return inner from the decorator we are telling Python to replace print_a_message with inner

Body:
What's the difference including/not including the parentheses on the return statement for inner function for decorators (and any nested functions)? Are the parenthesis only required if the function returns more than 1 variable?

In the example below I know this won't work unless I use return inner(), but I see other examples that don't use the () on the return and they work fine.

Terminology behind the reason would great so help me fully understand. Thanks.

def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner()

@stars
def func():
    print('Decorate this message.')

It initially prints my message, decorated. But if I call func() again, it will not print anything.

Another working example, but return inner works fine in this case, long as I have set up my function to support a callable variable, being msg for my example:

def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

@star
def func(msg):
    print(msg)
func("Another message to be decorated")

And I can call func('my new message') each time to print my message, decorated. Why is this compared to the previous example when I don't use a callable function?

Body:
In a decorator you should not do return inner()

That would mean you are replacing the decorated func with the result of calling the wrapped func

Your code will immediately print the modified message, without you even trying to call func()!!

**************************************************
Decorate this message.
**************************************************

But that is not what is intended when you decorate a function.

You intend to modify the behaviour of the function, but you still expect to have to call the function manually.

That is why the code should be:

def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner

@stars
def func():
    print('Decorate this message.')

func()
**************************************************
Decorate this message.
**************************************************

To explain further:

When you use the decorator syntax

@stars
def func():

You are telling python to do the following:

func = stars(func)

In other words, def func but replace the function with the result of calling stars(func)

You might find it less confusing if you don't reuse the name func in the code. For example:

def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner

@stars
def print_a_message():
    print('Decorate this message.')

print_a_message()
**************************************************
Decorate this message.
**************************************************

Maybe it's clearer now that when we do return inner from the decorator we are telling Python to replace print_a_message with inner


问:
Safely Storing Credentials for Different Users on Heroku Slack App
I'm making a Slack App and just implemented OAuth to take advantage of Slack's Web API. I am using the single Access Token for my particular team that I am testing on.

Should I want to distribute this app on the Slack App Directory, will I have to store the Access Token for every single team? How should I go about securely storing these? Will the Heroku database suffice?

答:
Yes, your app needs to store the access token for each Slack team that installs it. And your app will need to access those tokens in order to enable access to that team's Slack (e.g. post a message). Most people will use a local database (e.g. MySQL) on the server to store the access tokens of each team. </p>

<p>No idea how secure the Heroku database is. However, since Heroku is a commercial service I would assume it can provide sufficient security for your app. </p>

Body:
Yes, your app needs to store the access token for each Slack team that installs it. And your app will need to access those tokens in order to enable access to that team's Slack (e.g. post a message). Most people will use a local database (e.g. MySQL) on the server to store the access tokens of each team.

No idea how secure the Heroku database is. However, since Heroku is a commercial service I would assume it can provide sufficient security for your app.


问:
Count and list occurrences inside list ordering count by DESC
Here is my function:

```<code>public static void countKeywords(List<String> list) {
    Map<String, Long> counts =
            list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    System.out.println(counts);
}
</code>```

And here is the sample that it outputs:

```<code>{alarm=2, player=1, factory=3}
</code>```

I need it to be ordered by occurrence count in descending direction. So output must be like:

```<code>  factory - 3
  alarm - 2
  player - 1
</code>```

What am I doing wrong?

答:
The issue is the data structure your using. A normal map does not guarantee order or sorting. If your set on using a Map as your structure, I would take a look at the TreeMap API. It lets you define a comparator in your map constructor.

https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

```<code>public static void countKeywords(List<String> list) {
    Map<String, Long> counts = list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    System.out.println(counts);

    TreeMap<String, Long> sortedMap = new TreeMap<String, Long>(new Comparator<String>() {
        @Override
        public int compare(String key1, String key2) {
            return counts.get(key2).compareTo(counts.get(key1));
        }
    });

    sortedMap.putAll(counts);
    System.out.println(sortedMap);
}
</code>```

Body:
Here is my function:

public static void countKeywords(List<String> list) {
    Map<String, Long> counts =
            list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    System.out.println(counts);
}

And here is the sample that it outputs:

{alarm=2, player=1, factory=3}

I need it to be ordered by occurrence count in descending direction. So output must be like:

  factory - 3
  alarm - 2
  player - 1

What am I doing wrong?

Body:
The issue is the data structure your using. A normal map does not guarantee order or sorting. If your set on using a Map as your structure, I would take a look at the TreeMap API. It lets you define a comparator in your map constructor.

https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

public static void countKeywords(List<String> list) {
    Map<String, Long> counts = list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    System.out.println(counts);

    TreeMap<String, Long> sortedMap = new TreeMap<String, Long>(new Comparator<String>() {
        @Override
        public int compare(String key1, String key2) {
            return counts.get(key2).compareTo(counts.get(key1));
        }
    });

    sortedMap.putAll(counts);
    System.out.println(sortedMap);
}


问:
Efficient way to run a function over the columns of a pandas Dataframe?
I want to run a function over the columns of a Pandas Dataframe.
Corpus is a pd.Dataframe

```<code>import pandas as pd
import numpy as np
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]],index=["stark","groß","schwach","klein", "dick"],columns=["d1", "d2", "d3","d4","d5","d6"])
</code>```

And I have query. Query is a Pandas Series.

```<code>query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])
</code>```

Now I want to run the cosine function over every column in corpus and the query.

```<code>for column in corpus:
print("Similarity of Documents", column," and query: \n" ,1-cosine(query, corpus[column]))
</code>```

Is there a better way to run the cosine fuction over the columns? Maybe some method that gets the columns and runs the function over every column. I want to avoid the for Loop.

答:
apply-ing functions is a neat, readable and a quick way for such a job:

```<code>import pandas as pd
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]], index=["stark","groß","schwach","klein", "dick"], columns=["d1", "d2", "d3","d4","d5","d6"])
query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])

corpus.apply(lambda x:1-cosine(query, x),  # Apply your function
             axis=0)                       # For each column

# d1    0.980581
# d2    0.707107
# d3    0.288675
# d4    0.801784
# d5    0.500000
# d6    0.894315
# dtype: float64
</code>```

Body:
I want to run a function over the columns of a Pandas Dataframe.
Corpus is a pd.Dataframe

import pandas as pd
import numpy as np
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]],index=["stark","groß","schwach","klein", "dick"],columns=["d1", "d2", "d3","d4","d5","d6"])

And I have query. Query is a Pandas Series.

query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])

Now I want to run the cosine function over every column in corpus and the query.

for column in corpus:
print("Similarity of Documents", column," and query: \n" ,1-cosine(query, corpus[column]))

Is there a better way to run the cosine fuction over the columns? Maybe some method that gets the columns and runs the function over every column. I want to avoid the for Loop.

Body:
apply-ing functions is a neat, readable and a quick way for such a job:

import pandas as pd
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]], index=["stark","groß","schwach","klein", "dick"], columns=["d1", "d2", "d3","d4","d5","d6"])
query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])

corpus.apply(lambda x:1-cosine(query, x),  # Apply your function
             axis=0)                       # For each column

# d1    0.980581
# d2    0.707107
# d3    0.288675
# d4    0.801784
# d5    0.500000
# d6    0.894315
# dtype: float64


问:
How to secure passwords in the Software Development?
how do you secure your passwords in propertie Files?
Encryption / Encoding?

Or do you use a different approach to handle Database User / Passwords for connection Strings?

Thanks for you help!

Update: Thanks for your responses! In this special case we talk about two tier architecture. We have many clients with direct connections to the databases. Propertie Files are on a network share.

答:
you might have a closer look to aspnet_regiis. This commandLine programm has some pretty nice parameters such aus -pef (encrypt) and -pdf (decrypt).

so you may encrypt your complete (or just a port of) xxx.config file while it stays useable for your application.


问:
std::ptr_fun replacement for c++17
I am using std::ptr_fun as follows:

```<code>static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}
</code>```

as presented in this answer.

However this does not compile with C++17 (using Microsoft Visual Studio 2017), with the error:

```<code>error C2039: 'ptr_fun': is not a member of 'std'
</code>```

How can this be fixed?

答:
According to cppreference, std::ptr_fun is deprecated since C++11 and discontinued since C++17.

Similarly, std::not1 is deprecated since C++17.

So best don't use either, but a lambda (as explained in other answers).

Title: std::ptr_fun replacement for c++17

Body:
I am using std::ptr_fun as follows:

static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

as presented in this answer.

However this does not compile with C++17 (using Microsoft Visual Studio 2017), with the error:

error C2039: 'ptr_fun': is not a member of 'std'

How can this be fixed?


问:
Sql Query results to CSV to a specified file path after stored procedure execution
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

```<code>EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1
</code>```

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

答:
Invoking CMD is one way to achieve it and can automate it </p>

```<code>Declare @sql VARCHAR(max)
declare @CsvFile NVARCHAR(500)
DECLARE @cmd NVARCHAR(4000)
set @sql = 'Exec [dbo].[Usp_CSVextract]'
set @CsvFile = 'C:\Test.csv'
SET @cmd =
'bcp '+CHAR(34)+@sql+CHAR(34)+' queryout '+CHAR(34)+@CsvFile+CHAR(34)+' -S '+@@servername
+' -c -t'+CHAR(34)+','+CHAR(34)+' -r'+CHAR(34)+'\n'+CHAR(34)+' -T'

exec master.dbo.xp_cmdshell @cmd
</code>```

Body:
I'm trying to execute a stored procedure (which i know works) in T-SQL that then gets those results into a CSV file and puts that file into a directory.  I'm not sure how to formulate that query, exactly though.  Here's what i've tried thus far to no avail:

EXECUTE CLR_ExportQueryToCSV @QueryCommand = 'execute databaseName.dbo.StoredProcedureName',
                          @FilePath = 'C:\Directory',
                          @FileName = '\FileToExport.csv',
                          @IncludeHeaders = 1

I realize CLR_ExportQueryToCSV doesn't exist.  Is there any system stored procedure that will do what i'm wanting?

Body:
Invoking CMD is one way to achieve it and can automate it

Declare @sql VARCHAR(max)
declare @CsvFile NVARCHAR(500)
DECLARE @cmd NVARCHAR(4000)
set @sql = 'Exec [dbo].[Usp_CSVextract]'
set @CsvFile = 'C:\Test.csv'
SET @cmd =
'bcp '+CHAR(34)+@sql+CHAR(34)+' queryout '+CHAR(34)+@CsvFile+CHAR(34)+' -S '+@@servername
+' -c -t'+CHAR(34)+','+CHAR(34)+' -r'+CHAR(34)+'\n'+CHAR(34)+' -T'

exec master.dbo.xp_cmdshell @cmd


问:
set up website on local machine
I have a fast dedicated internet connection and a static IP address at my office. I also have a web site that I want to host on my server machine (win server 2003). I know how to setup a web site through IIS but have no clue how to point my domain to my site and configure my server to serve for that domain. Can anyone point me to a preferably step-by-step guide on how to achieve this?</p>

答:
If you have a static IP address, and the IP is exposed publicly, and your domain registrar is hosting your DNS, then it's easy, provided the registrar allows you access to edit your DNS settings.  Just log into your registrar account, find the DNS management tools, create a new (or otherwise make there there's at least one) "A" record pointing to your static IP address, make sure that record is either "www" or "*", and you're done -- assuming you don't have any software or hardware firewalls in the way, and you know how to set up the site in IIS, as you say.

It's tough to say more without knowing your configuration, or whether you're having any specific problems, but yeah, it sounds like the only missing piece conceptually is pointing an A record to your machine.  Good luck!

OwnerDisplayName: Emin

Title: set up website on local machine

OwnerDisplayName: Christian Nunciato


问:
where should I put the EF entity and data annotations in asp.net mvc + entity framework project
So I have a DataEntity class generated by EntityFramework4 for my sqlexpress08 database. This data context is exposed via a WCF Data Service/Odata to silverlight and win forms clients.

Should the data entities + edmx file (generated by EF4) go in a separate class library?

The problem here then is I would specify data annotations for a few entities and then some of them would require specific MVC attributes (like CompareAttribute) so the class library would also reference mvc dlls. There also happen to be entity users which will be encapsulated or wrapped into an IIdentity in the website. So its pretty tied to the mvc website. Or Should it maybe go in a Base folder in the mvc project itself?

Mostly the website is data driven around the database, like approve users, change global settings etc. The real business happens in the silverlight and win forms apps.

Im using mvc3 rc2 with Razor.

Thanks

答:
Should the data entities + edmx file (generated by EF4) go in a separate class library?

IMHO all data access logic which is specific to some data access technology (in your case Entity Framework) should go into a separate assembly. There should be no MVC specific assemblies referenced there.

In your ASP.NET MVC application you would then reference this assembly and write view models. It is those view models that will contain any MVC specific attributes. Then you could map between your model classes and those view models which would be passed to the view. AutoMapper could be used to facilitate this task.


问:
Post-processing the heatmap in python or ImageMagick
How could I make this heatmap look more clear without the blurred effect. How could I sharpen it Python (or ImageMagick)? also, how could I get a pixel-grid on the background?

Here is what I used to get the current image:

```<code>maxsize = (1030, 2056)
for i in range(1,334,1):
    img = Image.open('C:Desktop/Img/image'+'_'+ str(i)+'.png')
    img = img.resize(maxsize, Image.BICUBIC)
    img.save('C:/Desktop/Res/img'+'_'+ str(i)+'.png', dpi = (7040,7040))
</code>```

I also tried in ImageMagick (but that did not help much, atleast looking visually):

```<code>magick img_244.png -sharpen 0x3 out.png
</code>```

Thank you very much in advance,

答:
What module did you import as is Image? What you need is a nearest neighbor interpolation, not bicubic interpolation. Probably something like

```<code>img = img.resize(maxsize, Image.INTER_NEAREST)
</code>```

Body:
How could I make this heatmap look more clear without the blurred effect. How could I sharpen it Python (or ImageMagick)? also, how could I get a pixel-grid on the background?

Here is what I used to get the current image:

maxsize = (1030, 2056)
for i in range(1,334,1):
    img = Image.open('C:Desktop/Img/image'+'_'+ str(i)+'.png')
    img = img.resize(maxsize, Image.BICUBIC)
    img.save('C:/Desktop/Res/img'+'_'+ str(i)+'.png', dpi = (7040,7040))

I also tried in ImageMagick (but that did not help much, atleast looking visually):

magick img_244.png -sharpen 0x3 out.png

Thank you very much in advance,

Body:
What module did you import as is Image? What you need is a nearest neighbor interpolation, not bicubic interpolation. Probably something like

img = img.resize(maxsize, Image.INTER_NEAREST)


问:
Edit default .htaccess in wordpress docker
I have a wordpress container which gets generated by a docker-compose file. Wordpress container contains <code>.htaccess</code> file by default. I want to  edit that such that that the edit is performed only once when container is created. </p>

答:
The easiest way is to build your own image based on wordpress:with-netcat, with all required preparations:

```<code>FROM wordpress:with-netcat

RUN /. EDIT YOUR .htaccess file here ./

ENTRYPOINT ...
CMD ...
</code>```

And to use this image instead of the original one.

Body: I have a wordpress container which gets generated by a docker-compose file. Wordpress container contains .htaccess file by default. I want to  edit that such that that the edit is performed only once when container is created.

Body:
The easiest way is to build your own image based on wordpress:with-netcat, with all required preparations:

FROM wordpress:with-netcat

RUN /. EDIT YOUR .htaccess file here ./

ENTRYPOINT ...
CMD ...

And to use this image instead of the original one.


问:
How to store a List<String> from spring JPA to text[] array in database
I am trying to write an Java- Array List into postgres database.　But i am not able to DO, i don't get error as well. I am trying to post data

```<code>"skill":["java,dotnet"]
</code>```

using postman tool but on Post nothing happens and i don't see any data in db.I also don't get any error in my console.please help me out on this i m wondering how to do this

I am able to read Array data from database but cannot write

```<code>    /*
     * Spring Entity:
     */
    @Column(name="skill" , columnDefinition = "text[]")
    @Convert(converter =ListToStringConverter.class)
        private List<String> skill=new ArrayList<>();
        ublic List<String> getSkill() {
            return skill;
        }
        public void setSkill(List<String> skill) {
            this.skill= skill;
        }

    @Converter
    public class ListToStringConverter implements AttributeConverter<List<String>, String> {

        @Override
        public String convertToDatabaseColumn(List<String> attribute) {
            if (attribute == null || attribute.isEmpty()) {
                return "";
            }
            return StringUtils.join(attribute, ",");
        }

        @Override
        public List<String> convertToEntityAttribute(String dbData) {
            if (dbData == null || dbData.trim().length() == 0) {
                return new ArrayList<String>();
            }

            String[] data = dbData.split(",");
            return Arrays.asList(data);
        }
    }

Controller Code:
</code>```

This is my Controller code to create a object in database and i use a interface service that is call from controller to Save to db-Postgres which is a JPA repo

```<code>    @RequestMapping(value = "/reqCreate", method = RequestMethod.POST)
    public ResponseEntity<Requirement> addRequirement(@RequestBody Requirement requirement) {
        reqService.save(requirement);
        return new ResponseEntity<Requirement>(requirement, HttpStatus.CREATED);
    }

Service:
    public void save(Requirement r) {
        reqRepo.save(r);
    }
</code>```

答:
The columnDefinition seems to be wrong.

You want to convert Collection into String, but you still declare column of array type.

Replace "text[]" with "text" and check if it works?

Body:
I am trying to write an Java- Array List into postgres database.　But i am not able to DO, i don't get error as well. I am trying to post data

"skill":["java,dotnet"]

using postman tool but on Post nothing happens and i don't see any data in db.I also don't get any error in my console.please help me out on this i m wondering how to do this

I am able to read Array data from database but cannot write

    /*
     * Spring Entity:
     */
    @Column(name="skill" , columnDefinition = "text[]")
    @Convert(converter =ListToStringConverter.class)
        private List<String> skill=new ArrayList<>();
        ublic List<String> getSkill() {
            return skill;
        }
        public void setSkill(List<String> skill) {
            this.skill= skill;
        }

    @Converter
    public class ListToStringConverter implements AttributeConverter<List<String>, String> {

        @Override
        public String convertToDatabaseColumn(List<String> attribute) {
            if (attribute == null || attribute.isEmpty()) {
                return "";
            }
            return StringUtils.join(attribute, ",");
        }

        @Override
        public List<String> convertToEntityAttribute(String dbData) {
            if (dbData == null || dbData.trim().length() == 0) {
                return new ArrayList<String>();
            }

            String[] data = dbData.split(",");
            return Arrays.asList(data);
        }
    }

Controller Code:

This is my Controller code to create a object in database and i use a interface service that is call from controller to Save to db-Postgres which is a JPA repo

    @RequestMapping(value = "/reqCreate", method = RequestMethod.POST)
    public ResponseEntity<Requirement> addRequirement(@RequestBody Requirement requirement) {
        reqService.save(requirement);
        return new ResponseEntity<Requirement>(requirement, HttpStatus.CREATED);
    }

Service:
    public void save(Requirement r) {
        reqRepo.save(r);
    }


问:
Error 330 (net::ERR_CONTENT_DECODING_FAILED):
Recently we migrated to a new server. After 2 days, I got the following issues

1) We had a crash on a session table, which we easily fixed by reparing it

2) We run OpenX as our adserver, and it also crashed, but there is no evidence in error.log
It let's you login, but at the moment of looking to dashboard.php, we get the:

```<code>Error 330 (net::ERR_CONTENT_DECODING_FAILED): (Google Chrome)
</code>```

and

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression. (Firefox)

OpenX uses the following services on PHP:

OpenX requires:
http://www.openx.com/docs/2.8/adminguide/System%20requirements

OpenX uses the default PHP settings. However, server administrators sometimes change these settings. Before you install OpenX check that the following settings are correct:

magic_quotes_runtime must be off
safe_mode must be off
register_argc_argv must be on if you want to run maintenance via command line
file_uploads need to be turned on to allow HTTP file uploads
OpenX requires the following PHP extensions:

Either the mysql extension, or the pgsql. The mysqli extension is not supported.
The ZLib extension, to convert links inside compressed Flash files generated by Flash MX.
The FTP extension. If this is not present OpenX will try to simulate it, which can be a less stable solution.

The GD extension, to generate graphs on the Home page. If the extension is not enabled you will not be able to view graphs or statistics on your Home page.
Either the openssl extension or an SSL-enabled curl extension are required in order to logon to the Home page. If SSL is not enabled you will receive an error message in the Home page, but there is no impact on operations.

Any clue on possible reasons or on how to gather more information will be much appreciated.
Thanks

答:
I was experiencing this issue on a drupal site and none of the other solutions in this thread helped. After some troubleshooting I found the local.settings.php had a closing tag with a space after it like so:

```<code><?php
$databases = array(
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'database' => 'xxx',
      'username' => 'xxx',
      'password' => 'xxx',
      'port' => '',
      'host' => 'xxx',
    ),
  ),
);
?>

</code>```

Updating local.settings.php to the following resolved:

```<code><?php
$databases = array(
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'database' => 'xxx',
      'username' => 'xxx',
      'password' => 'xxx',
      'port' => '',
      'host' => 'xxx',
    ),
  ),
);
</code>```

The closing "?>" PHP tag is not necessary here. If you choose to use a closing tag you must ensure there are no characters / whitespace after it.

Body:
Recently we migrated to a new server. After 2 days, I got the following issues

1) We had a crash on a session table, which we easily fixed by reparing it

2) We run OpenX as our adserver, and it also crashed, but there is no evidence in error.log
It let's you login, but at the moment of looking to dashboard.php, we get the:

Error 330 (net::ERR_CONTENT_DECODING_FAILED): (Google Chrome)

and

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression. (Firefox)

OpenX uses the following services on PHP:

OpenX requires:
http://www.openx.com/docs/2.8/adminguide/System%20requirements

OpenX uses the default PHP settings. However, server administrators sometimes change these settings. Before you install OpenX check that the following settings are correct:

magic_quotes_runtime must be off
safe_mode must be off
register_argc_argv must be on if you want to run maintenance via command line
file_uploads need to be turned on to allow HTTP file uploads
OpenX requires the following PHP extensions:

Either the mysql extension, or the pgsql. The mysqli extension is not supported.
The ZLib extension, to convert links inside compressed Flash files generated by Flash MX.
The FTP extension. If this is not present OpenX will try to simulate it, which can be a less stable solution.

The GD extension, to generate graphs on the Home page. If the extension is not enabled you will not be able to view graphs or statistics on your Home page.
Either the openssl extension or an SSL-enabled curl extension are required in order to logon to the Home page. If SSL is not enabled you will receive an error message in the Home page, but there is no impact on operations.

Any clue on possible reasons or on how to gather more information will be much appreciated.
Thanks

Body:
I was experiencing this issue on a drupal site and none of the other solutions in this thread helped. After some troubleshooting I found the local.settings.php had a closing tag with a space after it like so:

<?php
$databases = array(
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'database' => 'xxx',
      'username' => 'xxx',
      'password' => 'xxx',
      'port' => '',
      'host' => 'xxx',
    ),
  ),
);
?>

Updating local.settings.php to the following resolved:

<?php
$databases = array(
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'database' => 'xxx',
      'username' => 'xxx',
      'password' => 'xxx',
      'port' => '',
      'host' => 'xxx',
    ),
  ),
);

The closing "?>" PHP tag is not necessary here. If you choose to use a closing tag you must ensure there are no characters / whitespace after it.