问:
Wpf binding update happens too late
I use MVVM. There is a slow command. I want to use a log to indicate where is the execution.
xaml:

```<code> <TextBlock Height="200" Text="{Binding Log.Content, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</code>```

code:

```<code>Log.addLine("Ledger initialized.");
// slow1 operation
Log.addLine("slow1 operation.");
</code>```

The textblock is only updated when the whole command is finished. Both message appears at the same time when the GUI is active.

答:
In this example I used async/await to keep the UI responsive so that it is able to update itself at any time.
Otherwise the long running task would have to complete before any update can occur.

Because the long running task was started synchronously on the UI thread before  (in your example), the thread was busy executing your method, so no resources have been available to refresh the UI. Executing the method asynchronously executes it on a different thread so that the UI thread is free to execute UI related operations e.g. rendering or updating bindings.

Example

The view:

```<code>    <Window x:Class="TestRange.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:TestRange"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <local:ViewModel x:Key="ViewModel" />
        </Window.Resources>
        <StackPanel DataContext="{StaticResource ViewModel}">
            <Button Content="Long Running Task" Command="{Binding LongRunningCommand}" />
            <TextBlock Text="{Binding Text}" />
        </StackPanel>
</Window>
</code>```

The ViewModel:

```<code>class ViewModel : INotifyPropertyChanged
  {
    public ViewModel()
    {
    }

    public ICommand LongRunningCommand => new RelayCommand(
      async (param) => await this.LongRunningTaskAsync().ConfigureAwait(false), (param) => true);

    public async Task LongRunningTaskAsync()
    {
      await Task.Run(
        () =>
        {
          for (int i = 0; i < 3; i++)
          {
            Thread.Sleep(5000);
            this.Text = $"Iteration #{i + 1}  completed";
          }
        });
    }

    private string text;
    public string Text
    {
      get { return this.text; }
      set
      {
        this.text = value;
        OnPropertyChanged();
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
  }
</code>```

Title: Wpf binding update happens too late

Body:
I use MVVM. There is a slow command. I want to use a log to indicate where is the execution.
xaml:

 <TextBlock Height="200" Text="{Binding Log.Content, UpdateSourceTrigger=PropertyChanged}"></TextBlock>

code:

Log.addLine("Ledger initialized.");
// slow1 operation
Log.addLine("slow1 operation.");

The textblock is only updated when the whole command is finished. Both message appears at the same time when the GUI is active.

Body:
In this example I used async/await to keep the UI responsive so that it is able to update itself at any time.
Otherwise the long running task would have to complete before any update can occur.

Because the long running task was started synchronously on the UI thread before  (in your example), the thread was busy executing your method, so no resources have been available to refresh the UI. Executing the method asynchronously executes it on a different thread so that the UI thread is free to execute UI related operations e.g. rendering or updating bindings.

Example

The view:

    <Window x:Class="TestRange.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:TestRange"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <local:ViewModel x:Key="ViewModel" />
        </Window.Resources>
        <StackPanel DataContext="{StaticResource ViewModel}">
            <Button Content="Long Running Task" Command="{Binding LongRunningCommand}" />
            <TextBlock Text="{Binding Text}" />
        </StackPanel>
</Window>

The ViewModel:

class ViewModel : INotifyPropertyChanged
  {
    public ViewModel()
    {
    }

    public ICommand LongRunningCommand => new RelayCommand(
      async (param) => await this.LongRunningTaskAsync().ConfigureAwait(false), (param) => true);

    public async Task LongRunningTaskAsync()
    {
      await Task.Run(
        () =>
        {
          for (int i = 0; i < 3; i++)
          {
            Thread.Sleep(5000);
            this.Text = $"Iteration #{i + 1}  completed";
          }
        });
    }

    private string text;
    public string Text
    {
      get { return this.text; }
      set
      {
        this.text = value;
        OnPropertyChanged();
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
  }


来源: stackexchange

问:
How to index objects in For loop in R
I am trying to index "model" object so that I can choose the model with best fit right after. The result I would like to see is: model[i,j]. If I try to index it says:
"Error in model[i, j] <- glm(newcol ~ ., data = mod_data[c(mod_tab_new)],:incorrect number of subscripts on matrix"

here is the code:

```<code>rm(list = ls())

mod_data <- NULL
mod_data$Sex <- sample(0:1, size = 1000, replace = T)
mod_data$Age <- sample(18:99, size = 1000, replace = T)
mod_data <- data.frame(mod_data)

mod_data$newcol <- sample(0:1, size = nrow(mod_data), replace = T)

mod_headers <- names(mod_data[1:ncol(mod_data)-1])

f <- function(mod_headers){
  for(i in 1:length(mod_headers)){
    tab <- combn(mod_headers,i)
    for(j in 1:ncol(tab)){
      tab_new <- c(tab[,j])
      mod_tab_new <- c(tab_new, "newcol")
      model[i,j] <- glm(newcol ~., data=mod_data[c(mod_tab_new)], family = binomial(link = "logit"))
    }
  }
}

f(mod_headers)
</code>```

Thanks for the suggestions.

答:
Is this what you wanted?

```<code>f <- function(mod_headers){

model <- list()

for(i in 1:length(mod_headers)){
   tab <- combn(mod_headers,i)
   model[[i]] <- list()

      for(j in 1:ncol(tab)){

       tab_new <- c(tab[,j])
       mod_tab_new <- c(tab_new, "newcol")
       model[[i]][[j]] <- glm(newcol ~., data=mod_data[c(mod_tab_new)], family = binomial(link = "logit"))
   }
  }

model
}
</code>```

Always before a forloop where you intend to fill a data structure with values you have to define the data structure first. In this case I made a list and filled it with the glm objects.

ContentLicense: CC BY-SA 3.0

Title: How to index objects in For loop in R

Body:
I am trying to index "model" object so that I can choose the model with best fit right after. The result I would like to see is: model[i,j]. If I try to index it says:
"Error in model[i, j] <- glm(newcol ~ ., data = mod_data[c(mod_tab_new)],:incorrect number of subscripts on matrix"

here is the code:

rm(list = ls())

mod_data <- NULL
mod_data$Sex <- sample(0:1, size = 1000, replace = T)
mod_data$Age <- sample(18:99, size = 1000, replace = T)
mod_data <- data.frame(mod_data)

mod_data$newcol <- sample(0:1, size = nrow(mod_data), replace = T)

mod_headers <- names(mod_data[1:ncol(mod_data)-1])

f <- function(mod_headers){
  for(i in 1:length(mod_headers)){
    tab <- combn(mod_headers,i)
    for(j in 1:ncol(tab)){
      tab_new <- c(tab[,j])
      mod_tab_new <- c(tab_new, "newcol")
      model[i,j] <- glm(newcol ~., data=mod_data[c(mod_tab_new)], family = binomial(link = "logit"))
    }
  }
}

f(mod_headers)

Thanks for the suggestions.

Body:
Is this what you wanted?

f <- function(mod_headers){

model <- list()

for(i in 1:length(mod_headers)){
   tab <- combn(mod_headers,i)
   model[[i]] <- list()

      for(j in 1:ncol(tab)){

       tab_new <- c(tab[,j])
       mod_tab_new <- c(tab_new, "newcol")
       model[[i]][[j]] <- glm(newcol ~., data=mod_data[c(mod_tab_new)], family = binomial(link = "logit"))
   }
  }

model
}

Always before a forloop where you intend to fill a data structure with values you have to define the data structure first. In this case I made a list and filled it with the glm objects.


问:
wordpress if/else php conditional logic --- ignore if logged in, only work on these two pages
Can anybody point me in the right direction here. I have tried googling but can't find my exact use case.

I am having an issue editing a page using beaver builder when I am running chatra & proof on the site. so i am trying to use conditionals so that if a user is logged in do nothing and if you arent logged in and you are page x and y run the two app scripts.

The conditional i have now hides the scripts from admin (woohoo!) and displays them on pages ----but not only on the two pages listed.
here is the code i'm using :

https://gist.github.com/llamedia/30387f0913202f771b8299e3837e53d3

Am I barking up the wrong tree?

答:
! operator negates logical result of is_user_logged_in() method.

&& operator has meaning of logical AND.

So, If you want to add something to page when user is not logged in and is browsing page with ID 9 or 14, you should write this:

```<code><?php if (!is_user_logged_in() && (is_page(9) || is_page(14))): ?>
    <!-- user is not logged in and is browsing page 9 or 14 -->
    <script src="..."></script>
<?php endif; ?>
</code>```

To read more about PHP operators I suggest reading official PHP manual.

Body:
! operator negates logical result of is_user_logged_in() method.

&& operator has meaning of logical AND.

So, If you want to add something to page when user is not logged in and is browsing page with ID 9 or 14, you should write this:

<?php if (!is_user_logged_in() && (is_page(9) || is_page(14))): ?>
    <!-- user is not logged in and is browsing page 9 or 14 -->
    <script src="..."></script>
<?php endif; ?>

To read more about PHP operators I suggest reading official PHP manual.


问:
placeholder in termcolor python
I'm working on sentiments challenge for CS50 and I want to print in the console with color using Termcolor and placeholders but I have some problem.

This is my code:

```<code>    if score > 0:
        green = lambda x: colored(x, 'green')
        print(green("1 ", tweets))
    elif score < 0:
        red = lambda x: colored(x, 'red')
        print(red(tweets))
    else:
        yellow = lambda x: colored(x, 'yellow')
        print(yellow(tweets))
</code>```

I want to print the tweet based on the score (green, red or yellow) and that's ok, the code works well with lambda x, but I want also to print a number before the tweet in the same color.

I've tried lambda x, y but I have an error:

```<code>if score > 0:
   green = lambda x, y: colored(x, y, 'green')
   print(green("1 ", tweets))

Traceback (most recent call last):
File "./tweets", line 47, in <module>
  main()
File "./tweets", line 39, in main
  print(green("1 ", tweets))
File "./tweets", line 38, in <lambda>
  green = lambda x, y: colored(x, y, 'green')
File "/usr/lib/python3/dist-packages/termcolor.py", line 105, in colored
text = fmt_str % (COLORS[color], text)
  KeyError: 'Building Augmented Reality Experiences with Unity3D (and @Microsoft @HoloLens)  by @shekitup at @CS50 at @Harvard,'
</code>```

This is what I want to print:

```<code>1 + (tweets) in green if positive
-1 + (tweets) in red if negative
0 + (tweets) in yellow if neutral
</code>```

答:
does this way makes sense with your code ?

(This syntax works only for python >= 3.5, unpacked parameters should be the last to avoid ambiguity in prior versions)

```<code>if score > 0:
   green = lambda x: colored(*x, 'green')
   print(green(["1 ", tweets]))
</code>```

You pass a list of parameter, tweet alone, or number and tweet, and then it's unpack in the lambda

Title: placeholder in termcolor python

Body:
I'm working on sentiments challenge for CS50 and I want to print in the console with color using Termcolor and placeholders but I have some problem.

This is my code:

    if score > 0:
        green = lambda x: colored(x, 'green')
        print(green("1 ", tweets))
    elif score < 0:
        red = lambda x: colored(x, 'red')
        print(red(tweets))
    else:
        yellow = lambda x: colored(x, 'yellow')
        print(yellow(tweets))

I want to print the tweet based on the score (green, red or yellow) and that's ok, the code works well with lambda x, but I want also to print a number before the tweet in the same color.

I've tried lambda x, y but I have an error:

if score > 0:
   green = lambda x, y: colored(x, y, 'green')
   print(green("1 ", tweets))

Traceback (most recent call last):
File "./tweets", line 47, in <module>
  main()
File "./tweets", line 39, in main
  print(green("1 ", tweets))
File "./tweets", line 38, in <lambda>
  green = lambda x, y: colored(x, y, 'green')
File "/usr/lib/python3/dist-packages/termcolor.py", line 105, in colored
text = fmt_str % (COLORS[color], text)
  KeyError: 'Building Augmented Reality Experiences with Unity3D (and @Microsoft @HoloLens)  by @shekitup at @CS50 at @Harvard,'

This is what I want to print:

1 + (tweets) in green if positive
-1 + (tweets) in red if negative
0 + (tweets) in yellow if neutral

Body:
does this way makes sense with your code ?

(This syntax works only for python >= 3.5, unpacked parameters should be the last to avoid ambiguity in prior versions)

if score > 0:
   green = lambda x: colored(*x, 'green')
   print(green(["1 ", tweets]))

You pass a list of parameter, tweet alone, or number and tweet, and then it's unpack in the lambda


问:
How can one use regex to capture the text occurring between lines beginning with a single semicolon?
I want to capture the text between lines which begin with single semicolons:

sample input:

```<code>s = '''
;

the color blue

;

the color green

;

the color red

;
'''
</code>```

this is the desired output:

```<code>['the color blue', 'the color green', 'the color red']
</code>```

this attempted solution doesn't work:

```<code>import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)
</code>```

this is the wrong output:

```<code>['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']
</code>```

答:
You can have this as the pattern:

```<code>pat = r';\n\n([\w* *]*)'

r = re.findall(pat, s)
</code>```

That should capture what you need.

Body:
I want to capture the text between lines which begin with single semicolons:

sample input:

s = '''
;

the color blue

;

the color green

;

the color red

;
'''

this is the desired output:

['the color blue', 'the color green', 'the color red']

this attempted solution doesn't work:

import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)

this is the wrong output:

['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']

Body:
You can have this as the pattern:

pat = r';\n\n([\w* *]*)'

r = re.findall(pat, s)

That should capture what you need.


问:
Find which phrases have at most one capital letter
I am using RegEx (php) to find out which Addresses have one or less capital letters. For example:

av. St Joan 128 (Not match)

Av. st joan 122 (match)

av. St joan 212 (match)

Av. St.joan 121 (Not match)

AV. st joan 232 (Not match)

答:
I assume you just need pattern not php code, otherwise comment me please to delete the answer.

A simple negative lookahead assertion:

```<code>^(?!.*[A-Z].*[A-Z]).*$
</code>```

It does not match any entire line that has more than one capital letter.

And as you commented:

I need a regex to find out which of the address have one or less,ie, no capital letter

It also matches no capital letter

So it just matches lines with just one capital letter or matches lines with no capital letter

for the input:

```<code>av. St Joan 128 (Not maach) | more than one
Av. st joan 122 (match)     | just one
av. St joan 212 (match)     | just one
Av. St.joan 121 (Not match) | more than one
AV. st joan 232 (Not match) | more than one
av. tt joan 212 (match)     | no one
</code>```

the output is:

```<code>Av. st joan 122 (match)     | just one
av. St joan 212 (match)     | just one
av. tt joan 212 (match)     | no one
</code>```

^(?!.*[A-Z].*[A-Z]).*$

NOTE:
for inverting the match, you can simply change ?! to ?=:

```<code>^(?=.*[A-Z].*[A-Z]).*$
</code>```

And it matches:

```<code>av. St Joan 128 (Not maach) | more than one
Av. St.joan 121 (Not match) | more than one
AV. st joan 232 (Not match) | more than one
</code>```

Body:
I assume you just need pattern not php code, otherwise comment me please to delete the answer.

A simple negative lookahead assertion:

^(?!.*[A-Z].*[A-Z]).*$

It does not match any entire line that has more than one capital letter.

And as you commented:

I need a regex to find out which of the address have one or less,ie, no capital letter

It also matches no capital letter

So it just matches lines with just one capital letter or matches lines with no capital letter

for the input:

av. St Joan 128 (Not maach) | more than one
Av. st joan 122 (match)     | just one
av. St joan 212 (match)     | just one
Av. St.joan 121 (Not match) | more than one
AV. st joan 232 (Not match) | more than one
av. tt joan 212 (match)     | no one

the output is:

Av. st joan 122 (match)     | just one
av. St joan 212 (match)     | just one
av. tt joan 212 (match)     | no one

^(?!.*[A-Z].*[A-Z]).*$

NOTE:
for inverting the match, you can simply change ?! to ?=:

^(?=.*[A-Z].*[A-Z]).*$

And it matches:

av. St Joan 128 (Not maach) | more than one
Av. St.joan 121 (Not match) | more than one
AV. st joan 232 (Not match) | more than one


问:
C Man or manual in text or other format to use in command line shell in linux
Im looking for some kind of C text manual or man pages for C syntax or cockbook
which i can check in command line shell mode .
Thanks </p>

答: The man page for "C" syntax alone would be huge :-) "The C Programming Language" by Kernighan & Ritchie is still a thorough and readable way to learn C.</p>


