问:
lightSlider show all button next to thumbnails
I need create lightSlider (http://sachinchoolur.github.io/lightslider/) gallery where there is "Show all photos" next to thumbnails/.IsPager (if thumbnails count is >= 5 show button).

I tried to do it by position: absolute but show all button is over last thumbnail.

$('#lightSlider').lightSlider({
  gallery: true,
  item: 1,
  loop: true,
  slideMargin: 0,
  thumbItem: 6
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.demo {
  width: 420px;
  position: relative;
}
ul {
  list-style: none outside none;
  padding-left: 0;
  margin-bottom: 0;
}
li {
  display: block;
  float: left;
  margin-right: 6px;
  cursor: pointer;
}
img {
  display: block;
  height: auto;
  max-width: 100%;
}
.show-all {
  width: 80px;
  height: auto;
  background-color: #eee;
  border: 1px #ddd;
  float: left;
  position: absolute;
  right: 0;
  bottom: 0;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/lightslider/1.1.3/css/lightslider.min.css" rel="stylesheet" />

    Show all photos

```

Pager needs to be align in middle.

答:
Ok, so this is going to be a little tricky but it almost works.

https://jsfiddle.net/590f2t74/1/

Don't forget that the "See all photos" is going with append method now

```<code>$(".lSSlideOuter").append('<div class="show-all"><i class="fa fa-camera" aria-hidden="true"></i><span>Show all photos</span></div>');
</code>```

P.S: For the last image issue, you can put "See all photos" image and link that to all images as the JsFiddle.

Hope this will help.

Body:
I need create lightSlider (http://sachinchoolur.github.io/lightslider/) gallery where there is "Show all photos" next to thumbnails/.IsPager (if thumbnails count is >= 5 show button).

I tried to do it by position: absolute but show all button is over last thumbnail.

$('#lightSlider').lightSlider({
  gallery: true,
  item: 1,
  loop: true,
  slideMargin: 0,
  thumbItem: 6
});

.demo {
  width: 420px;
  position: relative;
}
ul {
  list-style: none outside none;
  padding-left: 0;
  margin-bottom: 0;
}
li {
  display: block;
  float: left;
  margin-right: 6px;
  cursor: pointer;
}
img {
  display: block;
  height: auto;
  max-width: 100%;
}
.show-all {
  width: 80px;
  height: auto;
  background-color: #eee;
  border: 1px #ddd;
  float: left;
  position: absolute;
  right: 0;
  bottom: 0;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/lightslider/1.1.3/css/lightslider.min.css" rel="stylesheet" />

    Show all photos

Pager needs to be align in middle.

Body:
Ok, so this is going to be a little tricky but it almost works.

https://jsfiddle.net/590f2t74/1/

Don't forget that the "See all photos" is going with append method now

$(".lSSlideOuter").append('<div class="show-all"><i class="fa fa-camera" aria-hidden="true"></i><span>Show all photos</span></div>');

P.S: For the last image issue, you can put "See all photos" image and link that to all images as the JsFiddle.

Hope this will help.


来源: stackexchange

问:
Error in calculation Winforms C#
I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.

```<code>num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
    tbNum1.Text = tbNum1.Text.Replace(",", ".");
}

double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
    tbNum2.Text = tbNum2.Text.Replace(",", ".");
}

double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();
</code>```

Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !

答:
Your parse to a double is wrong. You can do it like this:</p>

```<code>        double num1, num2, product = 0;

        if (tb1.Text.IndexOf(",") != -1)
        {
            tb1.Text = tb1.Text.Replace(",", ".");
        }
        num1 = double.Parse(tb1.Text, System.Globalization.CultureInfo.InvariantCulture);

        if(tb2.Text.IndexOf(",") != -1)
        {
            tb2.Text = tb2.Text.Replace(",", ".");
        }
        num2 = double.Parse(tb2.Text, System.Globalization.CultureInfo.InvariantCulture);

        product = Math.Round(num1 * num2,2);

        tb3.Text = product.ToString();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Error in calculation Winforms C#

Body:
I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.

num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
    tbNum1.Text = tbNum1.Text.Replace(",", ".");
}

double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
    tbNum2.Text = tbNum2.Text.Replace(",", ".");
}

double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();

Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !

Body:
Your parse to a double is wrong. You can do it like this:

        double num1, num2, product = 0;

        if (tb1.Text.IndexOf(",") != -1)
        {
            tb1.Text = tb1.Text.Replace(",", ".");
        }
        num1 = double.Parse(tb1.Text, System.Globalization.CultureInfo.InvariantCulture);

        if(tb2.Text.IndexOf(",") != -1)
        {
            tb2.Text = tb2.Text.Replace(",", ".");
        }
        num2 = double.Parse(tb2.Text, System.Globalization.CultureInfo.InvariantCulture);

        product = Math.Round(num1 * num2,2);

        tb3.Text = product.ToString();


问:
How to make a child element disappear after drop?
I have 2 divs (dragdiv1, dragdiv2) and each of them contains another div with a text. I'm dragging a photo from another div back and forth between the first 2 divs mentioned and when I drop the photo into one of them, I want the text disappear and then appear again when photo is dragged into the other div.

I'm very new to this so I'm kind of struggling to achieve it. Can someone give me a hint how to make it?

This is what I have so far, but no disappearing happens, so it's probably completely wrong, or am I at least somewhat close to my intention?

HTML part:

```<code><div class="photo">
   <img src="blahblah.jpg" draggable="true" ondragstart="drag(event)" id="drag1"></img>
</div>

<div id="0" class="dragdiv1" ondrop="drop(event)" ondragover="allowDrop(event)">
    <div class="draganddroptext">Drag&Drop Area</div>
</div>

<div id="1" class="dragdiv2" ondrop="drop(event)" ondragover="allowDrop(event)">
    <div class="draganddroptext">Drag&Drop Area</div>
</div>
</code>```

Javascript attempt:

```<code>function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
    var off = document.getElementsByClassName('draganddroptext');
    if (off.style.display == "none") {
        off.style.display = "inline";
    } else {
        off.style.display = "none";
    }
}
</code>```

--- update

```<code>function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
    var targetId = ev.target.id;
    var targetElems = document.getElementsByClassName('draganddroptext');
    var off;
    var on;
    if (targetId == 0) {
        off = targetElems[0];
        off.style.display = "none";
        on = targetElems[1];
        if (on.style.display == "none") ){
            on.style.display = "inline";
        }
    } else {
        off = targetElems[1];
        off.style.display = "none";
        on = targetElems[0];
        if (on.style.display == "none") ){
            on.style.display = "inline";
        }
    }
}
</code>```

Any help is highly appreciated!

答:
getElementsByClassName returns an array of elements. So to control the visibility of your elements you have to include which element you want to hide e.g.:

```<code>var off = document.getElementsByClassName('draganddroptext');
off[0].style.display = "none"; //hides first element
</code>```

You already have your target element so you can just get the relevant element by calling:

```<code>var off = ev.target.getElementsByClassName('draganddroptext')[0];
if (off.style.display == "none") {
    off.style.display = "inline";
} else {
    off.style.display = "none";
}
</code>```

Body:
I have 2 divs (dragdiv1, dragdiv2) and each of them contains another div with a text. I'm dragging a photo from another div back and forth between the first 2 divs mentioned and when I drop the photo into one of them, I want the text disappear and then appear again when photo is dragged into the other div.

I'm very new to this so I'm kind of struggling to achieve it. Can someone give me a hint how to make it?

This is what I have so far, but no disappearing happens, so it's probably completely wrong, or am I at least somewhat close to my intention?

HTML part:

Drag&Drop Area

Drag&Drop Area

Javascript attempt:

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
    var off = document.getElementsByClassName('draganddroptext');
    if (off.style.display == "none") {
        off.style.display = "inline";
    } else {
        off.style.display = "none";
    }
}

