问:
Keras: My model trains without any given labels. How's it possible?
Yesterday I created my first convolutional neural network in keras but I forgot to add labels and it trained ... somehow, and I have no idea how. Can someone explain how the heck it trained without any labels given?

Jupyter Notebook:
http://nbviewer.jupyter.org/github/getrasa/Jupyter-Notebook-Share/blob/master/Untitled.ipynb

Folder structure
files/ train/
 dogs/
  dog.0.jpg
 ...
 cats/
  cat.0.jpg
...
files/ validation/
 dogs/
  dog.1301.jpg
 ...
 cats/
  cat.1301.jpg
files/test/
 (1-13images).jpg

答:
No magic here. From the docs:

flow_from_directory(directory): Takes the path to a directory, and
  generates batches of augmented/normalized data. Yields batches
  indefinitely, in an infinite loop.

Arguments:

directory: path to the target directory. It should contain one
  subdirectory per class. Any PNG, JPG or BMP images inside each of the
  subdirectories directory tree will be included in the generator

As long as your data is split into subdirectories that correspond to your classes, ImageDataGenerator will produce labels out of these. For instance, take this directory structure:

```<code>train/
   cat/
   dog/
   eel/
</code>```

The flow_from_directory will by default take these as categorical and use one-hot encoding in the background. That's how you get labels.

One final note: since you have only two classes, you can consider changing class_mode to binary.

Body:
No magic here. From the docs:

flow_from_directory(directory): Takes the path to a directory, and
  generates batches of augmented/normalized data. Yields batches
  indefinitely, in an infinite loop.

Arguments:

directory: path to the target directory. It should contain one
  subdirectory per class. Any PNG, JPG or BMP images inside each of the
  subdirectories directory tree will be included in the generator

As long as your data is split into subdirectories that correspond to your classes, ImageDataGenerator will produce labels out of these. For instance, take this directory structure:

train/
   cat/
   dog/
   eel/

The flow_from_directory will by default take these as categorical and use one-hot encoding in the background. That's how you get labels.

One final note: since you have only two classes, you can consider changing class_mode to binary.


来源: stackexchange

问:
adsense api access & wrapper
Can anybody give me a definitive answer to the following question:

is adsense api available to any user? or are there restrictions?

And is there a simple PHP wrapper for either case?  I mostly need reporting from the adsense account.

答: The AdSense API is only avaliable to users with over 100,000 pageviews a day. If you're at or above that limit, some PHP examples are available here.</p>

ContentLicense: CC BY-SA 2.5

Title: adsense api access & wrapper


问:
Custom User Control not binding data
I've created a user control that have a label and textbox.
i added two DependencyProperties (Text and Label) and bind them to textbox.text and label.content.
however, i'm not able to see the text of textbox.

in the main window, when i'm not binding to any element the label is shown but if i binding the element is not shown. the textbox not showing either way.

here's the xaml:

```<code><UserControl x:Class="TestNewLabeltextbox.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal" Background="White" FlowDirection="RightToLeft">
    <Label x:Name="lbl" Content="{Binding Label, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100"  HorizontalAlignment="Left" Background="blue">
        <Label.Style>
            <Style TargetType="Label">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Label">
                            <StackPanel Orientation="Horizontal">
                                <Border Background="Blue" Width="200" BorderThickness="0,0,0,0">
                                    <StackPanel Orientation="Horizontal">
                                        <Viewbox StretchDirection="DownOnly" Stretch="Uniform">
                                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" TextBlock.FontSize="14" TextBlock.Foreground="#FFFFFF" Margin="5">
                                                <ContentPresenter.Effect>
                                                    <DropShadowEffect BlurRadius="0.0"
                                              Color="#032A6B"
                                              Direction="90"
                                              Opacity="1"
                                              ShadowDepth="1" />
                                                </ContentPresenter.Effect>
                                            </ContentPresenter>
                                        </Viewbox>
                                    </StackPanel>
                                </Border>
                            </StackPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Label.Style>
    </Label>
    <TextBox x:Name="txt" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="120" HorizontalAlignment="Right">
        <TextBox.Style>
            <Style TargetType="TextBox">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="TextBox">
                            <Border CornerRadius="0,0,0,50" BorderBrush="Black" Background="White" BorderThickness="0">
                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" TextBlock.FontSize="14" TextBlock.Foreground="#FFFFFF" Margin="5">
                                    <ContentPresenter.Effect>
                                        <DropShadowEffect BlurRadius="0.0"
                                              Color="#032A6B"
                                              Direction="90"
                                              Opacity="1"
                                              ShadowDepth="1" />
                                    </ContentPresenter.Effect>
                                </ContentPresenter>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TextBox.Style>
    </TextBox>
</StackPanel>
</code>```

Here'sUserControl1.cs:

```<code>public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }

    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
    public string Label
    {
        get { return (string)this.GetValue(LabelProperty); }
        set { this.SetValue(LabelProperty, value); }
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
    public string Text
    {
        get { return (string)this.GetValue(TextProperty); }
        set { this.SetValue(TextProperty, value); }
    }
}
</code>```

here's the window xaml + cs:

```<code><Window x:Class="TestNewLabeltextbox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:TestNewLabeltextbox"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel Orientation="Vertical" Height="150">
        <controls:UserControl1 Text="hello" Height="50" Label="{Binding Hello, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <controls:UserControl1 Text="hello" Height="50" Label="world" />
        <Label BorderBrush="Black" BorderThickness="2" Width="100" Height="50" Content="{Binding Hello, Mode=TwoWay}"/>
    </StackPanel>
</Grid>
</code>```

```<code>public partial class MainWindow : Window
{
    ViewModel vm = new ViewModel();
    public MainWindow()
    {
        InitializeComponent();
        vm.Hello = "555";
        this.DataContext = vm;
    }
}
</code>```

viewmodel.cs

```<code>public class ViewModel : INotifyPropertyChanged
{
    private string h = "Hello";
    public string Hello
    {
        get
        {
            return h;
        }
        set
        {
            h = value;
            NotifyPropertyChanged("Hello");
        }
    }

    #region "PropertyChanged Event"
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}
</code>```

答:
Default Source of binding is DataContext. But your Label and Text dependency properties defined in the control rather than in view-model. Change binding of Label to

```<code>{Binding Path=Label, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}
</code>```

and binding of TextBox to

```<code>{Binding Path=Text, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
</code>```

Please read about Mode and UpdateSourceTrigger properties of Binding. It seems that you don't know how they work. Mode=TwoWay, UpdateSourceTrigger=PropertyChanged doesn't make any sense for Content property.

ContentLicense: CC BY-SA 3.0

Title: Custom User Control not binding data

Body:
I've created a user control that have a label and textbox.
i added two DependencyProperties (Text and Label) and bind them to textbox.text and label.content.
however, i'm not able to see the text of textbox.

in the main window, when i'm not binding to any element the label is shown but if i binding the element is not shown. the textbox not showing either way.

here's the xaml:

<UserControl x:Class="TestNewLabeltextbox.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal" Background="White" FlowDirection="RightToLeft">

    <TextBox x:Name="txt" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="120" HorizontalAlignment="Right">
        <TextBox.Style>

        </TextBox.Style>
    </TextBox>
</StackPanel>

Here'sUserControl1.cs:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }

    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
    public string Label
    {
        get { return (string)this.GetValue(LabelProperty); }
        set { this.SetValue(LabelProperty, value); }
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
    public string Text
    {
        get { return (string)this.GetValue(TextProperty); }
        set { this.SetValue(TextProperty, value); }
    }
}

here's the window xaml + cs:

<Window x:Class="TestNewLabeltextbox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:TestNewLabeltextbox"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel Orientation="Vertical" Height="150">
        <controls:UserControl1 Text="hello" Height="50" Label="{Binding Hello, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <controls:UserControl1 Text="hello" Height="50" Label="world" />

    </StackPanel>
</Grid>

public partial class MainWindow : Window
{
    ViewModel vm = new ViewModel();
    public MainWindow()
    {
        InitializeComponent();
        vm.Hello = "555";
        this.DataContext = vm;
    }
}

viewmodel.cs

public class ViewModel : INotifyPropertyChanged
{
    private string h = "Hello";
    public string Hello
    {
        get
        {
            return h;
        }
        set
        {
            h = value;
            NotifyPropertyChanged("Hello");
        }
    }

    #region "PropertyChanged Event"
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}

Body:
Default Source of binding is DataContext. But your Label and Text dependency properties defined in the control rather than in view-model. Change binding of Label to

{Binding Path=Label, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}

and binding of TextBox to

{Binding Path=Text, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}

Please read about Mode and UpdateSourceTrigger properties of Binding. It seems that you don't know how they work. Mode=TwoWay, UpdateSourceTrigger=PropertyChanged doesn't make any sense for Content property.


问:
CodeIgniter SMTP email message - characters replaced with equal signs
I'm using the CodeIgniter email library to send emails using our Exchange server. The problem I get is that the content of the email gets messed up.

There are some words that get replaced with equal signs "=", I tried 2 different Exchange servers (they are in different locations and have no relation what so ever) and I still get the same issue. If I use any other server as an SMTP server to send emails everything works fine and the content stays intact and unchanged.

Content before sending:

```<code>Dear Customer

Please find attached a comprehensive explanation of how to get our brochure of Angola. This has been sent to you at the request of Alex.

The information has been taken from www.example.co.uk  "Company name" is one of the leading tile and marble companies in the UK.
</code>```

Content after sending it through the Microsoft Exchange:

```<code>Dear Customer

Please find attached a comprehensive explanation of how to get our brochure of A=gola. This has been sent to you at the request of Alex.

The information has been taken from www.example.co.uk  "Company name" is one of the leadi=g tile and marble companies in the UK.
</code>```

