问:
How to format number of decimal places in wpf using style/template?
I am writing a WPF program and I am trying to figure out a way to format data in a TextBox through some repeatable method like a style or template. I have a lot of TextBoxes (95 to be exact) and each one is bound to its own numeric data which can each have their own resolution defined. For example if the data is 99.123 with a resolution of 2 then it should display 99.12. Similarly a data value of 99 and resolution 3 should be displayed as 99.000 (not 99). Is there a way to do this?

Edit:
I should clarify, there are 95 TextBoxes on the current screen I'm working on, but I want every TextBox throughout the various screens in my program to display the correct number of decimal places. Now that I think about it, some of these are TextBoxes (like the screen I'm working on now) and some are DataGrids or ListViews, but if I can figure out how to get it working for TextBoxes I'm sure I can figure it out for the other controls as well.

There's not much code to share in this case but I'll attempt to make it clearer:

I have a View Model which contains the following properties (vb.net):

```<code>    Public ReadOnly Property Resolution As Integer
        Get
            Return _signal.DisplayResolution
        End Get
    End Property

    Public ReadOnly Property Value As Single
        Get
            Return Math.Round(_signal.DisplayValue, Resolution)
        End Get
    End Property
</code>```

and in the XAML I have:

```<code><UserControl.Resources>
    <vm:SignalViewModel x:Key="Signal" SignalPath="SomeSignal"/>
</UserControl.Resources>
<TextBox Grid.Column="3" IsEnabled="False" Text="{Binding Path=Value, Source={StaticResource Signal}, Mode=OneWay}" />
</code>```

EDIT2 (my solution):
It turns out that after walking away from the computer for a while, I came back to find a simple answer that was staring me in the face. Format the data in the view model!

```<code>    Public ReadOnly Property Value As String
        Get
            Return (Strings.FormatNumber(Math.Round(_signal.DisplayValue, _signal.DisplayResolution), _signal.DisplayResolution))
        End Get
    End Property
</code>```

答:
```<code>    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }
</code>```

Body:
I am writing a WPF program and I am trying to figure out a way to format data in a TextBox through some repeatable method like a style or template. I have a lot of TextBoxes (95 to be exact) and each one is bound to its own numeric data which can each have their own resolution defined. For example if the data is 99.123 with a resolution of 2 then it should display 99.12. Similarly a data value of 99 and resolution 3 should be displayed as 99.000 (not 99). Is there a way to do this?

Edit:
I should clarify, there are 95 TextBoxes on the current screen I'm working on, but I want every TextBox throughout the various screens in my program to display the correct number of decimal places. Now that I think about it, some of these are TextBoxes (like the screen I'm working on now) and some are DataGrids or ListViews, but if I can figure out how to get it working for TextBoxes I'm sure I can figure it out for the other controls as well.

There's not much code to share in this case but I'll attempt to make it clearer:

I have a View Model which contains the following properties (vb.net):

    Public ReadOnly Property Resolution As Integer
        Get
            Return _signal.DisplayResolution
        End Get
    End Property

    Public ReadOnly Property Value As Single
        Get
            Return Math.Round(_signal.DisplayValue, Resolution)
        End Get
    End Property

and in the XAML I have:

<UserControl.Resources>
    <vm:SignalViewModel x:Key="Signal" SignalPath="SomeSignal"/>
</UserControl.Resources>
<TextBox Grid.Column="3" IsEnabled="False" Text="{Binding Path=Value, Source={StaticResource Signal}, Mode=OneWay}" />

EDIT2 (my solution):
It turns out that after walking away from the computer for a while, I came back to find a simple answer that was staring me in the face. Format the data in the view model!

    Public ReadOnly Property Value As String
        Get
            Return (Strings.FormatNumber(Math.Round(_signal.DisplayValue, _signal.DisplayResolution), _signal.DisplayResolution))
        End Get
    End Property


来源: stackexchange

问:
Dygraph - Live data update with vertical zoom
I have dygrpah live data update which updated data every seconds.

Once i will do the vertical zoom and data will gets refreshed after a second so vertical zoom gets reset again; and chart start updating data as usual.

can any one have idea how to maintain vertical zoom and update the data?

Thanks

答:
Use "valueRange" property.

In "zoomCallback" callback function, you will getting the yRanges. Assign the range to the "valueRange" property. You could something similar to this,

```<code>grpah.updateOptions({
    valueRange: [zoomMinY, zoomMaxY]
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use "valueRange" property.

In "zoomCallback" callback function, you will getting the yRanges. Assign the range to the "valueRange" property. You could something similar to this,

grpah.updateOptions({
    valueRange: [zoomMinY, zoomMaxY]
});


问:
want to setup an Android app that will connect to a backend database
I want to setup an Android app that will connect to a backend database (web/database server that I maintain). What are some good resources for doing so?.my webserver is build with php</p>

答:
Usually you would connect to your database through a WebService.

Popular choices are:

SOAP (your webserver / PHP software must implement a SOAP protocol) - take a look here http://ksoap2.sourceforge.net/ and wikipedia on SOAP

custom JSON API - same like SOAP, but in a protocol called JSON (more concise)

Your custom API

You might want to refrain from using any JDBC alike connections. Others have asked this https://stackoverflow.com/search?q=[android]+jdbc

ContentLicense: CC BY-SA 2.5


问:
JWT/KONG: Cannot create JWTs with a shared secret
I'm playing around KONG API gateway recently.

I want to sign each JWT with a secret that is shared in all micros. I need this because I want other micros to be able to decode given JWT and extract payload data and work upon it (e.g. _user_id_ field in the payload).

When I try to create a JWT for the first consumer, it works just fine. But when I try to create it for the second consumer I'm getting the following error:

{u'secret': u"already exists with value 'secret'}

I'm not exactly sure but I think KONG/JWT requires unique secret for each consumer to create a JWT. Is it possible to configure JWT plugin properly to be able to use shared secret to sign JWTs?

PS: I'm not entirely sure that using a shared secret is a good practice. If there is a better way to do this please let me know. Thanks!

Kong version v0.10.2

答:
You can use private-public key  signing method.

Create your JWT token with a private key and share the public key with all other microservices. Other microservices can verify the signature of the token by using the shared public key.

You can use RSA algorithm for generating the keys & signing the tokens. The private key should be only with the service which is generating the token.

Snippet for generating keys:

```<code>    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair kp = kpg.genKeyPair();
    Key publicKey = kp.getPublic();
    Key privateKey = kp.getPrivate();
</code>```

Snippet to generate JWT token. I am using JJwt API for generating the token:

```<code>Jwts.builder()
            .setClaims(payload)
            .setExpiration(expiryDate)
            .signWith(SignatureAlgorithm.RS256, privateKey )
            .compact();
</code>```

Snippet to verify the token with public key:

```<code>Jwts.parser()
       .setSigningKey(publicKey )
       .parseClaimsJws(jwtToken)
</code>```

Hope this helps.

Body:
You can use private-public key  signing method.

Create your JWT token with a private key and share the public key with all other microservices. Other microservices can verify the signature of the token by using the shared public key.

You can use RSA algorithm for generating the keys & signing the tokens. The private key should be only with the service which is generating the token.

Snippet for generating keys:

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair kp = kpg.genKeyPair();
    Key publicKey = kp.getPublic();
    Key privateKey = kp.getPrivate();

Snippet to generate JWT token. I am using JJwt API for generating the token:

Jwts.builder()
            .setClaims(payload)
            .setExpiration(expiryDate)
            .signWith(SignatureAlgorithm.RS256, privateKey )
            .compact();

Snippet to verify the token with public key:

Jwts.parser()
       .setSigningKey(publicKey )
       .parseClaimsJws(jwtToken)

Hope this helps.


问:
How get marker position before dragging?
In Google Maps API v2, I want to store the previous location before dragging a marker, however, when I begin dragging the marker, it will always jump to some upper location, so in callback onMarkerDragStart, I can't get the last position.

Is it a bug, or can any fix the problem?

答:
the fact that the marker "Jumps" is because otherwise you could not see the marker due to the finger over it.
In order to get the marker position, you should keep it saved before start dragging. The documentation is pretty clear:

Called when a marker starts being dragged. The marker's location can be accessed via getPosition(); this position may be different to the position prior to the start of the drag because the marker is popped up above the touch point.

So the idea is to keep the position "cached" and get them from this cached variable when dragging starts.


问:
how to add confirmation fields to mysql table creation
I am following a tutorial on how to make table with mysql for android studio app
this is the code to create table

```<code>create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
</code>```

but the form in this tutorial only has:

```<code>name
email
password
</code>```

while my form has:

```<code>email
confirm email
name
password
confirm password
referral code
</code>```

how do i add the confirmation fields,e.g confirm password fields to mysql create table

答: Do not add confirm field in database as it would be against DRY(Do Not Repeat YourSelf) Because if adding Two column contain same value would wastage of storage. You can do validation at android side. This would be good option than adding field in database </p>

Body:
I am following a tutorial on how to make table with mysql for android studio app
this is the code to create table

create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);

but the form in this tutorial only has:

name
email
password

while my form has:

email
confirm email
name
password
confirm password
referral code

how do i add the confirmation fields,e.g confirm password fields to mysql create table


问:
Error 542 - N appears in the dimension of a variable
```<code>program factorial
implicit none
integer:: n1
real:: fact = 1.0
integer:: n = n1
integer, dimension(1:n):: x
integer:: i
print *, "Enter a number:"
read *, n1
x(1) = n1
do i=1,n1-1
  x(i+1) = n1-i
  fact = fact*x(i)