--- update

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
    var targetId = ev.target.id;
    var targetElems = document.getElementsByClassName('draganddroptext');
    var off;
    var on;
    if (targetId == 0) {
        off = targetElems[0];
        off.style.display = "none";
        on = targetElems[1];
        if (on.style.display == "none") ){
            on.style.display = "inline";
        }
    } else {
        off = targetElems[1];
        off.style.display = "none";
        on = targetElems[0];
        if (on.style.display == "none") ){
            on.style.display = "inline";
        }
    }
}

Any help is highly appreciated!

Body:
getElementsByClassName returns an array of elements. So to control the visibility of your elements you have to include which element you want to hide e.g.:

var off = document.getElementsByClassName('draganddroptext');
off[0].style.display = "none"; //hides first element

You already have your target element so you can just get the relevant element by calling:

var off = ev.target.getElementsByClassName('draganddroptext')[0];
if (off.style.display == "none") {
    off.style.display = "inline";
} else {
    off.style.display = "none";
}


问:
No way to color the border of a Tkinter Button?
It works with some other widgets, but not with Buttons.

```<code>from Tkinter import *
root = Tk()
root.geometry("600x300+400+50")

btn_up = Button(root, text='Go UP')
btn_up.config(highlightbackground="red", highlightcolor="red", highlightthickness=10, relief=SOLID)
btn_up.pack()

root.mainloop()
</code>```

Python 2.7 - Windows 10

答:
I am using linux and when I run your code, I get a button with a thick red border, so it looks like that the default Windows theme does not support highlightthickness while the default linux theme does.

If you want to change the border color, it is possible with some ttk themes like 'clam':

```<code>from Tkinter import *
import ttk
root = Tk()

style = ttk.Style(root)
style.theme_use('clam')
style.configure('my.TButton', bordercolor="red")

ttk_button = ttk.Button(root, text='Go UP', style='my.TButton')
ttk_button.pack()

root.mainloop()
</code>```

However, changing the borderwidth, with style.configure('my.TButton', borderwidth=10) does not increase the width of the red border as expected.

Body:
It works with some other widgets, but not with Buttons.

from Tkinter import *
root = Tk()
root.geometry("600x300+400+50")

btn_up = Button(root, text='Go UP')
btn_up.config(highlightbackground="red", highlightcolor="red", highlightthickness=10, relief=SOLID)
btn_up.pack()

root.mainloop()

Python 2.7 - Windows 10

Body:
I am using linux and when I run your code, I get a button with a thick red border, so it looks like that the default Windows theme does not support highlightthickness while the default linux theme does.

If you want to change the border color, it is possible with some ttk themes like 'clam':

from Tkinter import *
import ttk
root = Tk()

style = ttk.Style(root)
style.theme_use('clam')
style.configure('my.TButton', bordercolor="red")

ttk_button = ttk.Button(root, text='Go UP', style='my.TButton')
ttk_button.pack()

root.mainloop()

However, changing the borderwidth, with style.configure('my.TButton', borderwidth=10) does not increase the width of the red border as expected.


问:
How to change the Back Button Text on Xamarin.Forms
I have been trying to change the text of the back button in Xamarin.Forms without luck.

I tried already this code with no luck:

```<code>NavigationPage.SetBackButtonTitle(this, "");
</code>```

I'm using a MasterDetailPage.

I tried to add the code into the constructor of the XAML cs file.

Libraries used: PRISM 6.2.0, Xamarin Forms 2.3.1.114

Any suggestion or idea?

Thanks in advance

答:
You can also do it from the Code Behind of the current xaml page

```<code>public TodoPage()
{
    InitializeComponent();
    NavigationPage.SetBackButtonTitle(this, "Back");
}
</code>```

NB: It has to be done on the previous page you want to set.

e.g. Page A has to have the code if you want Page B to show "Back" title.

Body:
I have been trying to change the text of the back button in Xamarin.Forms without luck.

I tried already this code with no luck:

NavigationPage.SetBackButtonTitle(this, "");

I'm using a MasterDetailPage.

I tried to add the code into the constructor of the XAML cs file.

Libraries used: PRISM 6.2.0, Xamarin Forms 2.3.1.114

Any suggestion or idea?

Thanks in advance

Body:
You can also do it from the Code Behind of the current xaml page

public TodoPage()
{
    InitializeComponent();
    NavigationPage.SetBackButtonTitle(this, "Back");
}

NB: It has to be done on the previous page you want to set.

e.g. Page A has to have the code if you want Page B to show "Back" title.

ContentLicense: CC BY-SA 4.0


问:
Place imageview next to textview - (image view get repeated) CHAT UI
I would like to place imageview next to textview.

Here is my XML:

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

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    >
    <RelativeLayout
        android:id="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </RelativeLayout>

   <RelativeLayout
        android:layout_below="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@+id/rightText"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </RelativeLayout>
</RelativeLayout>```
</div>
</div>
</p>

<p>This is how it looks like in real world:</p>

<p><img src="https://i.stack.imgur.com/uXGFm.png" alt="In the picture below you can see the repeated images"></p>

<p>p.s. I tried & and not working: </p>

<p>android:layout_alignParentRight="true"</p>

<p>android:layout_toLeftOf="@+id/BLABLA"
and even </p>

<p>android:drawableLeft="@drawable/your_image_name"  </p>

<p>it was good try but not what I want.  HOW CAN I DISABLE THIS REPATABLE IMAGES AS YOU SEE IN SCREENSHOT? Thanks.</p>

<p>EDIT added my massage activity:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>adapter = new FirebaseRecyclerAdapter<ChatMessage, chat_rec>(ChatMessage.class,R.layout.msglist,chat_rec.class,ref.child("chat")) {
            @Override
            protected void populateViewHolder(chat_rec viewHolder, ChatMessage model, int position) {

                if (model.getMsgUser().equals("user")) {

                    viewHolder.rightText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.VISIBLE);
                    viewHolder.leftText.setVisibility(View.GONE);

                }
                else {
                    viewHolder.leftText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.GONE);
                    viewHolder.leftText.setVisibility(View.VISIBLE);

                }
            }
        };</code>```

答:
You need to change your RelativeLayout to LinearLayout like below</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </LinearLayout>

   <LinearLayout
        android:layout_below="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@+id/rightText"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </LinearLayout>