问:
How to display each block once in javascript
This is my code and I would like to display each block of 10 links in the right environment each time. First 10 lines are displayed correctly but then, the second time first 10 lines are displayed again + second 10 lines and so on. Can you please tell me what am I doing wrong?

I have an object called config which has two more object inside advertisers and env.
The advertisers object has advertisers as properties and each advertiser has locales, hotel_id and partner_id. The env has 3 different environments.

```<code>for (var prop in config.advertisers) {
  var partner= (`${prop}`);
  var locales_number = config.advertisers[partner].locales.length;

  var partner_folder = "<br>"+partner + "<br>"
  document.write(partner_folder);

    for (var prop in config.env)
    {
     var environment = (`${prop}`);

        var envrironment_text = "<br>"+environment + "<br>"

        document.write(envrironment_text);

        for (i = 0; i < config.advertisers[partner].hotel_id.length; i+locales_number)
        {

            for (j = 0; j < config.advertisers[partner].locales.length; j++) {

                var hotel_id = config.advertisers[partner].hotel_id[i];
                var locales = config.advertisers[partner].locales[j];

                link+= config.env[environment] + config.advertisers[partner].partner_id;
                link+= "/" + locales ;
                link+="/hotel/show?h[hotelId]=";
                link+=hotel_id+ "<br>";
                i++;
                if (i >= 10) { break; }
                }
        }
    document.write(link);
    }
</code>```

答:
Well you must reset your link variable for each environment iteration. Yo can do this just after your document.write instruction.</p>

```<code>document.write(link);
//variable reset
link = '';
</code>```

Body:
This is my code and I would like to display each block of 10 links in the right environment each time. First 10 lines are displayed correctly but then, the second time first 10 lines are displayed again + second 10 lines and so on. Can you please tell me what am I doing wrong?

I have an object called config which has two more object inside advertisers and env.
The advertisers object has advertisers as properties and each advertiser has locales, hotel_id and partner_id. The env has 3 different environments.