As you can see for some reason some of the "n" characters were replaced with equal signs "=" (Example: Angola > A=gola)

My email configuration:

```<code>$this->load->library('email');
$config['charset']      = 'utf-8';
$config['mailtype']     = 'html';

// SMTP
$config['protocol']     = 'smtp';
$config['smtp_host']    = 'exchange.example.com'; //ssl://
$config['smtp_user']    = 'email@example.com';
$config['smtp_pass']    = 'password';
$config['smtp_port']    = 25;

$this->email->set_newline( "\r\n" );

$this->email->initialize( $config );

$this->email->clear();

......

$this->email->from( $frome, $fromn );
$this->email->to( $email );

$this->email->subject( $subject );
$this->email->message( $send_message );

$this->email->send();
</code>```

Does anyone know why is the Microsoft exchange behaving this way? or is there some sort of setting I should use?

答:
I solved this (kinda) by setting $charlim = '998' in the _prep_quoted_printable function.

When I set $crlf = "\r\n" the resulting email was completely garbled for some reason. But I noticed that the = signs were appearing at regular intervals which was caused by the line length being limited to 76 characters. So increasing the max characters per line (998 is the RFC2822 limit) solves the problem, as long as you don't have really long lines.

Body:
I'm using the CodeIgniter email library to send emails using our Exchange server. The problem I get is that the content of the email gets messed up.

There are some words that get replaced with equal signs "=", I tried 2 different Exchange servers (they are in different locations and have no relation what so ever) and I still get the same issue. If I use any other server as an SMTP server to send emails everything works fine and the content stays intact and unchanged.

Content before sending:

Dear Customer

Please find attached a comprehensive explanation of how to get our brochure of Angola. This has been sent to you at the request of Alex.

The information has been taken from www.example.co.uk  "Company name" is one of the leading tile and marble companies in the UK.

Content after sending it through the Microsoft Exchange:

Dear Customer

Please find attached a comprehensive explanation of how to get our brochure of A=gola. This has been sent to you at the request of Alex.

The information has been taken from www.example.co.uk  "Company name" is one of the leadi=g tile and marble companies in the UK.

As you can see for some reason some of the "n" characters were replaced with equal signs "=" (Example: Angola > A=gola)

My email configuration:

$this->load->library('email');
$config['charset']      = 'utf-8';
$config['mailtype']     = 'html';

// SMTP
$config['protocol']     = 'smtp';
$config['smtp_host']    = 'exchange.example.com'; //ssl://
$config['smtp_user']    = 'email@example.com';
$config['smtp_pass']    = 'password';
$config['smtp_port']    = 25;

$this->email->set_newline( "\r\n" );

$this->email->initialize( $config );

$this->email->clear();

......

$this->email->from( $frome, $fromn );
$this->email->to( $email );

$this->email->subject( $subject );
$this->email->message( $send_message );

$this->email->send();

Does anyone know why is the Microsoft exchange behaving this way? or is there some sort of setting I should use?


问:
How to extract title from P tag
```<code><p class="mrgn-bttm-0 pop text-center" title="Chance of Precipitation"><small> 30%</small></p>
</code>```

I want to extract "Chance of Precipitation 30%" from the above example p tag. There are actually 14 of these tags, one for each day. I got all the p tags using;

```<code>f = soup.find('details', {'class':"panel panel-default wxo-fcst"})
</code>```

then I have tried:

```<code>for i in f:
    print i.find('p')['title']
</code>```

and

```<code>for i in x.findAll("p"):
    print i.find('p')['title'])
</code>```

but I am getting nowhere. Can someone assist please?

答:
Try this way out:

```<code>f = soup.find('details', {'class':"panel panel-default wxo-fcst"})
for i in f.find_all('p',{'class':'mrgn-bttm-0 pop text-center'}):
    print i['title']+" "+i.get_text().strip()
</code>```

Output:

```<code>Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation 60%
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation 60%
</code>```

Title: How to extract title from P tag

Body:
 30%

I want to extract "Chance of Precipitation 30%" from the above example p tag. There are actually 14 of these tags, one for each day. I got all the p tags using;

f = soup.find('details', {'class':"panel panel-default wxo-fcst"})

then I have tried:

for i in f:
    print i.find('p')['title']

and

for i in x.findAll("p"):
    print i.find('p')['title'])

but I am getting nowhere. Can someone assist please?

Body:
Try this way out:

f = soup.find('details', {'class':"panel panel-default wxo-fcst"})
for i in f.find_all('p',{'class':'mrgn-bttm-0 pop text-center'}):
    print i['title']+" "+i.get_text().strip()

Output:

Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation 60%
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation
Chance of Precipitation 60%


问:
Which backends are consuming Google Container Engine Kubernetes Quotas
I am trying to setup an Ingress on Kubernetes on Google Container Engine and am getting quota exceeded errors (see abbrieviated output below).

```<code>Name:                   my-ingress
Address:
Default backend:        default-http-backend:80 (10.0.2.2:8080)
Rules:
  Host  Path    Backends
  ----  ----    --------
  *
        service1  service1:7010 (<none>)
        service2  service2:6884 (<none>)
Annotations:
  ssl-redirect: false
Events:
  FirstSeen  LastSeen  Count   From                       Type       Reason          Message
  ---------  --------  -----   ----                       --------   ------          -------
  21s        21s       1       loadbalancer-controller    Normal     ADD             reference/reference-ingress
  13s        3s        10      loadbalancer-controller    Warning    GCE :Quota      googleapi: Error 403: Quota 'BACKEND_SERVICES' exceeded. Limit: 5.0, quotaExceeded
</code>```

I know how to increase my quotas, but my question is more specific:  how can I tell which "backends" are being consumed that are contributing the usage of the quota? (I will then want to see if I may be able to turn them off if needed).

答:
According to this page:

```<code>gcloud compute backend-services list
</code>```

will list all your backend services in all clusters.
For my case, it lists 6 and match my usage reported by:

```<code>gcloud compute project-info describe --project PROJECT_NAME
</code>```

Body:
I am trying to setup an Ingress on Kubernetes on Google Container Engine and am getting quota exceeded errors (see abbrieviated output below).

Name:                   my-ingress
Address:
Default backend:        default-http-backend:80 (10.0.2.2:8080)
Rules:
  Host  Path    Backends
  ----  ----    --------
  *
        service1  service1:7010 (<none>)
        service2  service2:6884 (<none>)
Annotations:
  ssl-redirect: false
Events:
  FirstSeen  LastSeen  Count   From                       Type       Reason          Message
  ---------  --------  -----   ----                       --------   ------          -------
  21s        21s       1       loadbalancer-controller    Normal     ADD             reference/reference-ingress
  13s        3s        10      loadbalancer-controller    Warning    GCE :Quota      googleapi: Error 403: Quota 'BACKEND_SERVICES' exceeded. Limit: 5.0, quotaExceeded

I know how to increase my quotas, but my question is more specific:  how can I tell which "backends" are being consumed that are contributing the usage of the quota? (I will then want to see if I may be able to turn them off if needed).

Body:
According to this page:

gcloud compute backend-services list

will list all your backend services in all clusters.
For my case, it lists 6 and match my usage reported by:

gcloud compute project-info describe --project PROJECT_NAME


问:
By declaring character type T, online judge shows Runtime Error(SIGSEGV)
```<code>#include<stdio.h>
#include<math.h>
int main(void)
{
    //variable declaration
    char T;
    int N, i;
    double f;

    scanf("%d",&T);

    //for loop for T times iteration
    for(i=1;i<=T;i++){
        //input number  for checking its square root
        scanf("%d", &N);
        //sqrt() library function for square root
        f= sqrt(N);

        //checking if N has int type square root
        if(f - (int)f == 0)
            printf("YES\n");

        else
            printf("NO\n");
    }//for loop ends

    return 0;
}
</code>```

Output in Code Blocks:

3

16

YES

15

NO

14

No

Online judge shows:
Result: runtime error (SIGSEGV)

The program will take input for number of lines to be printed. And in each line it will take an integer type number and checks whether the number is square root or not. If yes, then it will print 'YES'. Otherwise 'No'.

In my code, Range of T should be T<=100. So, I declared T as character data
type. And I know the range of char is -128 to 127 or 0 to 255. I think it
should work. I compiled this program in Code Blocks without any error. It
gives right output. But when I compiled in online judge it gives runtime
error (SIGSEGV).

Can anyone please help me why does it happen?
Thank you.

答:
Change char T; to int T;
Because char can not save value more than 255

Body:
#include<stdio.h>
#include<math.h>
int main(void)
{
    //variable declaration
    char T;
    int N, i;
    double f;

    scanf("%d",&T);

    //for loop for T times iteration
    for(i=1;i<=T;i++){
        //input number  for checking its square root
        scanf("%d", &N);
        //sqrt() library function for square root
        f= sqrt(N);

        //checking if N has int type square root
        if(f - (int)f == 0)
            printf("YES\n");

        else
            printf("NO\n");
    }//for loop ends

    return 0;
}

Output in Code Blocks:

3

16

YES

15

NO

14

No

Online judge shows:
Result: runtime error (SIGSEGV)

The program will take input for number of lines to be printed. And in each line it will take an integer type number and checks whether the number is square root or not. If yes, then it will print 'YES'. Otherwise 'No'.

In my code, Range of T should be T<=100. So, I declared T as character data
type. And I know the range of char is -128 to 127 or 0 to 255. I think it
should work. I compiled this program in Code Blocks without any error. It
gives right output. But when I compiled in online judge it gives runtime
error (SIGSEGV).

Can anyone please help me why does it happen?
Thank you.


问:
C# - Call the same javascript function inside a loop
Good day!

I am trying to achieve to change the color in the calendar cell of EXT Calendar for each holiday (holiday dates are from the database). But it only changes the first holiday which is the first line in the database.