</RelativeLayout>
</code>```

Body:
I would like to place imageview next to textview.

Here is my XML:

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

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    >
    <RelativeLayout
        android:id="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </RelativeLayout>

   <RelativeLayout
        android:layout_below="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@+id/rightText"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </RelativeLayout>
</RelativeLayout>

This is how it looks like in real world:

p.s. I tried & and not working:

android:layout_alignParentRight="true"

android:layout_toLeftOf="@+id/BLABLA"
and even

android:drawableLeft="@drawable/your_image_name"

it was good try but not what I want.  HOW CAN I DISABLE THIS REPATABLE IMAGES AS YOU SEE IN SCREENSHOT? Thanks.

EDIT added my massage activity:

adapter = new FirebaseRecyclerAdapter<ChatMessage, chat_rec>(ChatMessage.class,R.layout.msglist,chat_rec.class,ref.child("chat")) {
            @Override
            protected void populateViewHolder(chat_rec viewHolder, ChatMessage model, int position) {

                if (model.getMsgUser().equals("user")) {

                    viewHolder.rightText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.VISIBLE);
                    viewHolder.leftText.setVisibility(View.GONE);

                }
                else {
                    viewHolder.leftText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.GONE);
                    viewHolder.leftText.setVisibility(View.VISIBLE);

                }
            }
        };

Body:
You need to change your RelativeLayout to LinearLayout like below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </LinearLayout>

   <LinearLayout
        android:layout_below="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@+id/rightText"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </LinearLayout>
</RelativeLayout>


问:
Clean debug output function?
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

```<code>__FILE__
__LINE__
</code>```

but there's a problem in my opinion... When I'm writing a function like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}
</code>```

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}
</code>```

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

答:
Wrapping error() in a macro is indeed the right way to go - I'd write it like so:

```<code>#ifdef DEBUG
static void error(const char *file, long line, const char *msg)
{
  fprintf(stderr, "Error (%s:%ld): %s\n", file, line, msg);
}
#define error(msg) (error)(__FILE__, __LINE__, msg)
#else
#define error(msg) ((void)0)
#endif
</code>```

Title: Clean debug output function?

Body:
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

__FILE__
__LINE__

but there's a problem in my opinion... When I'm writing a function like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

Body:
Wrapping error() in a macro is indeed the right way to go - I'd write it like so:

#ifdef DEBUG
static void error(const char *file, long line, const char *msg)
{
  fprintf(stderr, "Error (%s:%ld): %s\n", file, line, msg);
}
#define error(msg) (error)(__FILE__, __LINE__, msg)
#else
#define error(msg) ((void)0)
#endif

ContentLicense: CC BY-SA 2.5


问:
Cant append  inside  tag
i want to append this new element

```<code><a data-toggle="tab"> <span class = "hyperspan"> </span> </a>
</code>```

but,  does not appear on the console after the append. it makes me not able to select element through button, must click text (element ).

Try Fill in the input form and submit in My JSFiddle and click the second button.

Button will not work if  is text not clicked.

Code Snippet Demonstration:

$('.submitButton').click(function () {
  var add = '
' +
      '
' +
        '
' +
          '

' +
          '
' +
            '
' +
              '
' +
                '
' +
                '
' +
              '
' +

              '' +

            '
' +
          '
' +
        '
' +
      '
' +
    '
';

    if( document.getElementById("addNew").value === '' ){
            alert("WRITE SOMETHING");
        } else {
          $('.nav').append(add)
      var inputan = document.getElementById("addNew").value;
            $('li:last').find('a').text(inputan);
            document.getElementById("newFoldr").value = "";
            }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._sideFolder {
  background-color: transparent;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active,
li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

<input type="text" id="addNew" placeholder="Write something">
<input type="button" class="submitButton" id="submitButton" value="Create" style="width:142px;margin-left: 5px;">

            Main Folder

            Second Folder

```

答:
You can use html()instead of text() if you want span as below.

```<code>$('li:last').find('a').html(inputan+'<span class="hyperspan"></span>');
</code>```

Title: Cant append <span> inside <a> tag

Body:
i want to append this new element

but,  does not appear on the console after the append. it makes me not able to select element through button, must click text (element ).

Try Fill in the input form and submit in My JSFiddle and click the second button.

Button will not work if  is text not clicked.

Code Snippet Demonstration:

$('.submitButton').click(function () {
  var add = '
' +
      '
' +
        '
' +
          '

' +
          '
' +
            '
' +
              '
' +
                '
' +
                '
' +
              '
' +

              '' +

            '
' +
          '
' +
        '
' +
      '
' +
    '
';

    if( document.getElementById("addNew").value === '' ){
            alert("WRITE SOMETHING");
        } else {
          $('.nav').append(add)
      var inputan = document.getElementById("addNew").value;
            $('li:last').find('a').text(inputan);
            document.getElementById("newFoldr").value = "";
            }
});