for (var prop in config.advertisers) {
  var partner= (`${prop}`);
  var locales_number = config.advertisers[partner].locales.length;

  var partner_folder = "
"+partner + "
"
  document.write(partner_folder);

    for (var prop in config.env)
    {
     var environment = (`${prop}`);

        var envrironment_text = "
"+environment + "
"

        document.write(envrironment_text);

        for (i = 0; i < config.advertisers[partner].hotel_id.length; i+locales_number)
        {

            for (j = 0; j < config.advertisers[partner].locales.length; j++) {

                var hotel_id = config.advertisers[partner].hotel_id[i];
                var locales = config.advertisers[partner].locales[j];

                link+= config.env[environment] + config.advertisers[partner].partner_id;
                link+= "/" + locales ;
                link+="/hotel/show?h[hotelId]=";
                link+=hotel_id+ "
";
                i++;
                if (i >= 10) { break; }
                }
        }
    document.write(link);
    }

Body:
Well you must reset your link variable for each environment iteration. Yo can do this just after your document.write instruction.

document.write(link);
//variable reset
link = '';


问:
Django (v1.11.3) UnorderedObjectListWarning even though list is ordered
I keep running into Django's UnorderedObjectListWarning when trying to display model instances in a paginated view for search results. However, there is a default ordering defined in the models.py file:

```<code>class Rfc(models.Model):
    class Meta:
        verbose_name='RFC'
        verbose_name_plural='RFCs'
        ordering=['number']
</code>```

The actual search happens in views.py and is defined as follows:

```<code># parse GET parameters
search_term = request.GET.get('q', '')
category = request.GET.get('c', 'cs')
page = request.GET.get('p', 1)

...

results_rfc = Rfc.objects.filter(
    Q(title__icontains=search_term) | Q(number__icontains=search_term)
)

if category=='cs':
    active_tab = 'cs'
    results = results_cs
else:
    active_tab = 'rfc'
    results = results_rfc

paginator = Paginator(results, 15)
</code>```

However, I cannot seem to make it work, even when explicitly telling Django to order_by('number') in the filter function above. The result is always:

```<code>UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'directory.models.Rfc'> QuerySet.
paginator = Paginator(results, 15)
</code>```

What baffles me even more is that this warning is not displayed when executing above code in manage.py shell. Clearly, I am missing something here. Any ideas?

答: Ugh.. so this is embarrassing: turns out that yes indeed, the object_list was sorted all along, but there was a copy of a faulty, older version of the view function at the bottom of the file, which of cause overwrote the first one's results.</p>

Body:
I keep running into Django's UnorderedObjectListWarning when trying to display model instances in a paginated view for search results. However, there is a default ordering defined in the models.py file:

class Rfc(models.Model):
    class Meta:
        verbose_name='RFC'
        verbose_name_plural='RFCs'
        ordering=['number']

The actual search happens in views.py and is defined as follows:

# parse GET parameters
search_term = request.GET.get('q', '')
category = request.GET.get('c', 'cs')
page = request.GET.get('p', 1)

...

results_rfc = Rfc.objects.filter(
    Q(title__icontains=search_term) | Q(number__icontains=search_term)
)

if category=='cs':
    active_tab = 'cs'
    results = results_cs
else:
    active_tab = 'rfc'
    results = results_rfc

paginator = Paginator(results, 15)

However, I cannot seem to make it work, even when explicitly telling Django to order_by('number') in the filter function above. The result is always:

UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'directory.models.Rfc'> QuerySet.
paginator = Paginator(results, 15)

What baffles me even more is that this warning is not displayed when executing above code in manage.py shell. Clearly, I am missing something here. Any ideas?


问:
Why does Visual Studio give you Page_Load for WebForms as a default?
When creating a new WebForm, Visual Studios creates a Page_Load handler in the code behind as a default, which is cool.  So for years, I have always put code for doing things like set properties of controls in Page_Load.  Recently, I used Reflector to look at some assemblies written by Microsoft and saw that they have put the same type of logic in a method called OnLoad (which supposedly raises the load event).  So I started to wonder, where is the best place really to set the properties of controls, in OnLoad or Page_Load?  Or in a different method altogether?  And if not Page_Load, why does Studio add that to the code behind?

My final thought:  Although I know that putting logic in OnLoad works fine, I will probably stick with Page_Load for now because that's conventional.  I asked the question really to find out if I had been missing out on something new after I started seeing OnLoad come up in other people's code.  Thank you all for your thoughtful answers!

答: All very valid points so far.  But don't let these guys scare you.  You won't hurt anything if you want to use the OnLoad method.  Just don't forget to call base.OnLoad().</p>

OwnerDisplayName: Barneytron

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Barneytron

OwnerDisplayName: Al W


答:
To exclude 3 columns while importing, you could do:</p>

```<code>data = pd.read_csv(
 sourceFileName,
 usecols=lambda col: col not in ["Country Name","Indicator Name","Counterpart Country Name"]
)
</code>```

Title: Exclude columns while importing csv to python dataframe

Body:
I was importing 2GB CSV file with 600 columns to dataframe but it gives memory error every time. Now I want to remove some columns while importing.

Please let me know how to achieve this.

My code:

sourceFileName=r'C:\sunil_plus\dataset\a3rfghj.csv'
data = pd.read_csv(sourceFileName,dtype=object)

Sample Data:

"Country Name","Country Code","Indicator Name","Indicator Code","Counterpart Country Name","Counterpart Country Code",Attribute,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1960Q1,1960M1,1960M2,1960M3,1960Q2,1960M4,1960M5,1960M6,1960Q3,1960M7,1960M8,1960M9,1960Q4,1960M10,1960M11,1960M12,1961,1961Q1,1961M1,1961M2,1961M3,1961Q2,1961M4,1961M5,1961M6,1961Q3,1961M7,1961M8,1961M9,1961Q4,1961M10,1961M11,1961M12,1962,1962Q1,1962M1,1962M2,1962M3,1962Q2,1962M4,1962M5,1962M6,1962Q3,1962M7,1962M8,1962M9,1962Q4,1962M10,1962M11,1962M12,1963,1963Q1,1963M1,1963M2,1963M3,1963Q2,1963M4,1963M5,1963M6,1963Q3,1963M7,1963M8,1963M9,1963Q4,1963M10,1963M11,1963M12,1964,1964Q1,1964M1,1964M2,1964M3,1964Q2,1964M4,1964M5,1964M6,1964Q3,1964M7,1964M8,1964M9,1964Q4,1964M10,1964M11,1964M12,1965,1965Q1,1965M1,1965M2,1965M3,1965Q2,1965M4,1965M5,1965M6,1965Q3,1965M7,1965M8,1965M9,1965Q4,1965M10,1965M11,1965M12,1966,1966Q1,1966M1,1966M2,1966M3,1966Q2,1966M4,1966M5,1966M6,1966Q3,1966M7,1966M8,1966M9,1966Q4,1966M10,1966M11,1966M12,1967,1967Q1,1967M1,1967M2,1967M3,1967Q2,1967M4,1967M5,1967M6,1967Q3,1967M7,1967M8,1967M9,1967Q4,1967M10,1967M11,1967M12,1968,1968Q1,1968M1,1968M2,1968M3,1968Q2,1968M4,1968M5,1968M6,1968Q3,1968M7,1968M8,1968M9,1968Q4,1968M10,1968M11,1968M12,1969,1969Q1,1969M1,1969M2,1969M3,1969Q2,1969M4,1969M5,1969M6,1969Q3,1969M7,1969M8,1969M9,1969Q4,1969M10,1969M11,1969M12,1970,1970Q1,1970M1,1970M2,1970M3,1970Q2,1970M4,1970M5,1970M6,1970Q3,1970M7,1970M8,1970M9,1970Q4,1970M10,1970M11,1970M12,1971,1971Q1,1971M1,1971M2,1971M3,1971Q2,1971M4,1971M5,1971M6,1971Q3,1971M7,1971M8,1971M9,1971Q4,1971M10,1971M11,1971M12,1972,1972Q1,1972M1,1972M2,1972M3,1972Q2,1972M4,1972M5,1972M6,1972Q3,1972M7,1972M8,1972M9,1972Q4,1972M10,1972M11,1972M12,1973,1973Q1,1973M1,1973M2,1973M3,1973Q2,1973M4,1973M5,1973M6,1973Q3,1973M7,1973M8,1973M9,1973Q4,1973M10,1973M11,1973M12,1974,1974Q1,1974M1,1974M2,1974M3,1974Q2,1974M4,1974M5,1974M6,1974Q3,1974M7,1974M8,1974M9,1974Q4,1974M10,1974M11,1974M12,1975,1975Q1,1975M1,1975M2,1975M3,1975Q2,1975M4,1975M5,1975M6,1975Q3,1975M7,1975M8,1975M9,1975Q4,1975M10,1975M11,1975M12,1976,1976Q1,1976M1,1976M2,1976M3,1976Q2,1976M4,1976M5,1976M6,1976Q3,1976M7,1976M8,1976M9,1976Q4,1976M10,1976M11,1976M12,1977,1977Q1,1977M1,1977M2,1977M3,1977Q2,1977M4,1977M5,1977M6,1977Q3,1977M7,1977M8,1977M9,1977Q4,1977M10,1977M11,1977M12,1978,1978Q1,1978M1,1978M2,1978M3,1978Q2,1978M4,1978M5,1978M6,1978Q3,1978M7,1978M8,1978M9,1978Q4,1978M10,1978M11,1978M12,1979,1979Q1,1979M1,1979M2,1979M3,1979Q2,1979M4,1979M5,1979M6,1979Q3,1979M7,1979M8,1979M9,1979Q4,1979M10,1979M11,1979M12,1980,1980Q1,1980M1,1980M2,1980M3,1980Q2,1980M4,1980M5,1980M6,1980Q3,1980M7,1980M8,1980M9,1980Q4,1980M10,1980M11,1980M12,1981,1981Q1,1981M1,1981M2,1981M3,1981Q2,1981M4,1981M5,1981M6,1981Q3,1981M7,1981M8,1981M9,1981Q4,1981M10,1981M11,1981M12,1982,1982Q1,1982M1,1982M2,1982M3,1982Q2,1982M4,1982M5,1982M6,1982Q3,1982M7,1982M8,1982M9,1982Q4,1982M10,1982M11,1982M12,1983,1983Q1,1983M1,1983M2,1983M3,1983Q2,1983M4,1983M5,1983M6,1983Q3,1983M7,1983M8,1983M9,1983Q4,1983M10,1983M11,1983M12,1984,1984Q1,1984M1,1984M2,1984M3,1984Q2,1984M4,1984M5,1984M6,1984Q3,1984M7,1984M8,1984M9,1984Q4,1984M10,1984M11,1984M12,1985,1985Q1,1985M1,1985M2,1985M3,1985Q2,1985M4,1985M5,1985M6,1985Q3,1985M7,1985M8,1985M9,1985Q4,1985M10,1985M11,1985M12,1986,1986Q1,1986M1,1986M2,1986M3,1986Q2,1986M4,1986M5,1986M6,1986Q3,1986M7,1986M8,1986M9,1986Q4,1986M10,1986M11,1986M12,1987,1987Q1,1987M1,1987M2,1987M3,1987Q2,1987M4,1987M5,1987M6,1987Q3,1987M7,1987M8,1987M9,1987Q4,1987M10,1987M11,1987M12,1988,1988Q1,1988M1,1988M2,1988M3,1988Q2,1988M4,1988M5,1988M6,1988Q3,1988M7,1988M8,1988M9,1988Q4,1988M10,1988M11,1988M12,1989,1989Q1,1989M1,1989M2,1989M3,1989Q2,1989M4,1989M5,1989M6,1989Q3,1989M7,1989M8,1989M9,1989Q4,1989M10,1989M11,1989M12,1990,1990Q1,1990M1,1990M2,1990M3,1990Q2,1990M4,1990M5,1990M6,1990Q3,1990M7,1990M8,1990M9,1990Q4,1990M10,1990M11,1990M12,1991,1991Q1,1991M1,1991M2,1991M3,1991Q2,1991M4,1991M5,1991M6,1991Q3,1991M7,1991M8,1991M9,1991Q4,1991M10,1991M11,1991M12,1992,1992Q1,1992M1,1992M2,1992M3,1992Q2,1992M4,1992M5,1992M6,1992Q3,1992M7,1992M8,1992M9,1992Q4,1992M10,1992M11,1992M12,1993,1993Q1,1993M1,1993M2,1993M3,1993Q2,1993M4,1993M5,1993M6,1993Q3,1993M7,1993M8,1993M9,1993Q4,1993M10,1993M11,1993M12,1994,1994Q1,1994M1,1994M2,1994M3,1994Q2,1994M4,1994M5,1994M6,1994Q3,1994M7,1994M8,1994M9,1994Q4,1994M10,1994M11,1994M12,1995,1995Q1,1995M1,1995M2,1995M3,1995Q2,1995M4,1995M5,1995M6,1995Q3,1995M7,1995M8,1995M9,1995Q4,1995M10,1995M11,1995M12,1996,1996Q1,1996M1,1996M2,1996M3,1996Q2,1996M4,1996M5,1996M6,1996Q3,1996M7,1996M8,1996M9,1996Q4,1996M10,1996M11,1996M12,1997,1997Q1,1997M1,1997M2,1997M3,1997Q2,1997M4,1997M5,1997M6,1997Q3,1997M7,1997M8,1997M9,1997Q4,1997M10,1997M11,1997M12,1998,1998Q1,1998M1,1998M2,1998M3,1998Q2,1998M4,1998M5,1998M6,1998Q3,1998M7,1998M8,1998M9,1998Q4,1998M10,1998M11,1998M12,1999,1999Q1,1999M1,1999M2,1999M3,1999Q2,1999M4,1999M5,1999M6,1999Q3,1999M7,1999M8,1999M9,1999Q4,1999M10,1999M11,1999M12,2000,2000Q1,2000M1,2000M2,2000M3,2000Q2,2000M4,2000M5,2000M6,2000Q3,2000M7,2000M8,2000M9,2000Q4,2000M10,2000M11,2000M12,2001,2001Q1,2001M1,2001M2,2001M3,2001Q2,2001M4,2001M5,2001M6,2001Q3,2001M7,2001M8,2001M9,2001Q4,2001M10,2001M11,2001M12,2002,2002Q1,2002M1,2002M2,2002M3,2002Q2,2002M4,2002M5,2002M6,2002Q3,2002M7,2002M8,2002M9,2002Q4,2002M10,2002M11,2002M12,2003,2003Q1,2003M1,2003M2,2003M3,2003Q2,2003M4,2003M5,2003M6,2003Q3,2003M7,2003M8,2003M9,2003Q4,2003M10,2003M11,2003M12,2004,2004Q1,2004M1,2004M2,2004M3,2004Q2,2004M4,2004M5,2004M6,2004Q3,2004M7,2004M8,2004M9,2004Q4,2004M10,2004M11,2004M12,2005,2005Q1,2005M1,2005M2,2005M3,2005Q2,2005M4,2005M5,2005M6,2005Q3,2005M7,2005M8,2005M9,2005Q4,2005M10,2005M11,2005M12,2006,2006Q1,2006M1,2006M2,2006M3,2006Q2,2006M4,2006M5,2006M6,2006Q3,2006M7,2006M8,2006M9,2006Q4,2006M10,2006M11,2006M12,2007,2007Q1,2007M1,2007M2,2007M3,2007Q2,2007M4,2007M5,2007M6,2007Q3,2007M7,2007M8,2007M9,2007Q4,2007M10,2007M11,2007M12,2008,2008Q1,2008M1,2008M2,2008M3,2008Q2,2008M4,2008M5,2008M6,2008Q3,2008M7,2008M8,2008M9,2008Q4,2008M10,2008M11,2008M12,2009,2009Q1,2009M1,2009M2,2009M3,2009Q2,2009M4,2009M5,2009M6,2009Q3,2009M7,2009M8,2009M9,2009Q4,2009M10,2009M11,2009M12,2010,2010Q1,2010M1,2010M2,2010M3,2010Q2,2010M4,2010M5,2010M6,2010Q3,2010M7,2010M8,2010M9,2010Q4,2010M10,2010M11,2010M12,2011,2011Q1,2011M1,2011M2,2011M3,2011Q2,2011M4,2011M5,2011M6,2011Q3,2011M7,2011M8,2011M9,2011Q4,2011M10,2011M11,2011M12,2012,2012Q1,2012M1,2012M2,2012M3,2012Q2,2012M4,2012M5,2012M6,2012Q3,2012M7,2012M8,2012M9,2012Q4,2012M10,2012M11,2012M12,2013,2013Q1,2013M1,2013M2,2013M3,2013Q2,2013M4,2013M5,2013M6,2013Q3,2013M7,2013M8,2013M9,2013Q4,2013M10,2013M11,2013M12,2014,2014Q1,2014M1,2014M2,2014M3,2014Q2,2014M4,2014M5,2014M6,2014Q3,2014M7,2014M8,2014M9,2014Q4,2014M10,2014M11,2014M12,2015,2015Q1,2015M1,2015M2,2015M3,2015Q2,2015M4,2015M5,2015M6,2015Q3,2015M7,2015M8,2015M9,2015Q4,2015M10,2015M11,2015M12,2016,2016Q1,2016M1,2016M2,2016M3,2016Q2,2016M4,2016M5,2016M6,2016Q3,2016M7,2016M8,2016M9,2016Q4,2016M10,2016M11,2016M12,2017Q1,2017M1,2017M2,2017M3,
"Advanced Economies","110","Goods, Value of Exports, Free on board (FOB), US Dollars","TXG_FOB_USD","Lao People's Democratic Republic","544","Value",,,,,,,,"600000","7500000","11200000","10100000","9900000","13590000",,,,,,,,,,,,,,,,,"31800000",,,,,,,,,,,,,,,,,"22190000",,,,,,,,,,,,,,,,,"19310000",,,,,,,,,,,,,,,,,"13400000",,,,,,,,,,,,,,,,,"17500000",,,,,,,,,,,,,,,,,"20000000",,,,,,,,,,,,,,,,,"21000000",,,,,,,,,,,,,,,,,"28220000",,,,,,,,,,,,,,,,,"46444000",,,,,,,,,,,,,,,,,"42244000",,,,,,,,,,,,,,,,,"28035000",,,,,,,,,,,,,,,,,"22672000",,,,,,,,,,,,,,,,,"35970000",,,,,,,,,,,,,,,,,"52015000",,,,,,,,,,,,,,,,,"24440000",,,,,,,,,,,,,,,,,"14690000",,,,,,,,,,,,,,,,,"32230000",,,,,,,,,,,,,,,,,"38550000",,,,,,,,,,,,,,,,,"34860000",,,,,,,,,,,,,,,,,"55760000",,,,,,,,,,,,,,,,,"37930000",,,,,,,,,,,,,,,,,"35560000",,,,,,,,,,,,,,,,,"39910000",,,,,,,,,,,,,,,,,"15670000",,,,,,,,,,,,,,,,,"26490000",,,,,,,,,,,,,,,,,"20760000",,,,,,,,,,,,,,,,,"26680000",,,,,,,,,,,,,,,,,"35095211.66717",,,,,,,,,,,,,,,,,"36724275.976975",,,,,,,,,,,,,,,,,"36915312.0753272",,,,,,,,,,,,,,,,,"46665636.4768923",,,,,,,,,,,,,,,,,"66109300.8664534",,,,,,,,,,,,,,,,,"87913998.4608552",,,,,,,,,,,,,,,,,"148354775.637297",,,,,,,,,,,,,,,,,"163819040.691337",,,,,,,,,,,,,,,,,"156024282.72955",,,,,,,,,,,,,,,,,"133137318.554441",,,,,,,,,,,,,,,,,"94399137.7518639",,,,,,,,,,,,,,,,,"117343069.557997",,,,,,,,,,,,,,,,,"117587881.503864",,,,,,,,,,,,,,,,,"98762873.9625738",,,,,,,,,,,,,,,,,"109005712.389615",,,,,,,,,,,,,,,,,"106595482.789968",,,,,,,,,,,,,,,,,"172941555.708648",,,,,,,,,,,,,,,,,"160810422.300987",,,,,,,,,,,,,,,,,"166500301.797628",,,,,,,,,,,,,,,,,"259543675.819615",,,,,,,,,,,,,,,,,"312728794.020366",,,,,,,,,,,,,,,,,"353281591.775144",,,,,,,,,,,,,,,,,"398101531.917045",,,,,,,,,,,,,,,,,"624671291.89195",,,,,,,,,,,,,,,,,"745336092.052549",,,,,,,,,,,,,,,,,"630395816.514461",,,,,,,,,,,,,,,,,"777975419.209323",,,,,,,,,,,,,,,,,"733654481.53557",,,,,,,,,,,,,,,,,"503096458.712403",,,,,,,,,,,,,,,,,,,,,

Body:
To exclude 3 columns while importing, you could do:

data = pd.read_csv(
 sourceFileName,
 usecols=lambda col: col not in ["Country Name","Indicator Name","Counterpart Country Name"]
)


问:
Generate PDF file from HTML code
I would like to generate a PDF file from a HTML code which contains the stylesheet rules, using PHP.

I am trying to do it using the MPDF library, but when is generated it doesn't look like the HTML page. Most of the elements are not situated in the right position and is like some css rules were not applied.

Does anyone know how can I make it look fine, please?

答:
You can check:

To generate PDF check:
https://github.com/dompdf/dompdf
or
https://github.com/KnpLabs/snappy

For word docs:
https://github.com/PHPOffice/PHPWord

Title: Generate PDF file from HTML code


问:
SQL wont allow me to add foreign key?
I'm building a question and answer site and for linking the user accounts to the questions I want to have the username from the login table be a foreign key of the questions table so when a user asks a question it must be linked to his or her username.  Can I not have foreign key's that are varchar datatype?  Or must the foreign key be only a primary key of another table?  The error I'm getting says 'Key column "'username' doesn't exist in table" .  What am I doing wrong?</p>

```<code>create table login (user_id int NOT NULL AUTO_INCREMENT, username
varchar (100), password varchar (100), primary key (user_id));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), foreign key (username) references
login (username));
</code>```

答:
Remember, Foreign Key is a Key and should expect to be linked with another Key. Now, username is simple column in one table, then how it can be key column for another table ?

The purpose of Foreign key is to show the relationship between the tables. You MUST have same column in both the table, which you are going relate.

Title: SQL wont allow me to add foreign key?

Body:
I'm building a question and answer site and for linking the user accounts to the questions I want to have the username from the login table be a foreign key of the questions table so when a user asks a question it must be linked to his or her username.  Can I not have foreign key's that are varchar datatype?  Or must the foreign key be only a primary key of another table?  The error I'm getting says 'Key column "'username' doesn't exist in table" .  What am I doing wrong?

create table login (user_id int NOT NULL AUTO_INCREMENT, username
varchar (100), password varchar (100), primary key (user_id));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), foreign key (username) references
login (username));