My client side code :

```<code>        var applyCss = function (param1) {
        var css = "#CalendarPanel1-month-day-" + param1 + " {background-color: pink;}";

        Ext.net.ResourceMgr.registerCssClass("someCssClassId", css);
    };
</code>```

My server side code:

```<code>DataTable holiday = Attendance.getInstance().getHolidays();

            for (var i = 0; i < holiday.Rows.Count; i++)
            {
                var hd = holiday.Rows[i]["holiday_date"].ToString();
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "applyCss(" + hd + ")", true);

            }
</code>```

Appreciate any recommendations / suggestions / solutions. Thanks!

答:
The reason is that you can only call Page.ClientScript.RegisterClientScriptBlock once per postback.

My suggestion: Create a string that will hold all the scripts you would like to run, and use that string in Page.ClientScript.RegisterClientScriptBlock:

```<code>DataTable holiday = Attendance.getInstance().getHolidays();
string script = string.Empty;

for (var i = 0; i < holiday.Rows.Count; i++)
{
     var hd = holiday.Rows[i]["holiday_date"].ToString();
     script += " applyCss(" + hd + "); ";
}
Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", script, true);
</code>```

Body:
Good day!

I am trying to achieve to change the color in the calendar cell of EXT Calendar for each holiday (holiday dates are from the database). But it only changes the first holiday which is the first line in the database.

My client side code :

        var applyCss = function (param1) {
        var css = "#CalendarPanel1-month-day-" + param1 + " {background-color: pink;}";

        Ext.net.ResourceMgr.registerCssClass("someCssClassId", css);
    };

My server side code:

DataTable holiday = Attendance.getInstance().getHolidays();

            for (var i = 0; i < holiday.Rows.Count; i++)
            {
                var hd = holiday.Rows[i]["holiday_date"].ToString();
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "applyCss(" + hd + ")", true);

            }

Appreciate any recommendations / suggestions / solutions. Thanks!

Body:
The reason is that you can only call Page.ClientScript.RegisterClientScriptBlock once per postback.

My suggestion: Create a string that will hold all the scripts you would like to run, and use that string in Page.ClientScript.RegisterClientScriptBlock:

DataTable holiday = Attendance.getInstance().getHolidays();
string script = string.Empty;

for (var i = 0; i < holiday.Rows.Count; i++)
{
     var hd = holiday.Rows[i]["holiday_date"].ToString();
     script += " applyCss(" + hd + "); ";
}
Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", script, true);


问:
Confusing artifacts in PyWavelet complex-Morlet analysis of 1-kHz signal
I have some artifacts in a PyWavelets transform that are really confusing me. I'm using version 0.5.2. Can someone explain what is happening here?

I start by creating a 1-kHz signal, and then I attempt to analyze this signal with a complex Morlet continuous wavelet transform. I'm doing so with 3 octaves: 0.5 kHz to 1 kHz, 1 kHz to 2 kHz, and 2 kHz to 4 kHz, each one with 40 log-scaled scales. My intuition says that there should be a single peak at y=40 (being equivalent to 1 kHz), and that any difference in time should be minimal. Instead, I'm getting a peak at around y=35 to 37 (0.92 to 0.95 kHz), and there's some kind of periodic effect. (Strangely, this effect seems to occur only in the real component of the transform--the imaginary component looks closer to how I imagined it should look, though it's still not centered correctly. I believe that the real component and the imaginary component should look like time-shifted versions of each other, when looking at a pure sine wave.)

Am I misusing PyWavelets? Is there possibly a bug here? Any help would be welcome.

```<code>import numpy
import pywt
import matplotlib.pyplot as plt

# makes a 1-kHz signal
def make_data(length, quality):
    tau = 2*numpy.pi
    x = numpy.arange(length)
    y = numpy.sin(tau * x/(quality/1000)) # the 1000 is for 1 kHz
    return y

# does the continuous wavelet transform, outputting pic
def do_transform(data, base_freq, num_octaves, voices_per_octave, quality):
    # calculate the scales, based on the desired frequencies
    base_scale = quality / (2*base_freq)
    far_scale = base_scale / 2**num_octaves
    scales = numpy.geomspace(base_scale, far_scale, num=num_octaves*voices_per_octave+1, endpoint=True)

    # actual calculation
    coeffs, freqs = pywt.cwt(data, scales, "cmor", 1/quality)

    print("freqs: " +str(freqs))

    # output
    truncated = coeffs[:, 100:200]
    plt.imshow(abs(truncated), origin='lower', interpolation='none')
    #plt.imshow(truncated.real, origin='lower', interpolation='none')
    #plt.imshow(truncated.imag, origin='lower', interpolation='none')
    plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.05)
    plt.show()

data = make_data(1000, 44100)
do_transform(data, 500, 3, 40, 44100)
</code>```

Magnitudes of transform

Real components of transform

Imaginary components of transform

答:
It turns out that this is a known issue. (It's still not clear if this is a bug or just unexpected behavior, but the discussion is here: https://github.com/PyWavelets/pywt/issues/307 .)

Thanks to everyone who looked at it and considered it.

Body:
I have some artifacts in a PyWavelets transform that are really confusing me. I'm using version 0.5.2. Can someone explain what is happening here?

I start by creating a 1-kHz signal, and then I attempt to analyze this signal with a complex Morlet continuous wavelet transform. I'm doing so with 3 octaves: 0.5 kHz to 1 kHz, 1 kHz to 2 kHz, and 2 kHz to 4 kHz, each one with 40 log-scaled scales. My intuition says that there should be a single peak at y=40 (being equivalent to 1 kHz), and that any difference in time should be minimal. Instead, I'm getting a peak at around y=35 to 37 (0.92 to 0.95 kHz), and there's some kind of periodic effect. (Strangely, this effect seems to occur only in the real component of the transform--the imaginary component looks closer to how I imagined it should look, though it's still not centered correctly. I believe that the real component and the imaginary component should look like time-shifted versions of each other, when looking at a pure sine wave.)

Am I misusing PyWavelets? Is there possibly a bug here? Any help would be welcome.

import numpy
import pywt
import matplotlib.pyplot as plt

# makes a 1-kHz signal
def make_data(length, quality):
    tau = 2*numpy.pi
    x = numpy.arange(length)
    y = numpy.sin(tau * x/(quality/1000)) # the 1000 is for 1 kHz
    return y

# does the continuous wavelet transform, outputting pic
def do_transform(data, base_freq, num_octaves, voices_per_octave, quality):
    # calculate the scales, based on the desired frequencies
    base_scale = quality / (2*base_freq)
    far_scale = base_scale / 2**num_octaves
    scales = numpy.geomspace(base_scale, far_scale, num=num_octaves*voices_per_octave+1, endpoint=True)

    # actual calculation
    coeffs, freqs = pywt.cwt(data, scales, "cmor", 1/quality)

    print("freqs: " +str(freqs))

    # output
    truncated = coeffs[:, 100:200]
    plt.imshow(abs(truncated), origin='lower', interpolation='none')
    #plt.imshow(truncated.real, origin='lower', interpolation='none')
    #plt.imshow(truncated.imag, origin='lower', interpolation='none')
    plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.05)
    plt.show()

data = make_data(1000, 44100)
do_transform(data, 500, 3, 40, 44100)

Magnitudes of transform

Real components of transform

Imaginary components of transform


问:
Record reader that can split by two kinds of separators
I have a case where I need to read files with lines of the format

```<code>Field1,Field2,Field3,Field4,Field5,Field6#Field1,Field2,Field3
</code>```

While one way to achive this would be to use a record reader like KeyValueLineRecordReader with the separator #. But I will have to split the key and value on , in my UDF using String.split which I feel can slow down the execution.

 1. Are there any record readers that serve formats of this type?
 2. If one such a record writer doesn't exist, what are my alternatives for reading such a line efficiently?

Input data is ~10GB.

答:
Since you have tagged the question with apache-pig,I'll give a PIG solution.Load the record into 1 field,replace # with ',' and then use STRSPLIT to get the individual fields.No need for java or any UDF.</p>

```<code>A = LOAD 'input.txt' AS (line:chararray);
B = FOREACH A GENERATE STRSPLIT(REPLACE(line,'#',','),',',9);
DUMP B;
</code>```

Body:
I have a case where I need to read files with lines of the format

Field1,Field2,Field3,Field4,Field5,Field6#Field1,Field2,Field3

While one way to achive this would be to use a record reader like KeyValueLineRecordReader with the separator #. But I will have to split the key and value on , in my UDF using String.split which I feel can slow down the execution.

 1. Are there any record readers that serve formats of this type?
 2. If one such a record writer doesn't exist, what are my alternatives for reading such a line efficiently?

Input data is ~10GB.

Body:
Since you have tagged the question with apache-pig,I'll give a PIG solution.Load the record into 1 field,replace # with ',' and then use STRSPLIT to get the individual fields.No need for java or any UDF.

A = LOAD 'input.txt' AS (line:chararray);
B = FOREACH A GENERATE STRSPLIT(REPLACE(line,'#',','),',',9);
DUMP B;


问:
Using PHP Printer functions in PHP Desktop application

In XAMPP environment

I develop and test my PHP code in XAMPP environment (local) and it success.

In PHP Desktop environment

I already copied the php_printer.dll into the ext folder and include this line extension=php_printer.dll in the php.ini file.

I also moved my folder from htdocs (XAMPP environment) to the www folder (PHP Desktop environment) but when I run the phpdesktop-chrome.exe it shows ...undefined function printer_list()... so I knew that it cannot recognize the library.

My question

How do I configure PHP Desktop to recognize the php_printer.dll as similar to my XAMPP behavior?

Update 1