._sideFolder {
  background-color: transparent;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active,
li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

<input type="text" id="addNew" placeholder="Write something">
<input type="button" class="submitButton" id="submitButton" value="Create" style="width:142px;margin-left: 5px;">

            Main Folder

            Second Folder

Body:
You can use html()instead of text() if you want span as below.

$('li:last').find('a').html(inputan+'<span class="hyperspan"></span>');


问:
Create multiple select box with output in string format
I'm trying to set up a multiple select box on my project that would provide output into one of my string fields in sql table. So far from what I've figured <% f.select %> with multiple set to true tries to pass an array instead of string, and that doesn't work for my project (in past this was a text field, but now it's required to only allow a selection of preset values to be put in it, and it's on live project, so no drastic changes). I found that doing something like this

```<code>@keywords = params['keywords']['keywords'].join(', ')
</code>```

would solve my problem, but I'm not sure how to implement it in my controller.

Code fragment I currently have for select in views is:

```<code><%= f.select :keywords, ['kw1', 'kw2', 'kw3', 'kw4', 'kw5'], {}, { :multiple => true, :size => 10, :class => 'form-control' } %>
</code>```

code segment from controller for creating new article currently is pretty basic:

```<code>@article = Article.new
</code>```

"keywords" is a string field in article table.

EDIT: Here is whole controller:

```<code>class ArticlesController < ApplicationController
  PRIORITY_COUNTRIES = %w[RU BR IN CN ZA]
  http_basic_authenticate_with name: "***", password: "***", except: [:index, :show]

  def index
    if params[:search] == nil
      @articles = Article.filter(params.slice(:category, :country, :src_url, :date, :lang, :keywords, :title, :rel)).where(is_active: true).order('id DESC').paginate(:page => params[:page])
    else
      @articles = Article.search(params[:search], :without => {:is_active => false}, :page => params[:page], :per_page => 9, :order => :id)
    end

    @countries = ISO3166::Country.countries.sort_by do |country|
      priority_index = PRIORITY_COUNTRIES.index(country.alpha2)
      priority_index.present? ? priority_index.to_s : country.name
    end
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.update(:is_active => false)

    redirect_to articles_path
  end

  def undelete
    @articles = Article.where(is_active: false).paginate(:per_page => 15, :page => params[:page])
  end

  def undestroy
    @article = Article.find(params[:id])
    @article.update(:is_active => true)

    redirect_to undelete_articles_path
  end

  private
    def article_params
      params.require(:article).permit(:title, :date, :src_url, :country, :author, :category, :keywords, :keywords2, :text, :lang, :rel)
    end
end
</code>```

And model:

```<code>class Article < ApplicationRecord
  before_validation do |article|
    article.keywords.reject!(&:blank?) if article.keywords
  end

  self.per_page = 9
  include Filterable
  validates :country, presence: true, length: { minimum: 2 }
  validates :category, presence: true
  validates :src_url, presence: true

  validates :keywords2, presence: true
  validates :text, presence: true, length: { minimum: 5 }
  validates :date, presence: true

  scope :country, -> (country) { where country: country }
  scope :category, -> (category) { where category: category }
  scope :src_url, -> (src_url) { where('src_url like ?', "%#{src_url}%")}
  scope :date, -> (date) { where date: date }
  scope :keywords, -> (keywords) { where('keywords like ?', "%#{keywords}%")}
  scope :title, -> (title) { where('title LIKE ?', "%#{title}%")}
  scope :rel, -> (rel) { where rel: rel }
end
</code>```

答:
You're on the right track, joining the keywords. You may have better luck dealing with the string requirement at the model layer, however.

With the requirement of the column needing a string, but the form and controller passing an array, you may consider doing the following:

```<code>class Article < ApplicationRecord
  ...
  def keywords=(value)
    return super value.join(", ") if value.is_a?(Array)

    super
  end
end
</code>```

This will override the keywords setter in your model, passing a joined string in the case an array is passed.

Body:
I'm trying to set up a multiple select box on my project that would provide output into one of my string fields in sql table. So far from what I've figured <% f.select %> with multiple set to true tries to pass an array instead of string, and that doesn't work for my project (in past this was a text field, but now it's required to only allow a selection of preset values to be put in it, and it's on live project, so no drastic changes). I found that doing something like this

@keywords = params['keywords']['keywords'].join(', ')

would solve my problem, but I'm not sure how to implement it in my controller.

Code fragment I currently have for select in views is:

<%= f.select :keywords, ['kw1', 'kw2', 'kw3', 'kw4', 'kw5'], {}, { :multiple => true, :size => 10, :class => 'form-control' } %>

code segment from controller for creating new article currently is pretty basic:

@article = Article.new

"keywords" is a string field in article table.

EDIT: Here is whole controller:

class ArticlesController < ApplicationController
  PRIORITY_COUNTRIES = %w[RU BR IN CN ZA]
  http_basic_authenticate_with name: "***", password: "***", except: [:index, :show]

  def index
    if params[:search] == nil
      @articles = Article.filter(params.slice(:category, :country, :src_url, :date, :lang, :keywords, :title, :rel)).where(is_active: true).order('id DESC').paginate(:page => params[:page])
    else
      @articles = Article.search(params[:search], :without => {:is_active => false}, :page => params[:page], :per_page => 9, :order => :id)
    end

    @countries = ISO3166::Country.countries.sort_by do |country|
      priority_index = PRIORITY_COUNTRIES.index(country.alpha2)
      priority_index.present? ? priority_index.to_s : country.name
    end
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.update(:is_active => false)

    redirect_to articles_path
  end

  def undelete
    @articles = Article.where(is_active: false).paginate(:per_page => 15, :page => params[:page])
  end

  def undestroy
    @article = Article.find(params[:id])
    @article.update(:is_active => true)

    redirect_to undelete_articles_path
  end

  private
    def article_params
      params.require(:article).permit(:title, :date, :src_url, :country, :author, :category, :keywords, :keywords2, :text, :lang, :rel)
    end
end

And model:

class Article < ApplicationRecord
  before_validation do |article|
    article.keywords.reject!(&:blank?) if article.keywords
  end

  self.per_page = 9
  include Filterable
  validates :country, presence: true, length: { minimum: 2 }
  validates :category, presence: true
  validates :src_url, presence: true

  validates :keywords2, presence: true
  validates :text, presence: true, length: { minimum: 5 }
  validates :date, presence: true

  scope :country, -> (country) { where country: country }
  scope :category, -> (category) { where category: category }
  scope :src_url, -> (src_url) { where('src_url like ?', "%#{src_url}%")}
  scope :date, -> (date) { where date: date }
  scope :keywords, -> (keywords) { where('keywords like ?', "%#{keywords}%")}
  scope :title, -> (title) { where('title LIKE ?', "%#{title}%")}
  scope :rel, -> (rel) { where rel: rel }
end

Body:
You're on the right track, joining the keywords. You may have better luck dealing with the string requirement at the model layer, however.

With the requirement of the column needing a string, but the form and controller passing an array, you may consider doing the following:

class Article < ApplicationRecord
  ...
  def keywords=(value)
    return super value.join(", ") if value.is_a?(Array)

    super
  end
end

This will override the keywords setter in your model, passing a joined string in the case an array is passed.


问:
MarkLogic unfiltered diacritic search is not working as expected
I am using ML 8.

unfiltered cts:search is not working as expected for diacritic cts:query.

Find the below example.

I have inserted the below xml in ML DB with uri /diacritic/a.xml

```<code><root>
    <name>öily</name>
</root>
</code>```

cts:search query which I am running.

```<code>cts:search(
    doc('/diacritic/a.xml'),
    cts:element-value-query(xs:QName('name'), 'oily', ('diacritic-sensitive')),
    'unfiltered'
)
</code>```

Above cts:query is returning me the above doc but it should not return as diacritic-sensitive option is present.

For filtered search it is working fine.

Note: fast diacritic sensitive searches is set to true

Please help.

答:
Collations are irrelevant for search (except for range queries).

The issue here is how indexing works. The keys do not know that they are diacritic-insensitive keys, they only know what the characters in the key are. To compute the diacritic-insensitive key for a word, we remove diacritics and form a key from what is left. To compute the diacritic-sensitive key for a word, we don't remove the diacritics and form a key from the word with them intact.

In this case diacritic-insensitive-key(oily) = diacritic-sensitive-ke(oily) = diacritic-insensitive-key(öily) != diacritic-sensitive-key(öily).

So the index can't resolve the difference here. A diacritic-sensitive search for öily would not match oily in the index, but the reverse is not true.

To get an accurate result here, you'll need to filter.

Addendum: why don't we include the diacritic-sensitivity into the key? Because that would drastically increase the size of the index (x2 for diacritics, x2 more for case).

Body:
I am using ML 8.

unfiltered cts:search is not working as expected for diacritic cts:query.

Find the below example.

I have inserted the below xml in ML DB with uri /diacritic/a.xml

<root>
    <name>öily</name>
</root>

cts:search query which I am running.

cts:search(
    doc('/diacritic/a.xml'),
    cts:element-value-query(xs:QName('name'), 'oily', ('diacritic-sensitive')),
    'unfiltered'
)

Above cts:query is returning me the above doc but it should not return as diacritic-sensitive option is present.

For filtered search it is working fine.

Note: fast diacritic sensitive searches is set to true

Please help.


问:
Awk - Call for a second associated value from file1 after finding a match in file2
I have a code to read gene names from file1 and find them in file2, then I put them together into a table, my problem is that I need to add another column with the associated "start" value from file1 into the table, but couldn't make it. I've tried, but I don't know much about awk in first place, so any help is welcomed.

The idea of final table is:

```<code>File1_gen  File2_gen  Start_from_file1  Value_1_from_file2  Value_2_from_file2
</code>```

File 1:
This file has ~70.000 rows and 4 columns; row number, gene name, gene start and gene end, and I just need gene name and start from this

```<code>        seqnames    start   end
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535
</code>```

File 2:
Then, the second file has ~100.000 rows and 3 columns; gene name, and start and end values, and I need the three of them

```<code>Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313
</code>```

I've already have a pseudocode that do almost all of this

```<code>awk '
FNR == NR {
  # reading file1
    scaf[$2]
    co_id[$3]
next
}
{
  # reading file2
  for (i in scaf) {
    id in co_id
    if ( i == $1 )
    print "[1] "  i "\t" "[2] " $1 "\t" "[3] " id "\t" "[4] " $4 "\t" "[5] "$5
    }
       }
 ' Search.txt Genes.txt
</code>```

Resulting something like this:

```<code>[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522    [4] 1    [5] 602
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 8838    [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 8838    [5] 12313
</code>```

As you can see, the [3] column is empty, and I know the 'id in co_id' is wrong, but it was the last attempt I tried.

In other words, how can I call the associated "start" value for each gene in file1 into the new table I've made?

Edit: Changed the sample data for something that should work. And if there is repeated gene names it should show all the combinations.

Body:
I have a code to read gene names from file1 and find them in file2, then I put them together into a table, my problem is that I need to add another column with the associated "start" value from file1 into the table, but couldn't make it. I've tried, but I don't know much about awk in first place, so any help is welcomed.

The idea of final table is:

File1_gen  File2_gen  Start_from_file1  Value_1_from_file2  Value_2_from_file2

File 1:
This file has ~70.000 rows and 4 columns; row number, gene name, gene start and gene end, and I just need gene name and start from this

        seqnames    start   end
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535

File 2:
Then, the second file has ~100.000 rows and 3 columns; gene name, and start and end values, and I need the three of them

Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313

I've already have a pseudocode that do almost all of this

awk '
FNR == NR {
  # reading file1
    scaf[$2]
    co_id[$3]
next
}
{
  # reading file2
  for (i in scaf) {
    id in co_id
    if ( i == $1 )
    print "[1] "  i "\t" "[2] " $1 "\t" "[3] " id "\t" "[4] " $4 "\t" "[5] "$5
    }
       }
 ' Search.txt Genes.txt

Resulting something like this:

[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522    [4] 1    [5] 602
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 8838    [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 8838    [5] 12313

As you can see, the [3] column is empty, and I know the 'id in co_id' is wrong, but it was the last attempt I tried.

In other words, how can I call the associated "start" value for each gene in file1 into the new table I've made?

Edit: Changed the sample data for something that should work. And if there is repeated gene names it should show all the combinations.

Body:
since your data is already sorted in the keys, you can use join for joining and awk for formatting.  Using the data by @markp (since yours don't have any common keys)

$ join -12 -21 -o1.2,2.1,1.3,2.2,2.3 file1 file2                |
  awk -v OFS="\t" '{for(i=1;i<=NF;i++)
                      printf "[%d] %s", i,$i (i==NF?ORS:OFS)}'  |
  column -ts$'\t'

[1] Gen_3989161.1  [2] Gen_3989161.1  [3] 696  [4] 1696  [5] 2720
[1] Gen_3989469.1  [2] Gen_3989469.1  [3] 693  [4] 1693  [5] 2733
[1] Gen_3989837.1  [2] Gen_3989837.1  [3] 462  [4] 1462  [5] 2515
[1] Gen_3990203.1  [2] Gen_3990203.1  [3] 27   [4] 127   [5] 2112
[1] Gen_3990467.1  [2] Gen_3990467.1  [3] 476  [4] 1476  [5] 2481
[1] Gen_3991323.1  [2] Gen_3991323.1  [3] 134  [4] 1134  [5] 2152
[1] Gen_3991401.1  [2] Gen_3991401.1  [3] 597  [4] 1597  [5] 2681
[1] Gen_3991403.1  [2] Gen_3991403.1  [3] 175  [4] 1175  [5] 2217
[1] Gen_3991951.1  [2] Gen_3991951.1  [3] 897  [4] 1897  [5] 2907

the final pipe to column is for pretty printing.  Obviously the repeat of the key twice doesn't make any sense, since they have to be equal for each row.


问:
Need a Javascript regex expression to match a language param in URL
I'm not familiar with regex and I haven't found any proper solution for my case.
My website utilizes such URLs:

```<code>(http(s)://www.)website.com/en/someURL
(http(s)://www.)website.com/anotherURL
(http(s)://www.)website.com/de/anotherURL
</code>```

If website.com/someURL, website.com/ or website.com is accessed the default language will be loaded.

I need a regex which will allow only these certain language codes, case sensitivity is not important:

```<code>(http(s)://www.)website.com/en
(http(s)://www.)website.com/en/
(http(s)://www.)website.com/
(http(s)://www.)website.com
(http(s)://www.)website.com/de
(http(s)://www.)website.com/de/
</code>```

答:
you only have to limit the number of letters to two and with that you get the language \w{2}

```<code>https?\:\/\/www\.website\.com\/((\w{2})\/?$|(\w{2})\/)
</code>```

e.g. https://regex101.com/r/SCbDyY/2

Body:
I'm not familiar with regex and I haven't found any proper solution for my case.
My website utilizes such URLs:

(http(s)://www.)website.com/en/someURL
(http(s)://www.)website.com/anotherURL
(http(s)://www.)website.com/de/anotherURL

If website.com/someURL, website.com/ or website.com is accessed the default language will be loaded.

I need a regex which will allow only these certain language codes, case sensitivity is not important:

(http(s)://www.)website.com/en
(http(s)://www.)website.com/en/
(http(s)://www.)website.com/
(http(s)://www.)website.com
(http(s)://www.)website.com/de
(http(s)://www.)website.com/de/

Body:
you only have to limit the number of letters to two and with that you get the language \w{2}

https?\:\/\/www\.website\.com\/((\w{2})\/?$|(\w{2})\/)

e.g. https://regex101.com/r/SCbDyY/2


问:
Browsersync Proxy Site Inject CSS
I'm having trouble understanding Browsersync serveStatic while pointed to a proxy URL. From my reading it seems that I should be able to inject CSS into the proxied website. In practice though I can't seem to get it to work. I have used rewriteRules to replace an existing CSS file on the proxy URL with my local CSS but I can't seem to just inject pure CSS if it's not replacing a file. To specify, my CSS is simply not being loaded. If I look at the network traffic, I don't see my stylesheet being loaded. Am I misunderstanding serveStatic or is my configuration incorrect? Below is a simplified extract from my Gulp file.

For reference I'm using Browsersync V2.8.3.

```<code>gulp.task('build-css', () => {
    return gulp.src('src/scss/**/*.scss')
        .pipe(gulpif(arg.sourcemap, sourcemaps.init()))
        .pipe(sassLint())
        .pipe(concat('styles.scss'))
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError())
        .pipe(sass())
        .pipe(autoprefixer('last 10 versions'))
        .pipe(cssnano())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('web/css'))
        .pipe(browserSync.stream({ match: '**/*.css' }));
});

gulp.task('serve', () => {
    browserSync.init({
        proxy: 'www.sampleurl.com',
        serveStatic: ['web/css'],
        reloadDelay: 50,
        reloadDebounce: 250
    });
    gulp.watch('src/scss/**/*.scss', ['build-css']);
});
</code>```

答:
For some reason I completely missed the Browsersync recipes section. There I found my solution. There I found a specific recipe titled Proxy example + injecting custom css file. Essentially it looks like there is no way to just include a list of files and just pop them in on page load. Instead, it's required to use snippetOptions and match something like head tag. Then you can simply append a link tag to the matched head content. The code below is copied from the recipe.</p>

```<code>var browserSync = require('browser-sync').create();

browserSync.init({
    proxy: "example.com",
    serveStatic: ["app/static"],
    files: "app/static/_custom.css",
    snippetOptions: {
        rule: {
            match: /<\/head>/i,
            fn: function (snippet, match) {
                return '<link rel="stylesheet" type="text/css" href="/_custom.css"/>' + snippet + match;
            }
        }
    }
});
</code>```

Title: Browsersync Proxy Site Inject CSS

Body:
I'm having trouble understanding Browsersync serveStatic while pointed to a proxy URL. From my reading it seems that I should be able to inject CSS into the proxied website. In practice though I can't seem to get it to work. I have used rewriteRules to replace an existing CSS file on the proxy URL with my local CSS but I can't seem to just inject pure CSS if it's not replacing a file. To specify, my CSS is simply not being loaded. If I look at the network traffic, I don't see my stylesheet being loaded. Am I misunderstanding serveStatic or is my configuration incorrect? Below is a simplified extract from my Gulp file.

For reference I'm using Browsersync V2.8.3.

gulp.task('build-css', () => {
    return gulp.src('src/scss/**/*.scss')
        .pipe(gulpif(arg.sourcemap, sourcemaps.init()))
        .pipe(sassLint())
        .pipe(concat('styles.scss'))
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError())
        .pipe(sass())
        .pipe(autoprefixer('last 10 versions'))
        .pipe(cssnano())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('web/css'))
        .pipe(browserSync.stream({ match: '**/*.css' }));
});

gulp.task('serve', () => {
    browserSync.init({
        proxy: 'www.sampleurl.com',
        serveStatic: ['web/css'],
        reloadDelay: 50,
        reloadDebounce: 250
    });
    gulp.watch('src/scss/**/*.scss', ['build-css']);
});

Body:
For some reason I completely missed the Browsersync recipes section. There I found my solution. There I found a specific recipe titled Proxy example + injecting custom css file. Essentially it looks like there is no way to just include a list of files and just pop them in on page load. Instead, it's required to use snippetOptions and match something like head tag. Then you can simply append a link tag to the matched head content. The code below is copied from the recipe.

var browserSync = require('browser-sync').create();

browserSync.init({
    proxy: "example.com",
    serveStatic: ["app/static"],
    files: "app/static/_custom.css",
    snippetOptions: {
        rule: {
            match: /<\/head>/i,
            fn: function (snippet, match) {
                return '<link rel="stylesheet" type="text/css" href="/_custom.css"/>' + snippet + match;
            }
        }
    }
});


问:
Laravel: How to update packages in storage/framework
I have removed a package with composer remove and it's now removed from composer.json and composer.lock files and also removed from vendor directory. But I noticed that it's still listed in these two files: storage/framework/packages.php and storage/framework/services.php. How can I update/rebuild these files?

Also, when I run php artisan in the root of my project, I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
    Class 'Morilog\Jalali\JalaliServiceProvider' not found

I searched in all the files of the project and found JalaliServiceProvider still listed only in the two above-mentioned files.

答:
Delete these two files:

bootstrap/cache/packages.php

bootstrap/cache/services.php


问:
How to get random value of attribute of Enum on each iteration?
I have created such Enum object:

```<code>class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])
</code>```

and i want to get really random value each time, but it does not work:

```<code>>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
</code>```

I have also tried use lambda, but it's looks not so good, although it works:

```<code>Gender.RANDOM()
</code>```

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

```<code>def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...
</code>```

答:
I tried a way with metaclasses. And it works!

```<code>import random
import enum
class RANDOM_ATTR(enum.EnumMeta):
    @property
    def RANDOM(self):
        return random.choice([Gender.MALE, Gender.FEMALE])

class Gender(enum.Enum,metaclass=RANDOM_ATTR): #this syntax works for python3 only
    FEMALE = 'female'
    MALE = 'male'

print(Gender.RANDOM)   #prints male or female randomly
</code>```

Here by making RANDOM_ATTR the metaclass of Gender, Gender is like an object of class RANDOM_ATTR, so Gender has the property RANDOM.

However,the below code you described in your question doesn't work the way you expect.

```<code>def full_name(gender=Gender.RANDOM):
    ...
</code>```

The RANDOM property will be called only once. To know why, please read this answer. Default arguments are like attributes to function, which will be initialised only once.

For that i would suggest you do something like this:

```<code>def full_name(gender=None):
    gender = gender or Gender.RANDOM
    ...
</code>```

Body:
I have created such Enum object:

class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])

and i want to get really random value each time, but it does not work:

>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>

I have also tried use lambda, but it's looks not so good, although it works:

Gender.RANDOM()

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...

Body:
I tried a way with metaclasses. And it works!

import random
import enum
class RANDOM_ATTR(enum.EnumMeta):
    @property
    def RANDOM(self):
        return random.choice([Gender.MALE, Gender.FEMALE])

class Gender(enum.Enum,metaclass=RANDOM_ATTR): #this syntax works for python3 only
    FEMALE = 'female'
    MALE = 'male'

print(Gender.RANDOM)   #prints male or female randomly

Here by making RANDOM_ATTR the metaclass of Gender, Gender is like an object of class RANDOM_ATTR, so Gender has the property RANDOM.

However,the below code you described in your question doesn't work the way you expect.

def full_name(gender=Gender.RANDOM):
    ...

The RANDOM property will be called only once. To know why, please read this answer. Default arguments are like attributes to function, which will be initialised only once.

For that i would suggest you do something like this:

def full_name(gender=None):
    gender = gender or Gender.RANDOM
    ...


问:
How to show an elements value in a vue modal?
I have several elements that are displayed as
 elements in a loop. For each element I want behavior such that when the element is clicked a modal box opens up. Inside the modal box I want contents that are specific to the element that was clicked.

The data below shows all the elements:

```<code>              {value: 10, name: "foo"},
              {value: 12, name: "bar"},
              {value: 14, name: "foobar"},
              {value: 22, name: "test"},
              {value: 1, name: "testtooo"},
              {value: 8, name: "something"}
</code>```

When I click on an element, I want to see the value property for it inside the modal box.

I've created a fiddle for this: https://jsfiddle.net/hvb9hvog/14/

Question

I've gotten the modal working, however, how can I show each elements value property inside the modal?

答:
Add "req" property to data

```<code>data() {
  return {
     ...
     req: {},
     ...
  }
}
</code>```

set click event:

```<code><a href="#" @click="showModal = true;req = request">{{request.name}}</a>
</code>```

add body slot

```<code> ...
 <h3 slot="header">custom header</h3>
 <div slot="body">
   {{req.value}}
 </div>
 ...
</code>```

https://jsfiddle.net/w4e6hr86/

Body:
I have several elements that are displayed as
 elements in a loop. For each element I want behavior such that when the element is clicked a modal box opens up. Inside the modal box I want contents that are specific to the element that was clicked.

The data below shows all the elements:

              {value: 10, name: "foo"},
              {value: 12, name: "bar"},
              {value: 14, name: "foobar"},
              {value: 22, name: "test"},
              {value: 1, name: "testtooo"},
              {value: 8, name: "something"}

When I click on an element, I want to see the value property for it inside the modal box.

I've created a fiddle for this: https://jsfiddle.net/hvb9hvog/14/

Question

I've gotten the modal working, however, how can I show each elements value property inside the modal?

Body:
Add "req" property to data

data() {
  return {
     ...
     req: {},
     ...
  }
}

set click event:

<a href="#" @click="showModal = true;req = request">{{request.name}}</a>

add body slot

 ...
 <h3 slot="header">custom header</h3>
 <div slot="body">
   {{req.value}}
 </div>
 ...

https://jsfiddle.net/w4e6hr86/


问:
Extend IsAjaxRequest() to include fetch api requests
I am currently building a site using MVC5 and I need to serve different content when an ajax request is made.

Usually we use jQuery and make an ajax request using $.ajax, but recently we have moved towards using the fetch api.  However, requests using the fetch api aren't registering with MVC as ajax requests so the wrong template is being used.

I have thought about making my own is ajax request extension but not sure what header to check for:

```<code>    public static bool IsAjaxOrFetchRequest(this HttpRequestBase request)
    {
        if (request != null && request.Headers != null)
        {
            if (request.Headers["Custom-Fetch-Header"] != null)
            {
                return true;
            }
        }

        return request.IsAjaxRequest();
    }
</code>```

Is there a header that fetch sends with all requests like Request.Headers["X-Requested-With"] == "XMLHttpRequest" ajax sends?

Stepping through the code, I couldn't see anything that stood out

答:
Ok looking into this further, I cannot seem to find any standard header being sent with the  request so I have created my own header:

```<code>const request = new Request(url, {
  headers: new Headers({
    'X-Is-Ajax-Request': 'True'
  })
});

return fetch(request)
  .then(html => {
    const $result = $(html);
    const $content = $result.filter('.js-sidebar-panel-content');
    return $content.length ? $content : $result;
  });
</code>```

Then I was able to update my extension with:

```<code>public static bool IsAjaxOrFetchRequest(this HttpRequestBase request)
{
    if (request != null && request.Headers != null)
    {
        if (request.Headers["X-Is-Ajax-Request"] != null)
        {
            return bool.Parse(request.Headers["X-Is-Ajax-Request"]);
        }
    }

    return request.IsAjaxRequest();
}
</code>```

Body:
I am currently building a site using MVC5 and I need to serve different content when an ajax request is made.

Usually we use jQuery and make an ajax request using $.ajax, but recently we have moved towards using the fetch api.  However, requests using the fetch api aren't registering with MVC as ajax requests so the wrong template is being used.

I have thought about making my own is ajax request extension but not sure what header to check for:

    public static bool IsAjaxOrFetchRequest(this HttpRequestBase request)
    {
        if (request != null && request.Headers != null)
        {
            if (request.Headers["Custom-Fetch-Header"] != null)
            {
                return true;
            }
        }

        return request.IsAjaxRequest();
    }

Is there a header that fetch sends with all requests like Request.Headers["X-Requested-With"] == "XMLHttpRequest" ajax sends?

Stepping through the code, I couldn't see anything that stood out

Body:
Ok looking into this further, I cannot seem to find any standard header being sent with the  request so I have created my own header:

const request = new Request(url, {
  headers: new Headers({
    'X-Is-Ajax-Request': 'True'
  })
});

return fetch(request)
  .then(html => {
    const $result = $(html);
    const $content = $result.filter('.js-sidebar-panel-content');
    return $content.length ? $content : $result;
  });

Then I was able to update my extension with:

public static bool IsAjaxOrFetchRequest(this HttpRequestBase request)
{
    if (request != null && request.Headers != null)
    {
        if (request.Headers["X-Is-Ajax-Request"] != null)
        {
            return bool.Parse(request.Headers["X-Is-Ajax-Request"]);
        }
    }

    return request.IsAjaxRequest();
}


问:
C++ dynamic array
I would like to make a dynamic array of a class with a constructor that has paramaters.

Where does the constructor's size parameter go?

ex. twoDArrayInDisguise = new dynamicArray(size)*[size];

Does not work

答:
You cannot do this directly (when using new[], the default constructor is used).

Instead, use a std::vector.  You can initialise each element in terms of a reference object, e.g.:

```<code>std::vector<T> vec(size, T(/* args */));
</code>```

Title: C++ dynamic array

Body:
You cannot do this directly (when using new[], the default constructor is used).

Instead, use a std::vector.  You can initialise each element in terms of a reference object, e.g.:

std::vector<T> vec(size, T(/* args */));


问:
Correct pattern for async dispatch
Please help me, is it correct pattern  for async dispatch with redux thunk?

```<code>//actions types
const ADD_ARTIST = 'ADD_ARTIST'

// action
function AddArtist(val){
  return {
    type: ADD_ARTIST,
    payload:val
  }
}

//some async events
function async1(id){
  return fetch(.....)
}

function async2(id){
  return fetch(.....)
}

function async3(id){
  return fetch(.....)
}

function auth(id) {
  return function (dispatch) {
    async1(10).then( (v) =>  dispatch(AddArtist(v)) );
    Promise.all([
      async2(26),
      async3(51),
    ]).then(
          (v) => dispatch(AddArtist(v[0] + v[1] )
      ));
  }
}

var ViewWrapper = connect(
  state => ({
    playlist: state.playlist,
    artist: state.artist,
  }),
  dispatch => (
    {
      dispatch,
      auth: bindActionCreators(auth, dispatch)
  })

)(View);
</code>```

and button :

```<code>  <input type='button' onClick={() =>
this.props.dispatch( this.props.auth() ) }   value='dispatch mapDispatch>>>>>>>' />
</code>```

答:
according to redux documentation, this looks fine but you also apply some code to error handling.

here you can write the better way

```<code>function auth(id) {
     return ((dispatch) => async1(10)
               ).then( (v) => dispatch(AddArtist(v))
               ).then( () =>
                 Promise.all([
                    async2(26),
                    async3(51),
               ])
              ).then( (v) => dispatch(AddArtist(v[0] + v[1]))
             )
      )
}
</code>```

Title: Correct pattern for async dispatch

Body:
Please help me, is it correct pattern  for async dispatch with redux thunk?

//actions types
const ADD_ARTIST = 'ADD_ARTIST'

// action
function AddArtist(val){
  return {
    type: ADD_ARTIST,
    payload:val
  }
}

//some async events
function async1(id){
  return fetch(.....)
}

function async2(id){
  return fetch(.....)
}

function async3(id){
  return fetch(.....)
}

function auth(id) {
  return function (dispatch) {
    async1(10).then( (v) =>  dispatch(AddArtist(v)) );
    Promise.all([
      async2(26),
      async3(51),
    ]).then(
          (v) => dispatch(AddArtist(v[0] + v[1] )
      ));
  }
}

var ViewWrapper = connect(
  state => ({
    playlist: state.playlist,
    artist: state.artist,
  }),
  dispatch => (
    {
      dispatch,
      auth: bindActionCreators(auth, dispatch)
  })

)(View);

and button :

  <input type='button' onClick={() =>
this.props.dispatch( this.props.auth() ) }   value='dispatch mapDispatch>>>>>>>' />

Body:
according to redux documentation, this looks fine but you also apply some code to error handling.

here you can write the better way

function auth(id) {
     return ((dispatch) => async1(10)
               ).then( (v) => dispatch(AddArtist(v))
               ).then( () =>
                 Promise.all([
                    async2(26),
                    async3(51),
               ])
              ).then( (v) => dispatch(AddArtist(v[0] + v[1]))
             )
      )
}


问:
JFX: Lock a stage ontop of another stage / detect stage order
Let's say I have three Java FX stages: A, B and C. Each with their own open window and am aiming for the following behavior:

If A takes focus, B should appear ontop and C ontop of B -> A-B-C

If B is taking focus, Be should appear in front of C and A in the back -> A-C-B

If C is taking focus, naturally -> A-B-C

Am aware of the toFront() function and have tried to manually enforce the order correspondingly by simply calling toFront() to every stage in the right order whenever one of the stages regains focus, however that results in undesired flickering because there is apparently no way to determine which windows are already in the right place.

Unfortunately I cannot use the modal-window system because all windows need to remain operational in parallel.

Is there any way to achieve this?

Huge thanks in advance!

答:
Just had the same problem.
The only "hack" i could find is to store the order in which the stages got focus and then travel in reverse order through all stages and call .toFront().

Whenever a stage gets the Focus i put in on Top of the List of open stages.
I then block the EventHandler globaly because every time a stage receives the .toFont() call it also gets the Focus.

Works well on Mac.
Does not work and shows a strange behavior under Windows

```<code>this.model.stage.focusedProperty().addListener((ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) -> {
        if (!mainModel.blockFocusRequest){
        if (t1){
            try{
                mainModel.openWindows.remove(this.model.stage);
                mainModel.openWindows.add(0,this.model.stage);
            mainModel.blockFocusRequest = true;
            for (int i=mainModel.openWindows.size()-1;i>=0;i--){
                mainModel.openWindows.get(i).toFront();
            }
            } finally{
                mainModel.blockFocusRequest = false;
            }
        }
        }
    });
</code>```

Body:
Just had the same problem.
The only "hack" i could find is to store the order in which the stages got focus and then travel in reverse order through all stages and call .toFront().

Whenever a stage gets the Focus i put in on Top of the List of open stages.
I then block the EventHandler globaly because every time a stage receives the .toFont() call it also gets the Focus.

Works well on Mac.
Does not work and shows a strange behavior under Windows

this.model.stage.focusedProperty().addListener((ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) -> {
        if (!mainModel.blockFocusRequest){
        if (t1){
            try{
                mainModel.openWindows.remove(this.model.stage);
                mainModel.openWindows.add(0,this.model.stage);
            mainModel.blockFocusRequest = true;
            for (int i=mainModel.openWindows.size()-1;i>=0;i--){
                mainModel.openWindows.get(i).toFront();
            }
            } finally{
                mainModel.blockFocusRequest = false;
            }
        }
        }
    });


问:
i got an error in php xpath scraping Trying to get property of non-object
i am trying to make a simple scrape code for my site but i get and error when i run it

i got this error code

Notice: Trying to get property of non-object

this is my code

```<code>function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;
}

libxml_use_internal_errors(true);
$url = 'https://www.mourjan.com/ae/abu-dhabi/lands';
$amer=get_web_page($url);
$html= $amer['content'];
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$dom = new DOMDocument;
$dom->loadHTML($html);

foreach ($dom->getElementsByTagName('p') as $td) {
    if ($td->hasAttribute('onclick')) {
        $links= $td->getAttribute('onclick');
        $links = str_replace("wo('/","",$links);
        $links = str_replace("/')","",$links);

        $url = 'https://www.mourjan.com/ae/abu-dhabi/lands/'.$links.'';
        $amer=get_web_page($url);
        $html= $amer['content'];
        $dom = new DOMDocument();
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
        $name = $xpath->query('*[@id="results"]/div[2]/div[2]/p');
        $phone= $xpath->query('*[@id="results"]/div[2]/div[2]/p/span');
        echo $name->item(0)->nodeValue;
        echo '<br />';
        echo str_replace(' ','',$phone->item(0)->nodeValue);
    }
}
</code>```

i hope that can someone help me in fixing this issue, i used this xpath because it is helpful better than the other

regards
Amer

答:
If the Xpath expression returns an empty node list then access ->item(0) will return NULL - hence the error message.

You could use ->length > 0 to validate that here is a node in the list before accessing the item.

Another possibility is using DOMXpath::evaluate() and casting the node list into a string in the Xpath expression. An empty list will result in an empty string:

```<code>$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$name = $xpath->evaluate('string(*[@id="results"]/div[2]/div[2]/p)');
$phone = $xpath->evaluate('string(*[@id="results"]/div[2]/div[2]/p/span)');
echo $name;
echo '<br />';
echo str_replace(' ','',$phone);
</code>```

Body:
i am trying to make a simple scrape code for my site but i get and error when i run it

i got this error code

Notice: Trying to get property of non-object

this is my code

function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;
}

libxml_use_internal_errors(true);
$url = 'https://www.mourjan.com/ae/abu-dhabi/lands';
$amer=get_web_page($url);
$html= $amer['content'];
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$dom = new DOMDocument;
$dom->loadHTML($html);

foreach ($dom->getElementsByTagName('p') as $td) {
    if ($td->hasAttribute('onclick')) {
        $links= $td->getAttribute('onclick');
        $links = str_replace("wo('/","",$links);
        $links = str_replace("/')","",$links);

        $url = 'https://www.mourjan.com/ae/abu-dhabi/lands/'.$links.'';
        $amer=get_web_page($url);
        $html= $amer['content'];
        $dom = new DOMDocument();
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
        $name = $xpath->query('*[@id="results"]/div[2]/div[2]/p');
        $phone= $xpath->query('*[@id="results"]/div[2]/div[2]/p/span');
        echo $name->item(0)->nodeValue;
        echo '
';
        echo str_replace(' ','',$phone->item(0)->nodeValue);
    }
}

i hope that can someone help me in fixing this issue, i used this xpath because it is helpful better than the other

regards
Amer

Body:
If the Xpath expression returns an empty node list then access ->item(0) will return NULL - hence the error message.

You could use ->length > 0 to validate that here is a node in the list before accessing the item.

Another possibility is using DOMXpath::evaluate() and casting the node list into a string in the Xpath expression. An empty list will result in an empty string:

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$name = $xpath->evaluate('string(*[@id="results"]/div[2]/div[2]/p)');
$phone = $xpath->evaluate('string(*[@id="results"]/div[2]/div[2]/p/span)');
echo $name;
echo '<br />';
echo str_replace(' ','',$phone);


问:
How to sort datatables with date in descending order
I wish to show the records using datatables with default ordering based on one of my rows with date & time in descending order. Please help me in editing the jquery structure for that

答:
I had same problem. I used date-eu sorting plugin to sort dates in the format DD/MM/YY and I included the following JS file :

```<code><script src="//cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js" type="text/javascript"></script>
</code>```

This worked for me.

```<code>$('#exemple').DataTable({
    "order": [[ 3, "desc" ]], //or asc
    "columnDefs" : [{"targets":3, "type":"date-eu"}],
});
</code>```

Read also this post on stackoverflow: Sorting date in datatable

Body:
I had same problem. I used date-eu sorting plugin to sort dates in the format DD/MM/YY and I included the following JS file :

<script src="//cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js" type="text/javascript"></script>

This worked for me.

$('#exemple').DataTable({
    "order": [[ 3, "desc" ]], //or asc
    "columnDefs" : [{"targets":3, "type":"date-eu"}],
});

Read also this post on stackoverflow: Sorting date in datatable


答:
Although modifying the class may be clearer and DRY-er in many cases, if you're only doing this once or don't want to modify the enum you could do:

random.choice([enm.value for enm in Gender])

Title: How to get random value of attribute of Enum on each iteration?


问:
Set value of a field without calling set method - Kotlin
I've been using Kotlin to develop some apps in Android and what i want to do currently is to set a field value inside the defining class without calling the setter method.

Here is the code inside my class:

```<code>var projectList: List<Project>? = null
    set(value) {
        saveProjects(value as ArrayList<Project>)
        field = value
    }

//GO to the database and retrieve list of projects
fun loadProjects(callback: Project.OnProjectsLoadedListener) {
   database.projectDao().getAll().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(

                    { success ->
                        callback.onProjectsLoaded(success)
                    //Here i don't want to save the projects, because i've loaded them from the database
                        this.projectList = success
                    },
                    { error -> GenericErrorHandler.handleError(error,callback.retrieveContext())}

                    )
}
</code>```

Does anybody know a way to do this without calling the set(value) method?

答:
You can only gain access to the field directly from the setter. Inside a setter, the field can be accessed through the invisible field variable.

There are perhaps some other ways around your requirements though. Here are 2 examples. You wouldn't have to follow them exactly, but could instead also combine them to make whatever solution you want.

You could use another shell property to act as the setter for your actual property:

```<code>class Example1 {
  var fieldProperty: Int = 0

  var setterPropertyForField: Int
    get() = fieldProperty
    set(value) {
      fieldProperty = value
    }
}
</code>```

You could use setters as you actually would in Java with a JVM field and a set method. The @JvmField is probably not necessary.

```<code>class Example2 {
  @JvmField var fieldProperty: Int = 0

  fun setField(value: Int) {
    fieldProperty = value
  }
}
</code>```

You could probably access the field and change it through reflection, but I don't recommend that approach. That would likely only lead to problems.

Body:
I've been using Kotlin to develop some apps in Android and what i want to do currently is to set a field value inside the defining class without calling the setter method.

Here is the code inside my class:

var projectList: List<Project>? = null
    set(value) {
        saveProjects(value as ArrayList<Project>)
        field = value
    }

//GO to the database and retrieve list of projects
fun loadProjects(callback: Project.OnProjectsLoadedListener) {
   database.projectDao().getAll().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(

                    { success ->
                        callback.onProjectsLoaded(success)
                    //Here i don't want to save the projects, because i've loaded them from the database
                        this.projectList = success
                    },
                    { error -> GenericErrorHandler.handleError(error,callback.retrieveContext())}

                    )
}

Does anybody know a way to do this without calling the set(value) method?

Body:
You can only gain access to the field directly from the setter. Inside a setter, the field can be accessed through the invisible field variable.

There are perhaps some other ways around your requirements though. Here are 2 examples. You wouldn't have to follow them exactly, but could instead also combine them to make whatever solution you want.

You could use another shell property to act as the setter for your actual property:

class Example1 {
  var fieldProperty: Int = 0

  var setterPropertyForField: Int
    get() = fieldProperty
    set(value) {
      fieldProperty = value
    }
}

You could use setters as you actually would in Java with a JVM field and a set method. The @JvmField is probably not necessary.

class Example2 {
  @JvmField var fieldProperty: Int = 0

  fun setField(value: Int) {
    fieldProperty = value
  }
}

You could probably access the field and change it through reflection, but I don't recommend that approach. That would likely only lead to problems.