问:
akka.cluster with double asp.net webapi on IIS
In out cluster we have five nodes composite of:

2 seed nodes (backend)

1 worker

2 webapi on IIS

The cluster is joined, up and running; but the second IIS when perform the first message to the cluster via router make all cluster unreachable and dissociated.
In addition the second IIS can't deliver any message.

Here is my IIS config:

```<code><hocon>
  <![CDATA[
        akka.loglevel = INFO
        akka.log-config-on-start = off
        akka.stdout-loglevel = INFO
        akka.actor {
            provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
            deployment {
              /Process {
                router = round-robin-group
                routees.paths = ["/user/Process"] # path of routee on each node
                # nr-of-instances = 3 # max number of total routees
                cluster {
                    enabled = on
                    allow-local-routees = off
                    use-role = Process
                }
              }
            }
            debug {
              receive = on
              autoreceive = on
              lifecycle = on
              event-stream = on
              unhandled = on
            }
        }
        akka.remote {
            helios.tcp {
                # transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                # applied-adapters = []
                # transport-protocol = tcp
                port = 0
                hostname = 172.16.1.8
            }
            log-remote-lifecyclo-events = DEBUG
        }
        akka.cluster {
          seed-nodes = [
            "akka.tcp://ClusterActorSystem@172.16.1.8:2551",
            "akka.tcp://ClusterActorSystem@172.16.1.8:2552"
          ]
          roles = [Send]
          auto-down-unreachable-after = 10s
          # how often should the node send out gossip information?
          gossip-interval = 1s
          # discard incoming gossip messages if not handled within this duration
          gossip-time-to-live = 2s
        }
        # http://getakka.net/docs/persistence/at-least-once-delivery
        akka.persistence.at-least-once-delivery.redeliver-interval = 300s
        # akka.persistence.at-least-once-delivery.redelivery-burst-limit =
        # akka.persistence.at-least-once-delivery.warn-after-number-of-unconfirmed-attempts =
        akka.persistence.at-least-once-delivery.max-unconfirmed-messages = 1000000
        akka.persistence.journal.plugin = "akka.persistence.journal.sql-server"
        akka.persistence.journal.publish-plugin-commands = on
        akka.persistence.journal.sql-server {
            class = "Akka.Persistence.SqlServer.Journal.SqlServerJournal, Akka.Persistence.SqlServer"
            plugin-dispatcher = "akka.actor.default-dispatcher"
            table-name = EventJournal
            schema-name = dbo
            auto-initialize = on
            connection-string-name = "HubAkkaPersistence"
            refresh-interval = 1s
            connection-timeout = 30s
            timestamp-provider = "Akka.Persistence.Sql.Common.Journal.DefaultTimestampProvider, Akka.Persistence.Sql.Common"
            metadata-table-name = Metadata
        }
        akka.persistence.snapshot-store.plugin = ""akka.persistence.snapshot-store.sql-server""
        akka.persistence.snapshot-store.sql-server {
          class = "Akka.Persistence.SqlServer.Snapshot.SqlServerSnapshotStore, Akka.Persistence.SqlServer"
          plugin-dispatcher = ""akka.actor.default-dispatcher""
          connection-string-name = "HubAkkaPersistence"
          schema-name = dbo
          table-name = SnapshotStore
          auto-initialize = on
        }
  ]]>
</hocon>
</code>```

inside the global.asax we create a new router to the cluster:

```<code>    ClusterActorSystem = ActorSystem.Create("ClusterActorSystem");

    var backendRouter =
        ClusterActorSystem.ActorOf(
            Props.Empty.WithRouter(FromConfig.Instance), "Process");

    Send = SistemiHubClusterActorSystem.ActorOf(
        Props.Create(() => new Common.Actors.Send(backendRouter)),
        "Send");
</code>```

and here is our backend config:

```<code><hocon><![CDATA[
    akka.loglevel = INFO
    akka.log-config-on-start = on
    akka.stdout-loglevel = INFO
    akka.actor {
        provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
        debug {
          receive = on
          autoreceive = on
          lifecycle = on
          event-stream = on
          unhandled = on
        }
    }
    akka.remote {
      helios.tcp {
            # transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
            # applied-adapters = []
            # transport-protocol = tcp
            #
            # seed-node ports 2551 and 2552
            # non-seed-node port 0
            port = 2551
            hostname = 172.16.1.8
        }
        log-remote-lifecyclo-events = INFO
    }
    akka.cluster {
      seed-nodes = [
        "akka.tcp://ClusterActorSystem@172.16.1.8:2551",
        "akka.tcp://ClusterActorSystem@172.16.1.8:2552"
      ]
      roles = [Process]
      auto-down-unreachable-after = 10s
    }
  ]]></hocon>
</code>```

The issue in present using Akka 1.1 and Akka 1.2

UPDATE

I have found that the issue is related to our LoadBalancer (NetScaler) if I call each IIS directly is working fine. If called by the balancer I face the reported issue; the balancer is trasparent (it only add some headers to the request). What can I check to solve this issue?

答: Finally I found the problem, we are using akka.persistence that requires a specific value declination for the PersistenceId for each IIS.</p>

Body:
In out cluster we have five nodes composite of:

2 seed nodes (backend)

1 worker

2 webapi on IIS

The cluster is joined, up and running; but the second IIS when perform the first message to the cluster via router make all cluster unreachable and dissociated.
In addition the second IIS can't deliver any message.

Here is my IIS config:

<hocon>
  <![CDATA[
        akka.loglevel = INFO
        akka.log-config-on-start = off
        akka.stdout-loglevel = INFO
        akka.actor {
            provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
            deployment {
              /Process {
                router = round-robin-group
                routees.paths = ["/user/Process"] # path of routee on each node
                # nr-of-instances = 3 # max number of total routees
                cluster {
                    enabled = on
                    allow-local-routees = off
                    use-role = Process
                }
              }
            }
            debug {
              receive = on
              autoreceive = on
              lifecycle = on
              event-stream = on
              unhandled = on
            }
        }
        akka.remote {
            helios.tcp {
                # transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                # applied-adapters = []
                # transport-protocol = tcp
                port = 0
                hostname = 172.16.1.8
            }
            log-remote-lifecyclo-events = DEBUG
        }
        akka.cluster {
          seed-nodes = [
            "akka.tcp://ClusterActorSystem@172.16.1.8:2551",
            "akka.tcp://ClusterActorSystem@172.16.1.8:2552"
          ]
          roles = [Send]
          auto-down-unreachable-after = 10s
          # how often should the node send out gossip information?
          gossip-interval = 1s
          # discard incoming gossip messages if not handled within this duration
          gossip-time-to-live = 2s
        }
        # http://getakka.net/docs/persistence/at-least-once-delivery
        akka.persistence.at-least-once-delivery.redeliver-interval = 300s
        # akka.persistence.at-least-once-delivery.redelivery-burst-limit =
        # akka.persistence.at-least-once-delivery.warn-after-number-of-unconfirmed-attempts =
        akka.persistence.at-least-once-delivery.max-unconfirmed-messages = 1000000
        akka.persistence.journal.plugin = "akka.persistence.journal.sql-server"
        akka.persistence.journal.publish-plugin-commands = on
        akka.persistence.journal.sql-server {
            class = "Akka.Persistence.SqlServer.Journal.SqlServerJournal, Akka.Persistence.SqlServer"
            plugin-dispatcher = "akka.actor.default-dispatcher"
            table-name = EventJournal
            schema-name = dbo
            auto-initialize = on
            connection-string-name = "HubAkkaPersistence"
            refresh-interval = 1s
            connection-timeout = 30s
            timestamp-provider = "Akka.Persistence.Sql.Common.Journal.DefaultTimestampProvider, Akka.Persistence.Sql.Common"
            metadata-table-name = Metadata
        }
        akka.persistence.snapshot-store.plugin = ""akka.persistence.snapshot-store.sql-server""
        akka.persistence.snapshot-store.sql-server {
          class = "Akka.Persistence.SqlServer.Snapshot.SqlServerSnapshotStore, Akka.Persistence.SqlServer"
          plugin-dispatcher = ""akka.actor.default-dispatcher""
          connection-string-name = "HubAkkaPersistence"
          schema-name = dbo
          table-name = SnapshotStore
          auto-initialize = on
        }
  ]]>
</hocon>

inside the global.asax we create a new router to the cluster:

    ClusterActorSystem = ActorSystem.Create("ClusterActorSystem");

    var backendRouter =
        ClusterActorSystem.ActorOf(
            Props.Empty.WithRouter(FromConfig.Instance), "Process");

    Send = SistemiHubClusterActorSystem.ActorOf(
        Props.Create(() => new Common.Actors.Send(backendRouter)),
        "Send");

and here is our backend config:

<hocon><![CDATA[
    akka.loglevel = INFO
    akka.log-config-on-start = on
    akka.stdout-loglevel = INFO
    akka.actor {
        provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
        debug {
          receive = on
          autoreceive = on
          lifecycle = on
          event-stream = on
          unhandled = on
        }
    }
    akka.remote {
      helios.tcp {
            # transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
            # applied-adapters = []
            # transport-protocol = tcp
            #
            # seed-node ports 2551 and 2552
            # non-seed-node port 0
            port = 2551
            hostname = 172.16.1.8
        }
        log-remote-lifecyclo-events = INFO
    }
    akka.cluster {
      seed-nodes = [
        "akka.tcp://ClusterActorSystem@172.16.1.8:2551",
        "akka.tcp://ClusterActorSystem@172.16.1.8:2552"
      ]
      roles = [Process]
      auto-down-unreachable-after = 10s
    }
  ]]></hocon>

The issue in present using Akka 1.1 and Akka 1.2

UPDATE

I have found that the issue is related to our LoadBalancer (NetScaler) if I call each IIS directly is working fine. If called by the balancer I face the reported issue; the balancer is trasparent (it only add some headers to the request). What can I check to solve this issue?


来源: stackexchange

问:
JSF composite does not store state with StateHelper
I am developing a JSF composite that gets a complex data structure as argument:

```<code><cc:interface componentType="MyComponent">
    <cc:attribute name="myModel"    required="true"     type="my.package.Model" />
</cc:interface>
</code>```

The backing component processes this model using an init() method that is invoked in the composite via an event:

```<code>    <cc:implementation>
        <f:event type="postAddToView" listener="#{cc.init}" />
        [...]
    </cc:implementation>
</code>```

