问:
UpsetR change set name labels in graph
I am trying to change the set name labels in my UpsetR plot (using Upset function) to be a string of multiple words.  Instead of 'A', 'B', 'C' as the set labels I want to have the set labels appear as 'A Description', 'B Description', 'C Description'. I do not want periods or underscores between the words.

```<code>test <- upset(grouped_hot,
sets= c("A Description", "B Description","C Description", "N Description"),
nintersects = 8,
mb.ratio = c(0.6, 0.4),
sets.x.label = "Number of Patients",
sets.bar.color =  "#56B4E9",
mainbar.y.label = "Number of Patients",
order.by = "freq",
empty.intersections = "on",
keep.order = FALSE,
 scale.sets = "identity",
att.pos = "top",
text.scale = c(2.5,2.5,2,1.5,2.5,2.5))
</code>```

The actual result is that my sets on my image are labeled A.Description, B.Description and C.Description. However, I do not want the periods between the words and instead want a space. Any ideas to change the names of the Set Name Labels just for the purposes of the plot? Thank you!

答:
I am using upset function in slighlty different way, but then it might help you if you are able to reformat/reorder your input data.

Here:

```<code>##make input list
listInput = list(data.list1,
                 data.list2,
                 data.list3)
##rename list
names(listInput) = c("Name 1", "Name 2", "Name 3")

#make diagram
upset(fromList(listInput), order.by = "freq", #input, descending order
      mainbar.y.label = "Number of common genes", #y axis
      sets.x.label = "Number of genes \nin the dataset", #x axis small plot
      main.bar.color = "black",
      sets.bar.color = "black",
      mainbar.y.max = 10 #y axis adjustment
        )
</code>```

It reads set names as Name 1, Name 2, and Name 3.

Hope it helps :)
Ana

Title: UpsetR change set name labels in graph

Body:
I am trying to change the set name labels in my UpsetR plot (using Upset function) to be a string of multiple words.  Instead of 'A', 'B', 'C' as the set labels I want to have the set labels appear as 'A Description', 'B Description', 'C Description'. I do not want periods or underscores between the words.

test <- upset(grouped_hot,
sets= c("A Description", "B Description","C Description", "N Description"),
nintersects = 8,
mb.ratio = c(0.6, 0.4),
sets.x.label = "Number of Patients",
sets.bar.color =  "#56B4E9",
mainbar.y.label = "Number of Patients",
order.by = "freq",
empty.intersections = "on",
keep.order = FALSE,
 scale.sets = "identity",
att.pos = "top",
text.scale = c(2.5,2.5,2,1.5,2.5,2.5))

The actual result is that my sets on my image are labeled A.Description, B.Description and C.Description. However, I do not want the periods between the words and instead want a space. Any ideas to change the names of the Set Name Labels just for the purposes of the plot? Thank you!

Body:
I am using upset function in slighlty different way, but then it might help you if you are able to reformat/reorder your input data.

Here:

##make input list
listInput = list(data.list1,
                 data.list2,
                 data.list3)
##rename list
names(listInput) = c("Name 1", "Name 2", "Name 3")

#make diagram
upset(fromList(listInput), order.by = "freq", #input, descending order
      mainbar.y.label = "Number of common genes", #y axis
      sets.x.label = "Number of genes \nin the dataset", #x axis small plot
      main.bar.color = "black",
      sets.bar.color = "black",
      mainbar.y.max = 10 #y axis adjustment
        )

It reads set names as Name 1, Name 2, and Name 3.

Hope it helps :)
Ana


来源: stackexchange

问:
What does "this" refer to in arrow functions in ES6?
I've read in several places that the key difference is that this is lexically bound in arrow functions. That's all well and good, but I don't actually know what that means.

I know it means it's unique within the confines of the braces defining the function's body, but I couldn't actually tell you the output of the following code, because I have no idea what this is referring to, unless it's referring to the fat arrow function itself....which doesn't seem useful.

var testFunction = () => {
  console.log(this)
};
testFunction();```

答:
In another example, if you click the age button below

```<code><script>
var person = {
    firstName: 'John',
    surname: 'Jones',
    dob: new Date('1990-01-01'),
    isMarried: false,
    age: function() {
        return new Date().getFullYear() - this.dob.getFullYear();
    }
};

var person2 = {
    firstName: 'John',
    surname: 'Jones',
    dob: new Date('1990-01-01'),
    isMarried: false,
    age: () => {
        return new Date().getFullYear() - this.dob.getFullYear();
    }
};

</script>