end do
print *, fact
end program factorial
</code>```

I have written a code for calculating factorial of a number. I am asking the user to put in an integer 'n1', after which it will create an array variable containing n1 compartments. I am unsuccessful in compiling this. I keep getting the following error!

factorial.F95(6) : error 542 - N appears in the dimension of a variable, yet is not a dummy argument, a variable available through USE or CONTAINS association, a COMMON variable, a PARAMETER, or a PURE FUNCTION

   Compilation failed.

How can I fix this? I want the array dimension to be equal to the input number. For example, say I want to calculate 5! (5 factorial), I want the x array to be of 5 (row or column) element length. Somehow, I am unable to do that!

答:
As Vladimir suggested, you have to allocate the array:

```<code>integer, dimension(:), allocatable :: x
integer :: alloc_stat

print *, "Enter a number:"
read *, n1

ALLOCATE( x(1:n1), STAT=alloc_stat )
IF ( alloc_stat .ne. 0 ) THEN
    WRITE(ERROR_UNIT,*) "Array allocation failed."
    ERROR_STOP alloc_stat
ENDIF
</code>```

(I always check the status of my ALLOCATE statements.  It's not whether you are paranoid or not, it's whether you're paranoid enough.)

Body:
program factorial
implicit none
integer:: n1
real:: fact = 1.0
integer:: n = n1
integer, dimension(1:n):: x
integer:: i
print *, "Enter a number:"
read *, n1
x(1) = n1
do i=1,n1-1
  x(i+1) = n1-i
  fact = fact*x(i)
end do
print *, fact
end program factorial

I have written a code for calculating factorial of a number. I am asking the user to put in an integer 'n1', after which it will create an array variable containing n1 compartments. I am unsuccessful in compiling this. I keep getting the following error!

factorial.F95(6) : error 542 - N appears in the dimension of a variable, yet is not a dummy argument, a variable available through USE or CONTAINS association, a COMMON variable, a PARAMETER, or a PURE FUNCTION

   Compilation failed.

How can I fix this? I want the array dimension to be equal to the input number. For example, say I want to calculate 5! (5 factorial), I want the x array to be of 5 (row or column) element length. Somehow, I am unable to do that!

Body:
As Vladimir suggested, you have to allocate the array:

integer, dimension(:), allocatable :: x
integer :: alloc_stat

print *, "Enter a number:"
read *, n1

ALLOCATE( x(1:n1), STAT=alloc_stat )
IF ( alloc_stat .ne. 0 ) THEN
    WRITE(ERROR_UNIT,*) "Array allocation failed."
    ERROR_STOP alloc_stat
ENDIF

(I always check the status of my ALLOCATE statements.  It's not whether you are paranoid or not, it's whether you're paranoid enough.)


问:
Removing similar rows using GROUP BY / DISTINCT
I currently have a table of document paths next to an ID and other metadata, however the same file path is referenced multiple times with different IDs.

An example data set:

```<code>ID           FullPath
1            \\some\file\path.txt
2            \\some\file\path.txt
3            \\some\file\path.txt
4            \\another\file\path.txt
5            \\another\file\path.txt
</code>```

I want to return a distinct set of paths and do not need the other IDs. It is probably quite a simple GROUP BY aggregate function but I can't figure it out. Please help!

I think I want something along these lines, but to be selecting the ID from the subquery instead of the path as the path causes it to return all rows. But I cant do that and GROUP BY the FullPath!

```<code>select *
from Documents
where FullPath in (
    select min(FullPath)
    from Documents
    group by FullPath
)
</code>```

Results I am after:

```<code>ID           FullPath
1            \\some\file\path.txt
4            \\another\file\path.txt
</code>```

答:
I would write a function that takes a string and returns the string up to the last .
Eg. fn_strip_path('\PLACE\Here\file.txt') returns '\PLACE\Here'
of course, fn_strip_path('\PLACE\Here') returns '\PLACE'

then select distinct fn_strip_path(full_path) from documents gives you want you want

Body:
I currently have a table of document paths next to an ID and other metadata, however the same file path is referenced multiple times with different IDs.

An example data set:

ID           FullPath
1            \\some\file\path.txt
2            \\some\file\path.txt
3            \\some\file\path.txt
4            \\another\file\path.txt
5            \\another\file\path.txt

I want to return a distinct set of paths and do not need the other IDs. It is probably quite a simple GROUP BY aggregate function but I can't figure it out. Please help!

I think I want something along these lines, but to be selecting the ID from the subquery instead of the path as the path causes it to return all rows. But I cant do that and GROUP BY the FullPath!

select *
from Documents
where FullPath in (
    select min(FullPath)
    from Documents
    group by FullPath
)

Results I am after:

ID           FullPath
1            \\some\file\path.txt
4            \\another\file\path.txt


问:
time pass algorithm in python
```<code>import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question

for i in random.sample(list(questions), 5):
     question = questions[i]
     if time.time() < current_time+allowed_time:
         answer = input("1. soru --> {} : ".format(i))
     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1