In this init() method I check if the model has already been processed (because I don't want to do that every time the user stays on the page, e.g. through ajax requests). Hence I store the processed model via StateHelper.put():

```<code>public void init()
{
    if (getMyModel() == null)
    {
        MyModel model = processModel(...);
        setMyModel(model);
    }
}

@SuppressWarnings("unchecked")
public MyModel getMyModel()
{
    return (MyModel) getStateHelper().get("MyModel");
}

public void setMyModel(MyModel MyModel)
{
    getStateHelper().put("MyModel", MyModel);
}
</code>```

I expect now, that if the init() method is invoked for example during an Ajax request (in the same view scope) it does not process the model a second time because I have stored it in the view scope via the StateHelper. But no matter what I try, if I click on a command link with void/null outcome the getMyModel() method always returns null.
Any ideas?

答: Implementing the restoreState() method in the backing component and setting a breakpoint revealed the problem. The postAddToView event is processed before the invocation of restoreState(). Using preRenderView instead resolved the issue for me.

ContentLicense: CC BY-SA 3.0

Body:
I am developing a JSF composite that gets a complex data structure as argument:

<cc:interface componentType="MyComponent">
    <cc:attribute name="myModel"    required="true"     type="my.package.Model" />
</cc:interface>

The backing component processes this model using an init() method that is invoked in the composite via an event:

    <cc:implementation>
        <f:event type="postAddToView" listener="#{cc.init}" />
        [...]
    </cc:implementation>

In this init() method I check if the model has already been processed (because I don't want to do that every time the user stays on the page, e.g. through ajax requests). Hence I store the processed model via StateHelper.put():

public void init()
{
    if (getMyModel() == null)
    {
        MyModel model = processModel(...);
        setMyModel(model);
    }
}

@SuppressWarnings("unchecked")
public MyModel getMyModel()
{
    return (MyModel) getStateHelper().get("MyModel");
}

public void setMyModel(MyModel MyModel)
{
    getStateHelper().put("MyModel", MyModel);
}

I expect now, that if the init() method is invoked for example during an Ajax request (in the same view scope) it does not process the model a second time because I have stored it in the view scope via the StateHelper. But no matter what I try, if I click on a command link with void/null outcome the getMyModel() method always returns null.
Any ideas?


问:
How to output a string with a space between each letter
For example, if I entered I love dogs, it would need to look like this:

```<code>I  l o v e  d o g s
</code>```

This code does not do what I need it to do:

```<code>def spaceitout(source):
    pile = ""
    for letter in source:
        pile = pile+letter
        print pile
    print pile
</code>```

答:
This lists your word( 'his' = ['h','i','s'] and then joins it with a space instead of a comma.</p>

```<code>def space(word):
   return ' '.join(list(word))
</code>```

Body:
For example, if I entered I love dogs, it would need to look like this:

I  l o v e  d o g s

This code does not do what I need it to do:

def spaceitout(source):
    pile = ""
    for letter in source:
        pile = pile+letter
        print pile
    print pile

Body:
This lists your word( 'his' = ['h','i','s'] and then joins it with a space instead of a comma.

def space(word):
   return ' '.join(list(word))


问:
how to set an parameter to not filter the SQL query when not set
I have a page with a list of artists and three buttons; photographers, makeup artists, all

I want to query the database to select each type through $_GET when any of the buttons is clicked which is easy for the first two I can set the url to ?type=photographers

however when I want to set the type to all, there's no value in the type column called all, i tried to set the type to * but it doesn't work

```<code>SELECT name, location, score, type FROM artists WHERE type = ?
</code>```

how to set type to show all what should the variable be equal to?

edit: I'm already using the !empty method, now I want to add more rules to my query and it's getting complicated, any other solution where I don't have to have two queries in the if and else?

答: Just do a condition on your $_GET and change your SQL query accordingly. If you want to select all your entries, you don't need WHERE. </p>

Body:
I have a page with a list of artists and three buttons; photographers, makeup artists, all

I want to query the database to select each type through $_GET when any of the buttons is clicked which is easy for the first two I can set the url to ?type=photographers

however when I want to set the type to all, there's no value in the type column called all, i tried to set the type to * but it doesn't work

SELECT name, location, score, type FROM artists WHERE type = ?

how to set type to show all what should the variable be equal to?

edit: I'm already using the !empty method, now I want to add more rules to my query and it's getting complicated, any other solution where I don't have to have two queries in the if and else?


问:
Can I redirect appname.herokuapp.com to www.app.com?
I Heroku, is there any way to get my heroapp domain to point to my custom domain? I have APPNAME.herokuapp.com which was setup by heroku and I got www.appname.com. www.appname.com works. But I want APPNAME.herokuapp.com to redirect to www.appname.com.

In short:
appname.herokuapp.com redirect -> www.appname.com

答:
Sure. You can detect the Host header in your code and redirect based on that.

In ruby for example:

```<code>if ENV["HTTP_HOST"] == "myapp.herokuapp.com"
  // Send the redirection and finish the request
end
</code>```

Body:
Sure. You can detect the Host header in your code and redirect based on that.

In ruby for example:

if ENV["HTTP_HOST"] == "myapp.herokuapp.com"
  // Send the redirection and finish the request
end


问:
Is there a way to change the __add__ method in python to be able to add a string and an int using only the + operator?
Is there a way to rewrite the __add__ method in the str class so that this operation is possible without an exception occurring:

```<code>"apple" + 123
</code>```

This error keeps popping up:

```<code>TypeError: Can't convert 'int' object to str implicitly
</code>```

答:
Short answer - No. You can not "override" the basic classes, but you can however provide a new subclass, but you will need to do it for both the strings and the integers, and then declare each item as an instance of your new class, which is pointless because the alternative is to simply do this:

```<code>myvar = 'apple' + str(123)
</code>```

You could however write a helper function to take care of that for you, if you're extremely lazy :) something like this:

```<code>def stradd(a,b):
    return str(a)+str(b)
</code>```

And from then on just use stradd('apple',123) to add things together

Body:
Is there a way to rewrite the __add__ method in the str class so that this operation is possible without an exception occurring:

"apple" + 123

This error keeps popping up:

TypeError: Can't convert 'int' object to str implicitly

Body:
Short answer - No. You can not "override" the basic classes, but you can however provide a new subclass, but you will need to do it for both the strings and the integers, and then declare each item as an instance of your new class, which is pointless because the alternative is to simply do this:

myvar = 'apple' + str(123)

You could however write a helper function to take care of that for you, if you're extremely lazy :) something like this:

def stradd(a,b):
    return str(a)+str(b)

And from then on just use stradd('apple',123) to add things together


问:
Why does Code::Blocks keep crashing when I try to run this code?
Code::Blocks keeps crashing when I enter the first score in this simple code. It is a perfectly type code to my understanding now I'm confused.</p>

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

int main() {
    float grade = 0;
    float scoreEntered = 0;
    float numtest = 0;
    float average = 0;

    printf("Press 0 when complete. \n\n");
    do {
        printf("Test: %.0f   Average: %.2f \n", numtest, average);
        printf("\nEnter test score ");
        scanf("%f", scoreEntered);
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
    } while (scoreEntered != 0);

    return 0;
}
</code>```

答:
The problem is you are passing scanf() the value of scoreEntered instead of its address.  You should write:

```<code>    scanf("%f", &scoreEntered);
</code>```

Note that the compiler can warn you about this kind of silly mistake it you increase the warning level.  Use gcc -Wall -Werror or clang -Weverything -Werror to get maximum help.

Note also that you should test the return value of scanf(). If it does not return 1 in the case of a single conversion, the target variable was not modified and the offending input will stay in the input stream, causing the same behavior to repeat indefinitely.  Try typing A as input and see for yourself (once you correct the missing &).

Here is a corrected and improved version:

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

int main(void) {
    float grade = 0;
    float scoreEntered = 0;
    float average = 0;
    int numtest = 0;

    printf("Press 0 when complete.\n");
    for (;;) {
        printf("\nEnter test score: ");
        if (scanf("%f", &scoreEntered) != 1 || scoreEntered == 0)
            break;
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
        printf("Test: %d   Average: %.2f\n", numtest, average);
    }

    return 0;
}
</code>```

Body:
Code::Blocks keeps crashing when I enter the first score in this simple code. It is a perfectly type code to my understanding now I'm confused.

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

int main() {
    float grade = 0;
    float scoreEntered = 0;
    float numtest = 0;
    float average = 0;

    printf("Press 0 when complete. \n\n");
    do {
        printf("Test: %.0f   Average: %.2f \n", numtest, average);
        printf("\nEnter test score ");
        scanf("%f", scoreEntered);
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
    } while (scoreEntered != 0);

    return 0;
}

Body:
The problem is you are passing scanf() the value of scoreEntered instead of its address.  You should write:

    scanf("%f", &scoreEntered);

Note that the compiler can warn you about this kind of silly mistake it you increase the warning level.  Use gcc -Wall -Werror or clang -Weverything -Werror to get maximum help.

Note also that you should test the return value of scanf(). If it does not return 1 in the case of a single conversion, the target variable was not modified and the offending input will stay in the input stream, causing the same behavior to repeat indefinitely.  Try typing A as input and see for yourself (once you correct the missing &).

Here is a corrected and improved version:

#include <stdio.h>

int main(void) {
    float grade = 0;
    float scoreEntered = 0;
    float average = 0;
    int numtest = 0;

    printf("Press 0 when complete.\n");
    for (;;) {
        printf("\nEnter test score: ");
        if (scanf("%f", &scoreEntered) != 1 || scoreEntered == 0)
            break;
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
        printf("Test: %d   Average: %.2f\n", numtest, average);
    }

    return 0;
}


问:
TFS Release Artifacts - How to Link Version Control Artifacts?
I am trying to setup some powershell scripts to be available on my TFS Release Agent.

From what I have learned thus far the way to do this is to link an artifact up and reference the artifact link in a PowerShell Task in TFS RM.

What I have trouble with is that TFS RM Artifacts will only allow me to download the entire Team Project in Version control while I only want powershell scripts in a specific subfolder downloaded to the agent.

I get an error message that says:

Field (Source Repository) Artifacts should have valid values

So, how do I link a SUBfolder of TFS as a downloadable artifact????

I there a custom task I can use to accomplish this instead?

I have yet to find one in the MarketPLace that downloads raw files in TFS Version Control binding and workspace free to execute on the Release agent server.

答:
The simple way is that you can get the file(s) by using Get a file REST API.

Click Run On agent

Check Allow scripts to access OAuth token option (make sure the build service account has the permission to download the file)

Add PowerShell task to release definition (Type: Inline Script)

Arguments:

```<code>-url '$(System.TeamFoundationCollectionUri)/_apis/tfvc/items?path=$/Scrum2015/ClassLibraryA/hello.ps1&api-version=1.0' -token "$(System.AccessToken)"  -filePath "$(System.DefaultWorkingDirectory)\hello.ps1"
</code>```

Scripts:

```<code>Param([string]$url,
  [string]$token,
  [string]$filePath
)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$token)))
Invoke-WebRequest -Method Get -Uri $url -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -OutFile $filePath
</code>```

If want to download many files in a folder, you can custom build task to call PowerShell to create workspace and get files by using Microsoft Team Foundation Server Extended Client package.

Body:
The simple way is that you can get the file(s) by using Get a file REST API.

Click Run On agent

Check Allow scripts to access OAuth token option (make sure the build service account has the permission to download the file)

Add PowerShell task to release definition (Type: Inline Script)

Arguments:

-url '$(System.TeamFoundationCollectionUri)/_apis/tfvc/items?path=$/Scrum2015/ClassLibraryA/hello.ps1&api-version=1.0' -token "$(System.AccessToken)"  -filePath "$(System.DefaultWorkingDirectory)\hello.ps1"

Scripts:

Param([string]$url,
  [string]$token,
  [string]$filePath
)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$token)))
Invoke-WebRequest -Method Get -Uri $url -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -OutFile $filePath

If want to download many files in a folder, you can custom build task to call PowerShell to create workspace and get files by using Microsoft Team Foundation Server Extended Client package.


问:
C++: how to build my own utility library?
I am starting to be proficient enough with C++ so that I can write my own C++ based scripts (to replace bash and PHP scripts I used to write before).

I find that I am starting to have a very small collection of utility functions and sub-routines that I'd like to use in several, otherwise unrelated C++ scripts.

I know I am not supposed to reinvent the wheel and that I could use external libraries for some of the utilities I'm creating for myself. However, it's fun to create my own utility functions, they are perfectly tailored to the job I have in mind, and it's for me a large part of the learning process. I'll see about using more polished external libraries when I am proficient enough to work on more serious, long term projects.

So, the question is: how do I manage my personal utility library in a way that the functions can be easily included in my various scripts?

I am using linux/Kubuntu, vim, g++, etc. and mostly coding CLI scripts.

Don't assume too much in terms of experience! ;) Links to tutorials or places where relevant topics are properly documented are welcome.

答:
Just stick your hpp and cpp files in seperate directories somewhere. That way, it's easy to add the directory containing the C++ files to any new project, and easy to add the headers to the include path.

If you find compile time starts to suffer, then you might want to consider putting these files in a static library.

ContentLicense: CC BY-SA 2.5


问:
How Make Form Input With Auto Tag HTML

How to make form input like above? is it plugin? how to add to my own website?
i want every user make enter, the component auto add tag

答:
Use these two scripts:

You can also used input as the replacement of textarea

     <form>
     <textarea>Next, get a free TinyMCE Cloud API key!</textarea>
     </form>

```

Title: How Make Form Input With Auto Tag HTML

Body:
Use these two scripts:

You can also used input as the replacement of textarea

<html>
<head>
     <script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
     <script>tinymce.init({ selector:'textarea' });</script>
</head>
<body>
     <form>
     <textarea>Next, get a free TinyMCE Cloud API key!</textarea>
     </form>
</body>
</html>


问:
How to call function from resolve?
I have been struggling with resolving in AngularJS. I wanted to load custom components and then call their functions but haven't managed to find a way.

In the below code I have tried to display SweetAlert (http://t4t5.github.io/sweetalert/) once the item has been successfully posted.

function config($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
    $urlRouterProvider.otherwise("/index/main");

```<code>$ocLazyLoadProvider.config({
    // Set to true if you want to see what and when is dynamically loaded
    debug: false
});
$stateProvider

    ....
    .state('index.item', {
        url: "/:itemId/edit",
        templateUrl: "views/item-edit.html",
        data: {pageTitle: 'Edit Item'},
        controller: function ($scope, $http, $stateParams, $rootScope, $state, $modal, $log, $ocLazyLoad) {
            //console.log($routeParams.itemId);

            var demo1 = function () {
                SweetAlert.swal({
                    title: "Welcome in Alerts",
                    text: "Lorem Ipsum is simply dummied text of the printing and typesetting industry."
                });
            }

            $scope.updateItem = function() {
                $log.log('Submiting item info');
                $http.post('/api/item', $scope.item)
                    .success(function(data) {
                        demo1();
                    })
                    .error(function(data) {
                        console.log('Error: ' + data);
                    });
            }
        },
        resolve: {
            loadPlugin: function ($ocLazyLoad) {
                return $ocLazyLoad.load([
                    {
                        files: ['js/plugins/sweetalert/sweetalert.min.js', 'css/plugins/sweetalert/sweetalert.css']
                    },
                    {
                        name: 'oitozero.ngSweetAlert',
                        files: ['js/plugins/sweetalert/angular-sweetalert.min.js']
                    }
                ]);
            }
        }
    })
</code>```

While trying to use the code above, I get the following error:

```<code>ReferenceError: SweetAlert is not defined
    at demo1 (config.js:156)
    at config.js:170
    at angular.js:9354
    at angular.js:13168
    at l.$eval (angular.js:14381)
    at l.$digest (angular.js:14197)
    at l.$apply (angular.js:14486)
    at l (angular.js:9644)
    at O (angular.js:9834)
    at XMLHttpRequest.w.onload (angular.js:9775)
</code>```

and the main reason is probably the property loadPlugin which is not called anywhere inside the controller. Does Anyone know how to modify the code in order to load the defined plugins and use them inside the controller?

Thanks!

答:
The problem is explicitly written in your error.

SweetAlert is not defined

Meaning that in your controller you forgot to add SweetAlert to your dependencies.

just add SweetAlert to the end of your conrtoller line:

```<code>controller: function ($scope, ... $ocLazyLoad, SweetAlert) {
</code>```

Title: How to call function from resolve?

Body:
I have been struggling with resolving in AngularJS. I wanted to load custom components and then call their functions but haven't managed to find a way.

In the below code I have tried to display SweetAlert (http://t4t5.github.io/sweetalert/) once the item has been successfully posted.

function config($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
    $urlRouterProvider.otherwise("/index/main");

$ocLazyLoadProvider.config({
    // Set to true if you want to see what and when is dynamically loaded
    debug: false
});
$stateProvider

    ....
    .state('index.item', {
        url: "/:itemId/edit",
        templateUrl: "views/item-edit.html",
        data: {pageTitle: 'Edit Item'},
        controller: function ($scope, $http, $stateParams, $rootScope, $state, $modal, $log, $ocLazyLoad) {
            //console.log($routeParams.itemId);

            var demo1 = function () {
                SweetAlert.swal({
                    title: "Welcome in Alerts",
                    text: "Lorem Ipsum is simply dummied text of the printing and typesetting industry."
                });
            }

            $scope.updateItem = function() {
                $log.log('Submiting item info');
                $http.post('/api/item', $scope.item)
                    .success(function(data) {
                        demo1();
                    })
                    .error(function(data) {
                        console.log('Error: ' + data);
                    });
            }
        },
        resolve: {
            loadPlugin: function ($ocLazyLoad) {
                return $ocLazyLoad.load([
                    {
                        files: ['js/plugins/sweetalert/sweetalert.min.js', 'css/plugins/sweetalert/sweetalert.css']
                    },
                    {
                        name: 'oitozero.ngSweetAlert',
                        files: ['js/plugins/sweetalert/angular-sweetalert.min.js']
                    }
                ]);
            }
        }
    })

While trying to use the code above, I get the following error:

ReferenceError: SweetAlert is not defined
    at demo1 (config.js:156)
    at config.js:170
    at angular.js:9354
    at angular.js:13168
    at l.$eval (angular.js:14381)
    at l.$digest (angular.js:14197)
    at l.$apply (angular.js:14486)
    at l (angular.js:9644)
    at O (angular.js:9834)
    at XMLHttpRequest.w.onload (angular.js:9775)

and the main reason is probably the property loadPlugin which is not called anywhere inside the controller. Does Anyone know how to modify the code in order to load the defined plugins and use them inside the controller?

Thanks!

Body:
The problem is explicitly written in your error.

SweetAlert is not defined

Meaning that in your controller you forgot to add SweetAlert to your dependencies.

just add SweetAlert to the end of your conrtoller line:

controller: function ($scope, ... $ocLazyLoad, SweetAlert) {


问:
Issues with undoing 'git push'
I accidentally pushed a project to Git using git push when I intended to simply have it on my local repository (should've stopped after git commit).

I want to undo this git push such that the server repo goes back to a specific commit. I have looked at other questions such as this one, but the git push -f doesn't work for me and pulls up the error: To prevent you from losing history, non-fast-forward updates were rejected.
I even tried

```<code>git push -f origin CommitSHA:mainline
</code>```

I thought the -f tag would force the push regardless of whether I was pushing a previous commit or not. How should I fix this error so that I can undo the git push?

答:
Isn't your message missing something? I believe it should say something like

Merge the remote changes (e.g. 'git pull') before pushing again

after the part about rejecting your push. So, that would mean the remote branch may have more recent changes than your local one, e.g. someone else pushed changes. In that case, I would advice not to force push since you may throw away commits of other people.

You could either:

Do it anyway (git pull first should work)

Use git revert instead to undo your commit. This will ultimately introduce a second commit reverting your first one, hence both of them will be in the history (https://git-scm.com/docs/git-revert). That's not ideal, but rewriting history on remote branches never is.

Title: Issues with undoing 'git push'

Body:
I accidentally pushed a project to Git using git push when I intended to simply have it on my local repository (should've stopped after git commit).

I want to undo this git push such that the server repo goes back to a specific commit. I have looked at other questions such as this one, but the git push -f doesn't work for me and pulls up the error: To prevent you from losing history, non-fast-forward updates were rejected.
I even tried

git push -f origin CommitSHA:mainline

I thought the -f tag would force the push regardless of whether I was pushing a previous commit or not. How should I fix this error so that I can undo the git push?


问:
Loop Through Column to find Match - VBA
I'm trying to create a VBA Command that goes through many cases in order to find a commission fee percentage. Starting off, I need to compare a ID to a list of Special IDs (Using one Integer, loop through a column of 30 integers). I also need to check to see if the 'komisija' value is greater than 40, which would then simply return 40.</p>

```<code>Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double

Set kSheet = ThisWorkbook.Sheets("komisijas")

'Set variables equal to the cell data
  klienta_nr = Range("A2").Value
  ISIN = Range("E2").Value
  Cena = Range("H2").Value
  Skaits = Range("I2").Value

'First, have case for non-special klients
If Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A40")) Then
      If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
        Komisija = (Cena * Skaits) * 0.003
        End If
      If Right(klienta_nr, 1) = 7 Then
        Komisija = (Cena * Skaits) * 0.01
        End If
      If Komisija > 40 Then
        Range("K2").Value = Komisija
        End If
      Range("K2").Value = Komisija
End If

Range("K2").Value = Komisija
</code>```

答:
I ended up using the Application.Match function to compare variables. By doing so I was able to get the expected result I was looking for.</p>

```<code>'Set variables equal to the cell data
klienta_nr = Range("A2").Value
ISIN = Range("E2").Value
Cena = Range("H2").Value
Skaits = Range("I2").Value
vk = Range("B2").Value

    If Not Application.Match(klienta_nr, kSheet.Range("A2:A100")) Then
      'IP2, 0.03% komisija, 40 EUR/USD Max
         If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then
            Komisija = (Cena * Skaits) * 0.003
            Range("K2").Value = Komisija
            End If
      'IP1, 0.1% komisija, 40 EUR/USD Max
        If Right(vk, 1) = 7 Then
            Komisija = (Cena * Skaits) * 0.01
            Range("K2").Value = Komisija
            End If
        'Komisija MAX is 40, so anything >=40 equals 40
        If Komisija >= 40 Then
            Range("K2").Value = 40
            End If
    End If
</code>```

Title: Loop Through Column to find Match - VBA

Body:
I'm trying to create a VBA Command that goes through many cases in order to find a commission fee percentage. Starting off, I need to compare a ID to a list of Special IDs (Using one Integer, loop through a column of 30 integers). I also need to check to see if the 'komisija' value is greater than 40, which would then simply return 40.

Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double

Set kSheet = ThisWorkbook.Sheets("komisijas")

'Set variables equal to the cell data
  klienta_nr = Range("A2").Value
  ISIN = Range("E2").Value
  Cena = Range("H2").Value
  Skaits = Range("I2").Value

'First, have case for non-special klients
If Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A40")) Then
      If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
        Komisija = (Cena * Skaits) * 0.003
        End If
      If Right(klienta_nr, 1) = 7 Then
        Komisija = (Cena * Skaits) * 0.01
        End If
      If Komisija > 40 Then
        Range("K2").Value = Komisija
        End If
      Range("K2").Value = Komisija
End If

Range("K2").Value = Komisija

Body:
I ended up using the Application.Match function to compare variables. By doing so I was able to get the expected result I was looking for.

'Set variables equal to the cell data
klienta_nr = Range("A2").Value
ISIN = Range("E2").Value
Cena = Range("H2").Value
Skaits = Range("I2").Value
vk = Range("B2").Value

    If Not Application.Match(klienta_nr, kSheet.Range("A2:A100")) Then
      'IP2, 0.03% komisija, 40 EUR/USD Max
         If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then
            Komisija = (Cena * Skaits) * 0.003
            Range("K2").Value = Komisija
            End If
      'IP1, 0.1% komisija, 40 EUR/USD Max
        If Right(vk, 1) = 7 Then
            Komisija = (Cena * Skaits) * 0.01
            Range("K2").Value = Komisija
            End If
        'Komisija MAX is 40, so anything >=40 equals 40
        If Komisija >= 40 Then
            Range("K2").Value = 40
            End If
    End If


问:
How to properly abstract Firebase
I'm interested in how to properly abstract Firebase in order to decouple it with my app in case I want to switch back ends in the future.

Right now I have a single class with static methods that access the Realtime Database and Storage. I call these static methods throughout the app.

Is this the best way to use Firebase in a production environment? My app is written in Swift.

答: I think the best way here is to have struct with static members for each main node in your Firebase database and also separate models for each main folder of Firebase storage. It should look like API's. You can change it in the future without any problems.

Title: How to properly abstract Firebase


问:
Beautiful soup Python extracing data
I am very new to python. Long time user of stackoverflow but first time posting a question.
I am trying to extract data from website using beautifulsoup.
Sample Code where I want to extract is (listed in and tagged in data)

The was able to extract in to list but I am unable to extract the acutal data.
the goal here is to extract
Listed in: Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women
Tagged in: Makeup, Beauty, Nail polish

Can you please tell me how to achive it.

```<code>import requests
from bs4 import BeautifulSoup

l1=[]
url='http://boxes.mysubscriptionaddiction.com/box/julep-maven'
source_code=requests.get(url)
plain_text=source_code.text
soup= BeautifulSoup(plain_text,"lxml")
for item in soup.find_all('p'):
       l1.append(item.contents)
search='\nListed in:\n'
for a in l1:
    if a[0] in ('\nTagged in:\n','\nListed in:\n'):
        print(a)
</code>```

答:
Since you're using lxml, why not use it in a more direct manner (lxml is believed to be faster than BeautifulSoup):

```<code>import requests
from lxml import html

url='http://boxes.mysubscriptionaddiction.com/box/julep-maven'
source_code=requests.get(url)
tree = html.fromstring(source_code.content) #parses the html
paras = tree.xpath('//div[@class="box-information"]/p') #gets the para elements

# This loop prints the desired para elements' text.
for ele in paras[1:]:
    print(ele.text_content())
</code>```

Output:

```<code>Listed in:
Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women

Tagged in:
Makeup, Beauty, Nail polish
</code>```

Note: The site is captcha-protected, so you may need to copy the source html from your browser's dev tools as a string and use it in tree = html.fromstring(copied_string) to make this code work.

Title: Beautiful soup Python extracing data

Body:
I am very new to python. Long time user of stackoverflow but first time posting a question.
I am trying to extract data from website using beautifulsoup.
Sample Code where I want to extract is (listed in and tagged in data)

The was able to extract in to list but I am unable to extract the acutal data.
the goal here is to extract
Listed in: Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women
Tagged in: Makeup, Beauty, Nail polish

Can you please tell me how to achive it.

import requests
from bs4 import BeautifulSoup

l1=[]
url='http://boxes.mysubscriptionaddiction.com/box/julep-maven'
source_code=requests.get(url)
plain_text=source_code.text
soup= BeautifulSoup(plain_text,"lxml")
for item in soup.find_all('p'):
       l1.append(item.contents)
search='\nListed in:\n'
for a in l1:
    if a[0] in ('\nTagged in:\n','\nListed in:\n'):
        print(a)

Body:
Since you're using lxml, why not use it in a more direct manner (lxml is believed to be faster than BeautifulSoup):

import requests
from lxml import html

url='http://boxes.mysubscriptionaddiction.com/box/julep-maven'
source_code=requests.get(url)
tree = html.fromstring(source_code.content) #parses the html
paras = tree.xpath('//div[@class="box-information"]/p') #gets the para elements

# This loop prints the desired para elements' text.
for ele in paras[1:]:
    print(ele.text_content())

Output:

Listed in:
Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women

Tagged in:
Makeup, Beauty, Nail polish

Note: The site is captcha-protected, so you may need to copy the source html from your browser's dev tools as a string and use it in tree = html.fromstring(copied_string) to make this code work.


问:
Trying to make platforms that I can jump through from underneath but land on top of. having trouble fine tuning the logic
My goal is to set up all my platforms in the .sks file for easier design of my levels.

this is declared at the top of game scene.swift before didMove:

```<code>private var JumpThroughPlatformObject = SKSpriteNode()
</code>```

and this is in DidMove:

```<code>if let JumpThroughPlatformObjectNode = self.childNode(withName: "//jumpThroughPlatform1") as? SKSpriteNode {
        JumpThroughPlatformObject = JumpThroughPlatformObjectNode}
</code>```

I reference the platform to get it's height from the .sks, since all my platforms are going to be the same height I only need to get it from one.

Below is what Im trying to use in my update method to turn off collisions until my player is totally above the platform. The main issue with only checking if my players velocity is greater than zero is: if the player is at the peak of a jump (his velocity slows to zero). if this happens and the player is inside a platform, he either instantly springs up to the top of the platform or gets launched downward.

I don't want my platforms to have to be 1 pixel high lines. I also need to have the player have a full collision box since he will be interacting with other types of environments. This leads me to believe that I somehow need to only register the top of the platform as a collision box and not the entire platform.

This if statement I wrote is supposed to take the y position of a platform and add half of its height to it, since the y position is based on the center of the sprite I figured this would put the collision for the platform on its top boundary.

I did the same for the player but in reverse. Putting the players collisions on only the bottom of his border. But its not working perfectly and I'm not sure why at this point.

```<code>if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2))
</code>```

The function below is giving me 3 main issues:

My players jump is always dy = 80. If I'm jumping up to a platform that position.y = 90, the players peak of the jump stops in the middle of the platform, but he teleports to the top of it instead of continuing to fall to the ground.

the left and right edges of the platforms still have full collision with the player if I'm falling

if my player is on a platform and there is another one directly above me, the player can't jump through it.

let zero:CGFloat = 0

```<code>    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy

        // when I jump dy is greater than zero else I'm falling

       if (dy! >= zero) {

           if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2)) {

                print(" platform y: \(JumpThroughPlatformObject.position.y)")
                print ("player position: \(player.position.y)")

                // Prevent collisions if the hero is jumping
                body.collisionBitMask = CollisionTypes.saw.rawValue | CollisionTypes.ground.rawValue

            }

       }
        else {
            // Allow collisions if the hero is falling
            body.collisionBitMask = CollisionTypes.platform.rawValue | CollisionTypes.ground.rawValue | CollisionTypes.saw.rawValue
        }
    }