php_printer.dll failed to load. By the way how do I identify my php_printer.dll  version whether it match PHP Desktop or not? Thank you.

Update 2

Okay I have the version as below:

PHP Desktop: phpdesktop-chrome-57.0-rc-php-7.1.3

php_printer.dll: php_printer-php5.6.30

答:
PHP extensions are often intended for specific PHP versions (eg. 5.12.xx and Thread-safe or non-thread-safe). If your extension doesn't match specific php version it won't work. In such case you should see a startup error if you enable it in php.ini.

For detecting problems during PHP startup see:

https://github.com/cztomczak/phpdesktop/wiki/Knowledge-Base#problem-running-php-script

https://github.com/cztomczak/phpdesktop/wiki/Knowledge-Base#error-500-internal-server-error-cgi-program-sent-malformed-or-too-big-16384-bytes-http-headers

Update

Your extension is for php 5.6.30, so you should download that specific php version, see: https://github.com/cztomczak/phpdesktop/wiki/Knowledge-Base#php-interpreter--extensions

Try non-thread-safe version first and then thread-safe version.


问:
Is it good practice to group methods into a more general method?
I have a bit of setup work that needs to be done in viewDidLoad. I have added all my helper methods into a configure method, so that in viewDidLoad, I just call configure() and everything works. Is this good practice or is it seen as a bad practice of coupling code together.  Any tip is appreciated!

```<code>//configure() called in viewDidLoad
private func configure() {

    UserProvider.sharedInstance.fetchUser(with: AuthProvider.sharedInstance.currentUserId(), completionHandler: {
        user in
        guard let user = user else { return }
        self.currentUser = user

        self.setupViews(currentUser: user)

        self.setupLocation()
    })
}

private func setupViews(currentUser: User) {
    setupCollectionView()
    updateDatasource(currentUser: currentUser)
}

private func setupCollectionView() {
    collectionView.dataSource = datasource
    collectionView.delegate = datasource
}

private func updateDatasource(currentUser: User) {
    UserProvider.sharedInstance.fetchNearbyUsers(for: currentUser, completionHandler: { nearbyUsers in
        guard nearbyUsers.isEmpty == false else { return }
        self.datasource.update(with: nearbyUsers, collectionView: self.collectionView)
    })
}
</code>```

答: It's actually pretty good because that way you can break down your code into smaller code which makes it easier for you to code and also for the person that might read the code. So yes this is a good practice. It doesn't affect the code at all, it just makes it easier for you and other.</p>

Body:
I have a bit of setup work that needs to be done in viewDidLoad. I have added all my helper methods into a configure method, so that in viewDidLoad, I just call configure() and everything works. Is this good practice or is it seen as a bad practice of coupling code together.  Any tip is appreciated!

//configure() called in viewDidLoad
private func configure() {

    UserProvider.sharedInstance.fetchUser(with: AuthProvider.sharedInstance.currentUserId(), completionHandler: {
        user in
        guard let user = user else { return }
        self.currentUser = user

        self.setupViews(currentUser: user)

        self.setupLocation()
    })
}

private func setupViews(currentUser: User) {
    setupCollectionView()
    updateDatasource(currentUser: currentUser)
}

private func setupCollectionView() {
    collectionView.dataSource = datasource
    collectionView.delegate = datasource
}

private func updateDatasource(currentUser: User) {
    UserProvider.sharedInstance.fetchNearbyUsers(for: currentUser, completionHandler: { nearbyUsers in
        guard nearbyUsers.isEmpty == false else { return }
        self.datasource.update(with: nearbyUsers, collectionView: self.collectionView)
    })
}


问:
What's wrong with this image cropper?
I'm making a cropping tool for images and I can't for the life of me figure out why it's producing the images that it's producing...

I'm following the accepted answer here, but its still being weird... Here's my code:

```<code>public void Crop(
    string FileName,
    Crop Crop) {
    using (Bitmap Source = ((Bitmap)Image.FromFile(FileName))) {
        using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
            using (Graphics Graphics = Graphics.FromImage(Target)) {
                Graphics.DrawImage(Source, new Rectangle(new Point(Crop.Left, Crop.Top), new Size(Crop.Width, Crop.Height)), new Rectangle(new Point(0, 0), new Size(Target.Width, Target.Height)), GraphicsUnit.Pixel);
            };

            Target.Save((FileName + ".temp"), JpegCodecInfo, HighQualityEncoder);
        };
    };

    this.NormalizeFileName(FileName);
}
</code>```

Please help me. I'm attaching an image of what I'm getting...

UPDATE

For @Aaronontheweb, here's the Crop class and how it's populated:

```<code>public class Crop {
    [Required]
    public short Height { get; set; }

    [Required]
    public short Left { get; set; }

    [Required]
    public short Top { get; set; }

    [Required]
    public short Width { get; set; }
}
</code>```

And the jQuery that populates it:

```<code>$("#Image input:submit").bind("click", function () {
    $("#Crop\\.Height").val(Crop.height());
    $("#Crop\\.Left").val(Crop.position().left);
    $("#Crop\\.Top").val(Crop.position().top);
    $("#Crop\\.Width").val(Crop.width());
});
</code>```

UPDATE 2

Never mind, I got it. I took a nap after asking my question just to clear my head and when I looked at it again after, I decided to switch the two rectangles and see what happens. Well, guess what, that fixed it.

At this point I would have to say that the names given in the API documentation are deceptive. For example the docs refer to the output image as source and the input image as display. Perhaps the API should be updated to have better naming?

答:
In the following line:

Graphics.DrawImage(Source, new Rectangle(new Point(Crop.Left, Crop.Top), new Size(Crop.Width, Crop.Height)), new Rectangle(new Point(0, 0), new Size(Target.Width, Target.Height)), GraphicsUnit.Pixel);

Make sure the Crop.Left and Crop.Top is set to 0, otherwise it will start setting the pixels at the weird offset you are getting. You can also just replace it with the following line to test:

Graphics.DrawImage(Source, new Rectangle(new Point(0,0), new Size(Crop.Width, Crop.Height)), new Rectangle(new Point(0, 0), new Size(Target.Width, Target.Height)), GraphicsUnit.Pixel);

Title: What's wrong with this image cropper?

Body:
I'm making a cropping tool for images and I can't for the life of me figure out why it's producing the images that it's producing...

I'm following the accepted answer here, but its still being weird... Here's my code:

public void Crop(
    string FileName,
    Crop Crop) {
    using (Bitmap Source = ((Bitmap)Image.FromFile(FileName))) {
        using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
            using (Graphics Graphics = Graphics.FromImage(Target)) {
                Graphics.DrawImage(Source, new Rectangle(new Point(Crop.Left, Crop.Top), new Size(Crop.Width, Crop.Height)), new Rectangle(new Point(0, 0), new Size(Target.Width, Target.Height)), GraphicsUnit.Pixel);
            };

            Target.Save((FileName + ".temp"), JpegCodecInfo, HighQualityEncoder);
        };
    };

    this.NormalizeFileName(FileName);
}

Please help me. I'm attaching an image of what I'm getting...

UPDATE

For @Aaronontheweb, here's the Crop class and how it's populated:

public class Crop {
    [Required]
    public short Height { get; set; }

    [Required]
    public short Left { get; set; }

    [Required]
    public short Top { get; set; }

    [Required]
    public short Width { get; set; }
}

And the jQuery that populates it:

$("#Image input:submit").bind("click", function () {
    $("#Crop\\.Height").val(Crop.height());
    $("#Crop\\.Left").val(Crop.position().left);
    $("#Crop\\.Top").val(Crop.position().top);
    $("#Crop\\.Width").val(Crop.width());
});

UPDATE 2

Never mind, I got it. I took a nap after asking my question just to clear my head and when I looked at it again after, I decided to switch the two rectangles and see what happens. Well, guess what, that fixed it.

At this point I would have to say that the names given in the API documentation are deceptive. For example the docs refer to the output image as source and the input image as display. Perhaps the API should be updated to have better naming?


问:
RabbitMQ Declare Exchange from Terminal - Access refused: /api/exchanges/
I'm using rabbitmq to handle messages between my databases for an enterprise application I work on. As part of the process, I'm trying to help automate the setup of the servers (e.g. script it). In this process, I've tried to use rabbitmqadmin to declare exchanges from the command prompt. I have 2 different servers running CentOS 5.x and CentOS 6.x and both are having the same issue.

So far I declared an administrator user and set its password, then I set its tag to be of the administrator tag, then I ensure it has permissions to the vhosts. After that I try to declare the exchange, with user and password specified and it fails.

```<code>rabbitmqctl add_user administrator password
rabbitmqctl set_user_tags administrator administrator
rabbitmqctl set_permissions -p / administrator ".*" ".*" ".*"
rabbitmqctl add_vhost vhostFoo
rabbitmqctl set_permissions -p vhostFoo administrator ".*" ".*" ".*"
rabbitmqadmin -u administrator -p password declare exchange --vhost=vhostFoo name=exchangeNew type=direct
</code>```

For the CentOS 5.x box I have to use python26 rabbitmqadmin instead of just rabbitmqadmin, but get the same result.

The last command results in:

```<code>*** Access refused: /api/exchanges/vhostFoo/exchangeNew
</code>```

Both my CentOS 5.x and Cent 6.x boxes are running rabbitmq 3.3.5. Any thoughts on what I'm missing or thoughts on how I can get more info on what's wrong (e.g. error log file or way to get more verbose output)?

答:
You can add the user with administrator rights locally on your system.
Type  http://localhost:15672/#/ in your browser. In that Admin tab, you can create a user with admin rights.</p>

Body:
I'm using rabbitmq to handle messages between my databases for an enterprise application I work on. As part of the process, I'm trying to help automate the setup of the servers (e.g. script it). In this process, I've tried to use rabbitmqadmin to declare exchanges from the command prompt. I have 2 different servers running CentOS 5.x and CentOS 6.x and both are having the same issue.