print()
print("right answer  :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)
</code>```

Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.

Could you help on how to do that?

答:
Probably the most simple and the most elegant (from the programmer's point of view) is simply to keep infinitely time for an answer but then reject it if it was answered after the given time limit:

```<code> start_time = time.time()
 answer = input("1. soru --> {} : ". format(i))
 if time.time() - start_time > allowed_time:
     # code for rejecting the answer
</code>```

So instead of your for loop use this (a tested one, and with an improvement):

```<code>for j, i in enumerate( random.sample(list(questions), 5) ):          # Slight change
     question = questions[i]
     start_time = time.time()
     answer = input("{}. soru --> {} : ". format(j + 1, i))          # Sligth change
     if time.time() - start_time > allowed_time:
         print("   Time-out: You didn't answer quickly enough.")
         answer = ""

     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1
</code>```

Not that I slightly changed your for statement and the answer = ... for the sake of printing correct ordinal numbers of questions (yours were always 1.)

Title: time pass algorithm in python

Body:
import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question

for i in random.sample(list(questions), 5):
     question = questions[i]
     if time.time() < current_time+allowed_time:
         answer = input("1. soru --> {} : ".format(i))
     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1
print()
print("right answer  :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)

Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.

Could you help on how to do that?

Body:
Probably the most simple and the most elegant (from the programmer's point of view) is simply to keep infinitely time for an answer but then reject it if it was answered after the given time limit:

 start_time = time.time()
 answer = input("1. soru --> {} : ". format(i))
 if time.time() - start_time > allowed_time:
     # code for rejecting the answer

So instead of your for loop use this (a tested one, and with an improvement):

for j, i in enumerate( random.sample(list(questions), 5) ):          # Slight change
     question = questions[i]
     start_time = time.time()
     answer = input("{}. soru --> {} : ". format(j + 1, i))          # Sligth change
     if time.time() - start_time > allowed_time:
         print("   Time-out: You didn't answer quickly enough.")
         answer = ""

     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1

Not that I slightly changed your for statement and the answer = ... for the sake of printing correct ordinal numbers of questions (yours were always 1.)


问:
Where is / where do I put the common library?
I am writing my first cross-platform app with Xamarin on Azure using Visual Studio 2017.

I've found a great walkthrough article by Adrian Hall at:

https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter1/firstapp_pc/

However, I have got the following stage and I'm stumped:

"Once the project is created, you will see that four new projects have been created: a common library which you named plus one project for each platform that has been chosen. Since we chose a project with three platforms, we get four projects:"

The next stage is the problem, entitled "Building the Common Library"... he writes:

"Let's start with the cloud service - this is defined in Abstractions\ICloudService.cs. It is used for initializing the connection and getting a table definition:"

My question is where is the common library into which I put "Abstractions\ICloudService.cs" or if the common library needs building, where do I put the common library files in a cross platform app like this??

Many thanks!

答:
Once the project is created, you will see that four new projects have been created: a common library which you named plus one project for each platform

It works exactly like the documentation says.  TodoList is your common library.  TodoList.{Platform} are your platform projects.


问:
Enum error while doing check
I have an enum like this

```<code> public enum ConnectionState : int
   {
      Unknown = 1,
      Connected = 2,
      Disconnected = 3,
   }
</code>```

I need to display value if it is connected i did this check

```<code>if(ConnectionState.Connected)
{
SubItems.Add(Data.value)
}
</code>```

But i am getting an error "Cannot implicitly convert type 'ConnectionState' to 'bool'".kindly suggest me how to proceed with this

答: Enums or enumerated data types ,as the name suggests are user defined datatypes.So they can not used directly in the condition statements.They can be compared within themselves.So you need to define your object and then compare its value with some other value in enum.</p>

Title: Enum error while doing check

Body:
I have an enum like this

 public enum ConnectionState : int
   {
      Unknown = 1,
      Connected = 2,
      Disconnected = 3,
   }

I need to display value if it is connected i did this check

if(ConnectionState.Connected)
{
SubItems.Add(Data.value)
}

But i am getting an error "Cannot implicitly convert type 'ConnectionState' to 'bool'".kindly suggest me how to proceed with this


问:
Passing multi parameters (radio) from view to controller using array
I would like to post between 55 and 100 items which could be false or true from view to my controller without using Model. This is my code in Razor View:

```<code>@using(Html.BeginForm("User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
    {

        <input type="radio" name="answer1">Choice one</input>
        <input type="radio" name="answer1">Choice two</input>
        <input type="radio" name="answer2">Choice three</input>
        <input type="radio" name="answer2">Choice four</input>

    ....

    <input type="radio" name="answer55">Choice fifty five</input>
    <input type="radio" name="answer55">Choice fifty six</input>

    <button type="submit">Send</button>
                                   }
</code>```

Controller:

```<code>[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}
</code>```

How can I send all of parameters (radio buttons) using an array to my controller. I appreciate all your solutions.

答:
Try its:
in your controller:

```<code> // GET: Home
        public ActionResult Index()
        {
            List<MyItem> radioItems = new List<MyItem>();
            radioItems.Add(new MyItem() { Caption="radio1", Value="radio1Value"});
            radioItems.Add(new MyItem() { Caption="radio2", Value="radio2Value"});
            radioItems.Add(new MyItem() { Caption="radio3", Value="radio3Value"});
            radioItems.Add(new MyItem() { Caption="radioN", Value="radioNValue"});
            return View(radioItems);
        }
        [HttpPost]
        public void IndexPost(List<string> items)
        {
            // todointo item has your selected item
            var x = items;

        }
</code>```

in your cshtml:

```<code>@using (Html.BeginForm("IndexPost", "Home", FormMethod.Post))
        {
            foreach (var item in Model)
            {

                <input type="checkbox" name="items" value="@item.Value">@item.Caption
            }

            <button Type="submit">Send</button>

        }
</code>```

Body:
I would like to post between 55 and 100 items which could be false or true from view to my controller without using Model. This is my code in Razor View:

@using(Html.BeginForm("User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
    {

        <input type="radio" name="answer1">Choice one</input>
        <input type="radio" name="answer1">Choice two</input>
        <input type="radio" name="answer2">Choice three</input>
        <input type="radio" name="answer2">Choice four</input>

    ....

    <input type="radio" name="answer55">Choice fifty five</input>
    <input type="radio" name="answer55">Choice fifty six</input>

    <button type="submit">Send</button>
                                   }

Controller:

[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}

How can I send all of parameters (radio buttons) using an array to my controller. I appreciate all your solutions.

Body:
Try its:
in your controller:

 // GET: Home
        public ActionResult Index()
        {
            List<MyItem> radioItems = new List<MyItem>();
            radioItems.Add(new MyItem() { Caption="radio1", Value="radio1Value"});
            radioItems.Add(new MyItem() { Caption="radio2", Value="radio2Value"});
            radioItems.Add(new MyItem() { Caption="radio3", Value="radio3Value"});
            radioItems.Add(new MyItem() { Caption="radioN", Value="radioNValue"});
            return View(radioItems);
        }
        [HttpPost]
        public void IndexPost(List<string> items)
        {
            // todointo item has your selected item
            var x = items;

        }

in your cshtml:

@using (Html.BeginForm("IndexPost", "Home", FormMethod.Post))
        {
            foreach (var item in Model)
            {

                <input type="checkbox" name="items" value="@item.Value">@item.Caption
            }

            <button Type="submit">Send</button>

        }


问:
How to call web url from controller code asp.net mvc Core
How do I call a url from controller. i.e. this one "http://xxx.ashx?Item=82f829e6&IsReadonly=false". It cannot be from a href link in the view but has to be from the controller. I am using asp.net MVC Core 1.1</p>

答:
can you try this</p>

```<code>public IActionResult YourAction()
{
    return Redirect("http://www.example.com");
}
</code>```

Body:
can you try this

public IActionResult YourAction()
{
    return Redirect("http://www.example.com");
}


问:
Unity3d 2D Raycast calls sometime passing through PolygonCollider2D's points
I'm a Unity beginner!

The rays from my Raycast2D calls sometimes pass through points of my PolygonCollider2D and I don't know why.

Hits are marked in the following images by a small yellow horizontal line.

Expected behavior:

A ray passing through:

Here is my code:

(path being the red points of the PolygonCollider2D)

```<code>Debug.DrawLine(origin, new Vector3(path[i].x, path[i].y, 0), Color.yellow, 0, false);
float angle = Mathf.Atan2(path[i].y - origin.y,  path[i].x - origin.x);
Vector2 direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
RaycastHit2D hit = Physics2D.Raycast(origin, direction);
Debug.DrawLine(new Vector3(hit.point.x, hit.point.y, 0), new Vector3(hit.point.x - .2f, hit.point.y, 0), Color.yellow);
Debug.DrawRay(new Vector3(origin.x, origin.y, 0), new Vector3(direction.x, direction.y));
</code>```

Is it due to bad rounding?

If so, how can I fix it?

答:
The problem originates from floating point precision. You cannot make exact comparisms when floats are involved. This is usually fine if you are using a normal collider that moves around a world, because the human eye cannot notice the very tiny offsets. The question is:

Do you need to hit the very exact positions of the polygon corners?

If no:

Cool your solution seems to work!

If yes:

You will have to increase the size of your collider by adding a skin. This is a technique that increases the likelyhood of a collider getting hit. If it gets hit you may need to validate the hitpoint to figure out if the hit is really a hit or not. You will still run into floating errors and you'll probably have to configure an acceptable error distance (skin width). I hope the images below illustrate my point.

In this first image is the example of your raycast not hitting the collider.

Note that the dimensions in my images are off to illustrate my point.

Here we are still using only 1 collider but we have increased its size.

Keep in mind that floating point arithmentic cannot be exact. If you want to do exact math you will need to somehow work around the issue. In this case the solution would be to add a skin. This might not be very easy for you because you are using polygon colliders though.

Body:
I'm a Unity beginner!

The rays from my Raycast2D calls sometimes pass through points of my PolygonCollider2D and I don't know why.

Hits are marked in the following images by a small yellow horizontal line.

Expected behavior:

A ray passing through:

Here is my code:

(path being the red points of the PolygonCollider2D)

Debug.DrawLine(origin, new Vector3(path[i].x, path[i].y, 0), Color.yellow, 0, false);
float angle = Mathf.Atan2(path[i].y - origin.y,  path[i].x - origin.x);
Vector2 direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
RaycastHit2D hit = Physics2D.Raycast(origin, direction);
Debug.DrawLine(new Vector3(hit.point.x, hit.point.y, 0), new Vector3(hit.point.x - .2f, hit.point.y, 0), Color.yellow);
Debug.DrawRay(new Vector3(origin.x, origin.y, 0), new Vector3(direction.x, direction.y));

Is it due to bad rounding?

If so, how can I fix it?


问:
CSS3: how to make a dynamic drop down navigation bar without JS
So I am trying to make a pure CSS3 dropdown navigation. Of all the stack overflow questions about this, this was the closest I found.

What I dislike, however, is the use of defined heights, which makes everything a pain to refactor if you wish to change the heights later on.

Below is my own attempt, which uses barely any css and gets close to the desire result. The only issues with it is:

the "drop down" is more of a shove up and

if the first point is fixed, it would look bad in a header (as the entire header would jump about)

How can I fix these issues with minimal CSS and in a way that is dynamic and flexible (e.g. no absolute positionings, no fixed heights, etc)

/* all the CSS needed to make the drop down*/

/* set horizontal navigation for list elements*/
nav ul li {
  display: inline-block;
}

/*remove padding from nested unordered list to get text to align*/
li > ul {
  padding: 0;
}

/* hide nested list elements*/
li > ul li{
  display: none;
  padding: 0;
}

/* when hovering on the outer list element display nested list elements */
li:hover ul li{
  display: block;
}

/* the following is added just to make the links clear to see*/

/*make text eady to see on dark background*/
li {
  border: 1px coral solid
}

/*highlight the issue with the header bouncing*/
nav {
  background-color: black;
  color: coral;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
    <ul>
      <li><a>Link</a></li>

      <li>
        <a>Drop Down</a>
        <ul>
            <li><a>1</a></li>
            <li><a>2</a></li>
            <li><a>3</a></li>
            <li><a>4</a></li>
        </ul>
      </li>

    </ul>
  </nav></code>```

答:
How is this, just added absolute positioning to the child ul - using absolute positioning doesn't make it any less responsive

/* all the CSS needed to make the drop down*/

/* set horizontal navigation for list elements*/

nav ul li {
  display: inline-block;
  position:relative;
}

/*remove padding from nested unordered list to get text to align*/

li>ul {
  padding: 0;
  position:absolute;
  width:100%;
  background: black; /* not sure if you want background-color on this */
}

/* hide nested list elements*/

li>ul li {
  display: none;
  padding: 0;
}

/* when hovering on the outer list element display nested list elements */

li:hover ul li {
  display: block;
}

/* the following is added just to make the links clear to see*/

/*make text eady to see on dark background*/

li {
  border: 1px coral solid
}

/*highlight the issue with the header bouncing*/

nav {
  background-color: black;
  color: coral;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li><a>Link</a></li>

    <li>
      <a>Drop Down</a>
      <ul>
        <li><a>1</a></li>
        <li><a>2</a></li>
        <li><a>3</a></li>
        <li><a>4</a></li>
      </ul>
    </li>

  </ul>
</nav></code>```

Body:
So I am trying to make a pure CSS3 dropdown navigation. Of all the stack overflow questions about this, this was the closest I found.

What I dislike, however, is the use of defined heights, which makes everything a pain to refactor if you wish to change the heights later on.

Below is my own attempt, which uses barely any css and gets close to the desire result. The only issues with it is:

the "drop down" is more of a shove up and

if the first point is fixed, it would look bad in a header (as the entire header would jump about)

How can I fix these issues with minimal CSS and in a way that is dynamic and flexible (e.g. no absolute positionings, no fixed heights, etc)

/* all the CSS needed to make the drop down*/

/* set horizontal navigation for list elements*/
nav ul li {
  display: inline-block;
}

/*remove padding from nested unordered list to get text to align*/
li > ul {
  padding: 0;
}

/* hide nested list elements*/
li > ul li{
  display: none;
  padding: 0;
}

/* when hovering on the outer list element display nested list elements */
li:hover ul li{
  display: block;
}

/* the following is added just to make the links clear to see*/

/*make text eady to see on dark background*/
li {
  border: 1px coral solid
}

/*highlight the issue with the header bouncing*/
nav {
  background-color: black;
  color: coral;
}

Link

        Drop Down

1

2

3

4

Body:
How is this, just added absolute positioning to the child ul - using absolute positioning doesn't make it any less responsive

/* all the CSS needed to make the drop down*/

/* set horizontal navigation for list elements*/

nav ul li {
  display: inline-block;
  position:relative;
}

/*remove padding from nested unordered list to get text to align*/

li>ul {
  padding: 0;
  position:absolute;
  width:100%;
  background: black; /* not sure if you want background-color on this */
}

/* hide nested list elements*/

li>ul li {
  display: none;
  padding: 0;
}

/* when hovering on the outer list element display nested list elements */

li:hover ul li {
  display: block;
}

/* the following is added just to make the links clear to see*/

/*make text eady to see on dark background*/

li {
  border: 1px coral solid
}

/*highlight the issue with the header bouncing*/

nav {
  background-color: black;
  color: coral;
}

<nav>
  <ul>
    <li><a>Link</a></li>

    <li>
      <a>Drop Down</a>
      <ul>
        <li><a>1</a></li>
        <li><a>2</a></li>
        <li><a>3</a></li>
        <li><a>4</a></li>
      </ul>
    </li>

  </ul>
</nav>


问:
message java.lang.IllegalStateException: No output folder
I am new to Tomcat on Windows. I am trying to deploy my Java project which I have made in RHEL 5 using Tomcat. Now I want to run that project on window. So I copied and pasted my project folder inside the Tomcat web apps Directory

```<code>i.e C:\Program Files\apache-tomcat-6.0.37\webapps
</code>```

but I am unable to run the project as I am facing below error while opening my first login page. Do I need to make any further changes in code or web.xml file as I am now deploying it on Windows?

```<code>type Exception report

message java.lang.IllegalStateException: No output folder

**Description** The server encountered an internal error that prevented
it from fulfilling this request.

Exception

org.apache.jasper.JasperException: java.lang.IllegalStateException: No output folder
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:538)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:364)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
root cause

java.lang.IllegalStateException: No output folder
    org.apache.jasper.JspCompilationContext.createOutputDir(JspCompilationContext.java:678)
    org.apache.jasper.JspCompilationContext.getOutputDir(JspCompilationContext.java:197)
    org.apache.jasper.JspCompilationContext.getClassFileName(JspCompilationContext.java:514)
    org.apache.jasper.compiler.Compiler.isOutDated(Compiler.java:453)
    org.apache.jasper.compiler.Compiler.isOutDated(Compiler.java:399)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.
</code>```

答:
It can be because of lack of write permissions to cache directory (/var/lib/tomcat6 on Linux). If this is your case, use the following commands to grant full access and restart Tomcat:

sudo /etc/init.d/tomcat6 stop
sudo chown -R tomcat6 /var/lib/tomcat6
sudo chmod -R 777 /var/lib/tomcat6
sudo /etc/init.d/tomcat6 start
```

If this was working for you previously, sometimes the work directory is simply in a bad state and you can fix it by simply deleting it and allowing Tomcat to create a new one from scratch.

Body:
I am new to Tomcat on Windows. I am trying to deploy my Java project which I have made in RHEL 5 using Tomcat. Now I want to run that project on window. So I copied and pasted my project folder inside the Tomcat web apps Directory

i.e C:\Program Files\apache-tomcat-6.0.37\webapps

but I am unable to run the project as I am facing below error while opening my first login page. Do I need to make any further changes in code or web.xml file as I am now deploying it on Windows?

type Exception report

message java.lang.IllegalStateException: No output folder

**Description** The server encountered an internal error that prevented
it from fulfilling this request.

Exception

org.apache.jasper.JasperException: java.lang.IllegalStateException: No output folder
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:538)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:364)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
root cause