</code>```

Any advice would be greatly appreciated. I've been tearing my hair out for a couple days now.

EDIT in didBegin and didEnd:

```<code>   func didBegin(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy
        let platform = JumpThroughPlatformObject
        let zero:CGFloat = 0

    if contact.bodyA.node == player {
      // playerCollided(with: contact.bodyB.node!)

            if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

                body.collisionBitMask &= ~CollisionTypes.platform.rawValue

            }

    } else if contact.bodyB.node == player {
     //  playerCollided(with: contact.bodyA.node!)
        isPlayerOnGround = true

        if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

            body.collisionBitMask &= ~CollisionTypes.platform.rawValue}
        }
    }
}

func didEnd(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
//            let dy = player.physicsBody?.velocity.dy
//            let platform = JumpThroughPlatformObject

    if contact.bodyA.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }else if contact.bodyB.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }
    }
}
</code>```

Adding what I did, the player can no longer jump through the platform.

答:
Here is a link to the project that I made for macOS and iOS targets:

   https://github.com/fluidityt/JumpUnderPlatform

Basically, this all has to do with

Detecting collision of a platform

Then determining if your player is under the platform

Allow your player to go through the platform (and subsequently land on it)

--

SK Physics makes this a little complicated:

On collision detection, your player's .position.y or .velocity.dy
may already have changed to a "false" state in reference to satisfying the #2 check from above (meaning #3 will never happen). Also, your player will bounce off the platform on first contact.

There is no "automatic" way to determine when your player has finished passing through the object (thus to allow player to land on the platform)

--

So to get everything working, a bit of creativity and ingenuity must be used!

1: Detecting collision of a platform:

So, to tackle 1 is the simplest: we just need to use the built in didBegin(contact:)

We are going to be relying heavily on the 3 big bitMasks, contact, category, and collision:

(fyi, I don't like using enums and bitmath for physics because I'm a rebel idiot):

```<code>struct BitMasks {
  static let playerCategory = UInt32(2)
  static let jupCategory    = UInt32(4) // JUP = JumpUnderPlatform
}