问:
REST assured testing for non spring dependent java projects
I have a java project which has REST end points. This java project is a plugin to the main project, which has all the spring dependencies.

How can I write REST assured integration tests for my REST endpoints for the non-spring java project?

Is adding the spring dependencies under test scope is the only way?

Thanks in advance.

答:
If you are able to execute your REST project(project) independently you can use rest assured without mock and without Spring dependencies, but in case you need you main project to have plugin one running you need the dependencies.

Also, if you want to do real-time automation testing, not a unit testing with mock, you just need to make sure you REST endpoints is up and running and then you can freely use rest assured


问:
problem with conditional switch
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

```<code><?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>
</code>```

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

答:
case ($totaltime < 1): means 1 to PHP (that equation returns true)

case ($totaltime > 1): means 0 to PHP (that equation returns false)

Since $totaltime is 0, you get that output

In other words PHP compares $totaltime to the result of the comparisons.

EDIT regarding EDIT in OP:

You need to get rid of the switch()-statement. You only use it to easily compare against different values and not use additional expressions with it.

I mean what is wrong with

```<code><?php
$totaltime = 0;

if ($totaltime < 1) {
    echo "That was fast!";
} else if ($totaltime > 10) {
    echo "That's slooooow";
} else if ($totaltime > 1) {
    echo "Not fast!";
}

?>
</code>```

EDIT: please note that I switched the last two if-statements to make it really work.

Title: problem with conditional switch

Body:
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

<?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

Body:
case ($totaltime < 1): means 1 to PHP (that equation returns true)

case ($totaltime > 1): means 0 to PHP (that equation returns false)

Since $totaltime is 0, you get that output

In other words PHP compares $totaltime to the result of the comparisons.

EDIT regarding EDIT in OP:

You need to get rid of the switch()-statement. You only use it to easily compare against different values and not use additional expressions with it.