java.lang.IllegalStateException: No output folder
    org.apache.jasper.JspCompilationContext.createOutputDir(JspCompilationContext.java:678)
    org.apache.jasper.JspCompilationContext.getOutputDir(JspCompilationContext.java:197)
    org.apache.jasper.JspCompilationContext.getClassFileName(JspCompilationContext.java:514)
    org.apache.jasper.compiler.Compiler.isOutDated(Compiler.java:453)
    org.apache.jasper.compiler.Compiler.isOutDated(Compiler.java:399)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.

Body:
It can be because of lack of write permissions to cache directory (/var/lib/tomcat6 on Linux). If this is your case, use the following commands to grant full access and restart Tomcat:

sudo /etc/init.d/tomcat6 stop
sudo chown -R tomcat6 /var/lib/tomcat6
sudo chmod -R 777 /var/lib/tomcat6
sudo /etc/init.d/tomcat6 start

If this was working for you previously, sometimes the work directory is simply in a bad state and you can fix it by simply deleting it and allowing Tomcat to create a new one from scratch.


问:
Need to run .jar from console for it to work
I have a java application.
I'm using eclipse to write, compile and create a runnable .jar.

The program is used to discover OCF devices.

It uses UDP and multicast.

Multicast code

```<code>public static void sendMulticast(byte[] data) throws Exception{
        DatagramPacket pack = new DatagramPacket(data, data.length, mgroup, mport);
        msocket.send(pack);
    }
public static byte[] recieveMulticast(int timeout) throws Exception{
        DatagramPacket packet;
        byte[] data = new byte[AppConfig.ocf_buffer_size];

        packet = new DatagramPacket(data, data.length);
        msocket.setSoTimeout(timeout);
        msocket.receive(packet);

        return data;
    }
</code>```

The code works when I start it from eclipse. It also works when I run the .jar from console on Linux.

But when I start it with a double click, it doesn't work.

When started from console, it finds my test device in less then a second. When started with a double click it doesn't find it ever.

I haven't tested it on Windows yet, but the problem remains on Linux all the same.

What is the difference when you start .jar from console or by double clicking?
Why is it effecting messages on multicast?

I'm using "Package required libraries into generated JAR".
I'm using java 1.7 in eclipse, and 1.8 on Linux, maybe thats the problem? But why does running it from console work?
I would understand if I used sudo, but I didn't.

答:
The problem was in current location, system property

user.dir

This is the first function I call in my main. It doesn't work from eclipse, so I'll put an argument for disabling it (it will be disabled only during development).

```<code>static void setCurrentDir() throws URISyntaxException{
    String s;
    s = ESP8266_Configurator.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
    s = s.substring(0, s.lastIndexOf('/'));
    System.setProperty("user.dir",s);
}
</code>```

I hope this helps someone. Code should be exported with extracted libraries, not packaged, otherwise it doesn't work.

Body:
I have a java application.
I'm using eclipse to write, compile and create a runnable .jar.

The program is used to discover OCF devices.

It uses UDP and multicast.

Multicast code

public static void sendMulticast(byte[] data) throws Exception{
        DatagramPacket pack = new DatagramPacket(data, data.length, mgroup, mport);
        msocket.send(pack);
    }