So far I declared an administrator user and set its password, then I set its tag to be of the administrator tag, then I ensure it has permissions to the vhosts. After that I try to declare the exchange, with user and password specified and it fails.

rabbitmqctl add_user administrator password
rabbitmqctl set_user_tags administrator administrator
rabbitmqctl set_permissions -p / administrator ".*" ".*" ".*"
rabbitmqctl add_vhost vhostFoo
rabbitmqctl set_permissions -p vhostFoo administrator ".*" ".*" ".*"
rabbitmqadmin -u administrator -p password declare exchange --vhost=vhostFoo name=exchangeNew type=direct

For the CentOS 5.x box I have to use python26 rabbitmqadmin instead of just rabbitmqadmin, but get the same result.

The last command results in:

*** Access refused: /api/exchanges/vhostFoo/exchangeNew

Both my CentOS 5.x and Cent 6.x boxes are running rabbitmq 3.3.5. Any thoughts on what I'm missing or thoughts on how I can get more info on what's wrong (e.g. error log file or way to get more verbose output)?


问:
Unable to debug azure function locally
I wrote a simple azure function on the Azure portal and now since I've to add some more trivial code I decided to write it with vs2017 enterprise then package the dll and deploy it.
My azure function is a timer function and when I try to run it locally I got this

where should I set this config.UserTimers()?

Thanks.

答:
Please try to see if you are debuging in "Release" or "Debug" mode on the tool bar

The correct mode should be "Debug"

When running in release mode .pdb files are not get created and then you can't debug

Title: Unable to debug azure function locally


问:
What is the function of the "out" and ".idea" folder in Intellij?
Can someone clearly explain what is "out" and ".idea" folders in the project structure indicate? Though I'm not a beginner in Java, I need help understanding how all the components in a typical IDE work together. I previously used BlueJ which was very easy to use, but it masked all the background processes which I have difficulty understanding now.

Edit: Sorry I didn't check thoroughly for ".idea" but the "out" folder hasn't been defined in a general sense.

答:
Read official doc here :- .out :- .out folder intellij

And .idea  :- .idea folder

In Short all the project specific files goes to .idea folder and it will be recreate if you delete the project.

And .out folder contains the output of your project when you build/compile it ie contains .class files.

ContentLicense: CC BY-SA 4.0


问:
How to create unique id for each form submission in contact form 7?
I need to provide a unique id for all participants of the event who is registering for the events online. I wanted to give a unique id something like "17CONF001, 17CONF002, ..."

How to achieve this?

I am using the contact-form-7-dynamic-text-extension plugin for a registration process in my website for this purpose.

Work done:

I am using the following function to generate ticket number.

```<code>/* Generate Quote Ticket */
function genTicketString() {
$length = 3;
$iclaa = "17ICLAA";
$characters = "0123456789";
for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $iclaa.$string;
}
add_shortcode('quoteticket', 'genTicketString');
</code>```

in  my functions.php and I have added

```<code>[dynamictext ticket "quoteticket"]
</code>```

in my form in contact form 7 and made this field invisible through css.

Lastly, I have added [ticket] to your my e-mail body.

As per the solution given by AMCD.

Problems with this code:

Each refresh gives different reference number whereas it should generate the reference number for each submission of forms.

答:
hope this can help, add this code to your function.php

```<code>//Define the key to store in the database
define( 'CF7_COUNTER', 'cf7-counter' );

//Create the shortcode which will set the value for the DTX field
function cf7dtx_counter(){
    $kodeawal = "FJY";
    $val = get_option( CF7_COUNTER, 0) + 1;  //Increment the current count
    return $kodeawal.$val;
}
add_shortcode('CF7_counter', 'cf7dtx_counter');

//Action performed when the mail is actually sent by CF7
function cf7dtx_increment_mail_counter(){
    $val = get_option( CF7_COUNTER, 0) + 1; //Increment the current count
    update_option(CF7_COUNTER, $val); //Update the settings with the new count
}
add_action('wpcf7_mail_sent', 'cf7dtx_increment_mail_counter');
</code>```

Then, add this to your contact form 7

```<code><p>[dynamictext cf7-counter "CF7_counter"]</p>
</code>```

The output on your form will be "FJY1", "FJY2", and so

Thank you to sevenspark:
http://sevenspark.com/tutorials/how-to-create-a-counter-for-contact-form-7

Body:
I need to provide a unique id for all participants of the event who is registering for the events online. I wanted to give a unique id something like "17CONF001, 17CONF002, ..."

How to achieve this?

I am using the contact-form-7-dynamic-text-extension plugin for a registration process in my website for this purpose.

Work done:

I am using the following function to generate ticket number.

/* Generate Quote Ticket */
function genTicketString() {
$length = 3;
$iclaa = "17ICLAA";
$characters = "0123456789";
for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $iclaa.$string;
}
add_shortcode('quoteticket', 'genTicketString');

in  my functions.php and I have added

[dynamictext ticket "quoteticket"]

in my form in contact form 7 and made this field invisible through css.

Lastly, I have added [ticket] to your my e-mail body.

As per the solution given by AMCD.

Problems with this code:

Each refresh gives different reference number whereas it should generate the reference number for each submission of forms.

Body:
hope this can help, add this code to your function.php

//Define the key to store in the database
define( 'CF7_COUNTER', 'cf7-counter' );

//Create the shortcode which will set the value for the DTX field
function cf7dtx_counter(){
    $kodeawal = "FJY";
    $val = get_option( CF7_COUNTER, 0) + 1;  //Increment the current count
    return $kodeawal.$val;
}
add_shortcode('CF7_counter', 'cf7dtx_counter');

//Action performed when the mail is actually sent by CF7
function cf7dtx_increment_mail_counter(){
    $val = get_option( CF7_COUNTER, 0) + 1; //Increment the current count
    update_option(CF7_COUNTER, $val); //Update the settings with the new count
}
add_action('wpcf7_mail_sent', 'cf7dtx_increment_mail_counter');

Then, add this to your contact form 7

<p>[dynamictext cf7-counter "CF7_counter"]</p>

The output on your form will be "FJY1", "FJY2", and so

Thank you to sevenspark:
http://sevenspark.com/tutorials/how-to-create-a-counter-for-contact-form-7


问:
Maximum Weight / Minimum Cost Bipartite Matching Code in Python
I'm searching for Python code for maximum weight / minimum cost matching in a bipartite graph.  I've been using the general case max weight matching code in NetworkX, but am finding it too slow for my needs.  This is likely due to both the fact that the general algorithm is slower, and the fact that the NetworkX solution is implemented entirely in Python.  Ideally, I'd like to find a some Python code for the bipartite matching problem that wraps some C/C++ code, but right now, anything faster than the NetworkX implementation would be helpful.</p>

答: After some further investigation, I've found the following two modules particularly helpful (http://pypi.python.org/pypi/pyLAPJV/0.3 and http://pypi.python.org/pypi/hungarian).  They are both algorithms implemented in C++ with Python bindings, and run much faster than the NetworkX matching implementation.  The pyLAPJV implementation, however, seems to be a bit too fickle for my needs and doesn't properly handle identically weighted edges well.  The hungarian module (though supposedly slower than the pyLAPJV algorithm) runs about 3 orders of magnitude faster than the NetworkX implementation on the data sizes I'm currently dealing with. I'm also going to give another look at the code suggested by kunigami, as I believe that it can be run though Shedskin fairly easily to give a reasonably fast implementation. </p>


问:
Issue in drupal the directory sites/default/files is not writable
To solve these issues display in process of installing Drupal as:

Go to your "drupal" folder and make permission 777

Then open "sites" folder and make it 777

Choose "default" folder and make it 777

Open "files" and choose "setting.php" to change permission to 777

答:
You are giving public right to execute read and write files in your directories. Clearly not a good idea.
Check this link for more infos on what to do in production environnement (it also explains basic chmod values wich you seem to not be understanding) : https://www.drupal.org/node/244924</p>


问:
Unable to print array in node.js
Here is my code in routes

```<code>router.get('/chkjson', function(req, res, next) {
    req.getConnection(function(err,connection){
        var ItemArray = [];
        var myset = [];

        var query = connection.query('SELECT `db_name` FROM `database`',function(err,rows)
        {
            ItemArray.push({
                allDb : []
            });
            var k=0;
            for (var i in rows) {
                    retset = JSON.stringify(rows[i]);
                    var jsonset =  JSON.parse(retset);
                    console.log(ItemArray);
                    console.log("========");
                    myset.push(ItemArray);
                    ItemArray[0].allDb.push(jsonset.db_name);
            }
        });
        console.log(myset);   //blank array
        console.log("-----");
        console.log(ItemArray);   //blank array
        console.log("-----");
            res.render( 'new/post-select-table',
                {
                    title: 'Select Database',
                    session_store:req.session,
                });
        });
});
</code>```

I'm getting blank array when I'm trying to print array outside for loop. Can anyone help me where im going wrong.

答:
Couldn't you just return the array and push it to global variables?</p>

```<code>var query = connection.query("soandso", function(err, result) {
    var allDb = [];

    return allDb;
}

ItemArray.push(query);
</code>```

Title: Unable to print array in node.js

Body:
Here is my code in routes

router.get('/chkjson', function(req, res, next) {
    req.getConnection(function(err,connection){
        var ItemArray = [];
        var myset = [];

        var query = connection.query('SELECT `db_name` FROM `database`',function(err,rows)
        {
            ItemArray.push({
                allDb : []
            });
            var k=0;
            for (var i in rows) {
                    retset = JSON.stringify(rows[i]);
                    var jsonset =  JSON.parse(retset);
                    console.log(ItemArray);
                    console.log("========");
                    myset.push(ItemArray);
                    ItemArray[0].allDb.push(jsonset.db_name);
            }
        });
        console.log(myset);   //blank array
        console.log("-----");
        console.log(ItemArray);   //blank array
        console.log("-----");
            res.render( 'new/post-select-table',
                {
                    title: 'Select Database',
                    session_store:req.session,
                });
        });
});