I mean what is wrong with

<?php
$totaltime = 0;

if ($totaltime < 1) {
    echo "That was fast!";
} else if ($totaltime > 10) {
    echo "That's slooooow";
} else if ($totaltime > 1) {
    echo "Not fast!";
}

?>

EDIT: please note that I switched the last two if-statements to make it really work.


答:
You can create a subtask and call it too:</p>

```<code>def show_tweets_by_color(num, col, tweets):
  green = lambda x: colored(x, 'green')
  print(colored(str(num), " green") + green(tweets))

if score > 0:
    show_tweets_by_color(1, "green", tweets)
...
</code>```

Title: placeholder in termcolor python

Body:
You can create a subtask and call it too:

def show_tweets_by_color(num, col, tweets):
  green = lambda x: colored(x, 'green')
  print(colored(str(num), " green") + green(tweets))

if score > 0:
    show_tweets_by_color(1, "green", tweets)
...


问:
php sql Displaying images from different contributors
Basically I am trying to create a gallery with a list of users (all links) pulled from a users table (userId, userName, userEmail and userPass) in my database. When the user uploads a photo it save to a uploads directory but the information saves to a database table called images (imgId, userId, imgName, imgLocation and uploadDate). What i want to do is have a list of users pulled from the users table and when you click a user it displays only the photos they have uploaded.

I have this code so far for displaying users in list as links.

```<code><?php
ob_start();
session_start();
require_once 'dbconnect.php';

// if session is not set this will redirect to login page
if( !isset($_SESSION['user']) ) {
    header("Location: index.php");
    exit;
}
// select loggedin users detail
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
?>

<?php
$query = mysql_query("SELECT userName FROM `users`");

echo '<table>';
while($rowtwo = mysql_fetch_array($query)){
echo    '<tr>
        <td class="userlist"><font size="4" face="Lucida Sans Unicode"color="black"><a href="" >'.$rowtwo['userName'].'</a></td>
        </tr>';
   }
echo '</table>';
?>
</code>```

I don't know how to link the users to the images, and then display the images to the right of the list of users. I want to use the userId which is saved to the images table whenever a image is submitted, but i am completely lost.

Any help would be great(if i have made any sense), still fairly new to this.

答:
After clicking the user, send the userId in the request and fetch the images from the images table using this query,

```<code>select 'imgName', 'imgLocation' from images where userId = '$YourUserId';
</code>```

then using a loop you can display images by looping  tag,

```<code><img src="IMAGE_LOCATION" alt="IMAGE_NAME" height="42" width="42">
</code>```

Body:
Basically I am trying to create a gallery with a list of users (all links) pulled from a users table (userId, userName, userEmail and userPass) in my database. When the user uploads a photo it save to a uploads directory but the information saves to a database table called images (imgId, userId, imgName, imgLocation and uploadDate). What i want to do is have a list of users pulled from the users table and when you click a user it displays only the photos they have uploaded.

I have this code so far for displaying users in list as links.

<?php
ob_start();
session_start();
require_once 'dbconnect.php';

// if session is not set this will redirect to login page
if( !isset($_SESSION['user']) ) {
    header("Location: index.php");
    exit;
}
// select loggedin users detail
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
?>

<?php
$query = mysql_query("SELECT userName FROM `users`");

echo '
';
while($rowtwo = mysql_fetch_array($query)){
echo    '

        '.$rowtwo['userName'].'

';
   }
echo '
';
?>

I don't know how to link the users to the images, and then display the images to the right of the list of users. I want to use the userId which is saved to the images table whenever a image is submitted, but i am completely lost.

Any help would be great(if i have made any sense), still fairly new to this.

Body:
After clicking the user, send the userId in the request and fetch the images from the images table using this query,

select 'imgName', 'imgLocation' from images where userId = '$YourUserId';

then using a loop you can display images by looping  tag,

<img src="IMAGE_LOCATION" alt="IMAGE_NAME" height="42" width="42">


问:
How to create multiple filters within same function in R?
I've written some code with help to a previously answered question. Initially I had this code:

```<code>getT <- function(df, ID, Number){
  df %>%
    group_by(ID, Number) %>%
    mutate( Distance = finish - begin) %>%
    select(-begin,-finish,-symbols) %>%
    nest() %>%
    mutate( data = map( data, ~ filter(.x, Distance == max(Distance)))) %>%
    unnest()
}

getallT <- as.data.frame(getT(df))

getTID <- function(df, ID) {
  subset(x = getallT, subset = (ID))
}
</code>```

Which gave this output:

```<code>ID     Number     Time     Distance
33         1      2.00         870
33         2      1.98         859
33         3      0.82         305
33         4      2.02         651
33         5      2.53         502
</code>```

I wanted to filter it by Time so I used this code(thanks to a post below):

```<code>getHLN <- function(df, ID) {
  getallT %>% filter (ID ==id & !between(Time, 1.50, 2.10))
}
</code>```

Which now gives this output:

```<code>  ID Number Time Distance
1 33      3 0.82      305
2 33      4 2.02      651
3 33      5 2.53      502
</code>```

But now I've come across an issue so now I'm left wondering how to either:
A. Filter out Number 4 & 5 so that I can create a separate function with a different Time filter for it. To later create another different function to merge the two previous functions into one.
OR
B. Create a different Time filter specifically for Number 4 & 5 within the same function.

I tried doing A. by using filter (getallT, Number >= 3) %>% but doesn't work. I would rather go with B though if possible. So something like...
For ID numbers 1-3: filter(!between(Time,1,2))
For ID numbers 4-5: filter(!between(Time 1.5,2.3)) within the same function.
I've been trying out a few things for the past day but keep getting error messages such as Error in filter_impl(.data, quo) :
  Evaluation error: operations are possible only for numeric, logical or complex types.

I've been trying out what's on here but must not be doing something write so need some insight!
http://genomicsclass.github.io/book/pages/dplyr_tutorial.html

Here is an example dataset

```<code>df <- data.frame(ID=rep(33,5),
                 Number=1:5,
                 Time=c(2.00,1.98,0.82,2.02,2.53),
                 Distance=c(870,859,305,651,502))
</code>```

Any help would be much appreciated.

答:
This function is somewhat confusing:

```<code>getHLN <- function(df, ID) {
  data_df1 <- getT(race_df)
  subset(x = getallT, subset = (ID)) %>%
    filter (!between(Time, 1.50, 2.10))
}
</code>```

Mainly because it takes a df argument, which it doesn't within, and uses  two data.frames from the outer environment in race_df and getallT. Your calls to subset are also a tad mystifying. As it stands, the function will return whatever the expression beginning with subset will return, and will throw away data_df1.

```<code>getHLN <- function(df, ID) {
  # this gets locally assigned within the function and then
  # becomes unreachable once the function ends
  data_df1 <- getT(df)
  # this expression would produce the last value of the function
  # and so the function would return its value
  subset(x = getallT, subset = (ID)) %>%
    filter (!between(Time, 1.50, 2.10))
}
</code>```

We can do the sort of filtering you described by creating ID %in% ... & !between() logic for both sets of criteria you described, wrapping each in parentheses so that they're evaluated as "and" logic, and then adding both to the filter function and joining them with the | operator ("or"), which filter will then evaluate as "filter df where (criteria a AND B) OR (criteria c AND d)".

```<code>getHLN <- function(df) {
  df %>% filter(
    (Number %in% 1:3 & !between(Time, 1, 2)) |
      (Number %in% 4:5 & !between(Time, 1.50, 2.10))
    )
}
</code>```

Body:
I've written some code with help to a previously answered question. Initially I had this code:

getT <- function(df, ID, Number){
  df %>%
    group_by(ID, Number) %>%
    mutate( Distance = finish - begin) %>%
    select(-begin,-finish,-symbols) %>%
    nest() %>%
    mutate( data = map( data, ~ filter(.x, Distance == max(Distance)))) %>%
    unnest()
}

getallT <- as.data.frame(getT(df))

getTID <- function(df, ID) {
  subset(x = getallT, subset = (ID))
}

Which gave this output:

ID     Number     Time     Distance
33         1      2.00         870
33         2      1.98         859
33         3      0.82         305
33         4      2.02         651
33         5      2.53         502

I wanted to filter it by Time so I used this code(thanks to a post below):

getHLN <- function(df, ID) {
  getallT %>% filter (ID ==id & !between(Time, 1.50, 2.10))
}

Which now gives this output:

  ID Number Time Distance
1 33      3 0.82      305
2 33      4 2.02      651
3 33      5 2.53      502

But now I've come across an issue so now I'm left wondering how to either:
A. Filter out Number 4 & 5 so that I can create a separate function with a different Time filter for it. To later create another different function to merge the two previous functions into one.
OR
B. Create a different Time filter specifically for Number 4 & 5 within the same function.

I tried doing A. by using filter (getallT, Number >= 3) %>% but doesn't work. I would rather go with B though if possible. So something like...
For ID numbers 1-3: filter(!between(Time,1,2))
For ID numbers 4-5: filter(!between(Time 1.5,2.3)) within the same function.
I've been trying out a few things for the past day but keep getting error messages such as Error in filter_impl(.data, quo) :
  Evaluation error: operations are possible only for numeric, logical or complex types.

I've been trying out what's on here but must not be doing something write so need some insight!
http://genomicsclass.github.io/book/pages/dplyr_tutorial.html

Here is an example dataset

df <- data.frame(ID=rep(33,5),
                 Number=1:5,
                 Time=c(2.00,1.98,0.82,2.02,2.53),
                 Distance=c(870,859,305,651,502))

Any help would be much appreciated.

Body:
This function is somewhat confusing:

getHLN <- function(df, ID) {
  data_df1 <- getT(race_df)
  subset(x = getallT, subset = (ID)) %>%
    filter (!between(Time, 1.50, 2.10))
}

Mainly because it takes a df argument, which it doesn't within, and uses  two data.frames from the outer environment in race_df and getallT. Your calls to subset are also a tad mystifying. As it stands, the function will return whatever the expression beginning with subset will return, and will throw away data_df1.

getHLN <- function(df, ID) {
  # this gets locally assigned within the function and then
  # becomes unreachable once the function ends
  data_df1 <- getT(df)
  # this expression would produce the last value of the function
  # and so the function would return its value
  subset(x = getallT, subset = (ID)) %>%
    filter (!between(Time, 1.50, 2.10))
}

We can do the sort of filtering you described by creating ID %in% ... & !between() logic for both sets of criteria you described, wrapping each in parentheses so that they're evaluated as "and" logic, and then adding both to the filter function and joining them with the | operator ("or"), which filter will then evaluate as "filter df where (criteria a AND B) OR (criteria c AND d)".

getHLN <- function(df) {
  df %>% filter(
    (Number %in% 1:3 & !between(Time, 1, 2)) |
      (Number %in% 4:5 & !between(Time, 1.50, 2.10))
    )
}