public static byte[] recieveMulticast(int timeout) throws Exception{
        DatagramPacket packet;
        byte[] data = new byte[AppConfig.ocf_buffer_size];

        packet = new DatagramPacket(data, data.length);
        msocket.setSoTimeout(timeout);
        msocket.receive(packet);

        return data;
    }

The code works when I start it from eclipse. It also works when I run the .jar from console on Linux.

But when I start it with a double click, it doesn't work.

When started from console, it finds my test device in less then a second. When started with a double click it doesn't find it ever.

I haven't tested it on Windows yet, but the problem remains on Linux all the same.

What is the difference when you start .jar from console or by double clicking?
Why is it effecting messages on multicast?

I'm using "Package required libraries into generated JAR".
I'm using java 1.7 in eclipse, and 1.8 on Linux, maybe thats the problem? But why does running it from console work?
I would understand if I used sudo, but I didn't.

Body:
The problem was in current location, system property

user.dir

This is the first function I call in my main. It doesn't work from eclipse, so I'll put an argument for disabling it (it will be disabled only during development).

static void setCurrentDir() throws URISyntaxException{
    String s;
    s = ESP8266_Configurator.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
    s = s.substring(0, s.lastIndexOf('/'));
    System.setProperty("user.dir",s);
}

I hope this helps someone. Code should be exported with extracted libraries, not packaged, otherwise it doesn't work.


问:
Feathersjs REST Query $like
I have an problem to send a REST query to featherjs with the $like operator.

Table:

ID Textfield

1  andreas

Query get

localhost:3030/table?textfield[$like]=andreas

returs the row

Query get
localhost:3030/table?textfield[$like]=andrea

localhost:3030/table?textfield[$like]=andrea%

localhost:3030/table?textfield[$like]=andrea*

all this query return 0 rows

Model is Sequelize -> SQL Server

Whats wrong with the url.

答:
I setup your example with the addition of a createdAt and updatedAt field in your test table.

I used a feathersjs Model of Sequelize -> MySQL

Table:

ID Textfield

1 andreas

I used postman to test your GET queries:

```<code>localhost:3030/table?textfield[$like]=andreas

returns:

{
  "total": 1,
  "limit": 20,
  "skip": 0,
  "data": [
    {
     "id": 1,
      "textfield": "andreas",
      "createdAt": "2017-06-05T11:33:38.000Z",
      "updatedAt": null
    }
  ]
}

localhost:3030/table?textfield[$like]=andrea%

returns:

{
  "total": 1,
  "limit": 20,
  "skip": 0,
  "data": [
    {
     "id": 1,
      "textfield": "andreas",
      "createdAt": "2017-06-05T11:33:38.000Z",
      "updatedAt": null
    }
  ]
}

localhost:3030/table?textfield[$like]=%drea%

returns:

{
  "total": 1,
  "limit": 20,
  "skip": 0,
  "data": [
    {
     "id": 1,
      "textfield": "andreas",
      "createdAt": "2017-06-05T11:33:38.000Z",
      "updatedAt": null
    }
  ]
}
</code>```

The following queries should return nothing because 'andrea' can not be exactly matched in the database and the asterisk (*) is not a wild card in the SQL LIKE syntax https://www.w3schools.com/SQL/sql_like.asp :

```<code>localhost:3030/table?textfield[$like]=andrea
localhost:3030/table?textfield[$like]=andrea*

{
  "total": 0,
  "limit": 20,
  "skip": 0,
  "data": []
}
</code>```

Title: Feathersjs REST Query $like

Body:
I setup your example with the addition of a createdAt and updatedAt field in your test table.

I used a feathersjs Model of Sequelize -> MySQL

Table:

ID Textfield

1 andreas

I used postman to test your GET queries:

localhost:3030/table?textfield[$like]=andreas

returns:

{
  "total": 1,
  "limit": 20,
  "skip": 0,
  "data": [
    {
     "id": 1,
      "textfield": "andreas",
      "createdAt": "2017-06-05T11:33:38.000Z",
      "updatedAt": null
    }
  ]
}

localhost:3030/table?textfield[$like]=andrea%

returns:

{
  "total": 1,
  "limit": 20,
  "skip": 0,
  "data": [
    {
     "id": 1,
      "textfield": "andreas",
      "createdAt": "2017-06-05T11:33:38.000Z",
      "updatedAt": null
    }
  ]
}

localhost:3030/table?textfield[$like]=%drea%

returns:

{
  "total": 1,
  "limit": 20,
  "skip": 0,
  "data": [
    {
     "id": 1,
      "textfield": "andreas",
      "createdAt": "2017-06-05T11:33:38.000Z",
      "updatedAt": null
    }
  ]
}

The following queries should return nothing because 'andrea' can not be exactly matched in the database and the asterisk (*) is not a wild card in the SQL LIKE syntax https://www.w3schools.com/SQL/sql_like.asp :

localhost:3030/table?textfield[$like]=andrea
localhost:3030/table?textfield[$like]=andrea*

{
  "total": 0,
  "limit": 20,
  "skip": 0,
  "data": []
}


问:
libGDX - My Box2D Body doesnt jump
I'm trying to make a little game with the java game engine called libGDX. I already got the player but he can't jump and I dont know why.

This is my GameScreen class:

```<code>public class GameScreen extends ScreenManager{
    //For the view of the game and the rendering
    private SpriteBatch batch;
    private OrthographicCamera cam;

    //DEBUG
    private Box2DDebugRenderer b2dr;

    //World, Player and so on
    private GameWorld world;
    private Player player;
    private Ground ground;

    public static float w, h;

    public GameScreen(Game game) {
        super(game);
        //vars
        w = Gdx.graphics.getWidth();
        h = Gdx.graphics.getHeight();

        //view and rendering
        batch = new SpriteBatch();
        cam = new OrthographicCamera();
        cam.setToOrtho(false, w/2, h/2);

        //debug
        b2dr = new Box2DDebugRenderer();

        //world, bodies ...
        player = new Player(world);
        ground = new Ground(world);

    }

    @Override
    public void pause() {

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        //clearing the screen
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        //updating
        update(Gdx.graphics.getDeltaTime());

        //render
        batch.setProjectionMatrix(cam.combined);

        //debug
        b2dr.render(world.getWorld(), cam.combined);

    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }

    @Override
    public void onKlick(float delta) {

    }

    public void update(float delta){
        world.update(delta);
        player.keyInput();
        System.out.println(player.getBody().getPosition().x);
        System.out.println(player.getBody().getPosition().y);
    }

}
</code>```

and this is my Player class:

```<code>public class Player {
    public static Body body;
    public static BodyDef def;
    private FixtureDef fd;

    //set form
    private PolygonShape shape;

    private GameScreen gs;

    public Player(GameWorld world){
        def = new BodyDef();
        def.fixedRotation = true;
        def.position.set(gs.w / 4, gs.h / 4);
        def.type = BodyType.DynamicBody;

        body = world.getWorld().createBody(def);

        shape = new PolygonShape();
        shape.setAsBox(32 / 2, 32 / 2);

        fd = new FixtureDef();
        fd.shape = shape;
        fd.density = 30;

        body.createFixture(fd);
        shape.dispose();
    }

    public static Body getBody() {
        return body;
    }

    public static BodyDef getDef() {
        return def;
    }

    public static void keyInput(){
        if(Gdx.input.isKeyPressed(Input.Keys.UP)){
            body.applyForceToCenter(0, 900, false);
            System.out.println("PRESSED");
        }
    }

}
</code>```

this finally is my GameWorld class:

```<code>public class GameWorld {
    public static World world;

    public GameWorld(){
        world = new World(new Vector2(0f, -10f), false);

    }

    public void update(float delta){
        world.step(1 / 60f, 5, 2);
        System.out.println("WorldUPDATE");
    }

    public static World getWorld() {
        return world;
    }

}
</code>```