I'm getting blank array when I'm trying to print array outside for loop. Can anyone help me where im going wrong.

Body:
Couldn't you just return the array and push it to global variables?

var query = connection.query("soandso", function(err, result) {
    var allDb = [];

    return allDb;
}

ItemArray.push(query);


答:
When you use a JetBrains product such as Intellij Idea all the project specific settings are stored in the directory .idea. Here is a link from JetBrains documenting .idea directory: Documentation.

As for the out folder it contains all your compiled classes, when you run your program from the IDE, all your classes are compiled in the out directory.

Title: What is the function of the "out" and ".idea" folder in Intellij?

Body:
Can someone clearly explain what is "out" and ".idea" folders in the project structure indicate? Though I'm not a beginner in Java, I need help understanding how all the components in a typical IDE work together. I previously used BlueJ which was very easy to use, but it masked all the background processes which I have difficulty understanding now.

Edit: Sorry I didn't check thoroughly for ".idea" but the "out" folder hasn't been defined in a general sense.


问:
multiple datepicker in a page (php)
im trying to use two date picker in a page. it seems to worked fine but after  clicked on the submit button the date entered is not the same as the choosen date. both of the date inserted to the database is 01-01-1970.

how can i fix this?

```<code><div class="form-group">
    <label class="control-label col-sm-4">Date Issued</label>
    <div class="col-sm-5">
        <input class="form-control" type="text" id="dateIssuedpc" name="dateissued" required class="form-control" placeholder="Enter Date Issued"/>
    </div>
</div>

<div class="form-group">
    <label class="control-label col-sm-4">Date Expired</label>
    <div class="col-sm-5">
    <input class="form-control" type="text" id="dateExpiredpc" name="dateexpired" required class="form-control"  placeholder="Enter Date Expired" />
    </div>
</div>

<script>
$( function() {
$( "#dateIssuedpc").datepicker({
  dateFormat: "dd-mm-yy",
  changeMonth: true,
  changeYear: true
});
$( "#dateExpiredpc" ).datepicker({
  dateFormat: "dd-mm-yy",
  changeMonth: true,
  changeYear: true
  });
  } );
 </script>
</code>```

答:
You need to format your date properly. First of all change format from dateFormat: "dd-mm-yy", to *dateFormat: "dd-mm-yyyy",* to better recognise year.

After that from php side you something like this

```<code>$dateissued = date("Y-m-d", strtotime($_POST['dateissued']) ); //MySql date format
</code>```

Title: multiple datepicker in a page (php)

Body:
im trying to use two date picker in a page. it seems to worked fine but after  clicked on the submit button the date entered is not the same as the choosen date. both of the date inserted to the database is 01-01-1970.

how can i fix this?

    Date Issued

        <input class="form-control" type="text" id="dateIssuedpc" name="dateissued" required class="form-control" placeholder="Enter Date Issued"/>

    Date Expired

    <input class="form-control" type="text" id="dateExpiredpc" name="dateexpired" required class="form-control"  placeholder="Enter Date Expired" />

Body:
You need to format your date properly. First of all change format from dateFormat: "dd-mm-yy", to *dateFormat: "dd-mm-yyyy",* to better recognise year.

After that from php side you something like this

$dateissued = date("Y-m-d", strtotime($_POST['dateissued']) ); //MySql date format


问:
align labels and textbox horizontally and veritcally
I am working on making a form as shown just like in this image but I am not able to figure out how can I align those labels and textbox vertically and horizontally in the same format shown in that image.

Here is my jsfiddle: https://jsfiddle.net/w6Lq9a1m/1/

And below is my simple HTML:

 INSURANCE FORM

 BASIC DETAILS

  <form action="/action_page.php">
    FIRST NAME

    <input type="text" name="fname" value="Mickey">

 LAST NAME

    <input type="text" name="lname" value="Mouse">

 EMAIL

    <input type="text" name="email" value="abc@host.com">

 PHONE NUMBER

    <input type="text" name="number" value="123-456-789">

 COUNTRY

    <select name="country">
      <option value="canada">Canada</option>
    </select>

 PROVINCE

    <select name="province">
      <option value="ontario">ONTARIO</option>
    </select>

 CITY

    <select name="city">
      <option value="ottawa">OTTAWA</option>
    </select>

  </form>

```

答:
Try this using Bootstrap

.form-horizontal .form-control {
  border-radius:0;
  border:none;
  box-shadow:none;
  border-bottom:1px solid orange;
}
.form-horizontal .form-control:focus{
  box-shadow:none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-sm-12">
  <h2> INSURANCE FORM</h2>
  <h4> <i>BASIC DETAILS</i></h4>

  <form action="/action_page.php" class="form-horizontal">
    <div class="form-group">
      <div class="col-sm-6">
      <label>FIRST NAME</label>
        <input type="text" class="form-control" name="fname" value="Mickey">
      </div>
      <div class="col-sm-6">
      <label>LAST NAME</label>
        <input type="text" class="form-control" name="lname" value="Mouse">
      </div>
    </div>

    <div class="form-group">
      <div class="col-sm-6">
      <label>EMAIL</label>
        <input type="text" class="form-control" name="email" value="abc@host.com">
      </div>
      <div class="col-sm-6">
      <label>PHONE NUMBER</label>
        <input type="text" class="form-control" name="number" value="123-456-789">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-6">
      <label>COUNTRY</label>
        <select name="country" class="form-control">
          <option value="canada">Canada</option>
        </select>
      </div>
      <div class="col-sm-3">
      <label>PROVINCE</label>
        <select name="province" class="form-control">
          <option value="ontario">ONTARIO</option>
        </select>
      </div>
      <div class="col-sm-3">
      <label>CITY</label>
        <select name="city" class="form-control">
          <option value="ottawa">OTTAWA</option>
        </select>
      </div>
    </div>
  </form>
</div></code>```

Body:
Try this using Bootstrap

.form-horizontal .form-control {
  border-radius:0;
  border:none;
  box-shadow:none;
  border-bottom:1px solid orange;
}
.form-horizontal .form-control:focus{
  box-shadow:none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-sm-12">
  <h2> INSURANCE FORM</h2>
  <h4> <i>BASIC DETAILS</i></h4>

  <form action="/action_page.php" class="form-horizontal">
    <div class="form-group">
      <div class="col-sm-6">
      <label>FIRST NAME</label>
        <input type="text" class="form-control" name="fname" value="Mickey">
      </div>
      <div class="col-sm-6">
      <label>LAST NAME</label>
        <input type="text" class="form-control" name="lname" value="Mouse">
      </div>
    </div>

    <div class="form-group">
      <div class="col-sm-6">
      <label>EMAIL</label>
        <input type="text" class="form-control" name="email" value="abc@host.com">
      </div>
      <div class="col-sm-6">
      <label>PHONE NUMBER</label>
        <input type="text" class="form-control" name="number" value="123-456-789">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-6">
      <label>COUNTRY</label>
        <select name="country" class="form-control">
          <option value="canada">Canada</option>
        </select>
      </div>
      <div class="col-sm-3">
      <label>PROVINCE</label>
        <select name="province" class="form-control">
          <option value="ontario">ONTARIO</option>
        </select>
      </div>
      <div class="col-sm-3">
      <label>CITY</label>
        <select name="city" class="form-control">
          <option value="ottawa">OTTAWA</option>
        </select>
      </div>
    </div>
  </form>
</div>


问:
ActiveRecord scope based on hour
iteration

```<code><% @challenges.with_exact.each do |challenge| %>
 etc...
<% end %>
</code>```

model scope attempts

```<code>scope :with_exact, -> { where("exact == ?", Time.zone.now.hour) } # Error: PG::UndefinedFunction: ERROR:  operator does not exist: time without time zone == integer
scope :with_exact, -> { where(exact: Time.zone.now.hour) } # Error: PG::InvalidDatetimeFormat: ERROR:  invalid input syntax for type time: "13"
</code>```

Some challenges will have a nil exact.

How can I iterate challenges only where Time.zone.now.strftime('%H') == challenge.exact.strftime('%H')

答:
You can use date_part(text, timestamp) postgres function:

```<code>where("date_part('hour', exact) = ?", Time.zone.now.hour)
</code>```

Here is also month, year and so on.

There is an another way with extract(field from timestamp)

```<code>where("extract(hour from exact) = ?", Time.zone.now.hour)
</code>```

Title: ActiveRecord scope based on hour

Body:
iteration

<% @challenges.with_exact.each do |challenge| %>
 etc...
<% end %>

model scope attempts

scope :with_exact, -> { where("exact == ?", Time.zone.now.hour) } # Error: PG::UndefinedFunction: ERROR:  operator does not exist: time without time zone == integer
scope :with_exact, -> { where(exact: Time.zone.now.hour) } # Error: PG::InvalidDatetimeFormat: ERROR:  invalid input syntax for type time: "13"

Some challenges will have a nil exact.

How can I iterate challenges only where Time.zone.now.strftime('%H') == challenge.exact.strftime('%H')

Body:
You can use date_part(text, timestamp) postgres function:

where("date_part('hour', exact) = ?", Time.zone.now.hour)

Here is also month, year and so on.

There is an another way with extract(field from timestamp)

where("extract(hour from exact) = ?", Time.zone.now.hour)


问:
How do I do a function callback in Azure Functions on a function imported from a node module?
I have spent hours over the last few days trying to figure out how to do a callback to get data out of a function I am importing from a node module and use it with context.res in an azure function.

I don't understand callbacks well enough to get my head around this, or I am completely off base.

module.exports = function (context, req) {

var QuickBooks = require('node-quickbooks')
var qboAuth = require('./config')
var consumerKey = qboAuth.consumerKey
var consumerSecret = qboAuth.consumerSecret
var oauthToken = qboAuth.token
var oauthTokenSecret = qboAuth.tokenSecret
var realmId = qboAuth.realmId

    var qbo = new QuickBooks(consumerKey,
                         consumerSecret,
                         oauthToken,
                         oauthTokenSecret,
                         realmId,
                         false, // use the sandbox?
                         true); // enable debugging?

    qbo.getAccount(req.query.id, function(err, account) {
            context.log(account)

    } );

context.res = {
    body: account
}

context.done()
}```

So the context.log(account) in the qbo.getAccount() function outputs fine, however through which ever means I use I cannot get this to output to context.res = {}.

I think this is complicated by running in the Azure Function sandbox, but I am not sure.

Is someone able to point me in the right direction?

Thanks,

Dion

答:
The function getAccount() should be an asynchronous function, you can move the assignment and complete function of Azure Function into the callback expression. E.G.

```<code>qbo.getAccount(req.query.id, function(err, account) {
    context.log(account);
    context.res = {
        body: account
    }
    context.done()
    }
);
</code>```

Body:
I have spent hours over the last few days trying to figure out how to do a callback to get data out of a function I am importing from a node module and use it with context.res in an azure function.

I don't understand callbacks well enough to get my head around this, or I am completely off base.

module.exports = function (context, req) {

var QuickBooks = require('node-quickbooks')
var qboAuth = require('./config')
var consumerKey = qboAuth.consumerKey
var consumerSecret = qboAuth.consumerSecret
var oauthToken = qboAuth.token
var oauthTokenSecret = qboAuth.tokenSecret
var realmId = qboAuth.realmId

    var qbo = new QuickBooks(consumerKey,
                         consumerSecret,
                         oauthToken,
                         oauthTokenSecret,
                         realmId,
                         false, // use the sandbox?
                         true); // enable debugging?

    qbo.getAccount(req.query.id, function(err, account) {
            context.log(account)

    } );

context.res = {
    body: account
}

context.done()
}

So the context.log(account) in the qbo.getAccount() function outputs fine, however through which ever means I use I cannot get this to output to context.res = {}.

I think this is complicated by running in the Azure Function sandbox, but I am not sure.

Is someone able to point me in the right direction?

Thanks,

Dion

Body:
The function getAccount() should be an asynchronous function, you can move the assignment and complete function of Azure Function into the callback expression. E.G.

qbo.getAccount(req.query.id, function(err, account) {
    context.log(account);
    context.res = {
        body: account
    }
    context.done()
    }
);


答:
This is not datepicker problem, rather problem is with PHP code.

Mysql date format is always YYYY-MM-DD HH:II:SS

So while inserting data to mysql table, you have to convert the format for mysql

Ex:

```<code>$postDate = $_POST['date'];// just collect value from post fields.
$date = date("Y-m-d H:i:s",strtotime($postDate));
</code>```

Title: multiple datepicker in a page (php)

Body:
This is not datepicker problem, rather problem is with PHP code.

Mysql date format is always YYYY-MM-DD HH:II:SS

So while inserting data to mysql table, you have to convert the format for mysql

Ex:

$postDate = $_POST['date'];// just collect value from post fields.
$date = date("Y-m-d H:i:s",strtotime($postDate));


问:
How do I give a name to a VisualVM "<Unknown Application>"?
JDK 1.6 comes bundled with a handy tool called VisualVM that lets you inspect and interact with running Java processes.  One feature is that it auto-detects running JVMs on the local machine.  Most are listed as " (pid xxxx)" but some have a name and an icon, like VisualVM itself and others like NetBeans (see the screenshot in this dzone article for example).

How do I inject my application name and icon into the JVM so it shows up properly in VisualVM's application list?  Does my app need to be running JRE 1.6 or can I do this under 1.5 too?

答:
I solved half of my own question via a NetBeans forum post answer.  Adding a JVM command line arg of -Dvisualvm.display.name=FooBar makes VisualVM show the app as "FooBar".  But I still can't figure out how to affect the icon.

UPDATE: Alas, I think I found my answer for the icon.  The icons are hard-coded into VisualVM via MainClassApplicationTypeFactory in the VisualVM source, invoked from the static method ApplicationTypeFactory.getApplicationTypeFor(Application).  I can't see any way to inject a new icon into VisualVM except by making a VisualVM plugin which could register a new type factory -- the Glassfish plugin does this via GlassFishApplicationTypeFactory.initialize() for example.


问:
What difference between
I have first query

```<code>select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Created_at BETWEEN '2017-05-01' AND '2017-05-31')
</code>```

and result is 1050

i also have second query :

```<code>select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Month(Created_at) =5 and Year(Created_at) = 2017)
</code>```

and result is 1111

I think 2 query have same meaning but it return 2 different result.
Info about column "Created_at": COLUMN_NAME Created_at,  COLUMN_TYPE timestamp,  IS_NULLABLE NO,  COLUMN_KEY ,  COLUMN_DEFAULT CURRENT_TIMESTAMP

Please help what difference between 2 query?

答:
Between does take only up to '2017-05-30 23:59:59' and after 2017-05-01 00:00:00. It should not consider 31th full day.

If you want first query return same data as second query you can use like this

```<code>select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Created_at >= '2017-05-01' AND Created_at < '2017-06-01')
</code>```

Title: What difference between

Body:
I have first query

select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Created_at BETWEEN '2017-05-01' AND '2017-05-31')

and result is 1050

i also have second query :

select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Month(Created_at) =5 and Year(Created_at) = 2017)

and result is 1111

I think 2 query have same meaning but it return 2 different result.
Info about column "Created_at": COLUMN_NAME Created_at,  COLUMN_TYPE timestamp,  IS_NULLABLE NO,  COLUMN_KEY ,  COLUMN_DEFAULT CURRENT_TIMESTAMP

Please help what difference between 2 query?

Body:
Between does take only up to '2017-05-30 23:59:59' and after 2017-05-01 00:00:00. It should not consider 31th full day.

If you want first query return same data as second query you can use like this

select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Created_at >= '2017-05-01' AND Created_at < '2017-06-01')


问:
Ltac pattern matching: why does `forall x, ?P x` not match `forall x, x`?
```<code>Ltac checkForall H :=
  let T := type of H in
  match T with
  | forall x, ?P x =>
    idtac
  | _ =>
    fail 1 "not a forall"
  end.