override func didBegin(_ contact: SKPhysicsContact) {

  // Crappy way to do "bit-math":
  let contactedSum = contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask

  switch contactedSum {

  case BitMasks.jupCategory + BitMasks.playerCategory:
  // ...
}
</code>```

--

Now, you said that you wanted to use the SKSEditor, so I have accommodated you:

```<code>// Do all the fancy stuff you want here...
class JumpUnderPlatform: SKSpriteNode {

  var pb: SKPhysicsBody { return self.physicsBody! } // If you see this on a crash, then WHY DOES JUP NOT HAVE A PB??

  // NOTE: I could not properly configure any SKNode properties here..
  // it's like they all get RESET if you put them in here...
  required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}
</code>```

--

Now for the player:

```<code>class Player: SKSpriteNode {

  // If you see this on a crash, then WHY DOES PLAYER NOT HAVE A PB??
  var pb: SKPhysicsBody { return self.physicsBody! }

  static func makePlayer() -> Player {

    let newPlayer = Player(color: .blue, size: CGSize(width: 50, height: 50))
    let newPB = SKPhysicsBody(rectangleOf: newPlayer.size)

    newPB.categoryBitMask = BitMasks.playerCategory
    newPB.usesPreciseCollisionDetection = true

    newPlayer.physicsBody = newPB
    newPlayer.position.y -= 200 // For demo purposes.

    return newPlayer
  }
}
</code>```

2. (and dealing with #4): Determining if under platform on contact:

There are many ways to do this, but I chose to use the player.pb.velocity.dy approach as mentioned by KOD to keep track of the player's position... if your dy is over 0, then you are jumping (under a platform) if not, then you are either standing still or falling (need to make contact with the platform and stick to it).

To accomplish this we have to get a bit more technical, because again, the physics system and the way SK works in its loop doesn't always mesh 100% with how we think it should work.

Basically, I had to make an initialDY property for Player that is constantly updated each frame in update

This initialDY will give us the correct data that we need for the first contact with the platform, allowing us to tell us to change the collision mask, and also to reset our player's CURRENT dy to the initial dy (so the player doesn't bounce off).

3. (and dealing with #5): Allow player to go through platform

To go through the platform, we need to play around with the collisionBitMasks. I chose to make the player's collision mask = the player's categoryMask, which is probably not the right way to do it, but it works for this demo.

You end up with magic like this in didBegin:

```<code>  // Check if jumping; if not, then just land on platform normally.
  guard player.initialDY > 0 else { return }

  // Gives us the ability to pass through the platform!
  player.pb.collisionBitMask = BitMasks.playerCategory
</code>```

Now, dealing with #5 is going to require us to add another piece of state to our player class.. we need to temporarily store the contacted platform so we can check if the player has successfully finished passing through the platform (so we can reset the collision mask)

Then we just check in didFinishUpdate if the player's frame is above that platform, and if so, we reset the masks.

Here are all of the files , and again a link to the github:

https://github.com/fluidityt/JumpUnderPlatform

Player.swift:

```<code>class Player: SKSpriteNode {

  // If you see this on a crash, then WHY DOES PLAYER NOT HAVE A PB??
  var pb: SKPhysicsBody { return self.physicsBody! }

  // This is set when we detect contact with a platform, but are underneath it (jumping up)
  weak var platformToPassThrough: JumpUnderPlatform?

  // For use inside of gamescene's didBeginContact (because current DY is altered by the time we need it)
  var initialDY = CGFloat(0)
}

// MARK: - Funkys:
extension Player {
  static func makePlayer() -> Player {

    let newPlayer = Player(color: .blue, size: CGSize(width: 50, height: 50))
    let newPB = SKPhysicsBody(rectangleOf: newPlayer.size)

    newPB.categoryBitMask = BitMasks.playerCategory
    newPB.usesPreciseCollisionDetection = true

    newPlayer.physicsBody = newPB
    newPlayer.position.y -= 200 // For demo purposes.

    return newPlayer
  }

  func isAbovePlatform() -> Bool {
    guard let platform = platformToPassThrough else { fatalError("wtf is the platform!") }

    if frame.minY > platform.frame.maxY { return true  }
    else                                { return false }
  }

  func landOnPlatform() {
      print("resetting stuff!")
      platformToPassThrough = nil
      pb.collisionBitMask = BitMasks.jupCategory
  }
}

// MARK: - Player GameLoop:
extension Player {

  func _update() {
    // We have to keep track of this for proper detection of when to pass-through platform
    initialDY = pb.velocity.dy
  }

  func _didFinishUpdate() {

    // Check if we need to reset our collision mask (allow us to land on platform again)
    if platformToPassThrough != nil {
      if isAbovePlatform() { landOnPlatform() }
    }
  }
}
</code>```

JumpUnderPlatform & BitMasks.swift (respectively:)

```<code>// Do all the fancy stuff you want here...
class JumpUnderPlatform: SKSpriteNode {

  var pb: SKPhysicsBody { return self.physicsBody! } // If you see this on a crash, then WHY DOES JUP NOT HAVE A PB??

  required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }

}