<input type=button onClick="alert(person2.age());" value="Age">
</code>```

it will throw an exception like this

×JavaScript error: Uncaught TypeError: Cannot read property
  'getFullYear' of undefined on line 18

But if you change person2's this line

```<code>return new Date().getFullYear() - this.dob.getFullYear();
</code>```

to

```<code>return new Date().getFullYear() - person2.dob.getFullYear();
</code>```

it will work because this scope has changed in person2

ContentLicense: CC BY-SA 4.0

Body:
In another example, if you click the age button below

<script>
var person = {
    firstName: 'John',
    surname: 'Jones',
    dob: new Date('1990-01-01'),
    isMarried: false,
    age: function() {
        return new Date().getFullYear() - this.dob.getFullYear();
    }
};

var person2 = {
    firstName: 'John',
    surname: 'Jones',
    dob: new Date('1990-01-01'),
    isMarried: false,
    age: () => {
        return new Date().getFullYear() - this.dob.getFullYear();
    }
};

</script>

<input type=button onClick="alert(person2.age());" value="Age">

it will throw an exception like this

×JavaScript error: Uncaught TypeError: Cannot read property
  'getFullYear' of undefined on line 18

But if you change person2's this line

return new Date().getFullYear() - this.dob.getFullYear();

to

return new Date().getFullYear() - person2.dob.getFullYear();

it will work because this scope has changed in person2


问:
better way to replace query string value in a given url
Okay.. so basically, say we have a link:

```<code>$url = "http://www.site.com/index.php?sub=Mawson&state=QLD&cat=4&page=2&sort=z";
</code>```

Basically, I need to create a function, which replaces each thing in the URL, for example:

```<code><a href="<?=$url;?>?sort=a">Sort by A-Z</a>
<a href="<?=$url;?>?sort=z">Sort by Z-A</a>
</code>```

Or, for another example:

```<code><a href="<?=$url;?>?cat=1">Category 1</a>
<a href="<?=$url;?>?cat=2">Category 2</a>
</code>```

Or, another example:

```<code><a href="<?=$url;?>?page=1">1</a>
<a href="<?=$url;?>?page=2">2</a>
<a href="<?=$url;?>?page=3">3</a>
<a href="<?=$url;?>?page=4">4</a>
</code>```

So basically, we need a function which will replace the specific $_GET from the URL so that we don't get a duplicate, such as: ?page=2&page=3

Having said that, it needs to be smart, so it knows if the beginning of the parameter is a ? or an &

We also need it to be smart so that we can have the URL like so:

```<code><a href="<?=$url;?>page=3">3</a> (without the ? - so it will detect automatically wether to use an `&` or a `?`
</code>```

I don't mind making different variables for each preg_replace for the certain $_GET parameters, but I am looking for the best way to do this.

Thank you.

答:
```<code><?php
//current url: http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=2&sort=a

/**
* URL Parameters : Replace query string value in a url
*
* @version 2023.02.21 Jwu
*
* @param string $queryKey Variable name
* @param string|null $queryValue Property value
*
* @return string
*/
function changeQueryString($queryKey, $queryValue){
    $queryStr = $_SERVER['QUERY_STRING'];
    parse_str($queryStr, $output);
    if($queryValue == null){
        unset($output[$queryKey]);
    }else{
        $output[$queryKey] = $queryValue;
    }
    $actualLink = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    return $actualLink . '?' . http_build_query($output);
}
</code>```

usage:

```<code><a href="<?php echo changeQueryString("sort",'z');?>">sort by z</a>
</code>```

http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=2&sort=z

```<code><a href="<?php echo changeQueryString("page",'5');?>">Page 5</a>
</code>```

http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=5&sort=a

ContentLicense: CC BY-SA 3.0

Body:
Okay.. so basically, say we have a link:

$url = "http://www.site.com/index.php?sub=Mawson&state=QLD&cat=4&page=2&sort=z";

Basically, I need to create a function, which replaces each thing in the URL, for example:

<a href="<?=$url;?>?sort=a">Sort by A-Z
<a href="<?=$url;?>?sort=z">Sort by Z-A

Or, for another example:

<a href="<?=$url;?>?cat=1">Category 1
<a href="<?=$url;?>?cat=2">Category 2

Or, another example:

<a href="<?=$url;?>?page=1">1
<a href="<?=$url;?>?page=2">2
<a href="<?=$url;?>?page=3">3
<a href="<?=$url;?>?page=4">4

So basically, we need a function which will replace the specific $_GET from the URL so that we don't get a duplicate, such as: ?page=2&page=3

Having said that, it needs to be smart, so it knows if the beginning of the parameter is a ? or an &

We also need it to be smart so that we can have the URL like so:

<a href="<?=$url;?>page=3">3 (without the ? - so it will detect automatically wether to use an `&` or a `?`

I don't mind making different variables for each preg_replace for the certain $_GET parameters, but I am looking for the best way to do this.

Thank you.

Body:
<?php
//current url: http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=2&sort=a

/**
* URL Parameters : Replace query string value in a url
*
* @version 2023.02.21 Jwu
*
* @param string $queryKey Variable name
* @param string|null $queryValue Property value
*
* @return string
*/
function changeQueryString($queryKey, $queryValue){
    $queryStr = $_SERVER['QUERY_STRING'];
    parse_str($queryStr, $output);
    if($queryValue == null){
        unset($output[$queryKey]);
    }else{
        $output[$queryKey] = $queryValue;
    }
    $actualLink = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    return $actualLink . '?' . http_build_query($output);
}

usage:

<a href="<?php echo changeQueryString("sort",'z');?>">sort by z</a>

http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=2&sort=z

<a href="<?php echo changeQueryString("page",'5');?>">Page 5</a>

http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=5&sort=a


问:
Display month of sale and number of sales done in that month sorted in descending order of sales
Display month of sale and number of sales done in that month sorted in descending order of sales.

I have used the extract function  to extract month from date but it gives month number not the full name of the month

```<code>select extract(month from sldate) as month, count(sid) as number_sale from sale
 group by sldate
order by sid desc
</code>```

this is  the table

Sale Table

```<code>SALEID  SID SLDATE
1001    1   01-JAN-14
1002    5   02-JAN-14
1003    4   01-FEB-14
1004    1   01-MAR-14
1005    2   01-FEB-14
1006    1   01-JUN-15
</code>```

Expected Result

```<code>MONTH        NUMBER_SALE
February    2
January         2
March           1
June            1
</code>```

答:
select to_char(sldate,'Month') as Month,count(*) as number_sale from sale group by to_char(sldate,'Month') order by count(*) desc
this is simplier solution

Body:
Display month of sale and number of sales done in that month sorted in descending order of sales.

I have used the extract function  to extract month from date but it gives month number not the full name of the month

select extract(month from sldate) as month, count(sid) as number_sale from sale
 group by sldate
order by sid desc

this is  the table

Sale Table

SALEID  SID SLDATE
1001    1   01-JAN-14
1002    5   02-JAN-14
1003    4   01-FEB-14
1004    1   01-MAR-14
1005    2   01-FEB-14
1006    1   01-JUN-15

Expected Result

MONTH        NUMBER_SALE
February    2
January         2
March           1
June            1


问:
How to include layout inside layout?
How to include layout inside layout in Android?

I am creating common layout. I want to include that layout in another page.

答:
Edit: As in a comment rightly requested here some more information. Use the include tag

```<code><include
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   layout="@layout/yourlayout" />
</code>```

to include the layout you want to reuse.

Check this link out...

Title: How to include layout inside layout?

Body:
Edit: As in a comment rightly requested here some more information. Use the include tag

<include
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   layout="@layout/yourlayout" />

to include the layout you want to reuse.

Check this link out...


问:
ImportError: No module named Mail python sendgrid
User.views.py
this is the folder of Mail/views.py im having error when i started the local development server

```<code>from Mail.views import sendgrid_mail

content['url'] = input_values["host"] + "/EmailVerification/" +
user.email + '/' + md5_key
message = render_to_string('accountverification.html', content)
# sendMail.delay("[GavaGives] Account created successfully", message,
content['email'])
sendgrid_mail('info', user.email, '[GavaGives] Account created
successfully', message, 'user_offline_donation')

return response("create", "success", [])
</code>```

Mail.views.py

```<code>def sendgrid_mail(from_email, to_email, subject, content, template):
sg = sendgrid.SendGridClient(config('SENDGRID_API_KEY'))
mail = sendgrid.Mail()

mail.add_to(to_email)
mail.set_from(mail_from(from_email))
mail.set_subject(subject)
mail.set_html(content)

mail.add_filter('templates', 'enable', '1')
mail.add_filter('templates', 'template_id', get_templates(template))

sg.send(mail)
</code>```

Settings.py
this is the folder of the main project/settings.py im having error when i started the local development server

```<code>INSTALLED_APPS = [
'django.contrib.sessions',
'corsheaders',  # CORS installation
'django_cron',  # celery
'django_crontab',  # Cron jobs
'celery',
'djcelery',
'Users',
'Campaign',
'Donor',
'Media',
'Admin',
'Common',
'CommonModules',
'Event',
'Cards',
'Mail'
]
</code>```

this my project Folder Structure base on django. any help would be much appreciated. thanks

```<code>```
[projectname]/
├── [admin]/
├── campaign/
├── card/
├── common/
├── commonmodules/
├── donor/
├── event/
├── gavagives/
│       ├── __init__.py
│       ├── cel.py
│       ├── cronjobs.py
│       ├── custom_commands.py
│       ├── settings.py
│       ├── urls.py
│       ├── views.py
│       ├── wsgi.py
├── logs/
├── Mail/
│       ├── mail.py
│       ├── views.py
├── node_modules/
├── manage.py
├── README.rst
├── requirements.txt
├── .env
├── Users/
│       ├── __init__.py
│       ├── admin.py
│       ├── apps.py
│       ├── cronjobs.py
│       ├── models.py
│       ├── urls.py
│       ├── validations.py
│       ├── views.py
├── venv/
│       ├── include
│       ├── Lib
│       ├── Scripts
│       ├── tcl
├── License.txt
├── .gitignore
```
</code>```

答: As per django documentation, an app must contain models to be treated as a django app. Basically here you are creating a package, so you don't need to include it in INSTALLED_APPS. To allow other apps/packages/modules in your project to use your files inside the Mail folder, you need to create an __init__.py file inside that folder. Without having a __init__.py file inside the folder, Python will no longer look for submodules inside that directory, so attempts to import the module will fail. More information can be found in python documentation regarding how to import from regular package.

Body:
User.views.py
this is the folder of Mail/views.py im having error when i started the local development server

from Mail.views import sendgrid_mail

content['url'] = input_values["host"] + "/EmailVerification/" +
user.email + '/' + md5_key
message = render_to_string('accountverification.html', content)
# sendMail.delay("[GavaGives] Account created successfully", message,
content['email'])
sendgrid_mail('info', user.email, '[GavaGives] Account created
successfully', message, 'user_offline_donation')

return response("create", "success", [])

Mail.views.py

def sendgrid_mail(from_email, to_email, subject, content, template):
sg = sendgrid.SendGridClient(config('SENDGRID_API_KEY'))
mail = sendgrid.Mail()

mail.add_to(to_email)
mail.set_from(mail_from(from_email))
mail.set_subject(subject)
mail.set_html(content)

mail.add_filter('templates', 'enable', '1')
mail.add_filter('templates', 'template_id', get_templates(template))

sg.send(mail)

Settings.py
this is the folder of the main project/settings.py im having error when i started the local development server

INSTALLED_APPS = [
'django.contrib.sessions',
'corsheaders',  # CORS installation
'django_cron',  # celery
'django_crontab',  # Cron jobs
'celery',
'djcelery',
'Users',
'Campaign',
'Donor',
'Media',
'Admin',
'Common',
'CommonModules',
'Event',
'Cards',
'Mail'
]

this my project Folder Structure base on django. any help would be much appreciated. thanks

[projectname]/
├── [admin]/
├── campaign/
├── card/
├── common/
├── commonmodules/
├── donor/
├── event/
├── gavagives/
│       ├── __init__.py
│       ├── cel.py
│       ├── cronjobs.py
│       ├── custom_commands.py
│       ├── settings.py
│       ├── urls.py
│       ├── views.py
│       ├── wsgi.py
├── logs/
├── Mail/
│       ├── mail.py
│       ├── views.py
├── node_modules/
├── manage.py
├── README.rst
├── requirements.txt
├── .env
├── Users/
│       ├── __init__.py
│       ├── admin.py
│       ├── apps.py
│       ├── cronjobs.py
│       ├── models.py
│       ├── urls.py
│       ├── validations.py
│       ├── views.py
├── venv/
│       ├── include
│       ├── Lib
│       ├── Scripts
│       ├── tcl
├── License.txt
├── .gitignore


问:
Xamarin.Forms Strange behavior of ListView
Im having a problem with listview and im almost giving upp.

I have a CustomButton inside a ListView, OnPressUp it should trigger an event.

The problem is that when i touch on button its trigering an event of multiple other buttons somehow.

Here is my Code please tell if you figure out something strange.

XAML

```<code>    <StackLayout Orientation="Vertical">
                        <Label Text="Video Properties" Style="{ StaticResource HeaderContainer}"></Label>
                        <controls:YListView x:Name="lstVideosProperties" OnSelected="LstVideosProperties_OnSelected">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <Grid VerticalOptions="FillAndExpand">
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="2*"></ColumnDefinition>
                                                <ColumnDefinition Width="8*"></ColumnDefinition>
                                            </Grid.ColumnDefinitions>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="60"></RowDefinition>
                                            </Grid.RowDefinitions>
                                            <Image Aspect="Fill" VerticalOptions="FillAndExpand" Source="{Binding DefaultThumbnailUrl}" Grid.Row="0" Grid.Column="0"></Image>
                                            <Grid Grid.Row="0" Grid.Column="1">
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition Width="7*"></ColumnDefinition>
                                                    <ColumnDefinition Width="3*"></ColumnDefinition>
                                                </Grid.ColumnDefinitions>
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="4*"></RowDefinition>
                                                    <RowDefinition Height="6*"></RowDefinition>
                                                </Grid.RowDefinitions>
                                                <StackLayout Style="{StaticResource FormFloatLeft}" Grid.Row="0" Grid.Column="0">
                                                    <Label Text="{Binding Title}"  Style="{StaticResource Header}" />
                                                </StackLayout>
                                                <controls:CustomButton Grid.RowSpan="2"
                                                                       CommandParameter="{Binding VideoId}"
                                                                       IsEnabled="{Binding VideoId ,Converter={StaticResource Downloadable}}"
                                                                       Grid.Row="0" Grid.Column="1"
                                                                       x:Name="_btnDownload"
                                                                       OnPressUp="_btnDownload_OnPressUp"
                                                                       Image="download.png"
                                                                       HorizontalOptions="EndAndExpand"
                                                                       VerticalOptions="StartAndExpand"
                                                                       Style="{StaticResource Icon}" />
                                                <StackLayout VerticalOptions="Start" Style="{StaticResource FormFloatLeft}" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
                                                    <Label Text="{Binding Views}" Style="{StaticResource UnderText}" />
                                                </StackLayout>
                                            </Grid>
                                        </Grid>
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </controls:YListView>
</code>```

DATABIND ITEMS

```<code> lstVideosProperties.ItemsSource = _videos;
</code>```

CUSTOMBUTTON

```<code> public class CustomButton : Button
    {
        public CustomButton()
        {
            ColorBeforeSelection = Color.Transparent;
        }
        public Color OnPressColor { get; set; } = ((Color)Application.Current.Resources["pressed"]);
        private Color ColorBeforeSelection;
        public TextAlignment? TextAlignment { get; set; }

        public event EventHandler OnPressUp;
        public event EventHandler OnPressDown;
        public Action<double, double> SizeAllocated;

        public bool _isSelected;
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {

                _isSelected = value;

                if (_isSelected)
                {
                    if (this.BackgroundColor != OnPressColor)
                        ColorBeforeSelection = this.BackgroundColor;
                    this.BackgroundColor = OnPressColor;
                }
                else
                    this.BackgroundColor = ColorBeforeSelection;

            }
        }

        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            SizeAllocated?.Invoke(width, height);

        }

        public void OnPressed()
        {
            OnPressDown?.Invoke(this, null);
        }

        public void OnReleased()
        {
            OnPressUp?.Invoke(this, null);
        }
    }