Example test : (forall x, x) -> True.
Proof.
  intros H.
  Fail checkForall H. (* not a forall *)
Abort.
</code>```

I would naively expect checkForall H to succeed, but it doesn't.

In his book Certified Programming with Dependent Types, Adam Chlipala discusses a limitation of pattern matching on dependent types:

The problem is that unification variables may not contain locally bound variables.

Is this the reason for the behaviour I'm seeing here?

答:
The type of H is forall x, x, not forall x, P x.

```<code>Ltac checkForall H :=
  let T := type of H in
  match T with
  | forall x, ?P x =>
    idtac
  | forall x, x =>
    idtac "this matches"
  | _ =>
    fail 1 "not a forall"
  end.

Example test : (forall x, x) -> True.
Proof.
  intros H.
  checkForall H. (* not a forall *)

Abort.
</code>```

or to match your checkForall

```<code>Example test {T} (f:T->Prop)  : (forall x, f x) -> True.
Proof.
  intros H.
  checkForall H.
</code>```

Body:
Ltac checkForall H :=
  let T := type of H in
  match T with
  | forall x, ?P x =>
    idtac
  | _ =>
    fail 1 "not a forall"
  end.

Example test : (forall x, x) -> True.
Proof.
  intros H.
  Fail checkForall H. (* not a forall *)
Abort.

I would naively expect checkForall H to succeed, but it doesn't.

In his book Certified Programming with Dependent Types, Adam Chlipala discusses a limitation of pattern matching on dependent types:

The problem is that unification variables may not contain locally bound variables.

Is this the reason for the behaviour I'm seeing here?

Body:
The type of H is forall x, x, not forall x, P x.

Ltac checkForall H :=
  let T := type of H in
  match T with
  | forall x, ?P x =>
    idtac
  | forall x, x =>
    idtac "this matches"
  | _ =>
    fail 1 "not a forall"
  end.

Example test : (forall x, x) -> True.
Proof.
  intros H.
  checkForall H. (* not a forall *)

Abort.

or to match your checkForall

Example test {T} (f:T->Prop)  : (forall x, f x) -> True.
Proof.
  intros H.
  checkForall H.


问:
I can't add another row of buttons
I want my fragment look like it has 3 buttons that fill the screen in both vertically and horizontally on the phone. I managed to do that somehow but I can't add another row of buttons. This is my layout... what am I doing wrong?</p>

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >

            <Button
                android:id="@+id/button1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <Button
                android:id="@+id/button2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1" />
            <Button
                android:id="@+id/button3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1" />

        </LinearLayout>

    </ScrollView>

</LinearLayout>
</code>```

答:
First Note  : scroll view remove effect of weight property
Delete the scroll view element from your layout

Second note : each button make

```<code><Button ...
 android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
</code>```

Because 0dp let the Android system calculate the height of button Equally

Title: I can't add another row of buttons

Body:
I want my fragment look like it has 3 buttons that fill the screen in both vertically and horizontally on the phone. I managed to do that somehow but I can't add another row of buttons. This is my layout... what am I doing wrong?

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >

            <Button
                android:id="@+id/button1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <Button
                android:id="@+id/button2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1" />
            <Button
                android:id="@+id/button3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1" />

        </LinearLayout>

    </ScrollView>