struct BitMasks {
  static let playerCategory = UInt32(2)
  static let jupCategory    = UInt32(4)
}
</code>```

GameScene.swift:

-

MAKE SURE YOU HAVE THE TWO NODES IN YOUR SKS EDITOR:

-

```<code>// MARK: - Props:
class GameScene: SKScene, SKPhysicsContactDelegate {

  // Because I hate crashes related to spelling errors.
  let names = (jup: "jup", resetLabel: "resetLabel")

  let player = Player.makePlayer()
}

// MARK: - Physics handling:
extension GameScene {

  private func findJup(contact: SKPhysicsContact) -> JumpUnderPlatform? {
    guard let nodeA = contact.bodyA.node, let nodeB = contact.bodyB.node else { fatalError("how did this happne!!??") }

    if      nodeA.name == names.jup { return (nodeA as! JumpUnderPlatform) }
    else if nodeB.name == names.jup { return (nodeB as! JumpUnderPlatform) }
    else                            { return nil }
  }

  // Player is 2, platform is 4:
  private func doContactPlayer_X_Jup(platform: JumpUnderPlatform) {

    // Check if jumping; if not, then just land on platform normally.
    guard player.initialDY > 0 else { return }

    // Gives us the ability to pass through the platform!
    player.physicsBody!.collisionBitMask = BitMasks.playerCategory

    // Will push the player through the platform (instead of bouncing off) on first hit
    if player.platformToPassThrough == nil { player.pb.velocity.dy = player.initialDY }
    player.platformToPassThrough = platform
  }

func _didBegin(_ contact: SKPhysicsContact) {

  // Crappy way to do bit-math:
  let contactedSum = contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask

  switch contactedSum {

  case BitMasks.jupCategory + BitMasks.playerCategory:
      guard let platform = findJup(contact: contact) else { fatalError("must be platform!") }
      doContactPlayer_X_Jup(platform: platform)

    // Put your other contact cases here...
    // case BitMasks.xx + BitMasks.yy:

    default: ()
    }
  }
}

// MARK: - Game loop:
extension GameScene {

  // Scene setup:
  override func didMove(to view: SKView) {
    physicsWorld.contactDelegate = self
    physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    addChild(player)
  }

  // Touch handling: (convert to touchesBegan for iOS):
  override func mouseDown(with event: NSEvent) {
    // Make player jump:
    player.pb.applyImpulse(CGVector(dx: 0, dy: 50))

    // Reset player on label click (from sks file):
    if nodes(at: event.location(in: self)).first?.name == names.resetLabel {
      player.position.y = frame.minY + player.size.width/2 + CGFloat(1)
    }
  }

  override func update(_ currentTime: TimeInterval) {
    player._update()
  }

  func didBegin(_ contact: SKPhysicsContact) {
    self._didBegin(contact)
  }