问:
Swift 3 - store the User Location and call it from different View Controllers
I'm pretty new in programming and this is my first app, so sorry if the approach is very shabby.

I created a helper method to get the user location, because I need to call it from different view controllers so I thought this was a cleaner way to do it. But I don't know why is not working now (no errors, it just show the general view of Europe). But when it was inside the view controller it worked perfectly fine.

I got this new approach from the course I'm doing and I've been researching in many sources. I've also checked this question but I didn't find any solution yet.

Here is the method I created in the GMSClient file. It will get the user location, but if the user disables this option, it will show the default position (centred in Berlin):

```<code>    extension GMSClient: CLLocationManagerDelegate {

    //MARK: Initial Location: Berlin

    func setDefaultInitialLocation(_ map: GMSMapView) {
        let camera = GMSCameraPosition.camera(withLatitude: 52.520736, longitude: 13.409423, zoom: 8)
        map.camera = camera

        let initialLocation = CLLocationCoordinate2DMake(52.520736, 13.409423)
        let marker = GMSMarker(position: initialLocation)
        marker.title = "Berlin"
        marker.map = map

    }

    //MARK: Get user location

    func getUserLocation(_ map: GMSMapView,_ locationManager: CLLocationManager) {

        var userLocation: String?

        locationManager.requestWhenInUseAuthorization()

        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

            if status == .authorizedWhenInUse {
                locationManager.startUpdatingLocation()

                map.isMyLocationEnabled = true
                map.settings.myLocationButton = true

            } else {
                setDefaultInitialLocation(map)
            }
        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if let location = locations.first {

                map.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                locationManager.stopUpdatingLocation()

                //Store User Location
                userLocation = "\(location.coordinate.latitude), \(location.coordinate.longitude)"
                print("userLocation is: \((userLocation) ?? "No user Location")")

            }
        }
    }
}
</code>```

This file has also this singelton:

```<code>// MARK: Shared Instance

    class func sharedInstance() -> GMSClient {
        struct Singleton {
            static var sharedInstance = GMSClient()
        }
        return Singleton.sharedInstance
    }
</code>```

And then I call it in my view controller like this:

```<code>class MapViewController: UIViewController, CLLocationManagerDelegate {

    // MARK: Outlets

    @IBOutlet weak var mapView: GMSMapView!

    // MARK: Properties

    let locationManager = CLLocationManager()
    var userLocation: String?
    let locationManagerDelegate = GMSClient()

    // MARK: Life Cycle

    override func viewDidLoad() {

        super.viewDidLoad()

        self.locationManager.delegate = locationManagerDelegate

        GMSClient.sharedInstance().getUserLocation(mapView, locationManager)

    }
</code>```

Anyone has an idea of what can be wrong?

Thanks!

答:
Following what Paulw11 said, I found the faster solution using Notifications.

Send notification from the LocationManager delegate method inside the first view Controller:

```<code>class MapViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

                if status == .authorizedWhenInUse {
                    locationManager.startUpdatingLocation()

                    mapView.isMyLocationEnabled = true
                    mapView.settings.myLocationButton = true
                } else {
                    initialLocation()
                }
            }

            func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

                if let location = locations.first {

                    mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                    locationManager.stopUpdatingLocation()

                    let userInfo : NSDictionary = ["location" : location]

                    NotificationCenter.default.post(name: NSNotification.Name("UserLocationNotification"), object: self, userInfo: userInfo as [NSObject : AnyObject])

                }
            }
     }
</code>```

Set the second view controller as observer. This way I can store the userLocation and use it later for the search request:

```<code>class NeighbourhoodPickerViewController: UIViewController, UITextFieldDelegate {

var userLocation: String?
var currentLocation: CLLocation!

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(locationUpdateNotification), name: Notification.Name("UserLocationNotification"), object: nil)

}

func locationUpdateNotification(notification: NSNotification) {
    if let userInfo = notification.userInfo?["location"] as? CLLocation {
        self.currentLocation = userInfo
        self.userLocation = "\(userInfo.coordinate.latitude), \(userInfo.coordinate.longitude)"
    }
}
</code>```

Body:
I'm pretty new in programming and this is my first app, so sorry if the approach is very shabby.

I created a helper method to get the user location, because I need to call it from different view controllers so I thought this was a cleaner way to do it. But I don't know why is not working now (no errors, it just show the general view of Europe). But when it was inside the view controller it worked perfectly fine.

I got this new approach from the course I'm doing and I've been researching in many sources. I've also checked this question but I didn't find any solution yet.

Here is the method I created in the GMSClient file. It will get the user location, but if the user disables this option, it will show the default position (centred in Berlin):

    extension GMSClient: CLLocationManagerDelegate {

    //MARK: Initial Location: Berlin

    func setDefaultInitialLocation(_ map: GMSMapView) {
        let camera = GMSCameraPosition.camera(withLatitude: 52.520736, longitude: 13.409423, zoom: 8)
        map.camera = camera

        let initialLocation = CLLocationCoordinate2DMake(52.520736, 13.409423)
        let marker = GMSMarker(position: initialLocation)
        marker.title = "Berlin"
        marker.map = map

    }

    //MARK: Get user location

    func getUserLocation(_ map: GMSMapView,_ locationManager: CLLocationManager) {

        var userLocation: String?

        locationManager.requestWhenInUseAuthorization()

        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

            if status == .authorizedWhenInUse {
                locationManager.startUpdatingLocation()

                map.isMyLocationEnabled = true
                map.settings.myLocationButton = true

            } else {
                setDefaultInitialLocation(map)
            }
        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if let location = locations.first {

                map.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                locationManager.stopUpdatingLocation()

                //Store User Location
                userLocation = "\(location.coordinate.latitude), \(location.coordinate.longitude)"
                print("userLocation is: \((userLocation) ?? "No user Location")")

            }
        }
    }
}

This file has also this singelton:

// MARK: Shared Instance

    class func sharedInstance() -> GMSClient {
        struct Singleton {
            static var sharedInstance = GMSClient()
        }
        return Singleton.sharedInstance
    }

And then I call it in my view controller like this:

class MapViewController: UIViewController, CLLocationManagerDelegate {

    // MARK: Outlets

    @IBOutlet weak var mapView: GMSMapView!

    // MARK: Properties

    let locationManager = CLLocationManager()
    var userLocation: String?
    let locationManagerDelegate = GMSClient()

    // MARK: Life Cycle

    override func viewDidLoad() {

        super.viewDidLoad()

        self.locationManager.delegate = locationManagerDelegate

        GMSClient.sharedInstance().getUserLocation(mapView, locationManager)

    }

Anyone has an idea of what can be wrong?

Thanks!

Body:
Following what Paulw11 said, I found the faster solution using Notifications.

Send notification from the LocationManager delegate method inside the first view Controller:

class MapViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

                if status == .authorizedWhenInUse {
                    locationManager.startUpdatingLocation()

                    mapView.isMyLocationEnabled = true
                    mapView.settings.myLocationButton = true
                } else {
                    initialLocation()
                }
            }

            func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

                if let location = locations.first {

                    mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                    locationManager.stopUpdatingLocation()

                    let userInfo : NSDictionary = ["location" : location]

                    NotificationCenter.default.post(name: NSNotification.Name("UserLocationNotification"), object: self, userInfo: userInfo as [NSObject : AnyObject])

                }
            }
     }

Set the second view controller as observer. This way I can store the userLocation and use it later for the search request:

class NeighbourhoodPickerViewController: UIViewController, UITextFieldDelegate {

var userLocation: String?
var currentLocation: CLLocation!

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(locationUpdateNotification), name: Notification.Name("UserLocationNotification"), object: nil)

}

func locationUpdateNotification(notification: NSNotification) {
    if let userInfo = notification.userInfo?["location"] as? CLLocation {
        self.currentLocation = userInfo
        self.userLocation = "\(userInfo.coordinate.latitude), \(userInfo.coordinate.longitude)"
    }
}


问:
Appending a list to create a nested list in python
I'm trying to make a nested list in Python, by asking the user to input the text file.
The input file is as shown below:

1.3 2.6 3.2 4.1
1 -3 2
-4.1

And finally the output should be:
[[1.3, 2.6, 3.2, 4.1], [1.0, -3.0, 2.0], [-4.1]]

My code can display the individual list one below the other, but I'm having difficulty in appending the lists.
As I'm new to python, any help is much appreciated. Thanks in advance.
My code is as follows:

```<code>#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the file to read the content
infile=open(file_name,'r')

#Iterating for line in the file
for line in infile:
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])

    nlist=[[] for line in range(3)]
    nlist=nlist.append([line_str])
    print(nlist)
</code>```

答:
[EDIT]
Sorry, I previously misunderstood your question and assumed that your input file is all in separate lines, but I think it is structured like

1.3 2.6 3.2 4.1
1 -3 2
-4.1

If you are simply asking how to append a list to a list to create a nested list in Python, here is how you do it:

```<code>list1 = [1,2,3,4]
list2 = [5,6,7,8]
nested_list = []
nested_list.append(list1)
nested_list.append(list2)
</code>```

This will result in:

[ [1,2,3,4] , [5,6,7,8] ]

I think the answer above gave a pretty concise answer with list comprehensions, but you can also do something with lambda functions as such:

```<code># Ask the user to input a file name
file_name = input("Enter the Filename: ")

nlist = []

# Opening the file to read the content
with open(file_name, 'r') as infile:
    for line in infile:
        ls = list(map(lambda x: float(x), line.split()))
        nlist.append(ls)

print(nlist)
</code>```

In addition, you can even shorter this into a one-liner as such:

```<code># Ask the user to input a file name
file_name = input("Enter the Filename: ")

# Opening the file to read the content
with open(file_name, 'r') as infile:
    ls = list(map(lambda line: list(map(lambda x: float(x), line.split())), infile))
</code>```

I hope this helped.

Body:
I'm trying to make a nested list in Python, by asking the user to input the text file.
The input file is as shown below:

1.3 2.6 3.2 4.1
1 -3 2
-4.1

And finally the output should be:
[[1.3, 2.6, 3.2, 4.1], [1.0, -3.0, 2.0], [-4.1]]

My code can display the individual list one below the other, but I'm having difficulty in appending the lists.
As I'm new to python, any help is much appreciated. Thanks in advance.
My code is as follows:

#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the file to read the content
infile=open(file_name,'r')

#Iterating for line in the file
for line in infile:
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])

    nlist=[[] for line in range(3)]
    nlist=nlist.append([line_str])
    print(nlist)

Body:
[EDIT]
Sorry, I previously misunderstood your question and assumed that your input file is all in separate lines, but I think it is structured like

1.3 2.6 3.2 4.1
1 -3 2
-4.1

If you are simply asking how to append a list to a list to create a nested list in Python, here is how you do it:

list1 = [1,2,3,4]
list2 = [5,6,7,8]
nested_list = []
nested_list.append(list1)
nested_list.append(list2)