</code>```

CustomButtonRenderer

```<code>public class CustomButtonRenderer : ButtonRenderer
    {
        Context _context;
        public CustomButtonRenderer(Context context) : base(context)
        {
            _context = context;
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            var customRendererButton = e.NewElement as CustomButton;

            var control = Control as Android.Widget.Button;

            switch (customRendererButton.TextAlignment)
            {
                case Xamarin.Forms.TextAlignment.Center:
                    control.Gravity = GravityFlags.Center | GravityFlags.CenterVertical;
                    break;
                case Xamarin.Forms.TextAlignment.Start:
                    control.Gravity = GravityFlags.Left | GravityFlags.CenterVertical;

                    break;
                case Xamarin.Forms.TextAlignment.End:
                    control.Gravity = GravityFlags.End | GravityFlags.CenterVertical;
                    break;
            }

            if (!customRendererButton.IsEnabled)
            {
                control.SetBackgroundColor(new Android.Graphics.Color(
                    ContextCompat.GetColor(_context, Resource.Color.disabled_background)
                    ));
            }

            bool selected = customRendererButton.IsSelected;
            bool prevent = false;
            Timer _timer = null;
            control.Touch += (object sender, TouchEventArgs args) =>
                {
                    if (!customRendererButton.IsEnabled)
                    {
                        control.SetBackgroundColor(new Android.Graphics.Color(
                            ContextCompat.GetColor(_context, Resource.Color.disabled_background)
                            ));

                        return;
                    }

                    if (args.Event.Action == MotionEventActions.Up)
                    {
                        _timer.Stop();
                        if (!selected)
                            customRendererButton.IsSelected = false;

                        if (!prevent)
                            customRendererButton.OnReleased();
                        prevent = false; // reset
                        return;
                    }
                    else if (args.Event.Action == MotionEventActions.Down)
                    {
                        _timer?.Stop();
                        _timer = new Timer(200);
                        _timer.Elapsed += new ElapsedEventHandler((o, arg) =>
                                    {
                                        if (!selected)
                                            customRendererButton.IsSelected = false;
                                        prevent = true;
                                    });
                        _timer.Start();
                        selected = customRendererButton.IsSelected;
                        if (!customRendererButton.IsSelected)
                            customRendererButton.IsSelected = true;
                        customRendererButton.OnPressed();
                        return;
                    }
                    else if (args.Event.Action == MotionEventActions.Move)
                    {

                    }
                };
        }
    }
</code>```

答:
Bind button's command in this way :

```<code>Command="{Binding Path=BindingContext.CommandName,Source={x:Reference root}}" CommandParameter="{Binding .}"
</code>```

Define page name as this "x:Name="root"" in your page's opening bracket.(name can be anything)

Body:
Im having a problem with listview and im almost giving upp.

I have a CustomButton inside a ListView, OnPressUp it should trigger an event.

The problem is that when i touch on button its trigering an event of multiple other buttons somehow.

Here is my Code please tell if you figure out something strange.

XAML

    <StackLayout Orientation="Vertical">

                        <controls:YListView x:Name="lstVideosProperties" OnSelected="LstVideosProperties_OnSelected">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <Grid VerticalOptions="FillAndExpand">
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="2*"></ColumnDefinition>
                                                <ColumnDefinition Width="8*"></ColumnDefinition>
                                            </Grid.ColumnDefinitions>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="60"></RowDefinition>
                                            </Grid.RowDefinitions>
                                            <Image Aspect="Fill" VerticalOptions="FillAndExpand" Source="{Binding DefaultThumbnailUrl}" Grid.Row="0" Grid.Column="0"></Image>
                                            <Grid Grid.Row="0" Grid.Column="1">
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition Width="7*"></ColumnDefinition>
                                                    <ColumnDefinition Width="3*"></ColumnDefinition>
                                                </Grid.ColumnDefinitions>
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="4*"></RowDefinition>
                                                    <RowDefinition Height="6*"></RowDefinition>
                                                </Grid.RowDefinitions>
                                                <StackLayout Style="{StaticResource FormFloatLeft}" Grid.Row="0" Grid.Column="0">

                                                </StackLayout>
                                                <controls:CustomButton Grid.RowSpan="2"
                                                                       CommandParameter="{Binding VideoId}"
                                                                       IsEnabled="{Binding VideoId ,Converter={StaticResource Downloadable}}"
                                                                       Grid.Row="0" Grid.Column="1"
                                                                       x:Name="_btnDownload"
                                                                       OnPressUp="_btnDownload_OnPressUp"
                                                                       Image="download.png"
                                                                       HorizontalOptions="EndAndExpand"
                                                                       VerticalOptions="StartAndExpand"
                                                                       Style="{StaticResource Icon}" />
                                                <StackLayout VerticalOptions="Start" Style="{StaticResource FormFloatLeft}" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">

                                                </StackLayout>
                                            </Grid>
                                        </Grid>
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </controls:YListView>

DATABIND ITEMS

 lstVideosProperties.ItemsSource = _videos;

CUSTOMBUTTON

 public class CustomButton : Button
    {
        public CustomButton()
        {
            ColorBeforeSelection = Color.Transparent;
        }
        public Color OnPressColor { get; set; } = ((Color)Application.Current.Resources["pressed"]);
        private Color ColorBeforeSelection;
        public TextAlignment? TextAlignment { get; set; }

        public event EventHandler OnPressUp;
        public event EventHandler OnPressDown;
        public Action<double, double> SizeAllocated;

        public bool _isSelected;
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {

                _isSelected = value;

                if (_isSelected)
                {
                    if (this.BackgroundColor != OnPressColor)
                        ColorBeforeSelection = this.BackgroundColor;
                    this.BackgroundColor = OnPressColor;
                }
                else
                    this.BackgroundColor = ColorBeforeSelection;

            }
        }

        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            SizeAllocated?.Invoke(width, height);

        }

        public void OnPressed()
        {
            OnPressDown?.Invoke(this, null);
        }

        public void OnReleased()
        {
            OnPressUp?.Invoke(this, null);
        }
    }

CustomButtonRenderer

public class CustomButtonRenderer : ButtonRenderer
    {
        Context _context;
        public CustomButtonRenderer(Context context) : base(context)
        {
            _context = context;
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            var customRendererButton = e.NewElement as CustomButton;

            var control = Control as Android.Widget.Button;

            switch (customRendererButton.TextAlignment)
            {
                case Xamarin.Forms.TextAlignment.Center:
                    control.Gravity = GravityFlags.Center | GravityFlags.CenterVertical;
                    break;
                case Xamarin.Forms.TextAlignment.Start:
                    control.Gravity = GravityFlags.Left | GravityFlags.CenterVertical;

                    break;
                case Xamarin.Forms.TextAlignment.End:
                    control.Gravity = GravityFlags.End | GravityFlags.CenterVertical;
                    break;
            }

            if (!customRendererButton.IsEnabled)
            {
                control.SetBackgroundColor(new Android.Graphics.Color(
                    ContextCompat.GetColor(_context, Resource.Color.disabled_background)
                    ));
            }

            bool selected = customRendererButton.IsSelected;
            bool prevent = false;
            Timer _timer = null;
            control.Touch += (object sender, TouchEventArgs args) =>
                {
                    if (!customRendererButton.IsEnabled)
                    {
                        control.SetBackgroundColor(new Android.Graphics.Color(
                            ContextCompat.GetColor(_context, Resource.Color.disabled_background)
                            ));

                        return;
                    }

                    if (args.Event.Action == MotionEventActions.Up)
                    {
                        _timer.Stop();
                        if (!selected)
                            customRendererButton.IsSelected = false;

                        if (!prevent)
                            customRendererButton.OnReleased();
                        prevent = false; // reset
                        return;
                    }
                    else if (args.Event.Action == MotionEventActions.Down)
                    {
                        _timer?.Stop();
                        _timer = new Timer(200);
                        _timer.Elapsed += new ElapsedEventHandler((o, arg) =>
                                    {
                                        if (!selected)
                                            customRendererButton.IsSelected = false;
                                        prevent = true;
                                    });
                        _timer.Start();
                        selected = customRendererButton.IsSelected;
                        if (!customRendererButton.IsSelected)
                            customRendererButton.IsSelected = true;
                        customRendererButton.OnPressed();
                        return;
                    }
                    else if (args.Event.Action == MotionEventActions.Move)
                    {

                    }
                };
        }
    }

Body:
Bind button's command in this way :

Command="{Binding Path=BindingContext.CommandName,Source={x:Reference root}}" CommandParameter="{Binding .}"

Define page name as this "x:Name="root"" in your page's opening bracket.(name can be anything)


问:
Skip login screen while opening a vue route link
I am using laravel and vue js in my app. All the vue routes ask for a login when opened as i am using laravel auth. I want to create some routes that should be accessable without a user to be logged in. In other words I want some route that can be accessed by guest user as well. But at the moment all routes require user to be authenticated. These are my routes

```<code>const routes = [
    { path: '/dashboard_admin', component:  require('./components/dashboard.vue').default},
    { path: '/ongoing_events_admin', component:  require('./components/events.vue').default } ,
    { path: '/courses_admin', component:  require('./components/courses.vue').default},
    { path: '/front_images_admin', component:  require('./components/front_images.vue').default},
    { path: '/news_admin', component:  require('./components/news.vue').default},

    { path: '/main', component:  require('./components/main_view/index_view_general.vue') ,
    name: 'index',
    props: true ,
    beforeEnter:DontrequireLogin
    },

    //general vue

  // { path: '/', component:  require('./components/main_view/index_view_general.vue').default},

  ]

  const router = new VueRouter({
    mode: 'history',
    routes // short for `routes: routes`
  })