  override func didFinishUpdate() {
    player._didFinishUpdate()
  }
}
</code>```

I HOPE THIS HELPS SOME!

Body:
My goal is to set up all my platforms in the .sks file for easier design of my levels.

this is declared at the top of game scene.swift before didMove:

private var JumpThroughPlatformObject = SKSpriteNode()

and this is in DidMove:

if let JumpThroughPlatformObjectNode = self.childNode(withName: "//jumpThroughPlatform1") as? SKSpriteNode {
        JumpThroughPlatformObject = JumpThroughPlatformObjectNode}

I reference the platform to get it's height from the .sks, since all my platforms are going to be the same height I only need to get it from one.

Below is what Im trying to use in my update method to turn off collisions until my player is totally above the platform. The main issue with only checking if my players velocity is greater than zero is: if the player is at the peak of a jump (his velocity slows to zero). if this happens and the player is inside a platform, he either instantly springs up to the top of the platform or gets launched downward.

I don't want my platforms to have to be 1 pixel high lines. I also need to have the player have a full collision box since he will be interacting with other types of environments. This leads me to believe that I somehow need to only register the top of the platform as a collision box and not the entire platform.

This if statement I wrote is supposed to take the y position of a platform and add half of its height to it, since the y position is based on the center of the sprite I figured this would put the collision for the platform on its top boundary.

I did the same for the player but in reverse. Putting the players collisions on only the bottom of his border. But its not working perfectly and I'm not sure why at this point.

if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2))

The function below is giving me 3 main issues:

My players jump is always dy = 80. If I'm jumping up to a platform that position.y = 90, the players peak of the jump stops in the middle of the platform, but he teleports to the top of it instead of continuing to fall to the ground.

the left and right edges of the platforms still have full collision with the player if I'm falling

if my player is on a platform and there is another one directly above me, the player can't jump through it.

let zero:CGFloat = 0

    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy

        // when I jump dy is greater than zero else I'm falling

       if (dy! >= zero) {

           if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2)) {

                print(" platform y: \(JumpThroughPlatformObject.position.y)")
                print ("player position: \(player.position.y)")

                // Prevent collisions if the hero is jumping
                body.collisionBitMask = CollisionTypes.saw.rawValue | CollisionTypes.ground.rawValue

            }

       }
        else {
            // Allow collisions if the hero is falling
            body.collisionBitMask = CollisionTypes.platform.rawValue | CollisionTypes.ground.rawValue | CollisionTypes.saw.rawValue
        }
    }

Any advice would be greatly appreciated. I've been tearing my hair out for a couple days now.

EDIT in didBegin and didEnd:

   func didBegin(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy
        let platform = JumpThroughPlatformObject
        let zero:CGFloat = 0

    if contact.bodyA.node == player {
      // playerCollided(with: contact.bodyB.node!)

            if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

                body.collisionBitMask &= ~CollisionTypes.platform.rawValue

            }

    } else if contact.bodyB.node == player {
     //  playerCollided(with: contact.bodyA.node!)
        isPlayerOnGround = true

        if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

            body.collisionBitMask &= ~CollisionTypes.platform.rawValue}
        }
    }
}

func didEnd(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
//            let dy = player.physicsBody?.velocity.dy
//            let platform = JumpThroughPlatformObject

    if contact.bodyA.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }else if contact.bodyB.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }
    }
}

Adding what I did, the player can no longer jump through the platform.

Body:
Here is a link to the project that I made for macOS and iOS targets:

   https://github.com/fluidityt/JumpUnderPlatform

Basically, this all has to do with

Detecting collision of a platform

Then determining if your player is under the platform

Allow your player to go through the platform (and subsequently land on it)

--

SK Physics makes this a little complicated:

On collision detection, your player's .position.y or .velocity.dy
may already have changed to a "false" state in reference to satisfying the #2 check from above (meaning #3 will never happen). Also, your player will bounce off the platform on first contact.

There is no "automatic" way to determine when your player has finished passing through the object (thus to allow player to land on the platform)

--

So to get everything working, a bit of creativity and ingenuity must be used!

1: Detecting collision of a platform:

So, to tackle 1 is the simplest: we just need to use the built in didBegin(contact:)

We are going to be relying heavily on the 3 big bitMasks, contact, category, and collision:

(fyi, I don't like using enums and bitmath for physics because I'm a rebel idiot):

struct BitMasks {
  static let playerCategory = UInt32(2)
  static let jupCategory    = UInt32(4) // JUP = JumpUnderPlatform
}

override func didBegin(_ contact: SKPhysicsContact) {

  // Crappy way to do "bit-math":
  let contactedSum = contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask

  switch contactedSum {

  case BitMasks.jupCategory + BitMasks.playerCategory:
  // ...
}

--

Now, you said that you wanted to use the SKSEditor, so I have accommodated you:

// Do all the fancy stuff you want here...
class JumpUnderPlatform: SKSpriteNode {

  var pb: SKPhysicsBody { return self.physicsBody! } // If you see this on a crash, then WHY DOES JUP NOT HAVE A PB??

  // NOTE: I could not properly configure any SKNode properties here..
  // it's like they all get RESET if you put them in here...
  required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}

--

Now for the player:

class Player: SKSpriteNode {

  // If you see this on a crash, then WHY DOES PLAYER NOT HAVE A PB??
  var pb: SKPhysicsBody { return self.physicsBody! }

  static func makePlayer() -> Player {

    let newPlayer = Player(color: .blue, size: CGSize(width: 50, height: 50))
    let newPB = SKPhysicsBody(rectangleOf: newPlayer.size)

    newPB.categoryBitMask = BitMasks.playerCategory
    newPB.usesPreciseCollisionDetection = true

    newPlayer.physicsBody = newPB
    newPlayer.position.y -= 200 // For demo purposes.

    return newPlayer
  }
}

2. (and dealing with #4): Determining if under platform on contact:

There are many ways to do this, but I chose to use the player.pb.velocity.dy approach as mentioned by KOD to keep track of the player's position... if your dy is over 0, then you are jumping (under a platform) if not, then you are either standing still or falling (need to make contact with the platform and stick to it).

To accomplish this we have to get a bit more technical, because again, the physics system and the way SK works in its loop doesn't always mesh 100% with how we think it should work.

Basically, I had to make an initialDY property for Player that is constantly updated each frame in update

This initialDY will give us the correct data that we need for the first contact with the platform, allowing us to tell us to change the collision mask, and also to reset our player's CURRENT dy to the initial dy (so the player doesn't bounce off).

3. (and dealing with #5): Allow player to go through platform

To go through the platform, we need to play around with the collisionBitMasks. I chose to make the player's collision mask = the player's categoryMask, which is probably not the right way to do it, but it works for this demo.

You end up with magic like this in didBegin:

  // Check if jumping; if not, then just land on platform normally.
  guard player.initialDY > 0 else { return }

  // Gives us the ability to pass through the platform!
  player.pb.collisionBitMask = BitMasks.playerCategory

Now, dealing with #5 is going to require us to add another piece of state to our player class.. we need to temporarily store the contacted platform so we can check if the player has successfully finished passing through the platform (so we can reset the collision mask)

Then we just check in didFinishUpdate if the player's frame is above that platform, and if so, we reset the masks.

Here are all of the files , and again a link to the github:

https://github.com/fluidityt/JumpUnderPlatform

Player.swift:

class Player: SKSpriteNode {

  // If you see this on a crash, then WHY DOES PLAYER NOT HAVE A PB??
  var pb: SKPhysicsBody { return self.physicsBody! }

  // This is set when we detect contact with a platform, but are underneath it (jumping up)
  weak var platformToPassThrough: JumpUnderPlatform?

  // For use inside of gamescene's didBeginContact (because current DY is altered by the time we need it)
  var initialDY = CGFloat(0)
}

// MARK: - Funkys:
extension Player {
  static func makePlayer() -> Player {

    let newPlayer = Player(color: .blue, size: CGSize(width: 50, height: 50))
    let newPB = SKPhysicsBody(rectangleOf: newPlayer.size)

    newPB.categoryBitMask = BitMasks.playerCategory
    newPB.usesPreciseCollisionDetection = true

    newPlayer.physicsBody = newPB
    newPlayer.position.y -= 200 // For demo purposes.

    return newPlayer
  }

  func isAbovePlatform() -> Bool {
    guard let platform = platformToPassThrough else { fatalError("wtf is the platform!") }

    if frame.minY > platform.frame.maxY { return true  }
    else                                { return false }
  }

  func landOnPlatform() {
      print("resetting stuff!")
      platformToPassThrough = nil
      pb.collisionBitMask = BitMasks.jupCategory
  }
}

// MARK: - Player GameLoop:
extension Player {

  func _update() {
    // We have to keep track of this for proper detection of when to pass-through platform
    initialDY = pb.velocity.dy
  }

  func _didFinishUpdate() {

    // Check if we need to reset our collision mask (allow us to land on platform again)
    if platformToPassThrough != nil {
      if isAbovePlatform() { landOnPlatform() }
    }
  }
}

JumpUnderPlatform & BitMasks.swift (respectively:)

// Do all the fancy stuff you want here...
class JumpUnderPlatform: SKSpriteNode {

  var pb: SKPhysicsBody { return self.physicsBody! } // If you see this on a crash, then WHY DOES JUP NOT HAVE A PB??

  required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }

}

struct BitMasks {
  static let playerCategory = UInt32(2)
  static let jupCategory    = UInt32(4)
}

GameScene.swift:

-

MAKE SURE YOU HAVE THE TWO NODES IN YOUR SKS EDITOR:

-

// MARK: - Props:
class GameScene: SKScene, SKPhysicsContactDelegate {

  // Because I hate crashes related to spelling errors.
  let names = (jup: "jup", resetLabel: "resetLabel")

  let player = Player.makePlayer()
}

// MARK: - Physics handling:
extension GameScene {

  private func findJup(contact: SKPhysicsContact) -> JumpUnderPlatform? {
    guard let nodeA = contact.bodyA.node, let nodeB = contact.bodyB.node else { fatalError("how did this happne!!??") }

    if      nodeA.name == names.jup { return (nodeA as! JumpUnderPlatform) }
    else if nodeB.name == names.jup { return (nodeB as! JumpUnderPlatform) }
    else                            { return nil }
  }

  // Player is 2, platform is 4:
  private func doContactPlayer_X_Jup(platform: JumpUnderPlatform) {

    // Check if jumping; if not, then just land on platform normally.
    guard player.initialDY > 0 else { return }

    // Gives us the ability to pass through the platform!
    player.physicsBody!.collisionBitMask = BitMasks.playerCategory

    // Will push the player through the platform (instead of bouncing off) on first hit
    if player.platformToPassThrough == nil { player.pb.velocity.dy = player.initialDY }
    player.platformToPassThrough = platform
  }

func _didBegin(_ contact: SKPhysicsContact) {

  // Crappy way to do bit-math:
  let contactedSum = contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask

  switch contactedSum {

  case BitMasks.jupCategory + BitMasks.playerCategory:
      guard let platform = findJup(contact: contact) else { fatalError("must be platform!") }
      doContactPlayer_X_Jup(platform: platform)

    // Put your other contact cases here...
    // case BitMasks.xx + BitMasks.yy:

    default: ()
    }
  }
}

// MARK: - Game loop:
extension GameScene {

  // Scene setup:
  override func didMove(to view: SKView) {
    physicsWorld.contactDelegate = self
    physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    addChild(player)
  }

  // Touch handling: (convert to touchesBegan for iOS):
  override func mouseDown(with event: NSEvent) {
    // Make player jump:
    player.pb.applyImpulse(CGVector(dx: 0, dy: 50))

    // Reset player on label click (from sks file):
    if nodes(at: event.location(in: self)).first?.name == names.resetLabel {
      player.position.y = frame.minY + player.size.width/2 + CGFloat(1)
    }
  }

  override func update(_ currentTime: TimeInterval) {
    player._update()
  }

  func didBegin(_ contact: SKPhysicsContact) {
    self._didBegin(contact)
  }

  override func didFinishUpdate() {
    player._didFinishUpdate()
  }
}

I HOPE THIS HELPS SOME!


问:
FizzBuzz returning empty array
I'm not quite sure why this is returning an empty array, does anyone have any clues or hints? Any help is appreciated.

function fizzBuzz() {
  var array = [];
  for (var i = 1; i <= 100; i++) {
    if (i % 3 === 0) {
      array.push("Fizz");
    } else if (i % 5 === 0) {
      array.push("Buzz");
    } else if (i % 3 === 0 && i % 5 === 0) {
      array.push("FizzBuzz");
    }
    return array;
  }
}
fizzBuzz();```