This will result in:

[ [1,2,3,4] , [5,6,7,8] ]

I think the answer above gave a pretty concise answer with list comprehensions, but you can also do something with lambda functions as such:

# Ask the user to input a file name
file_name = input("Enter the Filename: ")

nlist = []

# Opening the file to read the content
with open(file_name, 'r') as infile:
    for line in infile:
        ls = list(map(lambda x: float(x), line.split()))
        nlist.append(ls)

print(nlist)

In addition, you can even shorter this into a one-liner as such:

# Ask the user to input a file name
file_name = input("Enter the Filename: ")

# Opening the file to read the content
with open(file_name, 'r') as infile:
    ls = list(map(lambda line: list(map(lambda x: float(x), line.split())), infile))

I hope this helped.


问:
A view that is moving
I've no experience in making something move in my app. And I observed this effect in Flickit Pro. The Tap for details view will shake for one or two second and then stop. It looks cute and very user-friendly.

So how can I make effects like this? A gif that is moving? Or some other methods with the help of Cocoa Touch?

Thanks in advance.

Di

答:
There are already some answers on stackoverflow on this:

Shake visual effect on iPhone (NOT shaking the device)

UIView shake animation

how to create iphone's wobbling icon effect?

and here is a link that does it on mac:

http://www.cimgf.com/2008/02/27/core-animation-tutorial-window-shake-effect/

I hope these are enough links to help.

Title: A view that is moving


问:
clicking button within UITableview cell gives wrong result while search
Within the cells of a tableview I have a button. The button basically opens the file that the cell refers to. This is working fine while the search is not on. But while the search is on, I can't seem to get the correct row within the search results array.
This is what I have tried so far:
in the cellForRowAtIndexPath I tagged the button.

```<code>myDownloadsBtn = (UIButton *) [cell viewWithTag:106];
</code>```

the action is set as follows:

```<code>[myDownloadsBtn addTarget:self action: @selector(downloadClicked:event:) forControlEvents:UIControlEventTouchUpInside];
</code>```

then in downloadClicked I have the following

```<code>    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    NSString *todoRow;
    CGPoint currentTouchPosition = [touch locationInView:self->tableview];
    NSIndexPath *indexPath = [self->tableview indexPathForRowAtPoint: currentTouchPosition];
</code>```

but it gives me the indexPath of the VISIBLE current position, not the position of the row within the search results array.

Also, my delegate method ofdidSelectRowAtIndexPath works fine with and without the search. It is just for buttons within the cells.

I have found this question, but there is no answer:
how to get selected tableview button value while search in iOS.

the other questions deal with how to know the actual cell selected when searching, but that is not my problem.

Thank you.

答:
For the identification of object on particular index of tebleview you need to give your particular indexpath.row as tag to your UIButton.

Here is the best approch for that.

```<code>aCell.yourButton.tag = indexPath.row

[aCell.yourButton addTarget:self action: @selector(downloadClicked:event:) forControlEvents:UIControlEventTouchUpInside];
</code>```

After that you need to handle this event

```<code>-(IBAction)myDownloadsBtn:(id)sender
 {
   UIButton *tappedBtn = (UIButton*)sender;
   Nslog("%d",tappedBtn.tag); // it gives index of object related to your cell
 }
</code>```

but what you said is you are not getting the right result after performing the search.
What i am thinking is after getting the result from search you need to reload your tableview using

```<code>[yourTableView reloadData]
</code>```

Body:
Within the cells of a tableview I have a button. The button basically opens the file that the cell refers to. This is working fine while the search is not on. But while the search is on, I can't seem to get the correct row within the search results array.
This is what I have tried so far:
in the cellForRowAtIndexPath I tagged the button.

myDownloadsBtn = (UIButton *) [cell viewWithTag:106];

the action is set as follows:

[myDownloadsBtn addTarget:self action: @selector(downloadClicked:event:) forControlEvents:UIControlEventTouchUpInside];

then in downloadClicked I have the following

    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    NSString *todoRow;
    CGPoint currentTouchPosition = [touch locationInView:self->tableview];
    NSIndexPath *indexPath = [self->tableview indexPathForRowAtPoint: currentTouchPosition];

but it gives me the indexPath of the VISIBLE current position, not the position of the row within the search results array.

Also, my delegate method ofdidSelectRowAtIndexPath works fine with and without the search. It is just for buttons within the cells.

I have found this question, but there is no answer:
how to get selected tableview button value while search in iOS.

the other questions deal with how to know the actual cell selected when searching, but that is not my problem.

Thank you.

Body:
For the identification of object on particular index of tebleview you need to give your particular indexpath.row as tag to your UIButton.

Here is the best approch for that.

aCell.yourButton.tag = indexPath.row

[aCell.yourButton addTarget:self action: @selector(downloadClicked:event:) forControlEvents:UIControlEventTouchUpInside];

After that you need to handle this event

-(IBAction)myDownloadsBtn:(id)sender
 {
   UIButton *tappedBtn = (UIButton*)sender;
   Nslog("%d",tappedBtn.tag); // it gives index of object related to your cell
 }

but what you said is you are not getting the right result after performing the search.
What i am thinking is after getting the result from search you need to reload your tableview using

[yourTableView reloadData]


问:
IdentityServer4 and ResourceOwnerPasswordValidator Dynamic ConnectionString
So, IResourceOwnerPasswordValidator is supposed to replace IUserService.
In the old version IdentityServer3 I could do the following:

```<code>factory.UserService = new Registration<IUserService>(typeof(MyIdentityUserService));
factory.Register(new Registration<IUserRepository>(userRepository));
</code>```

which passes a custom userRepository object with the proper connection string.
Now in IdentityServer4 I need to Connect to the proper Portal database in order for ID4 to authenticate the user against the correct portal database.

If I could pass a parameter to the constructor of the ResourceOwnerPasswordValidator class like below , then this would be fine but this is not possible with ASP.NET CORE.

```<code> public ResourceOwnerPasswordValidator(string MyConnString)
        {
            _connstring = MyConnString;
        }
</code>```

This can't work because the ConfigurationService registers this class without the ability to pass values. This makes sense since this registration process begins before the pipeline is built.  How do I dynamically pass a connection string to the ResourceOwnerPasswordValidator class? I am trying to authenticate against the portal making the call. In ID3 I could do this by using the acr_value.

I am trying to get ID4 to authenticate as a MultiTenant Authentication Server.

答:
You could inject a service or a DTO into a ResourceOwnerPasswordValidator constructor:

```<code>public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
    public ResourceOwnerPasswordValidator(IAuthRepository repository)
    {
    }
}
</code>```

Hence it is possible to pass a service which returns your connection string.

By default, validator's implementation is registered as Transient which means it will not be a singleton until it is resolved in a singleton (which is not a IdSrv4 case I guess).

If you need a Scoped connection string (i.e. per web request), register a scoped DTO with a factory method: services.AddScoped<T>(() => ) or use AsyncLocal<T>. Check this thread to get more details:

How to Per-Request caching in ASP.net core

Body:
So, IResourceOwnerPasswordValidator is supposed to replace IUserService.
In the old version IdentityServer3 I could do the following:

factory.UserService = new Registration<IUserService>(typeof(MyIdentityUserService));
factory.Register(new Registration<IUserRepository>(userRepository));

which passes a custom userRepository object with the proper connection string.
Now in IdentityServer4 I need to Connect to the proper Portal database in order for ID4 to authenticate the user against the correct portal database.

If I could pass a parameter to the constructor of the ResourceOwnerPasswordValidator class like below , then this would be fine but this is not possible with ASP.NET CORE.

 public ResourceOwnerPasswordValidator(string MyConnString)
        {
            _connstring = MyConnString;
        }

This can't work because the ConfigurationService registers this class without the ability to pass values. This makes sense since this registration process begins before the pipeline is built.  How do I dynamically pass a connection string to the ResourceOwnerPasswordValidator class? I am trying to authenticate against the portal making the call. In ID3 I could do this by using the acr_value.

I am trying to get ID4 to authenticate as a MultiTenant Authentication Server.

Body:
You could inject a service or a DTO into a ResourceOwnerPasswordValidator constructor:

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
    public ResourceOwnerPasswordValidator(IAuthRepository repository)
    {
    }
}

Hence it is possible to pass a service which returns your connection string.

By default, validator's implementation is registered as Transient which means it will not be a singleton until it is resolved in a singleton (which is not a IdSrv4 case I guess).

If you need a Scoped connection string (i.e. per web request), register a scoped DTO with a factory method: services.AddScoped<T>(() => ) or use AsyncLocal<T>. Check this thread to get more details:

How to Per-Request caching in ASP.net core


问:
TCP server hangs after first connection
i am implementing a simple TCP echo server, which writes back whatever is written to it.i use telnet to connect to it when i first send some data to it,it is sent back(expected) but after that it hangs on i assume as nothing is sent back.

here is my code (a little modified version of example in  man getaddrinfo).is there any problem with how i recv() and send() below?

```<code>#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>

#define MAX_LISTEN_BACKLOG 1
#define BUFFER_SIZE 4096

int main(int argc, char* argv[]){
    char buf[BUFFER_SIZE];
    int sfd,n,s;
    struct addrinfo hints;
    struct addrinfo *result;
    struct addrinfo *rp;
    struct sockaddr_storage peer_addr;
    socklen_t peer_addr_len;
    ssize_t nread;
    int addr_info_error;

    memset(&hints,0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    hints.ai_protocol = 0;
    hints.ai_canonname = NULL;
    hints.ai_addr = NULL;
    hints.ai_next = NULL;

    s = getaddrinfo(NULL, argv[1], &hints, &result);
    if (s != 0){
        printf("got error getaddrinfo");
    }

    for( rp = result; rp !=NULL; rp = rp->ai_next){
      sfd = socket(rp->ai_family,rp->ai_socktype,rp->ai_protocol);
      if (sfd == -1) perror("could not create socket");
      if (bind(sfd,rp->ai_addr,rp->ai_addrlen) == 0 ) break;
      close(sfd);
    }

    if (rp == NULL){
        perror("could not bind");
    }
    freeaddrinfo(result);
    int nsfd;
    listen(sfd,100);

    for(;;){

        peer_addr_len = sizeof(struct sockaddr_storage);
        nsfd = accept(sfd,(struct sockaddr*) &peer_addr_len,&peer_addr_len);
        nread = recv(nsfd,buf,BUFFER_SIZE,0);
        if(nread == -1)
            continue;
        printf("got ...%d",nread); // this line never prints?????
        char host[NI_MAXHOST], service[NI_MAXSERV];
        s = getnameinfo((struct sockaddr*) &peer_addr,
                peer_addr_len,host,NI_MAXHOST,
                service,NI_MAXSERV,NI_NUMERICSERV);

        if (s == 0) printf("recieved %s bytes from host:%s port:%s",nread,host,service);
        else printf("got %d in s",s);
        if(send(nsfd,buf,nread,0) != nread)
            perror("error sending response");
    }
return 0;
}
</code>```