I don't know why the body can't jump please help me if you can (: Thank you in advance.

答:
Force pushes the body each timestep, while gravity pushes it back down again. There is a function applyLinearImpulse() which pushes it like once with all its "force" before gravity interferention.

When you are using applyForceToCenter() body should be pushed up, but its very slow process compared to impulse.

Title: libGDX - My Box2D Body doesnt jump

Body:
I'm trying to make a little game with the java game engine called libGDX. I already got the player but he can't jump and I dont know why.

This is my GameScreen class:

public class GameScreen extends ScreenManager{
    //For the view of the game and the rendering
    private SpriteBatch batch;
    private OrthographicCamera cam;

    //DEBUG
    private Box2DDebugRenderer b2dr;

    //World, Player and so on
    private GameWorld world;
    private Player player;
    private Ground ground;

    public static float w, h;

    public GameScreen(Game game) {
        super(game);
        //vars
        w = Gdx.graphics.getWidth();
        h = Gdx.graphics.getHeight();

        //view and rendering
        batch = new SpriteBatch();
        cam = new OrthographicCamera();
        cam.setToOrtho(false, w/2, h/2);

        //debug
        b2dr = new Box2DDebugRenderer();

        //world, bodies ...
        player = new Player(world);
        ground = new Ground(world);

    }

    @Override
    public void pause() {

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        //clearing the screen
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        //updating
        update(Gdx.graphics.getDeltaTime());

        //render
        batch.setProjectionMatrix(cam.combined);

        //debug
        b2dr.render(world.getWorld(), cam.combined);

    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }

    @Override
    public void onKlick(float delta) {

    }

    public void update(float delta){
        world.update(delta);
        player.keyInput();
        System.out.println(player.getBody().getPosition().x);
        System.out.println(player.getBody().getPosition().y);
    }

}

and this is my Player class:

public class Player {
    public static Body body;
    public static BodyDef def;
    private FixtureDef fd;

    //set form
    private PolygonShape shape;

    private GameScreen gs;

    public Player(GameWorld world){
        def = new BodyDef();
        def.fixedRotation = true;
        def.position.set(gs.w / 4, gs.h / 4);
        def.type = BodyType.DynamicBody;

        body = world.getWorld().createBody(def);

        shape = new PolygonShape();
        shape.setAsBox(32 / 2, 32 / 2);

        fd = new FixtureDef();
        fd.shape = shape;
        fd.density = 30;

        body.createFixture(fd);
        shape.dispose();
    }

    public static Body getBody() {
        return body;
    }

    public static BodyDef getDef() {
        return def;
    }

    public static void keyInput(){
        if(Gdx.input.isKeyPressed(Input.Keys.UP)){
            body.applyForceToCenter(0, 900, false);
            System.out.println("PRESSED");
        }
    }

}

this finally is my GameWorld class:

public class GameWorld {
    public static World world;

    public GameWorld(){
        world = new World(new Vector2(0f, -10f), false);

    }

    public void update(float delta){
        world.step(1 / 60f, 5, 2);
        System.out.println("WorldUPDATE");
    }

    public static World getWorld() {
        return world;
    }

}

I don't know why the body can't jump please help me if you can (: Thank you in advance.

ContentLicense: CC BY-SA 4.0


答:
Use absolute position to style the dropdown.So the height issue will be fixed.Also don't forgot to add position:relative to the parent li tags.So the dropdown will position relative to the li tags

/* all the CSS needed to make the drop down*/

/* set horizontal navigation for list elements*/
nav ul li {
  display: inline-block;
  position:relative;
}

/*remove padding from nested unordered list to get text to align*/
li > ul {
  padding: 0;
}

/* hide nested list elements*/
li > ul li{
  display: none;
  padding: 0;
}

/* when hovering on the outer list element display nested list elements */
li:hover ul li{
  display: block;
}

/* the following is added just to make the links clear to see*/

/*make text eady to see on dark background*/
li {
  border: 1px coral solid
}

/*highlight the issue with the header bouncing*/
nav {
  background-color: black;
  color: coral;
}

.dropdown{
  position:absolute;
  z-index:999;
  width:100%;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
    <ul>
      <li><a>Link</a></li>

      <li>
        <a>Drop Down</a>
        <ul class="dropdown">
            <li><a>1</a></li>
            <li><a>2</a></li>
            <li><a>3</a></li>
            <li><a>4</a></li>
        </ul>
      </li>

    </ul>
  </nav></code>```

Title: CSS3: how to make a dynamic drop down navigation bar without JS

Body:
Use absolute position to style the dropdown.So the height issue will be fixed.Also don't forgot to add position:relative to the parent li tags.So the dropdown will position relative to the li tags

/* all the CSS needed to make the drop down*/

/* set horizontal navigation for list elements*/
nav ul li {
  display: inline-block;
  position:relative;
}

/*remove padding from nested unordered list to get text to align*/
li > ul {
  padding: 0;
}

/* hide nested list elements*/
li > ul li{
  display: none;
  padding: 0;
}

/* when hovering on the outer list element display nested list elements */
li:hover ul li{
  display: block;
}

/* the following is added just to make the links clear to see*/

/*make text eady to see on dark background*/
li {
  border: 1px coral solid
}

/*highlight the issue with the header bouncing*/
nav {
  background-color: black;
  color: coral;
}

.dropdown{
  position:absolute;
  z-index:999;
  width:100%;
 }

<nav>
    <ul>
      <li><a>Link</a></li>

      <li>
        <a>Drop Down</a>
        <ul class="dropdown">
            <li><a>1</a></li>
            <li><a>2</a></li>
            <li><a>3</a></li>
            <li><a>4</a></li>
        </ul>
      </li>

    </ul>
  </nav>


问:
Get checksum of the source codes in Android library
I am developing an android library and I want to apply a tamper-detection mechanism to my code, since it calls some sensitive financial web services.

What I'm going to implement is to calculate the checksum of the apk ( or important parts of it), programmatically on the runtime, so I can prevent a repackaged or recompiled apk from being able to do any harm (tamper prevention).

What I have come up with so far, is to calculate the checksum of the applicationInfo.publicSourceDir. but I'm not sure what happens with the apps that have multiple dex files or multiple splitApks.

What is the most reliable way to calculate checksum based on the code-base of an application in Android, programmatically?

答: If you distribute via play you might have a look into SafetyNet: https://developer.android.com/training/safetynet/index.html</p>


问:
Does dereferencing a pointer make a copy of it?
Does dereferencing a pointer and passing that to a function which takes its argument by reference create a copy of the object?</p>

答:
In this case the value at the pointer is copied (though this is not necessarily the case as the optimiser may optimise it out).

```<code>int val = *pPtr;
</code>```

In this case however no copy will take place:

```<code>int& rVal = *pPtr;
</code>```

The reason no copy takes place is because a reference is not a machine code level construct.  It is a higher level construct and thus is something the compiler uses internally rather than generating specific code for it.

The same, obviously, goes for function parameters.

Body:
In this case the value at the pointer is copied (though this is not necessarily the case as the optimiser may optimise it out).

int val = *pPtr;

In this case however no copy will take place:

int& rVal = *pPtr;

The reason no copy takes place is because a reference is not a machine code level construct.  It is a higher level construct and thus is something the compiler uses internally rather than generating specific code for it.

The same, obviously, goes for function parameters.


答:
In View :For Arrays to work, name the Radio buttons in format as below for model binding to work

```<code>@using (Html.BeginForm("Index", "Home")) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <input type="radio" name="param[0]" value="one" >
    <input type="radio" name="param[0]" value="two" >
    <input type="radio" name="param[1]" value="three" >
    <input type="radio" name="param[1]" value="four" >
    <input type="radio" name="param[2]" value="five" >
    <input type="radio" name="param[2]" value="six" >
  <input type="submit" value="submit" />
}
</code>```

In Post ActionMethod :

```<code> [HttpPost]
 public ActionResult Index(string[] param)
                { //
    }
</code>```

then you will get the value in param array in the action method.
You can have as many number of Radio buttons as you wish & ModelBinder will take care of the binding.

Title: Passing multi parameters (radio) from view to controller using array

Body:
In View :For Arrays to work, name the Radio buttons in format as below for model binding to work

@using (Html.BeginForm("Index", "Home")) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <input type="radio" name="param[0]" value="one" >
    <input type="radio" name="param[0]" value="two" >
    <input type="radio" name="param[1]" value="three" >
    <input type="radio" name="param[1]" value="four" >
    <input type="radio" name="param[2]" value="five" >
    <input type="radio" name="param[2]" value="six" >
  <input type="submit" value="submit" />
}

In Post ActionMethod :

 [HttpPost]
 public ActionResult Index(string[] param)
                { //
    }

then you will get the value in param array in the action method.
You can have as many number of Radio buttons as you wish & ModelBinder will take care of the binding.


问:
css class not working properly
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h1>Audio Projects</h1>
    <blockquote>
     <h3>

              Class D Amplifier

      </h3>
      <div class="wrapper">
          <div class="left">
              <img src="Damp/Damp_front.JPG"/>
          </div>
          <div class="right">
              Some text that should be next to image
          </div>
      </div>
  </blockquote>
</article></code>```

答:
Your image is probably larger than the .left container (given that this is the only element that is not included in your snippet to test properly).

Try the following ...

```<code>img{
  height: auto;
  width: auto;
  max-height: 100%;
  max-width: 100%;
}
</code>```

... you should probably add a class for that image, rather than styling all images this way.

Title: css class not working properly

Body:
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}

Audio Projects

              Class D Amplifier

              Some text that should be next to image

Body:
Your image is probably larger than the .left container (given that this is the only element that is not included in your snippet to test properly).

Try the following ...

img{
  height: auto;
  width: auto;
  max-height: 100%;
  max-width: 100%;
}

... you should probably add a class for that image, rather than styling all images this way.


问:
Ruby modules for functions
It is possible to add methods to a class using modules. E.g.,

```<code>class Test
  include Singleton
end
</code>```

Is it possible to do the same with methods? E.g.,

```<code>class Test
  include Singleton

  def test
    include Instructions_to_add_to_the_method
    puts 'done'
  end
end
</code>```

where:

```<code>module Instructions_to_add_to_the_method
  puts 'hi !'
end
</code>```

When calling Test.instance.test, I want:

```<code>hi !
done
</code>```

I do not wish to call another method, as it would give me issues with the scope of my variables.

答:
This is probably a terrible idea. Messing with your classes at run-time will make problems hard to debug (which version of that method was I calling there?) and your code hard to follow (oh, right, I can't call that method yet because it's not defined yet, I need to call this method first).

Given what you said at the end of your question about variable scoping, I'm almost certain that this won't solve the problem you actually have, and I'd suggest actually posting your actual problem.

That said, the question you asked can be answered by using the included and extended hooks which, unsurprisingly, fire when a module gets included and extended:

module FooModule
  def self.included(base)
    puts 'FooModule included'
  end

  def self.extended(base)
    puts 'FooModule extended'
  end

  def new_method
    puts 'new method called'
  end
end

class Extender
  def test_extend
    self.extend FooModule
    puts 'done'
  end
end

class Includer
  def test_include
    self.class.include FooModule
    puts 'done'
  end
end

t1 = Extender.new
t2 = Extender.new
t1.test_extend # Prints out "FooModule extended" followed by "done"
t1.new_method # Prints out "new method called"
t2.new_method rescue puts 'error' # Prints out "error" - extend only modifies the instance that calls it

t1 = Includer.new
t2 = Includer.new
t1.test_include # Prints out "FooModule included" followed by "done"
t1.new_method # Prints out "new method called"
t2.new_method # Prints out "new method called" - all past and future instances of Includer have been modified
```

Title: Ruby modules for functions

Body:
It is possible to add methods to a class using modules. E.g.,

class Test
  include Singleton
end

Is it possible to do the same with methods? E.g.,

class Test
  include Singleton

  def test
    include Instructions_to_add_to_the_method
    puts 'done'
  end
end

where:

module Instructions_to_add_to_the_method
  puts 'hi !'
end

When calling Test.instance.test, I want:

hi !
done

I do not wish to call another method, as it would give me issues with the scope of my variables.


问:
Use Django's ORM in Celery
I have a few django micro-services.
Their main workload is constant background processes, not request handling.

The background processes constantly use Django's ORM, and since I needed to hack a few things for it to work properly (it did for quite a while), now I have problems with the DB connection, since Django is not really built for using DB connections a lot in the background I guess...

Celery is always suggested in these cases, but before switching the entire design, I want to know if it really is a good solution.

Can celery tasks (a lot of tasks, time-consuming tasks) use Django's ORM in the background without problems?

答:
Celery was originally written specifically as an offline task processor for Django, and although it was later generalised to deal with any Python code it still works perfectly well with Django.

How many tasks there are and how long they take is pretty much irrelevant to the choice of technology; each Celery worker runs as a separate process, so the limiting resource will be your server capacity.

Title: Use Django's ORM in Celery


问:
perl mojolicious - using flash gives wierd error
The below code is giving the error:

Can't use an undefined value as an ARRAY reference at /usr/local/share/perl/5.22.1/Mojolicious/Controller.pm line 286.

and I am not particularly sure how i'd go about handling it. Especially as it quotes an error in the source code that seems to be related to encryption of cookies. And my application contains no cookies or encryption so that is suprising.

```<code> sub remove {
    my $self = shift;
    my $host_id = $self->stash('host_id');

    $self->hosts->remove($self->stash('host')->{host_id});

    $self->flash(message => 'User created successfully!');
    $self->redirect_to('hosts');
}
</code>```

答:
This most likely happens when you have undef as your secrets. The error comes from the following line:

```<code>my $checksum = Mojo::Util::hmac_sha1_sum($value, $self->app->secrets->[0]);
</code>```

Normally, the secret is pre-generated which is insecure and needs to be defined by you in the config of the app. An example of it being used is in the Mojo::Pg example application:

```<code>{
    pg      => 'postgresql://tester:testing@/test',
    secrets => ['s3cret']
}
</code>```

Which is then consumed by the application itself

```<code>$self->secrets($self->config('secrets'));
</code>```

If your application sets the secrets from a config file but the config file doesn't declare a secrets, or the key has been misspelt, the error you write will be given back whenever you try to set a cookie, such as using the flash.

Body:
The below code is giving the error:

Can't use an undefined value as an ARRAY reference at /usr/local/share/perl/5.22.1/Mojolicious/Controller.pm line 286.

and I am not particularly sure how i'd go about handling it. Especially as it quotes an error in the source code that seems to be related to encryption of cookies. And my application contains no cookies or encryption so that is suprising.

 sub remove {
    my $self = shift;
    my $host_id = $self->stash('host_id');

    $self->hosts->remove($self->stash('host')->{host_id});

    $self->flash(message => 'User created successfully!');
    $self->redirect_to('hosts');
}

Body:
This most likely happens when you have undef as your secrets. The error comes from the following line:

my $checksum = Mojo::Util::hmac_sha1_sum($value, $self->app->secrets->[0]);

Normally, the secret is pre-generated which is insecure and needs to be defined by you in the config of the app. An example of it being used is in the Mojo::Pg example application:

{
    pg      => 'postgresql://tester:testing@/test',
    secrets => ['s3cret']
}

Which is then consumed by the application itself

$self->secrets($self->config('secrets'));

If your application sets the secrets from a config file but the config file doesn't declare a secrets, or the key has been misspelt, the error you write will be given back whenever you try to set a cookie, such as using the flash.


问:
Angular 2 append click button
I have a form that stores an undefined number of pairs: label/value:

```<code><form (submit)=new_answers_for_this_question()>
<div class="row">
    <div class="input-field col m5">
        <input placeholder="Label" id="label" type="text" class="validate">
    </div>
    <div class="input-field col m5">
        <input placeholder="Value" id="values" type="text" class="validate">
    </div>
    <div class="input-field col m2 center-align">
        <button class="btn-floating waves-effect waves-light" (click)="new_answer()"><i class="material-icons">add</i></button>
    </div>
</div>
<button>Insert Answers</button>
</form>
</code>```

I just want to fill both input and then press the add button to add a new line with a new label/value input, previous add button will disappear, and a new button to append a new possible line. Using jQuery is simple as append the full row div on the parent div but using angular I dont know how to handle this, ¿any ideas?

Edit: The purpose is to insert a row per pair of label and value for the same question in the DataBase.

i.e.:

```<code>**Question 1**
Label: 'good', value: '7-10'
Label: 'neutral', Value: '4-6'
Label: 'bad', Value: '1-3'
</code>```

答:
try this

angular.module('submitExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.list = [];

      $scope.submit = function() {
        if ($scope.text) {
          $scope.list.push(this.text);
          $scope.text = '';
        }
      };
    }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

<form ng-submit="submit()" ng-controller="ExampleController">
  Enter text and hit enter:
  <input type="text" ng-model="text" name="text" />
  <input type="submit" id="submit" value="Submit" />
  ```{{list}}```
</form></code>```

Title: Angular 2 append click button

Body:
I have a form that stores an undefined number of pairs: label/value:

<form (submit)=new_answers_for_this_question()>

        <input placeholder="Label" id="label" type="text" class="validate">

        <input placeholder="Value" id="values" type="text" class="validate">

        <button class="btn-floating waves-effect waves-light" (click)="new_answer()">add</button>

<button>Insert Answers</button>
</form>

I just want to fill both input and then press the add button to add a new line with a new label/value input, previous add button will disappear, and a new button to append a new possible line. Using jQuery is simple as append the full row div on the parent div but using angular I dont know how to handle this, ¿any ideas?

Edit: The purpose is to insert a row per pair of label and value for the same question in the DataBase.

i.e.:

**Question 1**
Label: 'good', value: '7-10'
Label: 'neutral', Value: '4-6'
Label: 'bad', Value: '1-3'

Body:
try this

angular.module('submitExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.list = [];

      $scope.submit = function() {
        if ($scope.text) {
          $scope.list.push(this.text);
          $scope.text = '';
        }
      };
    }]);