const app = new Vue({
    el: '#app',
    router
});
</code>```

These are my routes. I want some of these routes that can be accessed by guest user as well but at the moment all routes require user to be logged in.

答:
So you need to do this meta's, for more about this you can read from its official documentation Route Meta

Let me explain litle bit what meta's do .

in meta you define a bolean object which indicate , this route is for authenticated or users or for guest user. let see below example.

i have authenticated route, only for authenticated users.

```<code>{path: '/account-setting',component:accountSetting,meta:{auth:true}},
</code>```

so i pass auth object in meta and decide in route.beforeach what to do with this route.

so same a normal route

```<code>{path: '/about',component:about}
</code>```

in this i give no meta, which means its for all user.

read the documentation to know how to use it.

Body:
I am using laravel and vue js in my app. All the vue routes ask for a login when opened as i am using laravel auth. I want to create some routes that should be accessable without a user to be logged in. In other words I want some route that can be accessed by guest user as well. But at the moment all routes require user to be authenticated. These are my routes

const routes = [
    { path: '/dashboard_admin', component:  require('./components/dashboard.vue').default},
    { path: '/ongoing_events_admin', component:  require('./components/events.vue').default } ,
    { path: '/courses_admin', component:  require('./components/courses.vue').default},
    { path: '/front_images_admin', component:  require('./components/front_images.vue').default},
    { path: '/news_admin', component:  require('./components/news.vue').default},

    { path: '/main', component:  require('./components/main_view/index_view_general.vue') ,
    name: 'index',
    props: true ,
    beforeEnter:DontrequireLogin
    },

    //general vue

  // { path: '/', component:  require('./components/main_view/index_view_general.vue').default},

  ]

  const router = new VueRouter({
    mode: 'history',
    routes // short for `routes: routes`
  })

const app = new Vue({
    el: '#app',
    router
});

These are my routes. I want some of these routes that can be accessed by guest user as well but at the moment all routes require user to be logged in.

Body:
So you need to do this meta's, for more about this you can read from its official documentation Route Meta

Let me explain litle bit what meta's do .

in meta you define a bolean object which indicate , this route is for authenticated or users or for guest user. let see below example.

i have authenticated route, only for authenticated users.

{path: '/account-setting',component:accountSetting,meta:{auth:true}},

so i pass auth object in meta and decide in route.beforeach what to do with this route.

so same a normal route

{path: '/about',component:about}

in this i give no meta, which means its for all user.

read the documentation to know how to use it.


问:
JQuery Datatable Buttons not working/ not displayed
I have created a view for a datatable (Which is called upon a modal from a link in a datatable in another view), and I intend to put buttons to export the data to Excel, PDF, Print...etc.
I have added the script, but the buttons are not displayed in the final output.

What are the library files that I want to load in order to make the code working with the results that I expect from it?

Note: I have used JQuery 3.1.1

I have tried various methods, also by changing the script library references to no avail. I even tried the download builder from datatables.net, but any of it seemed not working too.

```<code>*The html code*
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="btn btn-default" data-dismiss="modal">Back</button>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h2 class="modal-title">Item</h2>
            <h4>TRANSFER HISTORY</h4>
        </div>
        <div>
            <table id="example" class="display" style="width:100%">
                <tr style="background-color:#b5bbc8">
                    <th>
                        From
                    </th>
                    <th>
                        To
                    </th>
                    <th>
                        Date
                    </th>
                    <th>
                        Cause
                    </th>
                    <th>
                        Updated By
                    </th>
                </tr>

                @foreach (var item in Model)
            {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.Center.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Center1.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.TransferDate)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.TransferCause)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.User.FirstName) @Html.DisplayFor(modelItem => item.User.LastName)
                        </td>
                    </tr>
                }
            </table>
        </div>
    </div>
</div>

*The Buttons script*
<script type="text/javascript">
    $(document).ready(function () {
        $('#example').DataTable({
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ]
        });
    });
</script>
</code>```

Update - I just found out what was missing. Actually, it was a reference in the parent view, from which this view is loaded. I fixed it, now everything works fine. Thank you all for your answers and feedback.

答: Just need to ask you did you have verify you'r script through live data table dom, if not please go to there and check / veriry your script and design link, i hope you will resolved your matter by testing online portal.</p>

Body:
I have created a view for a datatable (Which is called upon a modal from a link in a datatable in another view), and I intend to put buttons to export the data to Excel, PDF, Print...etc.
I have added the script, but the buttons are not displayed in the final output.

What are the library files that I want to load in order to make the code working with the results that I expect from it?

Note: I have used JQuery 3.1.1

I have tried various methods, also by changing the script library references to no avail. I even tried the download builder from datatables.net, but any of it seemed not working too.

*The html code*

            <button type="button" class="btn btn-default" data-dismiss="modal">Back</button>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Item

TRANSFER HISTORY

                        From

                        To

                        Date

                        Cause

                        Updated By

                @foreach (var item in Model)
            {

                            @Html.DisplayFor(modelItem => item.Center.Name)

                            @Html.DisplayFor(modelItem => item.Center1.Name)

                            @Html.DisplayFor(modelItem => item.TransferDate)

                            @Html.DisplayFor(modelItem => item.TransferCause)

                            @Html.DisplayFor(modelItem => item.User.FirstName) @Html.DisplayFor(modelItem => item.User.LastName)

                }

*The Buttons script*

Update - I just found out what was missing. Actually, it was a reference in the parent view, from which this view is loaded. I fixed it, now everything works fine. Thank you all for your answers and feedback.


问:
log4net and .net Framework 4.0
I was having issues in log4net when I updated my solutions to .net 4.0 , and then I downloaded the source of it and built log4net and targeted it to .net 4.0 and used it in my projects.

Initially when I referred log4net that is targeted to run time 2.0 it complied and run the application but log did not work.

Now when I run my project with log4net targeted to .net 4.0 I get the error "The type initializer for 'Log4NetTest.TestLog' threw an exception."

Any Idea how to solve this?

Edit: this is the inner exception:

```
InnerException: System.TypeLoadException Message=Inheritance security rules violated while overriding member:
'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'.
Security accessibility of the overriding method must match the security accessibility of the method being overriden.
  Source=log4net
  TypeName=log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)
  StackTrace:
    at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory loggerFactory)
    at log4net.Repository.Hierarchy.Hierarchy..ctor() in C:\src\Repository\Hierarchy\Hierarchy.cs:line 150
```

答:
I've found a compiled version of log4net for .NET client profile here:

http://gosheg.blogspot.com/2011/04/log4net-in-net-40-c-applications-net.html

Title: log4net and .net Framework 4.0

Body:
I was having issues in log4net when I updated my solutions to .net 4.0 , and then I downloaded the source of it and built log4net and targeted it to .net 4.0 and used it in my projects.

Initially when I referred log4net that is targeted to run time 2.0 it complied and run the application but log did not work.

Now when I run my project with log4net targeted to .net 4.0 I get the error "The type initializer for 'Log4NetTest.TestLog' threw an exception."

Any Idea how to solve this?

Edit: this is the inner exception:

InnerException: System.TypeLoadException Message=Inheritance security rules violated while overriding member:
'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'.
Security accessibility of the overriding method must match the security accessibility of the method being overriden.
  Source=log4net
  TypeName=log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)
  StackTrace:
    at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory loggerFactory)
    at log4net.Repository.Hierarchy.Hierarchy..ctor() in C:\src\Repository\Hierarchy\Hierarchy.cs:line 150


问:
Bootstrap Column Alignment Issue
I'm replicating a blog template similar to this page https://www.ideo.com/blog

The problem is, I can't get the grids to align the way I need. I've uploaded my version here on this fiddle here https://jsfiddle.net/f74d0ngr/9/  (Make sure you resize the output window to a larger size to understand the issue.)

I need latest - 2 and latest - 3 posts to align directly under latest - 1.
This is my code

```<code><div id="Blog-body">
      <div class="container">
        <div class="row">
          <div class="col-lg-8">
              <p class="text-center section-head" id="The-Latest">The Latest</p>
              <img src="img/Blog1.png" alt="" class="blog-img">
              <p class="lead less-spacing">Blog | Lorem Ipsum</p>
              <h3 class="title">Inviting Algorithms to the Design Team</h3>
          </div>

          <div class="col-lg-4">
              <p class="text-center section-head" id="The-Latest">Most Read</p>
              <p class="lead less-spacing">Blog | Lorem Ipsum</p>
              <h3 class="">The Best Managers Understand Their Employees’ Emotions—And Their Own</h3>

              <p class="lead less-spacing">Blog | Lorem Ipsum</p>
              <h3 class="">The Best Managers Understand Their Employees’ Emotions—And Their Own</h3>
              <p class="lead less-spacing">Blog | Lorem Ipsum</p>
              <h3 class="">The Best Managers Understand Their Employees’ Emotions—And Their Own</h3>
                   <p class="lead less-spacing">Blog | Lorem Ipsum</p>
              <h3 class="">The Best Managers Understand Their Employees’ Emotions—And Their Own</h3>

          </div>
        </div>
        <div class="row">

            <div class="col-lg-4">
                <p class="text-center section-head" id="The-Latest">The Latest</p>
                <img src="img/Blog1.png" alt="" class="blog-img">
                <p class="lead less-spacing">Blog | Lorem Ipsum</p>
                <h3 class="title">Inviting Algorithms to the Design Team</h3>

            </div>
            <div class="col-lg-4">
                <p class="text-center section-head" id="The-Latest">The Latest</p>
                <img src="img/Blog1.png" alt="" class="blog-img">
                <p class="lead less-spacing">Blog | Lorem Ipsum</p>
                <h3 class="title">Inviting Algorithms to the Design Team</h3>

            </div>

        </div>
      </div>
    </div>