</LinearLayout>

Body:
First Note  : scroll view remove effect of weight property
Delete the scroll view element from your layout

Second note : each button make

<Button ...
 android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />

Because 0dp let the Android system calculate the height of button Equally


问:
How do I send a notification to another user active when update?
I have an application with one DB which is used by many users. Whenever one user makes changes, we save the changes to the database.

Now, I need to notify other logged-in users about this change. How can this be done?

I'm thinking - when the application succcessfully saves / updates the data in the database, the application will send a notification to the connected clients with the new record updated or added.

I'm using C# and SQL Server database.

答:
Your immediate options are push-based notifications with something like a message bus, or polling loops on known ids.

Message busses operate on publish-subscribe models which work well for Windows applications. Have a look at MassTransit or MSMQ as a starting point. There are plenty of options out there. They can be combined into web apps using something that essentially wraps a polling loop with the client like SignalR.

Polling-based options work typically on a timer and do quick timestamp or version # checks against the database, reloading a record if a difference is found.

Push-based are more efficient but only notify of changes between supported applications. (Client to Client) they don't detect changes by applications that don't participate as publishers, nor do they see changes made directly to the database.

Polling-based options cover all changes, but are generally slower and require a schema that has version information to work effectively.


问:
Laravel 5.2 - Send welcome email after user registered
I would like to send some emails after users registered.
But, it doest work. I didn't receive an email in my SMTP mail. I'm using mailtrap.io.

I have set up a Registered event with a listener to NewUserRegistered.

Within my NewUserRegistered Controller\Auth\AuthController as follows:

```<code>    <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Log;
use Validator;
use Mail;

class AuthController extends Controller {
    /*
            |--------------------------------------------------------------------------
            | Registration & Login Controller
            |--------------------------------------------------------------------------
            |
            | This controller handles the registration of new users, as well as the
            | authentication of existing users. By default, this controller uses
            | a simple trait to add these behaviors. Why don't you explore it?
            |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware($this->guestMiddleware(), [
            'except' => 'logout'
        ]);

        }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data) {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'matric' => 'required|max:5',
            'faculty' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'address' => 'required',
            'phone' => 'required',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data) {

        return User::create([
            'name' => $data['name'],
            'matric' => $data['matric'],
            'faculty' => $data['faculty'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'address' => $data['address'],
            'phone' => $data['phone'],
        ]);

        event(new Registered($user));

    //sreturn User;
    }
}
</code>```

Within my Registered Events as follows:

```<code>    <?php

namespace App\Events;

use App\Events\Registered;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Registered extends Event
{
    use SerializesModels;
    /**
     * @var
     */
    public $user;

    /**
     * Create a new event instance.
     *
     * @param $user
     */
    public function __construct($user)
    {
        //
        $this->user = $user;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}
</code>```

Within my NewUserRegistered Listeners as follows:

```<code>    <?php

    namespace App\Listeners;

    use App\Events\Registered;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Mailer;
    use Mail;

    class NewUserRegistered
    {
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function welcome(Registered $event)
  {
     $data = [
       'user' => $event->user,
          'from' => 'hello@test.dev',
          'subject' => 'Welcome to test'
    ];

        $this->mailer->send('emails.auth.verify', $data, function($message) {
            $message->to($data['user']->email, $data['user']->matric)
                    ->subject($data['subject']);
        });
    }
}
</code>```

答:
Your event never fires because you're returning the user after creating them. Your code should have thrown errors when you attempted. Change your code to this.

```<code>use App\Events\Registered;

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'matric' => $data['matric'],
        'faculty' => $data['faculty'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'address' => $data['address'],
        'phone' => $data['phone'],
    ]);

    event(new Registered($user));

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

Also be sure to register your event listener.

Body:
I would like to send some emails after users registered.
But, it doest work. I didn't receive an email in my SMTP mail. I'm using mailtrap.io.

I have set up a Registered event with a listener to NewUserRegistered.

Within my NewUserRegistered Controller\Auth\AuthController as follows:

    <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Log;
use Validator;
use Mail;

class AuthController extends Controller {
    /*
            |--------------------------------------------------------------------------
            | Registration & Login Controller
            |--------------------------------------------------------------------------
            |
            | This controller handles the registration of new users, as well as the
            | authentication of existing users. By default, this controller uses
            | a simple trait to add these behaviors. Why don't you explore it?
            |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware($this->guestMiddleware(), [
            'except' => 'logout'
        ]);

        }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data) {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'matric' => 'required|max:5',
            'faculty' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'address' => 'required',
            'phone' => 'required',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data) {

        return User::create([
            'name' => $data['name'],
            'matric' => $data['matric'],
            'faculty' => $data['faculty'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'address' => $data['address'],
            'phone' => $data['phone'],
        ]);

        event(new Registered($user));

    //sreturn User;
    }
}

Within my Registered Events as follows:

    <?php

namespace App\Events;

use App\Events\Registered;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Registered extends Event
{
    use SerializesModels;
    /**
     * @var
     */
    public $user;

    /**
     * Create a new event instance.
     *
     * @param $user
     */
    public function __construct($user)
    {
        //
        $this->user = $user;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}

Within my NewUserRegistered Listeners as follows:

    <?php

    namespace App\Listeners;

    use App\Events\Registered;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Mailer;
    use Mail;

    class NewUserRegistered
    {
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function welcome(Registered $event)
  {
     $data = [
       'user' => $event->user,
          'from' => 'hello@test.dev',
          'subject' => 'Welcome to test'
    ];

        $this->mailer->send('emails.auth.verify', $data, function($message) {
            $message->to($data['user']->email, $data['user']->matric)
                    ->subject($data['subject']);
        });
    }
}

Body:
Your event never fires because you're returning the user after creating them. Your code should have thrown errors when you attempted. Change your code to this.

use App\Events\Registered;

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'matric' => $data['matric'],
        'faculty' => $data['faculty'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'address' => $data['address'],
        'phone' => $data['phone'],
    ]);

    event(new Registered($user));

    return $user;
}

Also be sure to register your event listener.


问:
Openerp 7- how to run datetime update query
I am having problem with this update query and I don't understand the error here. please help me to solve this.

Field

```<code>'sign_in' : fields.datetime("Sign In"),
</code>```

Variable

```<code>sgn_in1 = datetime.datetime.strptime(sign_in, DATETIME_FORMAT1).time()
</code>```

Query

```<code>cr.execute("""UPDATE allowance.attendances SET sign_in = %s WHERE id =%s"""%(sign_in1,colmn_id))
</code>```

Error

ProgrammingError: syntax error at or near ":" LINE 1: UPDATE
  allowance.attendances SET sign_in = 08:15:00

答:
Query should be like this,

```<code>cr.execute("UPDATE allowance_attendances SET sign_in = '%s' WHERE id =%s"%(sign_in1,colmn_id))
</code>```

Datetime / time / date value must be passed in single quote. For integer / long it's not required.

While you execute direct query in database then the odoo model doesn't contains . (dot) in name, it's only allowed to use while you perform operation via odoo ORM methods.

so Model shouldn't be allowance.attendances, it should be allowance_attendances

Body:
I am having problem with this update query and I don't understand the error here. please help me to solve this.

Field

'sign_in' : fields.datetime("Sign In"),

Variable

sgn_in1 = datetime.datetime.strptime(sign_in, DATETIME_FORMAT1).time()

Query

cr.execute("""UPDATE allowance.attendances SET sign_in = %s WHERE id =%s"""%(sign_in1,colmn_id))

Error

ProgrammingError: syntax error at or near ":" LINE 1: UPDATE
  allowance.attendances SET sign_in = 08:15:00

Body:
Query should be like this,

cr.execute("UPDATE allowance_attendances SET sign_in = '%s' WHERE id =%s"%(sign_in1,colmn_id))

Datetime / time / date value must be passed in single quote. For integer / long it's not required.

While you execute direct query in database then the odoo model doesn't contains . (dot) in name, it's only allowed to use while you perform operation via odoo ORM methods.

so Model shouldn't be allowance.attendances, it should be allowance_attendances


问:
Random number guessing game throws error: > or < cannot be used between str and int
I have the following code for a random number guessing game:

```<code>import random
number = random.randint(1,100)

name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")

guess1 = input()
if guess1 == number:
    print ("Good job, you got it!")
while guess1 != number:
    if guess1 > number:
        print ('your guess is too high')
    if guess1 < number:
        print ('your guess is too low')
</code>```

which throws the error that > or < cannot be used between str and int.

What should I do so it doesn't trigger that error?

答:
I hope this works for you:</p>

```<code>import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
    guess_number = int(input('Enter a number:'))
    guess += 1
    if guess_number < number:
        print('Your guess is to low')
    if guess_number > number:
        print('Your guess is to high')
    if guess_number == number:
        print('Your guess is correct the number is',number)
        break
    if guess == 4:
        break
print('The number i was thinking of is',number)
</code>```

Body:
I have the following code for a random number guessing game:

import random
number = random.randint(1,100)

name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")

guess1 = input()
if guess1 == number:
    print ("Good job, you got it!")
while guess1 != number:
    if guess1 > number:
        print ('your guess is too high')
    if guess1 < number:
        print ('your guess is too low')

which throws the error that > or < cannot be used between str and int.

What should I do so it doesn't trigger that error?

Body:
I hope this works for you:

import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
    guess_number = int(input('Enter a number:'))
    guess += 1
    if guess_number < number:
        print('Your guess is to low')
    if guess_number > number:
        print('Your guess is to high')
    if guess_number == number:
        print('Your guess is correct the number is',number)
        break
    if guess == 4:
        break
print('The number i was thinking of is',number)