<form ng-submit="submit()" ng-controller="ExampleController">
  Enter text and hit enter:
  <input type="text" ng-model="text" name="text" />
  <input type="submit" id="submit" value="Submit" />
  <pre>{{list}}</pre>
</form>


问:
view pdf in attachment
how

how to view pdf file on onclick of the button,one text box which i can able to select pdf file one hidden field which i can able to store path of this pdf, when i click a button it should concatenate both file name and path, and display the pdf file in pdf format

答:
Its not text box you should file input element

and attach onclick event to button

that can be done either

or

document.getElementById('pdfDisplayButton').onclick=function(){}

Title: view pdf in attachment


问:
multiple linear regression: error in user defined function
I have written my function for MLR. However, there seems to an issue with output (see examples in the end).

But when I run the code, line by line, the output is correct.

```<code>mlr <- function(dependentvar, dataset) {

x <- model.matrix(dependentvar ~., dataset) # Design Matrix for x

y <- dependentvar # dependent variable

betas <- solve(crossprod(x))%*%crossprod(x,y) # beta values

SST <- t(y)%*%y - (sum(y)^2/dim(dataset)[1]) # total sum of squares

SSres <- t(y)%*%y -(t(betas)%*%crossprod(x,y))  # sum of squares of residuals

SSreg <- SST - SSres  # regression sum of squares

sigmasqr <- SSres/(length(y) - dim(dataset)[2])  # variance or (MSE)

varofbeta <- sigmasqr[1]*solve( crossprod(x)) # variance of beta

cat("SST:", SST,"SSresiduals:", SSres,"SSregression:", SSreg, sep = "\n", append = FALSE)

return(betas)

}
</code>```