</code>```

CSS

```<code>.section-head{

  background-color: #fbef39;
  height: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 50px;
}
</code>```

I have tried placing all the sections in different rows, but could not get the alignment I needed. Any suggestions to fix this ?

答:
The sections Latest 2 and Latest 3 in your code should be in
 as well as Latest1 but in a different row.
I upadated the code here: https://jsfiddle.net/zedqugms/

Title: Bootstrap Column Alignment Issue

Body:
I'm replicating a blog template similar to this page https://www.ideo.com/blog

The problem is, I can't get the grids to align the way I need. I've uploaded my version here on this fiddle here https://jsfiddle.net/f74d0ngr/9/  (Make sure you resize the output window to a larger size to understand the issue.)

I need latest - 2 and latest - 3 posts to align directly under latest - 1.
This is my code

The Latest

Blog | Lorem Ipsum

Inviting Algorithms to the Design Team

Most Read

Blog | Lorem Ipsum

The Best Managers Understand Their Employees’ Emotions—And Their Own

Blog | Lorem Ipsum

The Best Managers Understand Their Employees’ Emotions—And Their Own

Blog | Lorem Ipsum

The Best Managers Understand Their Employees’ Emotions—And Their Own

Blog | Lorem Ipsum

The Best Managers Understand Their Employees’ Emotions—And Their Own

The Latest

Blog | Lorem Ipsum

Inviting Algorithms to the Design Team

The Latest

Blog | Lorem Ipsum

Inviting Algorithms to the Design Team

CSS

.section-head{

  background-color: #fbef39;
  height: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 50px;
}

I have tried placing all the sections in different rows, but could not get the alignment I needed. Any suggestions to fix this ?

Body:
The sections Latest 2 and Latest 3 in your code should be in <div class="col-lg-8"> as well as Latest1 but in a different row.
I upadated the code here: https://jsfiddle.net/zedqugms/


问:
Error : java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration
I am getting error java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration while running a spring code from spring tool suite

I have already googled and checked stackoverflow for the resolution ,but no luck .

This is my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.thoughtworkstest</groupId>
<artifactId>supermarket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>supermarket</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.3.156</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.6.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.6.RELEASE</version>
    </dependency>

    <!-- Dependencies for SQLite -->
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.25.2</version>
    </dependency>
    <dependency>
        <groupId>net.kemitix</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

This is app-context.xml

```<code><context:property-placeholder
  location="classpath:META-INF/spring/hibernate.properties"/>

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses" value="com.test.market.model.ItemDetails" />
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   </props>
  </property>
 </bean>

</beans>
</code>```

答:
Like @crizzis said try removing all other dependencies and provide only the following :

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</code>```

Spring starter data jpa already includes all the necessary dependencies like hibernate-core,hibernate-commons-annotations,javax.persistence-api,spring jdbc,h2 etc. So try removing all other data related dependencies from your pom and let springboot handle all such dependencies through it's starter.When you explicitly provide the version and dependency it will override the started dependency and may cause incompatible version issues if you are not careful.

Body:
I am getting error java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration while running a spring code from spring tool suite

I have already googled and checked stackoverflow for the resolution ,but no luck .

This is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath />
</parent>
<groupId>com.thoughtworkstest</groupId>
<artifactId>supermarket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>supermarket</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.3.156</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.6.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.6.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.25.2</version>
    </dependency>
    <dependency>
        <groupId>net.kemitix</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

This is app-context.xml

<context:property-placeholder
  location="classpath:META-INF/spring/hibernate.properties"/>

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses" value="com.test.market.model.ItemDetails" />
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   </props>
  </property>
 </bean>

</beans>

Body:
Like @crizzis said try removing all other dependencies and provide only the following :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Spring starter data jpa already includes all the necessary dependencies like hibernate-core,hibernate-commons-annotations,javax.persistence-api,spring jdbc,h2 etc. So try removing all other data related dependencies from your pom and let springboot handle all such dependencies through it's starter.When you explicitly provide the version and dependency it will override the started dependency and may cause incompatible version issues if you are not careful.


问:
F# reading custom configuration and representing it as ConfigurationSection with ConfigurationElements
I am rather new to F# but I have a question about creating and reading custom configuration file. I know how it would look in c# so for example I have a simple config file

```<code><?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>
    <section name="customSection" type="Tool.Lib.Config, Tool.Lib" />
  </configSections>

  <communicationSection>
    <responseTimeoutInMs value="900000" />
  </communicationSection>

</configuration>
</code>```

Basing on that in c# it is simple. I am creating model named Config with properties marked as ConfigurationProperty (witch relates to xml node name, in this case responseTimeoutInMs) something like:

```<code>[ConfigurationProperty("responseTimeoutInMs")]
public ResponseTimeoutConfigElement ResponseTimeoutInMs
{
   get => (ResponseTimeoutConfigElement)base["responseTimeoutInMs"];
   set => base["responseTimeoutInMs"] = value;
}
</code>```

And of course value is set as ConfigurationElement so:

```<code>public class ResponseTimeoutConfigElement : ConfigurationElement
{
    [ConfigurationProperty("value", IsRequired = true, IsKey = true, DefaultValue = 0)]
    public int Value => (int)base["value"];
}
</code>```

It is a nice mechanism, I can pin converters into it and create types I need while reading configuration.

I know i can read default config using ConfigurationManager and exe configuration map, but this is basic config reading using key and value.

So my question is, is there something similar in F# to this in C#?

答:
I'm not sure if it's quite what you're after as you mention using a "custom configuration file", but in the past I've used the AppSettings Type Provider to get strongly typed access to app variables.

If that's not appropriate, there's also a more standard XML type provider that might help?

I find type providers really useful in avoiding having to write boilerplate code for simple access, and they're a really nice feature of F# development.

Body:
I am rather new to F# but I have a question about creating and reading custom configuration file. I know how it would look in c# so for example I have a simple config file

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

  </configSections>

  <communicationSection>
    <responseTimeoutInMs value="900000" />
  </communicationSection>

</configuration>

Basing on that in c# it is simple. I am creating model named Config with properties marked as ConfigurationProperty (witch relates to xml node name, in this case responseTimeoutInMs) something like:

[ConfigurationProperty("responseTimeoutInMs")]
public ResponseTimeoutConfigElement ResponseTimeoutInMs
{
   get => (ResponseTimeoutConfigElement)base["responseTimeoutInMs"];
   set => base["responseTimeoutInMs"] = value;
}

And of course value is set as ConfigurationElement so:

public class ResponseTimeoutConfigElement : ConfigurationElement
{
    [ConfigurationProperty("value", IsRequired = true, IsKey = true, DefaultValue = 0)]
    public int Value => (int)base["value"];
}

It is a nice mechanism, I can pin converters into it and create types I need while reading configuration.

I know i can read default config using ConfigurationManager and exe configuration map, but this is basic config reading using key and value.

So my question is, is there something similar in F# to this in C#?


问:
How do I upgrade from PHP 7.0 to 7.3 on google cloud platform?
I am running the Wordpress multisite click to deploy on the compute engine.

```<code>Operating system
    Debian 9.8
Package contents
        Apache 2.4.25
        Google-Fluentd 1.6.9
        MySQL-Client 5.7.26
        MySQL-Server 5.7.26
        PHP 7.0.33
            Stackdriver-Agent 5.5.2
            WP-CLI 2.2.0
            WordPress 5.1.1
            phpMyAdmin 4.6.6
</code>```

I would like to upgrade PHP to 7.3

答:
You may follow this instructions on how to update your php version from 7.0 to 7.3.

For Debian:

```<code>$ sudo apt install apt-transport-https lsb-release

$ sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg # Download the signing key

$ sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list' # Add Ondrej's repo to sources list.

$ sudo apt update

$ sudo apt-get install php7.3

To check the current version after the installation:

$ php -v
</code>```

For Ubuntu:

```<code>$ sudo add-apt-repository ppa:ondrej/php # Press enter to confirm.

$ sudo apt-get update

$ sudo apt-get install php7.3
</code>```

If you encounter the error below during installation, you may execute the command "$ sudo rm /var/lib/dpkg/lock" then try installing the php7.3 again.

```<code>E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)

E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
</code>```

Hope this information helps.

Body:
I am running the Wordpress multisite click to deploy on the compute engine.

Operating system
    Debian 9.8
Package contents
        Apache 2.4.25
        Google-Fluentd 1.6.9
        MySQL-Client 5.7.26
        MySQL-Server 5.7.26
        PHP 7.0.33
            Stackdriver-Agent 5.5.2
            WP-CLI 2.2.0
            WordPress 5.1.1
            phpMyAdmin 4.6.6

I would like to upgrade PHP to 7.3

Body:
You may follow this instructions on how to update your php version from 7.0 to 7.3.

For Debian:

$ sudo apt install apt-transport-https lsb-release

$ sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg # Download the signing key

$ sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list' # Add Ondrej's repo to sources list.

$ sudo apt update

$ sudo apt-get install php7.3

To check the current version after the installation:

$ php -v

For Ubuntu:

$ sudo add-apt-repository ppa:ondrej/php # Press enter to confirm.

$ sudo apt-get update

$ sudo apt-get install php7.3

If you encounter the error below during installation, you may execute the command "$ sudo rm /var/lib/dpkg/lock" then try installing the php7.3 again.

E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)

E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?

Hope this information helps.


问:
First 5 rows summed per ref per type, all others equal 1, grouped by a team ID
I have an SQL statement where the first 5 rows per TYPE are selected per WSF_REF with the WEIGHTS summed together WHERE the STATUS = 'Approved'. All other rows per ref per type are classed as 1. This works fine. I'm looking to add a second group of TEAMID.

```<code> "SELECT WSF_REF, SUM(WEIGHT)
FROM (SELECT t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT
  HAVING COUNT(t2.ID) < 5
  UNION ALL
  SELECT t1.ID, t1.WSF_REF, t1.TYPE, 1
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE
  HAVING COUNT(t2.ID) >= 5) t
GROUP BY WSF_REF";
</code>```

Example Data

```<code>CREATE TABLE test (
  `ID` INTEGER,
  `WSF_REF` INTEGER,
  `TYPE` VARCHAR(4),
  `WEIGHT` INTEGER,
  `STATUS` VARCHAR(10),
  `TEAMID` VARCHAR(10)
);

INSERT INTO test
  (`ID`, `WSF_REF`, `TYPE`, `WEIGHT`, `STATUS`, `TEAMID` )
VALUES
  ('1', '1', 'Pike', '10', 'Approved', 'Red'),
  ('2', '1', 'Pike', '10', 'Approved', 'Red'),
  ('3', '1', 'Pike', '10', 'Approved', 'Red'),
  ('4', '1', 'Pike', '10', 'Approved', 'Red'),
  ('5', '1', 'Pike', '10', 'Approved', 'Red'),
  ('6', '1', 'Pike', '10', 'Approved', 'Red'),
  ('7', '1', 'Asp', '10', 'Approved', 'Red'),
  ('8', '1', 'Asp', '10', 'Approved', 'Red'),
  ('9', '1', 'Asp', '10', 'Approved', 'Red'),
  ('10', '1', 'Asp', '10', 'Approved', 'Red'),
  ('11', '1', 'Asp', '10', 'Approved', 'Red'),
  ('12', '1', 'Asp', '10', 'Approved', 'Red'),
  ('13', '2', 'Pike', '10', 'Approved', 'Red'),
  ('14', '3', 'Pike', '10', 'Approved', 'Blue');
</code>```

Intended Results

```<code>TEAM ID      WEIGHT
---------------------
Red           112
Blue           10
</code>```

So the WSF_REF is still used to work the initial totals but the GROUP BY needs to be TEAMID.

答:
Try below -

DEMO

```<code>SELECT  TEAMID,SUM(WEIGHT)
FROM (SELECT t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT,t1.TEAMID
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT,t1.TEAMID
  HAVING COUNT(t2.ID) < 5
  UNION ALL
  SELECT t1.ID, t1.WSF_REF, t1.TYPE, 1,t1.TEAMID
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE,t1.TEAMID
  HAVING COUNT(t2.ID) >= 5) t
GROUP BY TEAMID
</code>```

OUTPUT:

```<code>TEAMID  weight
Red     112
Blue    10
</code>```

Body:
I have an SQL statement where the first 5 rows per TYPE are selected per WSF_REF with the WEIGHTS summed together WHERE the STATUS = 'Approved'. All other rows per ref per type are classed as 1. This works fine. I'm looking to add a second group of TEAMID.

 "SELECT WSF_REF, SUM(WEIGHT)
FROM (SELECT t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT
  HAVING COUNT(t2.ID) < 5
  UNION ALL
  SELECT t1.ID, t1.WSF_REF, t1.TYPE, 1
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE
  HAVING COUNT(t2.ID) >= 5) t
GROUP BY WSF_REF";

Example Data

CREATE TABLE test (
  `ID` INTEGER,
  `WSF_REF` INTEGER,
  `TYPE` VARCHAR(4),
  `WEIGHT` INTEGER,
  `STATUS` VARCHAR(10),
  `TEAMID` VARCHAR(10)
);

INSERT INTO test
  (`ID`, `WSF_REF`, `TYPE`, `WEIGHT`, `STATUS`, `TEAMID` )
VALUES
  ('1', '1', 'Pike', '10', 'Approved', 'Red'),
  ('2', '1', 'Pike', '10', 'Approved', 'Red'),
  ('3', '1', 'Pike', '10', 'Approved', 'Red'),
  ('4', '1', 'Pike', '10', 'Approved', 'Red'),
  ('5', '1', 'Pike', '10', 'Approved', 'Red'),
  ('6', '1', 'Pike', '10', 'Approved', 'Red'),
  ('7', '1', 'Asp', '10', 'Approved', 'Red'),
  ('8', '1', 'Asp', '10', 'Approved', 'Red'),
  ('9', '1', 'Asp', '10', 'Approved', 'Red'),
  ('10', '1', 'Asp', '10', 'Approved', 'Red'),
  ('11', '1', 'Asp', '10', 'Approved', 'Red'),
  ('12', '1', 'Asp', '10', 'Approved', 'Red'),
  ('13', '2', 'Pike', '10', 'Approved', 'Red'),
  ('14', '3', 'Pike', '10', 'Approved', 'Blue');

Intended Results

TEAM ID      WEIGHT
---------------------
Red           112
Blue           10

So the WSF_REF is still used to work the initial totals but the GROUP BY needs to be TEAMID.

Body:
Try below -

DEMO

SELECT  TEAMID,SUM(WEIGHT)
FROM (SELECT t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT,t1.TEAMID
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE, t1.WEIGHT,t1.TEAMID
  HAVING COUNT(t2.ID) < 5
  UNION ALL
  SELECT t1.ID, t1.WSF_REF, t1.TYPE, 1,t1.TEAMID
  FROM test t1
  LEFT JOIN test t2 ON t2.WSF_REF = t1.WSF_REF AND t2.TYPE = t1.TYPE AND t2.STATUS = t1.STATUS AND t2.ID < t1.ID
  WHERE t1.STATUS = 'Approved'
  GROUP BY t1.ID, t1.WSF_REF, t1.TYPE,t1.TEAMID
  HAVING COUNT(t2.ID) >= 5) t
GROUP BY TEAMID

OUTPUT:

TEAMID  weight
Red     112
Blue    10


问:
Change view and remove element by Ext.Component.query
I have a TabPanel like this:

```<code>Ext.application({
name : 'Fiddle',

launch : function() {

Ext.create('Ext.TabPanel', {
items: [
    {
        title: "",
        reference: 'tabpanel',
        itemId: 'tab1',
        items: [{
            itemId: 'firstTab',
            xclass: 'viewClass'
        }],
    }, {
        title: "",
        reference: 'tab2',
        layout: 'fit',
        items: [{
            xclass: "view",
        }]
    }
]
</code>```

in the xclass component there is the path of a class where is defined the view. In the view should be a button, after tap on it, the view should refresh and show another class, for example the view should be defined by 'viewClass2' and not anymore by 'viewClass' I'm imaging a function triggered on button tap like this:

```<code>        Ext.getCmp('tab1').remove('firstTab');
        Ext.getCmp('tab1').add({
            itemId: 'firstTab',
            xclass: 'viewClass2'
        })
</code>```

BUT I must use itemId and not id so I cannot use "Ext.getCmp" and i should use Ext.Component.query but I don't know how to manage remove and add operations

答:
You have to get reference of the component first, then remove it.</p>

```<code>Ext.create('Ext.TabPanel', {
id: 'myTabPanel',
items: [
    {
        title: "",
        reference: 'tabpanel',
        itemId: 'tab1',
        items: [{
            itemId: 'firstTab',
            xclass: 'viewClass'
        }],
    }, {
        title: "",
        reference: 'tab2',
        layout: 'fit',
        items: [{
            xclass: "view",
        }]
    }
];

var tabPanel = Ext.getCmp('myTabPanel');
var tab = tabPanel.getComponent("tab1");

// remove by id
tab.remove(tab.down("[itemId='firstTab']").id);
// remove by reference
tab.remove(tab.down("[itemId='firstTab']"));
</code>```

Body:
I have a TabPanel like this:

Ext.application({
name : 'Fiddle',

launch : function() {

Ext.create('Ext.TabPanel', {
items: [
    {
        title: "",
        reference: 'tabpanel',
        itemId: 'tab1',
        items: [{
            itemId: 'firstTab',
            xclass: 'viewClass'
        }],
    }, {
        title: "",
        reference: 'tab2',
        layout: 'fit',
        items: [{
            xclass: "view",
        }]
    }
]

in the xclass component there is the path of a class where is defined the view. In the view should be a button, after tap on it, the view should refresh and show another class, for example the view should be defined by 'viewClass2' and not anymore by 'viewClass' I'm imaging a function triggered on button tap like this:

        Ext.getCmp('tab1').remove('firstTab');
        Ext.getCmp('tab1').add({
            itemId: 'firstTab',
            xclass: 'viewClass2'
        })

BUT I must use itemId and not id so I cannot use "Ext.getCmp" and i should use Ext.Component.query but I don't know how to manage remove and add operations

Body:
You have to get reference of the component first, then remove it.

Ext.create('Ext.TabPanel', {
id: 'myTabPanel',
items: [
    {
        title: "",
        reference: 'tabpanel',
        itemId: 'tab1',
        items: [{
            itemId: 'firstTab',
            xclass: 'viewClass'
        }],
    }, {
        title: "",
        reference: 'tab2',
        layout: 'fit',
        items: [{
            xclass: "view",
        }]
    }
];

var tabPanel = Ext.getCmp('myTabPanel');
var tab = tabPanel.getComponent("tab1");

// remove by id
tab.remove(tab.down("[itemId='firstTab']").id);
// remove by reference
tab.remove(tab.down("[itemId='firstTab']"));


问:
The upload path does not appear to be valid on multiple upload file and image
I get the same error like

Array ( [lpj] =>
  The upload path does not appear to be valid.
  ) Array ( [lpj] => Array ( [file_name] => lpjHIMASOS27052019140622aska-review-form-6(2).doc [upload_path] => ./dokumen/ [allowed_types] => pdf|doc|docx [max_size] => 1000 ) )

this my controller

```<code> $lpj = 'lpj'.$this->session->userdata('id_ukm').date('dmYHis').$_FILES["lpj"]['name'];
   $configlpj["lpj"]['file_name'] = $lpj;
   $configlpj["lpj"]['upload_path'] = './dokumen/';
    $configlpj["lpj"]['allowed_types'] = 'pdf|doc|docx'; //if your file is image
    $configlpj["lpj"]['max_size'] = '1000';
    $_FILES['lpj']['name'] = str_replace(' ','-',$_FILES['lpj']['name']);
    $this->load->library('upload', $configlpj, 'lpj');

    //Upload file sertifikat
    $sertifikat = $this->session->userdata('id_ukm').date('dmYHis') . str_replace(' ','-',$_FILES["sertifikat"]['name']);
    $configser["sertifikat"]['file_name'] = $sertifikat;
    $configser["sertifikat"]['upload_path'] = './image/';
    $configser["sertifikat"]['allowed_types'] = 'png|jpg|jpeg'; //if your file is dokumen
    $configser["sertifikat"]['max_size'] = '500';
    $this->load->library('upload', $configser, 'sertifikat');

    //Upload Foto Penyerahan Sertifikat/Penghargaan
    $penyerahan = $this->session->userdata('id_ukm').date('dmYHis') . str_replace(' ','-',$_FILES["penyerahan_penghargaan"]['name']);
    $configpen["penyerahan_penghargaan"]['file_name'] = $penyerahan;
    $configpen["penyerahan_penghargaan"]['upload_path'] = './image/';
    $configpen["penyerahan_penghargaan"]['allowed_types'] = 'png|jpg|jpeg'; //if your file is dokumen
    $configpen["penyerahan_penghargaan"]['max_size'] = '500';
    $this->load->library('upload', $configpen, 'penyerahan');

    $this->lpj->initialize($configlpj);
    $this->sertifikat->initialize($configser);
    $this->penyerahan->initialize($configpen);
    if (!$this->lpj->do_upload('lpj')) {
        $error = array('lpj' => $this->lpj->display_errors());
        print_r($error);
        print_r($configlpj);
    } elseif (!$this->upload->do_upload('sertifikat')) {
       $error = array('sertifikat' => $this->sertifikat->display_errors());
        print_r($error);
        print_r($configser);
    } elseif (!$this->upload->do_upload('penyerahan_penghargaan')){
       $error = array('penyerahan' => $this->penyerahan->display_errors());
        print_r($error);
        print_r($configpen);
</code>```

can sameone helpme please?

答:
Try like this  </p>

```<code>$dir_path = FCPATH.'assets/dokumen';
if(!is_dir($dir_path )){
   mkdir($dir_path);
}
$configlpj["lpj"]['upload_path'] = $dir_path;
</code>```

Body:
I get the same error like

Array ( [lpj] =>
  The upload path does not appear to be valid.
  ) Array ( [lpj] => Array ( [file_name] => lpjHIMASOS27052019140622aska-review-form-6(2).doc [upload_path] => ./dokumen/ [allowed_types] => pdf|doc|docx [max_size] => 1000 ) )

this my controller

 $lpj = 'lpj'.$this->session->userdata('id_ukm').date('dmYHis').$_FILES["lpj"]['name'];
   $configlpj["lpj"]['file_name'] = $lpj;
   $configlpj["lpj"]['upload_path'] = './dokumen/';
    $configlpj["lpj"]['allowed_types'] = 'pdf|doc|docx'; //if your file is image
    $configlpj["lpj"]['max_size'] = '1000';
    $_FILES['lpj']['name'] = str_replace(' ','-',$_FILES['lpj']['name']);
    $this->load->library('upload', $configlpj, 'lpj');

    //Upload file sertifikat
    $sertifikat = $this->session->userdata('id_ukm').date('dmYHis') . str_replace(' ','-',$_FILES["sertifikat"]['name']);
    $configser["sertifikat"]['file_name'] = $sertifikat;
    $configser["sertifikat"]['upload_path'] = './image/';
    $configser["sertifikat"]['allowed_types'] = 'png|jpg|jpeg'; //if your file is dokumen
    $configser["sertifikat"]['max_size'] = '500';
    $this->load->library('upload', $configser, 'sertifikat');

    //Upload Foto Penyerahan Sertifikat/Penghargaan
    $penyerahan = $this->session->userdata('id_ukm').date('dmYHis') . str_replace(' ','-',$_FILES["penyerahan_penghargaan"]['name']);
    $configpen["penyerahan_penghargaan"]['file_name'] = $penyerahan;
    $configpen["penyerahan_penghargaan"]['upload_path'] = './image/';
    $configpen["penyerahan_penghargaan"]['allowed_types'] = 'png|jpg|jpeg'; //if your file is dokumen
    $configpen["penyerahan_penghargaan"]['max_size'] = '500';
    $this->load->library('upload', $configpen, 'penyerahan');

    $this->lpj->initialize($configlpj);
    $this->sertifikat->initialize($configser);
    $this->penyerahan->initialize($configpen);
    if (!$this->lpj->do_upload('lpj')) {
        $error = array('lpj' => $this->lpj->display_errors());
        print_r($error);
        print_r($configlpj);
    } elseif (!$this->upload->do_upload('sertifikat')) {
       $error = array('sertifikat' => $this->sertifikat->display_errors());
        print_r($error);
        print_r($configser);
    } elseif (!$this->upload->do_upload('penyerahan_penghargaan')){
       $error = array('penyerahan' => $this->penyerahan->display_errors());
        print_r($error);
        print_r($configpen);

can sameone helpme please?

Body:
Try like this

$dir_path = FCPATH.'assets/dokumen';
if(!is_dir($dir_path )){
   mkdir($dir_path);
}
$configlpj["lpj"]['upload_path'] = $dir_path;


问:
how to do a SQL Join that returns the rows that are not present in my table 2
I want to run a query between my two tables and returns the results to me the lines that are not present in my table 2</p>

答:
Look at this post.

I copied the code:

```<code>select * from A left join B on A.x=B.y where B.y is null;
</code>```

Body:
Look at this post.

I copied the code:

select * from A left join B on A.x=B.y where B.y is null;


问:
Get the maximum and mininum value of a period setted by me
My intention is get the min and max value for a period setted for me.

Thank you for helping

```<code>study(title="Líneas verticales horarias- Aarón", shorttitle="Líneas verticales horarias - Aarón",overlay=true)
AsiaON = time(period, '0300-0900')
bgcolor(AsiaON > 0 ? yellow: na, transp=95)

EuropaON = time(period, '0902-1830')
bgcolor(EuropaON > 0 ? blue: na, transp=95)
// I get satisfactorily to draw the vertical lines for indicating my schedules

// Probably my problem is here
localMin = lowest(AsiaON,1)
localMax = highest(EuropaON, 1)
plotchar(localMin, location=location.belowbar, text=localMin)
plotchar(localMax, location=location.abovebar, text=localMax)
</code>```

答:
I don't think this is possible in pine-script, as described in the reference manual the highest() function expects an integer as its second parameter.

In your case, EuropaON and AsiaON are both a series and cannot be turned into an integer.

Body:
My intention is get the min and max value for a period setted for me.

Thank you for helping

study(title="Líneas verticales horarias- Aarón", shorttitle="Líneas verticales horarias - Aarón",overlay=true)
AsiaON = time(period, '0300-0900')
bgcolor(AsiaON > 0 ? yellow: na, transp=95)

EuropaON = time(period, '0902-1830')
bgcolor(EuropaON > 0 ? blue: na, transp=95)
// I get satisfactorily to draw the vertical lines for indicating my schedules

// Probably my problem is here
localMin = lowest(AsiaON,1)
localMax = highest(EuropaON, 1)
plotchar(localMin, location=location.belowbar, text=localMin)
plotchar(localMax, location=location.abovebar, text=localMax)


问:
Will the dart codes for iOS be removed when compiling for Android?
I'm using flutter to write an app for both iOS and Android platforms. Some functions are not the same.

For example:

```<code>if (Platform.isIOS) {
    int onlyForiOS = 10;
    onlyForiOS++;
    print("$onlyForiOS");
}
else if (Platform.isAndroid){
    int onlyForAndroid = 20;
    onlyForAndroid++;
    print("$onlyForAndroid");
}
</code>```

When I build for the Android platform, will the codes for iOS be compiled into the binary file? Or they are just removed for optimization?
For security reason, I don't want any of the codes for iOS appeared in the Android binary file.

答:
This depends on what expression you are evaluating.

Dart tree-shaking is based on constant variables. As such, the following will be tree-shaked:

```<code>const foo = false;
if (foo) {
  // will be removed on release builds
}
</code>```

But this example won't:

```<code>final foo = false;
if (foo) {
  // foo is not a const, therefore this if is not tree-shaked
}
</code>```

Now if we look at the implementation of Platform.isAndroid, we can see that it is not a constant, but instead a getter.

Therefore we can deduce that if (Platform.isAndroid) won't be tree-shaked.

Body:
I'm using flutter to write an app for both iOS and Android platforms. Some functions are not the same.

For example:

if (Platform.isIOS) {
    int onlyForiOS = 10;
    onlyForiOS++;
    print("$onlyForiOS");
}
else if (Platform.isAndroid){
    int onlyForAndroid = 20;
    onlyForAndroid++;
    print("$onlyForAndroid");
}

When I build for the Android platform, will the codes for iOS be compiled into the binary file? Or they are just removed for optimization?
For security reason, I don't want any of the codes for iOS appeared in the Android binary file.

Body:
This depends on what expression you are evaluating.

Dart tree-shaking is based on constant variables. As such, the following will be tree-shaked:

const foo = false;
if (foo) {
  // will be removed on release builds
}

But this example won't:

final foo = false;
if (foo) {
  // foo is not a const, therefore this if is not tree-shaked
}

Now if we look at the implementation of Platform.isAndroid, we can see that it is not a constant, but instead a getter.

Therefore we can deduce that if (Platform.isAndroid) won't be tree-shaked.


问:
Spring WebFlux: How to route to a different handler function based on query parameters?
I am writing a person API using Spring WebFlux functional programming, how to route to different handler functions based on the query param names?

```<code>    @Bean
    public RouterFunction<ServerResponse> route(PersonHandler personHandler) {
        return RouterFunctions.route(GET("/people/{id}").and(accept(APPLICATION_JSON)), personHandler::get)
                .andRoute(GET("/people").and(accept(APPLICATION_JSON)), personHandler::all)
                .andRoute(GET("/people/country/{country}").and(accept(APPLICATION_JSON)), personHandler::getByCountry)
//                .andRoute(GET("/people?name={name}").and(accept(APPLICATION_JSON)), personHandler::searchByName)
//                .andRoute(GET("/people?age={age}").and(accept(APPLICATION_JSON)), personHandler::searchByAge)
//                I am expecting to do something like this
                ;
    }
</code>```

Or do I need to handle it in the handler function?
like

    public Mono<ServerResponse> searchPeople(ServerRequest serverRequest) {
        final Optional<String> name = serverRequest.queryParam("name");
        final Optional<String> age = serverRequest.queryParam("age");
        Flux<People> result;

        if(name.isPresent()){
            result = name.map(peopleRepository::searchByName)
                    .orElseThrow();
        } else if(age.isPresent()){
            result = name.map(peopleRepository::searchByage)
                    .orElseThrow();
        }

        return ok().contentType(MediaType.APPLICATION_JSON).body(result, People.class);
    }
```

What is the best way to do it?

Thanks

答:
You can create your own RequestPredicate and use the existing infrastructure (by plugging it into a and()):

```<code>public static RequestPredicate hasQueryParam(String name) {
  return RequestPredicates.queryParam(name, p -> StringUtils.hasText(p));
}
</code>```

Body:
I am writing a person API using Spring WebFlux functional programming, how to route to different handler functions based on the query param names?

    @Bean
    public RouterFunction<ServerResponse> route(PersonHandler personHandler) {
        return RouterFunctions.route(GET("/people/{id}").and(accept(APPLICATION_JSON)), personHandler::get)
                .andRoute(GET("/people").and(accept(APPLICATION_JSON)), personHandler::all)
                .andRoute(GET("/people/country/{country}").and(accept(APPLICATION_JSON)), personHandler::getByCountry)
//                .andRoute(GET("/people?name={name}").and(accept(APPLICATION_JSON)), personHandler::searchByName)
//                .andRoute(GET("/people?age={age}").and(accept(APPLICATION_JSON)), personHandler::searchByAge)
//                I am expecting to do something like this
                ;
    }

Or do I need to handle it in the handler function?
like

    public Mono<ServerResponse> searchPeople(ServerRequest serverRequest) {
        final Optional<String> name = serverRequest.queryParam("name");
        final Optional<String> age = serverRequest.queryParam("age");
        Flux<People> result;

        if(name.isPresent()){
            result = name.map(peopleRepository::searchByName)
                    .orElseThrow();
        } else if(age.isPresent()){
            result = name.map(peopleRepository::searchByage)
                    .orElseThrow();
        }

        return ok().contentType(MediaType.APPLICATION_JSON).body(result, People.class);
    }

What is the best way to do it?

Thanks

Body:
You can create your own RequestPredicate and use the existing infrastructure (by plugging it into a and()):

public static RequestPredicate hasQueryParam(String name) {
  return RequestPredicates.queryParam(name, p -> StringUtils.hasText(p));
}


问:
Create a Vaadin Request Handler that handles the request before Spring Security gets a chance
So we're aiming to migrate an application from Thorntail to Spring Boot.

One issue is that we're using Vaadin 8 for legacy reasons.

The app provides password-less login suport (as in login-by-link).

Now vaadin is a single-page framework, so we've split off the /login and /passwordless login options into Vaadin UIs of their own s.t. we can configure

override fun configure(http: HttpSecurity) {
    http
        .csrf().disable()
        .httpBasic().disable()
        .formLogin().disable()
        .authorizeRequests()
            .antMatchers("/login").anonymous()
            .antMatchers("/passwordless/**").permitAll()
            .antMatchers("/vaadinServlet/UIDL/**").permitAll()
            .antMatchers("/vaadinServlet/HEARTBEAT/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .logout()
            .addLogoutHandler(logoutHandler())
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login?goodbye").permitAll()
            .and()
        .exceptionHandling()
            .authenticationEntryPoint(LoginUrlAuthenticationEntryPoint("/login"))
}
```

<p>Unfortunately, we'll have to support the old links that have already been distributed as well for backwards-compitability. And the old login-links were set up as</p>

```/#!passwordless/<login-token>
```

Which means even if we add a filter, we won't be able to distinguish the request from any other request to /.

Currently, we see no other option than to allow unauthenticated requests to / and manually redirect to the login page if the user is not authenticated, which is very ugly.

Can we somehow define a vaadin request handler (that DOES have access to the vaadin location /#!passwordless/<login-token> and therefore can read the <login-token> and redirect to /passwordless/<login-token>) before Spring-security can redirect us to /login?

答:
As the hash is not included in the HTTP request, it's impossible to have it on the server before a response has been sent.

Perhaps you could configure a filter that intercepts all requests to /. If the user is authenticated, it does nothing. Otherwise, it either redirects to another page that has some JavaScript, or then it returns some JavaScript directly, that checks the hash and does a client-side redirect either to /login or to /passwordless/<login-token>.

I guess this is basically what you describe as ugly, but as long as that filter is in place, it shouldn't be an issue.

Edit: An alternative, if the hash is forwarded to the login page, you could include a piece of JavaScript on the login page itself, that checks for the presence of the hash and redirects appropriately.

Body:
So we're aiming to migrate an application from Thorntail to Spring Boot.

One issue is that we're using Vaadin 8 for legacy reasons.

The app provides password-less login suport (as in login-by-link).

Now vaadin is a single-page framework, so we've split off the /login and /passwordless login options into Vaadin UIs of their own s.t. we can configure

override fun configure(http: HttpSecurity) {
    http
        .csrf().disable()
        .httpBasic().disable()
        .formLogin().disable()
        .authorizeRequests()
            .antMatchers("/login").anonymous()
            .antMatchers("/passwordless/**").permitAll()
            .antMatchers("/vaadinServlet/UIDL/**").permitAll()
            .antMatchers("/vaadinServlet/HEARTBEAT/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .logout()
            .addLogoutHandler(logoutHandler())
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login?goodbye").permitAll()
            .and()
        .exceptionHandling()
            .authenticationEntryPoint(LoginUrlAuthenticationEntryPoint("/login"))
}

Unfortunately, we'll have to support the old links that have already been distributed as well for backwards-compitability. And the old login-links were set up as

/#!passwordless/<login-token>

Which means even if we add a filter, we won't be able to distinguish the request from any other request to /.

Currently, we see no other option than to allow unauthenticated requests to / and manually redirect to the login page if the user is not authenticated, which is very ugly.

Can we somehow define a vaadin request handler (that DOES have access to the vaadin location /#!passwordless/<login-token> and therefore can read the <login-token> and redirect to /passwordless/<login-token>) before Spring-security can redirect us to /login?


问:
The Drawer is transparent
The drawer's background is transparent. I have tried to hot reload the entire code which i wrote from scratch again, yet it didn't work.

```<code>drawer: ListView(
        children: <Widget>[
          DrawerHeader(
            padding:
                EdgeInsets.symmetric(vertical: 20.0, horizontal: 100.0),
            child: Text('Hi!'),
            curve: Curves.easeInCubic,
          ),
          ListTile(
            contentPadding: EdgeInsets.all(100.0),
            leading: Icon(Icons.home),
            trailing: Icon(Icons.donut_small),
            title: Text(
              'Home',
              style: TextStyle(color: Colors.white),
            ),
          )
        ],
      ),
</code>```

Reference Image

答:
You should use Drawer widget as a parent of your ListView

```<code>drawer:
     Drawer(
        child: ListView(
           ....
</code>```

More info here: https://flutter.dev/docs/cookbook/design/drawer

Title: The Drawer is transparent

Body:
The drawer's background is transparent. I have tried to hot reload the entire code which i wrote from scratch again, yet it didn't work.

drawer: ListView(
        children: <Widget>[
          DrawerHeader(
            padding:
                EdgeInsets.symmetric(vertical: 20.0, horizontal: 100.0),
            child: Text('Hi!'),
            curve: Curves.easeInCubic,
          ),
          ListTile(
            contentPadding: EdgeInsets.all(100.0),
            leading: Icon(Icons.home),
            trailing: Icon(Icons.donut_small),
            title: Text(
              'Home',
              style: TextStyle(color: Colors.white),
            ),
          )
        ],
      ),

Reference Image

Body:
You should use Drawer widget as a parent of your ListView

drawer:
     Drawer(
        child: ListView(
           ....

More info here: https://flutter.dev/docs/cookbook/design/drawer