答:
[this text intended for people who cannot read the code]

Add an extra loop after accept() has succeeded. This loop finishes once the connection is terminated.

check errno after read() returns -1

diagnostic output should go to stderr, not stdout.

```<code>for(;;){

    peer_addr_len = sizeof(struct sockaddr_storage);
    nsfd = accept(sfd,(struct sockaddr*) &peer_addr_len,&peer_addr_len);
    if (nsfd ==-1) {perror("error sending response"); break; }

    for(;;) {
            nread = recv(nsfd,buf,BUFFER_SIZE,0);
            fprintf(stderr, "got ...%d",nread);
            if(nread == -1){
                    if(errno==EAGAIN) continue;
                    else break;
                    }
            if(nread == 0) break;

            char host[NI_MAXHOST], service[NI_MAXSERV];
            s = getnameinfo((struct sockaddr*) &peer_addr,
                    peer_addr_len,host,NI_MAXHOST,
                    service,NI_MAXSERV,NI_NUMERICSERV);

            if (s == 0) fprintf(stderr
                    , "received %s bytes from host:%s port:%s\n"
                    , nread,host,service);
            else fprintf(stderr, "got %d in s\n", s);

            if(send(nsfd,buf,nread,0) != nread) {
                    perror("error sending response");
                    break;
                    }

    }
    close(nsfd);
}
</code>```

Title: TCP server hangs after first connection

Body:
i am implementing a simple TCP echo server, which writes back whatever is written to it.i use telnet to connect to it when i first send some data to it,it is sent back(expected) but after that it hangs on i assume as nothing is sent back.

here is my code (a little modified version of example in  man getaddrinfo).is there any problem with how i recv() and send() below?

#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>

#define MAX_LISTEN_BACKLOG 1
#define BUFFER_SIZE 4096

int main(int argc, char* argv[]){
    char buf[BUFFER_SIZE];
    int sfd,n,s;
    struct addrinfo hints;
    struct addrinfo *result;
    struct addrinfo *rp;
    struct sockaddr_storage peer_addr;
    socklen_t peer_addr_len;
    ssize_t nread;
    int addr_info_error;

    memset(&hints,0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    hints.ai_protocol = 0;
    hints.ai_canonname = NULL;
    hints.ai_addr = NULL;
    hints.ai_next = NULL;

    s = getaddrinfo(NULL, argv[1], &hints, &result);
    if (s != 0){
        printf("got error getaddrinfo");
    }

    for( rp = result; rp !=NULL; rp = rp->ai_next){
      sfd = socket(rp->ai_family,rp->ai_socktype,rp->ai_protocol);
      if (sfd == -1) perror("could not create socket");
      if (bind(sfd,rp->ai_addr,rp->ai_addrlen) == 0 ) break;
      close(sfd);
    }

    if (rp == NULL){
        perror("could not bind");
    }
    freeaddrinfo(result);
    int nsfd;
    listen(sfd,100);

    for(;;){

        peer_addr_len = sizeof(struct sockaddr_storage);
        nsfd = accept(sfd,(struct sockaddr*) &peer_addr_len,&peer_addr_len);
        nread = recv(nsfd,buf,BUFFER_SIZE,0);
        if(nread == -1)
            continue;
        printf("got ...%d",nread); // this line never prints?????
        char host[NI_MAXHOST], service[NI_MAXSERV];
        s = getnameinfo((struct sockaddr*) &peer_addr,
                peer_addr_len,host,NI_MAXHOST,
                service,NI_MAXSERV,NI_NUMERICSERV);

        if (s == 0) printf("recieved %s bytes from host:%s port:%s",nread,host,service);
        else printf("got %d in s",s);
        if(send(nsfd,buf,nread,0) != nread)
            perror("error sending response");
    }
return 0;
}

Body:
[this text intended for people who cannot read the code]

Add an extra loop after accept() has succeeded. This loop finishes once the connection is terminated.

check errno after read() returns -1

diagnostic output should go to stderr, not stdout.

for(;;){

    peer_addr_len = sizeof(struct sockaddr_storage);
    nsfd = accept(sfd,(struct sockaddr*) &peer_addr_len,&peer_addr_len);
    if (nsfd ==-1) {perror("error sending response"); break; }

    for(;;) {
            nread = recv(nsfd,buf,BUFFER_SIZE,0);
            fprintf(stderr, "got ...%d",nread);
            if(nread == -1){
                    if(errno==EAGAIN) continue;
                    else break;
                    }
            if(nread == 0) break;

            char host[NI_MAXHOST], service[NI_MAXSERV];
            s = getnameinfo((struct sockaddr*) &peer_addr,
                    peer_addr_len,host,NI_MAXHOST,
                    service,NI_MAXSERV,NI_NUMERICSERV);

            if (s == 0) fprintf(stderr
                    , "received %s bytes from host:%s port:%s\n"
                    , nread,host,service);
            else fprintf(stderr, "got %d in s\n", s);

            if(send(nsfd,buf,nread,0) != nread) {
                    perror("error sending response");
                    break;
                    }

    }
    close(nsfd);
}


问:
Array conversion?
I'm really new to javascript, and when trying to achieve the following I stumbled upon some problems. I tried searching the forum - and a problem like this is probably something that has been solved before, but I don't know what to search for. This is also the reason for the extremely creative title:/

Anyhow - this is my current code:

```<code>var arraylength = 4;
var originalarray = new Array(new Array);
var originalarray = {
    [1, 1, 1, 1]
    [2, 2, 2, 2]
    [3, 3, 3, 3]
    [4, 4, 4, 4]
}

convertarray(originalarray, arraylength);

function convertarray(originalarray, arraylength){
    var converedtarray = new Array(new Array);
    var temparray = new Array;
    temparray.length = arraylength;

    for (h = 0; h < arraylength; h++) {
        var temparray  = [];
        var temparray = originalarray[h].split('');

        for (i = 0; i < arraylength; i++) {
            converedtarray[h][i] = temparray[i];
        }
    }
return convertedarray;
}
</code>```

I am not entirely sure if the code speaks for itself, but this is pseudo for what I want to achieve;

```<code>originalarray = 1111, 2222, 3333, 4444
converedtarray = 1234, 1324, 1234, 1234
</code>```

Can someone tell me what part I've missed or give me a hint of what I can do?
Because I'm getting "TypeError: undefined is not an object" at this part:

```<code>converedtarray[h][i] = temparray[i];
</code>```

I am by no means a professional coder - I know the code isn't pretty, but this is more or less the result of trial-and error... More error than trial actually.

Thank you in advance for your answer!

答:
There are a few problems with your code. Firstly if you want a nXn array you have defined originalarray wrong. Second new Array(new Array) won't declare an array of array for you if that is what you were thinking. You will need two loops here as you have already figured out the first one for maintaining columns and the second one for rows.

var arraylength = 4;
var originalarray = new Array();
var originalarray = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]
]

console.log(convertarray(originalarray, arraylength));

function convertarray(originalarray, arraylength){
var converedtarray = new Array();

for (h = 0; h < arraylength; h++) {
    converedtarray[h] = [];
    for (i = 0; i < arraylength; i++) {
        converedtarray[h].push(originalarray[i][h]);
    }
}
return converedtarray;
}```

Title: Array conversion?

Body:
I'm really new to javascript, and when trying to achieve the following I stumbled upon some problems. I tried searching the forum - and a problem like this is probably something that has been solved before, but I don't know what to search for. This is also the reason for the extremely creative title:/

Anyhow - this is my current code:

var arraylength = 4;
var originalarray = new Array(new Array);
var originalarray = {
    [1, 1, 1, 1]
    [2, 2, 2, 2]
    [3, 3, 3, 3]
    [4, 4, 4, 4]
}

convertarray(originalarray, arraylength);

function convertarray(originalarray, arraylength){
    var converedtarray = new Array(new Array);
    var temparray = new Array;
    temparray.length = arraylength;

    for (h = 0; h < arraylength; h++) {
        var temparray  = [];
        var temparray = originalarray[h].split('');

        for (i = 0; i < arraylength; i++) {
            converedtarray[h][i] = temparray[i];
        }
    }
return convertedarray;
}

I am not entirely sure if the code speaks for itself, but this is pseudo for what I want to achieve;

originalarray = 1111, 2222, 3333, 4444
converedtarray = 1234, 1324, 1234, 1234

Can someone tell me what part I've missed or give me a hint of what I can do?
Because I'm getting "TypeError: undefined is not an object" at this part:

converedtarray[h][i] = temparray[i];

I am by no means a professional coder - I know the code isn't pretty, but this is more or less the result of trial-and error... More error than trial actually.

Thank you in advance for your answer!


问:
perl6/rakudo: How could I disable autoflush?
I tried this, but it didn't work:</p>

```<code>$*OUT.autoflush( 0 );
</code>```

答:
Rakudo doesn't support autoflush. There's a note in 5to6-perlvar under the $OUTPUT_AUTOFLUSH entry.

Some examples from a long time ago mention an autoflush method, but that has disappeared:

```<code>$*ERR.autoflush = True;
$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";
</code>```

But that doesn't work:

No such method 'autoflush' for invocant of type 'IO::Handle'

I haven't seen any discussions about when this might show up as a feature, or a proclamation that it will never be a feature.

Body:
I tried this, but it didn't work:

$*OUT.autoflush( 0 );

Body:
Rakudo doesn't support autoflush. There's a note in 5to6-perlvar under the $OUTPUT_AUTOFLUSH entry.

Some examples from a long time ago mention an autoflush method, but that has disappeared:

$*ERR.autoflush = True;
$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";

But that doesn't work:

No such method 'autoflush' for invocant of type 'IO::Handle'

I haven't seen any discussions about when this might show up as a feature, or a proclamation that it will never be a feature.


问:
Facebook share shows 404 page not found
While sharing the following link https://cargo2share.com/ru/blog/aerophobia in facebook I am getting 404 page not found preview. When I share it in Google+, Vk.com or in another networks it shows the correct page and image in preview. Any ideas?

答: Thanks to @Rinos comment I could find the right solution. Apparently, Facebook has cached this page before it was existing. I had to go to Facebook Sharing Debugger under https://developers.facebook.com/tools/debug/sharing and for my URL press the Scrape Again button to renew the cached information.

Title: Facebook share shows 404 page not found


答:
A possible solution:

var arraylength = 4;
var originalarray = [
  [1, 1, 1, 1],
  [2, 2, 2, 2],
  [3, 3, 3, 3],
  [4, 4, 4, 4],
];

function convertarray(originalarray, arraylength) {
  var result = [];
  for (h = 0; h < arraylength; h++) {
    result.push(
      originalarray.map(function(subarray) {
        return subarray[h];
      })
    );
  }
  return result;
}

console.log(
  convertarray(originalarray, arraylength)
);```

Title: Array conversion?