To see the problem, try

```<code>mlr(trees$Height, trees)
</code>```

I get the same problem even if I get rid of $

```<code>Height <- trees$Height
mlr(Height, trees)
</code>```

答:
Use the following:

```<code>x <- model.matrix(reformulate(".", dependentvar), dataset)
y <- dataset[[dependentvar]]
</code>```

and pass in dependentvar as a string.

Example:

```<code>mlr("Height", trees)
</code>```

Body:
I have written my function for MLR. However, there seems to an issue with output (see examples in the end).

But when I run the code, line by line, the output is correct.

mlr <- function(dependentvar, dataset) {

x <- model.matrix(dependentvar ~., dataset) # Design Matrix for x

y <- dependentvar # dependent variable

betas <- solve(crossprod(x))%*%crossprod(x,y) # beta values

SST <- t(y)%*%y - (sum(y)^2/dim(dataset)[1]) # total sum of squares

SSres <- t(y)%*%y -(t(betas)%*%crossprod(x,y))  # sum of squares of residuals

SSreg <- SST - SSres  # regression sum of squares

sigmasqr <- SSres/(length(y) - dim(dataset)[2])  # variance or (MSE)

varofbeta <- sigmasqr[1]*solve( crossprod(x)) # variance of beta

cat("SST:", SST,"SSresiduals:", SSres,"SSregression:", SSreg, sep = "\n", append = FALSE)

return(betas)

}

To see the problem, try

mlr(trees$Height, trees)

I get the same problem even if I get rid of $

Height <- trees$Height
mlr(Height, trees)

Body:
Use the following:

x <- model.matrix(reformulate(".", dependentvar), dataset)
y <- dataset[[dependentvar]]

and pass in dependentvar as a string.

Example:

mlr("Height", trees)


问:
select a string from file csh
I have a file file.dat as follow:

```<code>1.1,2.1 1.4
3.1,2.1 2.4
2.4,4.5 11.5
..
</code>```

And I want to select each time the whole line (string) and replace it in another file. So far I tried the following

```<code>#!/bin/csh

set FILENAME = 'file.dat' # file in which the strings are
set str = "229.8,230.9 230.36" # initialize the first string
set n = 1
while ( $n <= 3 ) # number of lines in the FILENAME
   echo Testing the first string $str
   set rep = $(head -n $n "$FILENAME")
   @ n++ # increment the index
end
</code>```

When I tried to launch the script csh launch.sh I obtained the follow error message

```<code>Testing the first string 229.8,230.9 230.36
Illegal variable name. # connect with the rep definition(?)
</code>```

The file in which I want to change the string str is as follow (this is btw a secondary problem which I could figure out by myself once I understand what's wrong in the first lines):

```<code># Name    Type Par
Mi        FI   154.2355189465
So        UN   229.8,230.9 230.36 # line to be changed
Za        FI   0.8000020209
</code>```

May somebody help me, please?

答:
$(...) is Bash syntax for command substitution in Bash.

In C-shell you have to use backticks instead (yuck).

Title: select a string from file csh

Body:
I have a file file.dat as follow:

1.1,2.1 1.4
3.1,2.1 2.4
2.4,4.5 11.5
..

And I want to select each time the whole line (string) and replace it in another file. So far I tried the following

#!/bin/csh

set FILENAME = 'file.dat' # file in which the strings are
set str = "229.8,230.9 230.36" # initialize the first string
set n = 1
while ( $n <= 3 ) # number of lines in the FILENAME
   echo Testing the first string $str
   set rep = $(head -n $n "$FILENAME")
   @ n++ # increment the index
end

When I tried to launch the script csh launch.sh I obtained the follow error message

Testing the first string 229.8,230.9 230.36
Illegal variable name. # connect with the rep definition(?)

The file in which I want to change the string str is as follow (this is btw a secondary problem which I could figure out by myself once I understand what's wrong in the first lines):

# Name    Type Par
Mi        FI   154.2355189465
So        UN   229.8,230.9 230.36 # line to be changed
Za        FI   0.8000020209

May somebody help me, please?


问:
How to make a CakePHP3 login with username only
So i wanted to do a very basic authentication , and by following the Blog tutorial on https://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html i tried to make it only use Username to log in, but the login system doesn't work because

```<code>$user = $this->Auth->identify();
</code>```

Always returns false, I have searched cake's documentation on Authentication but can't find anything to help me.
Can someone tell me how do to make a costum login authentication.

Current login action:

```<code>  public function login()
  {
      if ($this->request->is('post')) {
          $user = $this->Auth->identify();
          if ($user) {
              $this->Auth->setUser($user);
              return $this->redirect($this->Auth->redirectUrl());
          }
          $this->Flash->error(__('Invalid username, try again'));
      }
  }
</code>```

And its View:

```<code><div class="users form">
<?= $this->Flash->render() ?>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username') ?></legend>
        <?= $this->Form->control('username') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
</code>```

AuthComponent Init:

```<code>  public function initialize(array $config)
{
    $controller = $this->_registry->getController();
    $this->eventManager($controller->eventManager());
    $this->response =& $controller->response;
    $this->session = $controller->request->session();
}
</code>```

答:
AFAIK, CakePHP doesn't have a method of logging in a user by just the username. I'm providing an example of what the could could/would look like. This is off the top of my head and in no way tested.</p>

```<code>   public function login() {
        if($this->request->is(['post'])) {
            if ($this->Users->exists(['username' => $this->request->getData('username')])) {
                $user = $this->Users->findByUsername($this->request->getData('username'))->first()->toArray();
                $this->Auth->setUser($user);
            }
        }
    }
</code>```

Body:
So i wanted to do a very basic authentication , and by following the Blog tutorial on https://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html i tried to make it only use Username to log in, but the login system doesn't work because

$user = $this->Auth->identify();

Always returns false, I have searched cake's documentation on Authentication but can't find anything to help me.
Can someone tell me how do to make a costum login authentication.

Current login action:

  public function login()
  {
      if ($this->request->is('post')) {
          $user = $this->Auth->identify();
          if ($user) {
              $this->Auth->setUser($user);
              return $this->redirect($this->Auth->redirectUrl());
          }
          $this->Flash->error(__('Invalid username, try again'));
      }
  }

And its View:

<?= $this->Flash->render() ?>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username') ?></legend>
        <?= $this->Form->control('username') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>

AuthComponent Init:

  public function initialize(array $config)
{
    $controller = $this->_registry->getController();
    $this->eventManager($controller->eventManager());
    $this->response =& $controller->response;
    $this->session = $controller->request->session();
}

Body:
AFAIK, CakePHP doesn't have a method of logging in a user by just the username. I'm providing an example of what the could could/would look like. This is off the top of my head and in no way tested.

   public function login() {
        if($this->request->is(['post'])) {
            if ($this->Users->exists(['username' => $this->request->getData('username')])) {
                $user = $this->Users->findByUsername($this->request->getData('username'))->first()->toArray();
                $this->Auth->setUser($user);
            }
        }
    }


问:
How to copy one hundred files from folder to folder?
I have one million files in one folder, I want to copy just one hundred files from them in another folder: </p>

```<code>import os
import shutil

dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")

for filename in os.listdir(dir_src):
    shutil.copy( dir_src + filename, dir_dst)
    print(filename)
</code>```

<p>This script copy for me all files, how to copy just 100000 files please? </p>

答:
Indexing your list will allow you to perform actions on the nth (or i in this case) iteration.</p>

```<code>import os
import shutil

dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")

dirList = os.listdir(dir_src)
for i in range(len(dirList)):
  if i == 100:
    break
  shutil.copy(dir_src + dirList[i], dir_dst)
  print(filename)
</code>```

Body:
I have one million files in one folder, I want to copy just one hundred files from them in another folder:

import os
import shutil

dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")

for filename in os.listdir(dir_src):
    shutil.copy( dir_src + filename, dir_dst)
    print(filename)

This script copy for me all files, how to copy just 100000 files please?

Body:
Indexing your list will allow you to perform actions on the nth (or i in this case) iteration.

import os
import shutil

dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")

dirList = os.listdir(dir_src)
for i in range(len(dirList)):
  if i == 100:
    break
  shutil.copy(dir_src + dirList[i], dir_dst)
  print(filename)