答:
First issue, The return statement is inside the loop. It will return an empty array after the first iteration. Place the return statement after the loop instead.

Second issue, You need to check the FizzBuzz in the first if statement else it won't ever hit

```<code>function fizzBuzz() {
  var array = [];
  for (var i = 1; i <= 100; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
      array.push("FizzBuzz");
    } else if (i % 3 === 0) {
      array.push("Fizz");
    } else if (i % 5 === 0) {
      array.push("Buzz");
    }
  }
  return array;
}
fizzBuzz();
</code>```

Title: FizzBuzz returning empty array

Body:
First issue, The return statement is inside the loop. It will return an empty array after the first iteration. Place the return statement after the loop instead.

Second issue, You need to check the FizzBuzz in the first if statement else it won't ever hit

function fizzBuzz() {
  var array = [];
  for (var i = 1; i <= 100; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
      array.push("FizzBuzz");
    } else if (i % 3 === 0) {
      array.push("Fizz");
    } else if (i % 5 === 0) {
      array.push("Buzz");
    }
  }
  return array;
}
fizzBuzz();


问:
Why doesn't the for loop in the code below run as an infinite loop (i continuing after -1 as 1 2 3...-3 -2 -1)?
```<code>    #include<stdio.h>
    int main()
    {
    char i = 0;
    for( i<=5 && i>=-1 ; ++i ; i>0)
        printf("%d ",i);
    return 0;
    }
</code>```

<p>output is 1 2 3 ...127 -128 -127 ... -3 -2 -1.Can anyone explain how it stops after printing -1? </p>

答:
Note first that the controlling expression in the for loop of the posted code is: ++i. So the loop will terminate only when ++i evaluates to 0. The first clause of this for loop, i<=5 && i>=-1, has no effect on the behavior of the loop.

Next, note that the behavior of this code is implementation-dependent. OP has signed char, but another implementation may have unsigned char. If instead char was really unsigned char, then the behavior would be well-defined, since overflow of unsigned integer types wraps around. It is likely that an unsigned char would have a range [0, 255], so when i reaches 255, ++i evaluates to 0, ending the loop and leaving the last printed result as 255.

But OP is working with signed char, and the behavior of signed integer overflow is implementation-defined. It appears that OP implementation also wraps around on overflow for signed integer types, so with a signed char range of [-128, 127], when i reaches 127, i++ evaluates to -128 (wrapping around), and the loop continues until i reaches -1, at which point ++i evaluates to 0. The loop is terminated and the final printed result is -1.

Also note that there is a type mismatch between the conversion specifier and the argument in the printf() statement; %d is for values of type int, and i is a char. According to the Standard, a mismatched conversion specifier and argument cause undefined behavior. Yet, here the day is saved by the integer promotions, which are applied to the arguments of variadic functions, of which printf() is one. i is promoted to type int, and there is no undefined behavior.

Body:
    #include<stdio.h>
    int main()
    {
    char i = 0;
    for( i<=5 && i>=-1 ; ++i ; i>0)
        printf("%d ",i);
    return 0;
    }

output is 1 2 3 ...127 -128 -127 ... -3 -2 -1.Can anyone explain how it stops after printing -1?


问:
C global static variable initialization is done by linker?
Let's say we have:

f1.c

```<code>#include <stdio.h>
static int x = 10;

void f1() {
  printf("f1.c : %d\n", x);
}
</code>```

main.c

```<code>extern void f1();
int main(int argc, char **argv) {
  f1();
  return 0;
}
</code>```

we will compile and read the two ELF file symboltables (rel. ELF and exec ELF):

```<code>$> gcc -c *.c
$> readelf -s f1.o | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
        5: 0000000000000000     4 OBJECT  LOCAL  DEFAULT    3 x
$> gcc *.o
$> readelf -s a.out | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
       38: 0000000000601038     4 OBJECT  LOCAL  DEFAULT   25 x
</code>```

I can see that the Value (also known as address) in which the global static variable x is 0000000000000000 from reading the relocatable object file f1.o.

Which means we haven't initialized it yet since it is still a rel. ELF object file and the linker will take care of this.

So my question is then, if the linker is the one to set x to the value of 10 at known address after linking of 0000000000601038, how does it do so?  Where does the linker get the information to set the value to 10 and who gives this information (f1.o?) ?

答:
This segment where static storage duration variables with specific values are stored, is known as .data (this is the name used by the ELF standard but other linkers tend to use the very same name too).

How these variables are set depend on the target system.

On RAM-based systems (such as a PC), the whole .data segment is initialized in advance as part of the executable and loaded to RAM together with the program.

On ROM-based systems (such as microcontrollers with flash), .data cannot be initialized in advance. Instead it is copied down from ROM to RAM before main() is called, by some start-up code ("CRT"). So it is actually set in run-time, meaning that there's always a delay at program start on such systems. To get rid of the delay, there's often a non-standard start-up alternative ("minimal") which skips initialization of static storage duration variables entirely.

Body:
Let's say we have:

f1.c

#include <stdio.h>
static int x = 10;

void f1() {
  printf("f1.c : %d\n", x);
}

main.c

extern void f1();
int main(int argc, char **argv) {
  f1();
  return 0;
}

we will compile and read the two ELF file symboltables (rel. ELF and exec ELF):

$> gcc -c *.c
$> readelf -s f1.o | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
        5: 0000000000000000     4 OBJECT  LOCAL  DEFAULT    3 x
$> gcc *.o
$> readelf -s a.out | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
       38: 0000000000601038     4 OBJECT  LOCAL  DEFAULT   25 x

I can see that the Value (also known as address) in which the global static variable x is 0000000000000000 from reading the relocatable object file f1.o.

Which means we haven't initialized it yet since it is still a rel. ELF object file and the linker will take care of this.

So my question is then, if the linker is the one to set x to the value of 10 at known address after linking of 0000000000601038, how does it do so?  Where does the linker get the information to set the value to 10 and who gives this information (f1.o?) ?


问:
Report shows blank page in browser
My report shows a blank page when I run it. The data table has information, but none of it shows on the page:

The stored procedure fetches data to data table:

```<code>rptDoc = new ReportDocument();
DataTable DTReport = new DataTable();

SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@Number", SqlDbType.VarChar, 50);
param[0].Value = Session["PrintNumber"].ToString();
param[1] = new SqlParameter("@LOTS", SqlDbType.VarChar, 255);
param[1].Value = Lots.Trim();
DTReport = objdAccess.ExecuteSpDataTable("SPfetch", param);
CrystalReportViewer1.ID = "DeliveryNote-" + Session["PrintNumber"].ToString();
string Report = "~/Reports/Report.rpt";
rptDoc.Load(Server.MapPath(Report));
rptDoc.SetDataSource(DTReport);
rptDoc.SetParameterValue("@number", Session["PrintNumber"].ToString());
rptDoc.SetParameterValue("@LOTS", Lots.Trim());

CrystalReportViewer1.ReportSource = rptDoc;
CrystalReportViewer1.DataBind();
CrystalReportViewer1.Visible = true;
</code>```

答: I just added "crystalreportviewers13" this folder to my project folder and it solved the issue.</p>

Title: Report shows blank page in browser

Body:
My report shows a blank page when I run it. The data table has information, but none of it shows on the page:

The stored procedure fetches data to data table:

rptDoc = new ReportDocument();
DataTable DTReport = new DataTable();

SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@Number", SqlDbType.VarChar, 50);
param[0].Value = Session["PrintNumber"].ToString();
param[1] = new SqlParameter("@LOTS", SqlDbType.VarChar, 255);
param[1].Value = Lots.Trim();
DTReport = objdAccess.ExecuteSpDataTable("SPfetch", param);
CrystalReportViewer1.ID = "DeliveryNote-" + Session["PrintNumber"].ToString();
string Report = "~/Reports/Report.rpt";
rptDoc.Load(Server.MapPath(Report));
rptDoc.SetDataSource(DTReport);
rptDoc.SetParameterValue("@number", Session["PrintNumber"].ToString());
rptDoc.SetParameterValue("@LOTS", Lots.Trim());

CrystalReportViewer1.ReportSource = rptDoc;
CrystalReportViewer1.DataBind();
CrystalReportViewer1.Visible = true;


问:
Doctrine 1.2 models returning integer fields as string values using Zend Framework and MySQL 5
Any idea why my Doctrine 1.2 models are returning string values for integer-defined fields?

Base model defined as:

```<code>abstract class Kwis_Model_Base_User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->setTableName('user');
        $this->hasColumn('id', 'integer', 4, array(
             'unsigned' => true,
             'primary' => true,
             'autoincrement' => true,
             ));

        // more fields
        // ...
    }
</code>```

Table Model is defined as:

```<code>class Kwis_Model_UserTable extends Kwis_Model_BaseTable
{

    /**
     * Returns an instance of this class.
     *
     * @return object Kwis_Model_UserTable
     */
    public static function getInstance()
    {
        $table = Doctrine_Core::getTable('Kwis_Model_User');
        return $table;
    }

    // other methods
    // ...
}
</code>```

Sample controller code:

```<code>class TestController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $userTable = Kwis_Model_UserTable::getInstance();
        $user = $userTable->find(1);
        echo "```" . var_dump($user->id) . "```"; die();
    }
}
</code>```

Produced output:

```<code> string '1' (length=1)
</code>```

Any ideas, greatly appreciated. ;-)

答: Isn't that the benefit of using typeless variables in PHP? What problem is this causing? You can still do mathematic operations on it if you want. Although, I would suspect that you'd never need to do any actions on a user ID other than string comparison.</p>

Body:
Any idea why my Doctrine 1.2 models are returning string values for integer-defined fields?

Base model defined as:

abstract class Kwis_Model_Base_User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->setTableName('user');
        $this->hasColumn('id', 'integer', 4, array(
             'unsigned' => true,
             'primary' => true,
             'autoincrement' => true,
             ));

        // more fields
        // ...
    }

Table Model is defined as:

class Kwis_Model_UserTable extends Kwis_Model_BaseTable
{

    /**
     * Returns an instance of this class.
     *
     * @return object Kwis_Model_UserTable
     */
    public static function getInstance()
    {
        $table = Doctrine_Core::getTable('Kwis_Model_User');
        return $table;
    }

    // other methods
    // ...
}

Sample controller code:

class TestController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $userTable = Kwis_Model_UserTable::getInstance();
        $user = $userTable->find(1);
        echo "
" . var_dump($user->id) . "
"; die();
    }
}

Produced output:

 string '1' (length=1)

Any ideas, greatly appreciated. ;-)


问:
Unable to locate webelement on text box?
I used below link to automate testing:

https://roundtheworld.skyteam.com/B2C/en/Home/WelcomePage

but I am not able to locate the text box web element.

please let me know, if any body know the solution how to locate web element for this website.

答:
You can access the text box web element marked with placeholder From through any of the following xpath:

```<code>//input[@id='CityOfOrigin']
</code>```

or

```<code>//input[@name='CityOfOrigin']
</code>```

or

```<code>//input[@title='From']
</code>```

Let me know if this Answers your Question.

Body:
You can access the text box web element marked with placeholder From through any of the following xpath:

//input[@id='CityOfOrigin']

or

//input[@name='CityOfOrigin']

or

//input[@title='From']

Let me know if this Answers your Question.


问:
How to instruct Spring to Autowire a field in a chain of tightly coupled objects
It's kinda hard to explain... Hope the question isn't vague...

you can look at the code to get the idea...

ClassA.java

```<code>public class ClassA {
    @Autowired
    InterA abcd;
    public void dododo() {
        abcd.doit();
    }
}
</code>```

ClassB.java

```<code>@Component
public class ClassB implements InterA {
    @Override
    public void doit() {
        System.out.println("hoo hoo");
    }
}
</code>```

ClassC.java

```<code>@Component("classc")
public class ClassC {
    public void doFromAbove() {
        ClassA cls = new ClassA();
        cls.dododo();
    }
}
</code>```

Interface InterA.java

```<code>public interface InterA {
    public void doit();
}
</code>```

Configuration ClassConfig.java (on the same package of other java class files)

```<code>@Configuration
@ComponentScan
public class ClassConfig {
}
</code>```

Main Method

```<code>public static void main(String[] args) {
    try(AbstractApplicationContext appctx = new AnnotationConfigApplicationContext(ClassConfig.class)) {
        ClassC obj = (ClassC) appctx.getBean("classc");
        obj.doFromAbove();
    }
}
</code>```

When I execute the main method, the Autowired field "abcd" in ClassA didn't get injected and results in a NullPointerException

It works only when I declare ClassA as a @Component and get it's bean... indirect autowiring is not happening

Should I decouple ClassA from ClassC and make everything loosely coupled?

Is there any simple annotation that I can use to tell Spring auto inject the @Autowired field even when the object is created in a tight coupled fashion?

Note
please don't tell me to use ApplicationContext in ClassC to create the bean of ClassA .

Any Spring Geek who could find an answer?

答:
The issue is in ClassC:

```<code>    ClassA cls = new ClassA();
</code>```

If you invoke the constructor of ClassA like this, Spring won't do its magic. If you need an instance of ClassA with injected fields, ask Spring for an instance (using injection or getBean()).

(To avoid having null fields where injection is assumed, I recommend using constructor injection.)

Body:
It's kinda hard to explain... Hope the question isn't vague...

you can look at the code to get the idea...

ClassA.java

public class ClassA {
    @Autowired
    InterA abcd;
    public void dododo() {
        abcd.doit();
    }
}

ClassB.java

@Component
public class ClassB implements InterA {
    @Override
    public void doit() {
        System.out.println("hoo hoo");
    }
}

ClassC.java

@Component("classc")
public class ClassC {
    public void doFromAbove() {
        ClassA cls = new ClassA();
        cls.dododo();
    }
}

Interface InterA.java

public interface InterA {
    public void doit();
}

Configuration ClassConfig.java (on the same package of other java class files)

@Configuration
@ComponentScan
public class ClassConfig {
}

Main Method

public static void main(String[] args) {
    try(AbstractApplicationContext appctx = new AnnotationConfigApplicationContext(ClassConfig.class)) {
        ClassC obj = (ClassC) appctx.getBean("classc");
        obj.doFromAbove();
    }
}

When I execute the main method, the Autowired field "abcd" in ClassA didn't get injected and results in a NullPointerException

It works only when I declare ClassA as a @Component and get it's bean... indirect autowiring is not happening

Should I decouple ClassA from ClassC and make everything loosely coupled?

Is there any simple annotation that I can use to tell Spring auto inject the @Autowired field even when the object is created in a tight coupled fashion?

Note
please don't tell me to use ApplicationContext in ClassC to create the bean of ClassA .

Any Spring Geek who could find an answer?

Body:
The issue is in ClassC:

    ClassA cls = new ClassA();

If you invoke the constructor of ClassA like this, Spring won't do its magic. If you need an instance of ClassA with injected fields, ask Spring for an instance (using injection or getBean()).

(To avoid having null fields where injection is assumed, I recommend using constructor injection.)


问:
Synchronized block will lock the whole object or the method alone?
I have multiple methods in a class and most of the methods are having critical sections(shared data). So I made those methods as synchronized. Say thread t1 is running one of the synchronized block . At the same time thread t2 can access the other methods critical section ? </p>

```<code>class Sample{

synchronized public void method1(){

}

synchronized public void method2(){

}

synchronized public void method3(){

}

public void method4(){

}

}
</code>```

答:
It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

When a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads

Body:
I have multiple methods in a class and most of the methods are having critical sections(shared data). So I made those methods as synchronized. Say thread t1 is running one of the synchronized block . At the same time thread t2 can access the other methods critical section ?

class Sample{

synchronized public void method1(){

}

synchronized public void method2(){

}

synchronized public void method3(){

}

public void method4(){

}

}


问:
How can i get extract integer number from float number modulus?

const int npart = 500;
double  x[npart], y[npart], z[npart];
bedheight of yaxis, ly=20, x_axis lx=20 and z_axis lz=20
int cell_height=4;

const int number_cell = 5;// (ly/cell_height);
int counter2[number_cell];
int cell_particle;

for (h=0;h<number_cell;h++)
      {
    counter2[h]=0;
      }
          for (i = 0; i < npart; i++)
          {
                 //cell_particle=int(y[i]) % cell_height;
                 cell_particle= int(fmod (y[i],cell_height));
              counter2[cell_particle]=counter2[cell_particle]+1;
           }
cout<<"particle counter="<<counter2[j]<<"      cell number="<<cell_particle<<"     position="<<(y[j])<<endl;
 sol_fract=counter2[i]*(Volume of particle/(lx*lz*cell_height));

Could you please tell why the counter2[cell_particle] and sol_fract is contain wrong value? I am waiting for your suggestion.```
</div>
</div>
</p>

```int number_cell=20;
int  counter2[20];
double y[500];
int cell_height=4;

for (h=0;h<number_cell;h++)

      {
        counter2[h]=0;
      }
        for (i = 0; i < npart; i++)

        {
         cell_particle=int((y[i]) % cell_height);
         counter2[cell_particle]=counter2[cell_particle]+1;
            }
cout<<"particle counter="<<counter2[j]<<"      cell number="<<cell_particle<<endl;

output: error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%
```

How can i get interger number from double values of modulus? It is noted that the value of y[i]=4.5, 8.9, 6 etc. I need integer value to put on counter2 array, but the problem is that conversion (error message is error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator% ). Could you please tell me how can i solve the problem?

答:
With int((y[i]) % cell_height) you attempt to convert the whole expression (y[i]) % cell_height into an int.

You probably want something like int(y[i]) % cell_height, which converts y[i] to an int before the modulo. Or what I prefer static_cast<int>(y[i]) % cell_height.

Or if you want to use floating-point modulo use std::fmod instead.

Body:
const int npart = 500;
double  x[npart], y[npart], z[npart];
bedheight of yaxis, ly=20, x_axis lx=20 and z_axis lz=20
int cell_height=4;

const int number_cell = 5;// (ly/cell_height);
int counter2[number_cell];
int cell_particle;

for (h=0;h<number_cell;h++)
      {
    counter2[h]=0;
      }
          for (i = 0; i < npart; i++)
          {
                 //cell_particle=int(y[i]) % cell_height;
                 cell_particle= int(fmod (y[i],cell_height));
              counter2[cell_particle]=counter2[cell_particle]+1;
           }
cout<<"particle counter="<<counter2[j]<<"      cell number="<<cell_particle<<"     position="<<(y[j])<<endl;
 sol_fract=counter2[i]*(Volume of particle/(lx*lz*cell_height));

Could you please tell why the counter2[cell_particle] and sol_fract is contain wrong value? I am waiting for your suggestion.

int number_cell=20;
int  counter2[20];
double y[500];
int cell_height=4;

for (h=0;h<number_cell;h++)

      {
        counter2[h]=0;
      }
        for (i = 0; i < npart; i++)

        {
         cell_particle=int((y[i]) % cell_height);
         counter2[cell_particle]=counter2[cell_particle]+1;
            }
cout<<"particle counter="<<counter2[j]<<"      cell number="<<cell_particle<<endl;

output: error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%

How can i get interger number from double values of modulus? It is noted that the value of y[i]=4.5, 8.9, 6 etc. I need integer value to put on counter2 array, but the problem is that conversion (error message is error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator% ). Could you please tell me how can i solve the problem?