问:
HTML dropdown buttom doesn't work -navbar
This is my HTML code. I'm trying to create a navbar but the dropdown buttom doesn't work. Which is the most efficient way to fix it?       </p>

```<code>      <nav class='navbar navbar-inverse navbar-fixed-top'>
          <div class='container'>
            <div class='navbar-header'>
              <button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#navbar' aria-expanded='false' aria-controls='navbar'>
                <span class='sr-only'>Toggle navigation</span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
              </button>
              <a class='navbar-brand' href='#'>Hello</a>
            </div>
            <div id='navbar' class='navbar-collapse collapse'>
              <ul class='nav navbar-nav'>
                <li class='active'><a href='#'>Project</a></li>
              </ul>
                   <ul class="nav navbar-nav navbar-right">
                   <li class="dropdown">

                         <li><a class="dropdown-toggle" data-toggle="dropdown" href="#"><span class="glyphicon glyphicon-user"></span> Sign Up <span class="caret"></span></a></li>
                               <ul class="dropdown-menu">
                                     <li><a href="#">Log off</a></li>
                               </ul>

                    </li>
                    </ul>
             </div>

        </nav>
</code>```

答:
Try the below code:</p>

```<code><ul class="nav navbar-nav navbar-right">
    <div class="dropdown">
        <button class="dropdown-toggle" type="button" data-toggle="dropdown"
            href="#">
            <span class="glyphicon glyphicon-user"></span> Sign Up <span
            class="caret"></span>
        </button>
        <ul class="dropdown-menu">
            <li><a href="#">Log off</a></li>
        </ul>
    </div>
</ul>
</code>```

Body:
This is my HTML code. I'm trying to create a navbar but the dropdown buttom doesn't work. Which is the most efficient way to fix it?

              <button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#navbar' aria-expanded='false' aria-controls='navbar'>
                Toggle navigation

              </button>
              Hello

Project

 Sign Up

Log off

Body:
Try the below code:

<ul class="nav navbar-nav navbar-right">
    <div class="dropdown">
        <button class="dropdown-toggle" type="button" data-toggle="dropdown"
            href="#">
            <span class="glyphicon glyphicon-user"></span> Sign Up <span
            class="caret"></span>
        </button>
        <ul class="dropdown-menu">
            <li><a href="#">Log off</a></li>
        </ul>
    </div>
</ul>


来源: stackexchange

问:
Wpf, How to drag object inside draggable element?
I am developing WPF application. I should implement designer page with draggable objects inside other draggable objects. Look at the picture:

Now my Drag and Drop 1 and 2 working, but when I am trying to drag Inner object 1 and execute Drag and Drop 3 it is not working properly. Instead of drag Inner object 1, I am dragging Master object 1.

My xaml code:

```<code><ItemsControl ItemsSource="{Binding MasterObjects}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Canvas/>
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
    <Style TargetType="ContentPresenter">
        <Setter Property="Canvas.Left" Value="{Binding Path=X}" />
        <Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
        <Setter Property="Width" Value="{Binding Path=Width}" />
        <Setter Property="Height" Value="{Binding Path=Height}" />
    </Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Grid behaviors:DragBehavior.Drag="True">
            <Rectangle Fill="LightGray" Stroke="SlateGray" StrokeThickness="1" />
            <TextBlock Text="{Binding Name}" />
            <ItemsControl ItemsSource="{Binding InnerObjects}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="ContentPresenter">
                        <Setter Property="Canvas.Left" Value="{Binding Path=X}" />
                        <Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
                        <Setter Property="Width" Value="{Binding Path=Width}" />
                        <Setter Property="Height" Value="{Binding Path=Height}" />
                    </Style>
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid behaviors:DragBehavior.Drag="True">
                            <Rectangle Fill="LightGray" Stroke="SlateGray" StrokeThickness="1" />
                            <TextBlock Text="{Binding Name}" />
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Grid>
    </DataTemplate>
</ItemsControl.ItemTemplate>
</code>```

And my DragBehavior class:

```<code>public class DragBehavior
{
    public readonly TranslateTransform Transform = new TranslateTransform();
    private Point _elementStartPosition2;
    private Point _mouseStartPosition2;
    private static DragBehavior _instance = new DragBehavior();
    public static DragBehavior Instance
    {
        get { return _instance; }
        set { _instance = value; }
    }

    public static bool GetDrag(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsDragProperty);
    }

    public static void SetDrag(DependencyObject obj, bool value)
    {
        obj.SetValue(IsDragProperty, value);
    }

    public static readonly DependencyProperty IsDragProperty =
      DependencyProperty.RegisterAttached(
          "Drag",
          typeof(bool),
          typeof(DragBehavior),
          new PropertyMetadata(false, OnDragChanged));

    private static void OnDragChanged(object sender, DependencyPropertyChangedEventArgs e)
    {

        // ignoring error checking
        var element = (UIElement)sender;
        var isDrag = (bool)(e.NewValue);

        Instance = new DragBehavior();
        ((UIElement)sender).RenderTransform = Instance.Transform;

        if (isDrag)
        {
            element.MouseLeftButtonDown += Instance.ElementOnMouseLeftButtonDown;
            element.MouseLeftButtonUp += Instance.ElementOnMouseLeftButtonUp;
            element.MouseMove += Instance.ElementOnMouseMove;
        }
        else
        {
            element.MouseLeftButtonDown -= Instance.ElementOnMouseLeftButtonDown;
            element.MouseLeftButtonUp -= Instance.ElementOnMouseLeftButtonUp;
            element.MouseMove -= Instance.ElementOnMouseMove;
        }
    }

    private void ElementOnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
    {
        var parent = Application.Current.MainWindow;
        _mouseStartPosition2 = mouseButtonEventArgs.GetPosition(parent);
        ((UIElement)sender).CaptureMouse();
    }

    private void ElementOnMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
    {
        ((UIElement)sender).ReleaseMouseCapture();
        _elementStartPosition2.X = Transform.X;
        _elementStartPosition2.Y = Transform.Y;
    }

    private void ElementOnMouseMove(object sender, MouseEventArgs mouseEventArgs)
    {
        var parent = Application.Current.MainWindow;
        var mousePos = mouseEventArgs.GetPosition(parent);
        var diff = (mousePos - _mouseStartPosition2);
        if (!((UIElement)sender).IsMouseCaptured) return;
        Transform.X = _elementStartPosition2.X + diff.X;
        Transform.Y = _elementStartPosition2.Y + diff.Y;
    }
}
</code>```

I guess I should to fix DragBehaviour class, but I don't have any idea how. Now I'm really confused.

答:
The MouseLeftButtonDown event is bubbling from the inner container to the parent one. Try setting the e.Handled property to true in your event handler. In this case, only the handler for the first clicked element will be raised and your code should work properly.

I also suggest that you use an attached behavior instead of a class with several attached properties. You can find it in a free MVVM Framework provided by DevExpress.
As a rule behaviors give you much more freedom in such scenarios.

ContentLicense: CC BY-SA 3.0

Body:
I am developing WPF application. I should implement designer page with draggable objects inside other draggable objects. Look at the picture:

Now my Drag and Drop 1 and 2 working, but when I am trying to drag Inner object 1 and execute Drag and Drop 3 it is not working properly. Instead of drag Inner object 1, I am dragging Master object 1.

My xaml code:

<ItemsControl ItemsSource="{Binding MasterObjects}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Canvas/>
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>

</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Grid behaviors:DragBehavior.Drag="True">
            <Rectangle Fill="LightGray" Stroke="SlateGray" StrokeThickness="1" />
            <TextBlock Text="{Binding Name}" />
            <ItemsControl ItemsSource="{Binding InnerObjects}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>

                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid behaviors:DragBehavior.Drag="True">
                            <Rectangle Fill="LightGray" Stroke="SlateGray" StrokeThickness="1" />
                            <TextBlock Text="{Binding Name}" />
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Grid>
    </DataTemplate>
</ItemsControl.ItemTemplate>

And my DragBehavior class:

public class DragBehavior
{
    public readonly TranslateTransform Transform = new TranslateTransform();
    private Point _elementStartPosition2;
    private Point _mouseStartPosition2;
    private static DragBehavior _instance = new DragBehavior();
    public static DragBehavior Instance
    {
        get { return _instance; }
        set { _instance = value; }
    }

    public static bool GetDrag(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsDragProperty);
    }

    public static void SetDrag(DependencyObject obj, bool value)
    {
        obj.SetValue(IsDragProperty, value);
    }

    public static readonly DependencyProperty IsDragProperty =
      DependencyProperty.RegisterAttached(
          "Drag",
          typeof(bool),
          typeof(DragBehavior),
          new PropertyMetadata(false, OnDragChanged));

    private static void OnDragChanged(object sender, DependencyPropertyChangedEventArgs e)
    {

        // ignoring error checking
        var element = (UIElement)sender;
        var isDrag = (bool)(e.NewValue);

        Instance = new DragBehavior();
        ((UIElement)sender).RenderTransform = Instance.Transform;

        if (isDrag)
        {
            element.MouseLeftButtonDown += Instance.ElementOnMouseLeftButtonDown;
            element.MouseLeftButtonUp += Instance.ElementOnMouseLeftButtonUp;
            element.MouseMove += Instance.ElementOnMouseMove;
        }
        else
        {
            element.MouseLeftButtonDown -= Instance.ElementOnMouseLeftButtonDown;
            element.MouseLeftButtonUp -= Instance.ElementOnMouseLeftButtonUp;
            element.MouseMove -= Instance.ElementOnMouseMove;
        }
    }

    private void ElementOnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
    {
        var parent = Application.Current.MainWindow;
        _mouseStartPosition2 = mouseButtonEventArgs.GetPosition(parent);
        ((UIElement)sender).CaptureMouse();
    }

    private void ElementOnMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
    {
        ((UIElement)sender).ReleaseMouseCapture();
        _elementStartPosition2.X = Transform.X;
        _elementStartPosition2.Y = Transform.Y;
    }

    private void ElementOnMouseMove(object sender, MouseEventArgs mouseEventArgs)
    {
        var parent = Application.Current.MainWindow;
        var mousePos = mouseEventArgs.GetPosition(parent);
        var diff = (mousePos - _mouseStartPosition2);
        if (!((UIElement)sender).IsMouseCaptured) return;
        Transform.X = _elementStartPosition2.X + diff.X;
        Transform.Y = _elementStartPosition2.Y + diff.Y;
    }
}

I guess I should to fix DragBehaviour class, but I don't have any idea how. Now I'm really confused.


问:
Jquery not working to hide and show div until Bootstrap tab clicked
I have 2 different divs that need to appear depending on which tab is active.

If tab "#myTab class overview" is active then the "rental div" should show. If "#myTab class overview" is not active them the "homeo div" should show.

My function does not work on page load, on page load both divs appear. If i click either tab then only does my function work.

Do you know how to get my function to be working on page load.

jQuery(document).ready(function () {
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rental">
DOWNLOAD APPLICATION
</div>

<div id="homeo">
Test
</div>

  <ul class="nav nav-pills">
    <li id="myTab" class="overview active">RENTAL</li>
    <li>HOMEOWNER</li>
  </ul></code>```

答:
.className is native javascript. jQuery objects don't have this property.

You want to use $("#myTab")[0].hasClass('overview')

jQuery hasClass documentation

Body:
I have 2 different divs that need to appear depending on which tab is active.

If tab "#myTab class overview" is active then the "rental div" should show. If "#myTab class overview" is not active them the "homeo div" should show.

My function does not work on page load, on page load both divs appear. If i click either tab then only does my function work.

Do you know how to get my function to be working on page load.

jQuery(document).ready(function () {
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })

DOWNLOAD APPLICATION

Test

RENTAL

HOMEOWNER


问:
how to get id value from listview on the ClickListener
I want to get the id from the listview, not the position. The id is in the JSON file so while I am displaying the data in a listview so when I click on it I get the id of that driver from JSON file.

[{lastName=wdkj fsj, firstName=jf jfn, id=1}, {lastName=singh,
  firstName=sunny, id=2}]

```<code>public class DriverData extends AppCompatActivity {
    private String TAG = DriverData.class.getSimpleName();

    ArrayAdapter<String> adapter;
    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://54.148.120.200:3000/getDrivers";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.driver_data);

        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.simpleListView);

        new DriverData.GetContacts().execute();

    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(DriverData.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("drivers");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");
                        JSONObject user = c.getJSONObject("user");
                        String firstName = user.getString("firstName");
                        String lastName = user.getString("lastName");

                        // Phone node is JSON Object

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("firstName", firstName);
                        contact.put("lastName", lastName);

                        // adding contact to contact list
                        contactList.add(contact);

                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
            System.out.println(contactList);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            /**
             * Updating parsed JSON data into ListView
             * */

            ListAdapter adapter = new SimpleAdapter(
                    DriverData.this, contactList,
                    R.layout.list_item, new String[]{"firstName", "lastName"
            }, new int[]{R.id.name, R.id.lastName});
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                }
            });

        }
    }
}
</code>```

答:
You have it in contactList, you can simply retrieve it.

Do this inside setOnItemClickListener()

```<code> lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            String id=contactList.get(position).get("id");
            }
        });
</code>```

Body:
I want to get the id from the listview, not the position. The id is in the JSON file so while I am displaying the data in a listview so when I click on it I get the id of that driver from JSON file.

[{lastName=wdkj fsj, firstName=jf jfn, id=1}, {lastName=singh,
  firstName=sunny, id=2}]

public class DriverData extends AppCompatActivity {
    private String TAG = DriverData.class.getSimpleName();

    ArrayAdapter<String> adapter;
    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://54.148.120.200:3000/getDrivers";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.driver_data);

        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.simpleListView);

        new DriverData.GetContacts().execute();

    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(DriverData.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("drivers");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");
                        JSONObject user = c.getJSONObject("user");
                        String firstName = user.getString("firstName");
                        String lastName = user.getString("lastName");

                        // Phone node is JSON Object

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("firstName", firstName);
                        contact.put("lastName", lastName);

                        // adding contact to contact list
                        contactList.add(contact);

                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
            System.out.println(contactList);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            /**
             * Updating parsed JSON data into ListView
             * */

            ListAdapter adapter = new SimpleAdapter(
                    DriverData.this, contactList,
                    R.layout.list_item, new String[]{"firstName", "lastName"
            }, new int[]{R.id.name, R.id.lastName});
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                }
            });

        }
    }
}

Body:
You have it in contactList, you can simply retrieve it.

Do this inside setOnItemClickListener()

 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            String id=contactList.get(position).get("id");
            }
        });


问:
Cron job start and stop at certain time
Is it possible to setup a cron job to work on certain days only at night, for example, the first day of each month from 03pm to 09pm?

I want to do an email campaign only at night when the server load is low.

Is it possible to run a cron job at a certain time and stop it at a certain time?

答:
Not really. You could probably set something up to terminate a running script after six hours, but that usually wouldn't be a good solution because your script has no chance of cleaning things up.

The best thing to do would be to do a clean exit from inside the script when the time limit has been reached.

ContentLicense: CC BY-SA 2.5

Title: Cron job start and stop at certain time


问:
Using Java+regex, I want to find repeating characters in a string and replace that substring(s) with character found and # of times it was found
sample

```<code>String str = "fghhhhjkjkljhdd"
</code>```

i need to transform it into output string "fgh4jkjkljhd2"

I have the following code but the problem here is that i only get a single occurence matched - "hhhh". I'm still missing "dd".
Once this problem is solved i can think about how to assign matches to a string(s) and count characters there, but for now i 'm not able to get multiple matches. Any pointers are appreciated.

```<code>    String str = "fghhhhjkjkljhdd";
    Pattern p = Pattern.compile("(\\w)\\1+");
    Matcher m = p.matcher(str);
    if (m.find()) System.out.println(m.group());
</code>```

答:
You can try it also with a simple loop</p>

```<code>    String str = "fghhhhjkjkkljhdd";
    StringBuffer sb = new StringBuffer(String.valueOf(str.charAt(0)));
    char lastChar = str.charAt(0);
    int counter = 1;

    for (int i = 1; i < str.length(); i++) {
        if (str.charAt(i) == lastChar) {
            counter++;
        } else {
            lastChar = str.charAt(i);
            if (counter != 1) sb.append(counter);
            sb.append(lastChar);
            counter = 1;
        }
    }
    if(counter != 1) sb.append(counter);
    System.out.println(sb.toString());
    //fgh4jkjk2ljhd2
</code>```

Body:
sample

String str = "fghhhhjkjkljhdd"

i need to transform it into output string "fgh4jkjkljhd2"

I have the following code but the problem here is that i only get a single occurence matched - "hhhh". I'm still missing "dd".
Once this problem is solved i can think about how to assign matches to a string(s) and count characters there, but for now i 'm not able to get multiple matches. Any pointers are appreciated.

    String str = "fghhhhjkjkljhdd";
    Pattern p = Pattern.compile("(\\w)\\1+");
    Matcher m = p.matcher(str);
    if (m.find()) System.out.println(m.group());

Body:
You can try it also with a simple loop

    String str = "fghhhhjkjkkljhdd";
    StringBuffer sb = new StringBuffer(String.valueOf(str.charAt(0)));
    char lastChar = str.charAt(0);
    int counter = 1;

    for (int i = 1; i < str.length(); i++) {
        if (str.charAt(i) == lastChar) {
            counter++;
        } else {
            lastChar = str.charAt(i);
            if (counter != 1) sb.append(counter);
            sb.append(lastChar);
            counter = 1;
        }
    }
    if(counter != 1) sb.append(counter);
    System.out.println(sb.toString());
    //fgh4jkjk2ljhd2


答:
You can schedule cron to start your program on the first day of the month at 3PM. Your program will have to take care of killing itself at 9PM.

http://en.wikipedia.org/wiki/Cron

Title: Cron job start and stop at certain time

Body:
Is it possible to setup a cron job to work on certain days only at night, for example, the first day of each month from 03pm to 09pm?

I want to do an email campaign only at night when the server load is low.

Is it possible to run a cron job at a certain time and stop it at a certain time?


问:
How to set same size images in tableviewcell?

I need the images in my table to be the same size, such as 40x40 or 30x40. How can I do this?

答: Give the height and width constraint to imageView and then make the clip to bounds property of imageView to true.</p>


问:
Laravel Join query eloquent
I have three models like following:

```<code>class Category extends Eloquent
{
protected $primaryKey = 'categoryID';
public $timestamps = false;

protected $fillable = [
    'categoryName',

];

public function categoriesfields()
{
    return $this->hasMany(\App\Models\Categoriesfield::class, 'categoryID');
}
}
</code>```

Categoriesfield:

```<code>class Categoriesfield extends Eloquent
{
protected $primaryKey = 'fieldID';
public $timestamps = false;

protected $casts = [

    'categoryID' => 'int'
];

protected $fillable = [
    'fieldName_ar',
    'categoryID'
];

public function category()
{
    return $this->belongsTo(\App\Models\Category::class, 'categoryID');
}

public function categoriesoptions()
{
    return $this->hasMany(\App\Models\Categoriesoption::class, 'fieldID');
}
}
</code>```

Categoriesoption:

```<code>class Categoriesoption extends Eloquent
{
protected $primaryKey = 'optionID';
public $timestamps = false;

protected $casts = [
    'optionParent' => 'int',
    'fieldID' => 'int'
];

protected $fillable = [
    'fieldID'
];

public function categoriesfield()
{
    return $this->belongsTo(\App\Models\Categoriesfield::class, 'fieldID');
}
}
</code>```

when I run this query I got this error :

```<code>$data= Category::with('category.categoriesfields')-
>with('category.categoriesfields.categoriesoptions')
            ->where('fieldID', '=', 3)->get();
</code>```

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fieldID' in 'where clause' (SQL: select * from categories where fieldID = 3)
Any help please to know what is the problem !!?

答:
See Constraining Eager Loads for this purpose:

```<code>$fieldID = 3; // added the variable here to see how to import it to the closure

$data = Category::with([
    'categoriesfields' => function ($query) use ($fieldID) {
         $query->with('categoriesoptions')->where('fieldID', '=', $fieldID);
    }
])->get();
</code>```

It happends because the where clause is added on the categories table which does not have the fieldID column.

Title: Laravel Join query eloquent

Body:
I have three models like following:

class Category extends Eloquent
{
protected $primaryKey = 'categoryID';
public $timestamps = false;

protected $fillable = [
    'categoryName',

];

public function categoriesfields()
{
    return $this->hasMany(\App\Models\Categoriesfield::class, 'categoryID');
}
}

Categoriesfield:

class Categoriesfield extends Eloquent
{
protected $primaryKey = 'fieldID';
public $timestamps = false;

protected $casts = [

    'categoryID' => 'int'
];

protected $fillable = [
    'fieldName_ar',
    'categoryID'
];

public function category()
{
    return $this->belongsTo(\App\Models\Category::class, 'categoryID');
}

public function categoriesoptions()
{
    return $this->hasMany(\App\Models\Categoriesoption::class, 'fieldID');
}
}

Categoriesoption:

class Categoriesoption extends Eloquent
{
protected $primaryKey = 'optionID';
public $timestamps = false;

protected $casts = [
    'optionParent' => 'int',
    'fieldID' => 'int'
];

protected $fillable = [
    'fieldID'
];

public function categoriesfield()
{
    return $this->belongsTo(\App\Models\Categoriesfield::class, 'fieldID');
}
}

when I run this query I got this error :

$data= Category::with('category.categoriesfields')-
>with('category.categoriesfields.categoriesoptions')
            ->where('fieldID', '=', 3)->get();

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fieldID' in 'where clause' (SQL: select * from categories where fieldID = 3)
Any help please to know what is the problem !!?

Body:
See Constraining Eager Loads for this purpose:

$fieldID = 3; // added the variable here to see how to import it to the closure

$data = Category::with([
    'categoriesfields' => function ($query) use ($fieldID) {
         $query->with('categoriesoptions')->where('fieldID', '=', $fieldID);
    }
])->get();

It happends because the where clause is added on the categories table which does not have the fieldID column.


问:
How to add/Remove Object at index swift
I have one array like

```<code>var arraybtnState: NSArray! = NSArray()
</code>```

For add/Remove object into array, I had cast it in to NSMutableArray...

```<code>(self.arraybtnState as! NSMutableArray).addObject(button.tag)
(self.arraybtnState as! NSMutableArray).removeObject(button.tag)
</code>```

But it gives me SIGABRT error:

Could not cast value of type 'Swift._SwiftDeferredNSArray' (0x453e08) to 'NSMutableArray'

I have already tried NSMutableArray but it gives me error in below line

```<code>self.arraybtnState = self.strSubscribe?.componentsSeparatedByString(",")
</code>```

The question is what is preferred way to add/remove object in array

答:
Please write in selected cell function. it is Automatically delete cell. when you select cell

arryName.remove(indexPath.row)

Title: How to add/Remove Object at index swift

Body:
I have one array like

var arraybtnState: NSArray! = NSArray()

For add/Remove object into array, I had cast it in to NSMutableArray...

(self.arraybtnState as! NSMutableArray).addObject(button.tag)
(self.arraybtnState as! NSMutableArray).removeObject(button.tag)

But it gives me SIGABRT error:

Could not cast value of type 'Swift._SwiftDeferredNSArray' (0x453e08) to 'NSMutableArray'

I have already tried NSMutableArray but it gives me error in below line

self.arraybtnState = self.strSubscribe?.componentsSeparatedByString(",")

The question is what is preferred way to add/remove object in array


问:
use jquery in angular js function is not working?
I am trying to just write jquery inside angularjs function.but don't know why it is not working?

HTML

```<code><div>
   <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false" ng-mouseover="image.showDeleteIcon=true" ng-mouseleave="image.showDeleteIcon=false">
   <span ng-if="$index == 3" ng-init="setImgCounter(post.postImages.length,$parent.$index+''+$index)"></span>
   <a id="{{$parent.$index}}{{$index}}" onclick="SetDataGallery(this.id)" ng-href="../upload/post-photos/{{image.attachmentURL}}">
   <img class="img-responsive feed-photo" ng-src="../upload/post-photos/{{image.attachmentURL}}" alt="Photo" style="display:inline;">
   <a href="#" class="imgDelete" ng-if="post.timelineStrore.hasControl" ng-show="image.showDeleteIcon" title="Delete Photo" ng-click="DeletePostAttachment(post.timelineStrore.id, image.postAttachmentId,'image')">
   <i class="fa fa-close"></i>
   </a>
   </a>
   </span>
</div>
</code>```

JS

```<code>$scope.setImgCounter = function (counter,id)
{
    $("#" + id + " img:first-child").css("opacity", "0.5");
}
</code>```

but its not working?

I also tried using =>

```<code>.att('style','opacity:0.5');
</code>```

答:
Better not to use jquery with angular

Here is an angular way to achieve your requirement

Since you are trying to make every first child image as opacity 0.5 the loop always makes every images as first child/

So, you can use ng-style in the image div to apply the opacity.

ng-style="{'opacity': '0.5'}"

```<code><div>
    <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false" ng-mouseover="image.showDeleteIcon=true" ng-mouseleave="image.showDeleteIcon=false">
        <span ng-if="$index == 3" ng-init="setImgCounter(post.postImages.length,$parent.$index+''+$index)"></span>
        <a id="{{$parent.$index}}{{$index}}" onclick="SetDataGallery(this.id)" ng-href="../upload/post-photos/{{image.attachmentURL}}">
            <img class="img-responsive feed-photo" ng-src="../upload/post-photos/{{image.attachmentURL}}" alt="Photo" style="display:inline;" ng-style="{ 'opacity' : ($index == 3) ? '0.5' : '1' }">
            <a href="#" class="imgDelete" ng-if="post.timelineStrore.hasControl" ng-show="image.showDeleteIcon" title="Delete Photo" ng-click="DeletePostAttachment(post.timelineStrore.id, image.postAttachmentId,'image')">
                <i class="fa fa-close"></i>
            </a>
        </a>
    </span>
</div>
</code>```

Since the image is the first-child to anchor, it will only apply to image..but not i tag.

Note: If you wanted to apply it only for 3rd index, you can also use condition in ng-style. Angular is so flexible.

ng-style="{ 'opacity' : ($index == 3) ? '0.5' : '1' }"

I think this is your requirement.. pls ask me if any queries.

Body:
I am trying to just write jquery inside angularjs function.but don't know why it is not working?

HTML

   <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false" ng-mouseover="image.showDeleteIcon=true" ng-mouseleave="image.showDeleteIcon=false">

JS

$scope.setImgCounter = function (counter,id)
{
    $("#" + id + " img:first-child").css("opacity", "0.5");
}

but its not working?

I also tried using =>

.att('style','opacity:0.5');

Body:
Better not to use jquery with angular

Here is an angular way to achieve your requirement

Since you are trying to make every first child image as opacity 0.5 the loop always makes every images as first child/

So, you can use ng-style in the image div to apply the opacity.

ng-style="{'opacity': '0.5'}"

<div>
    <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false" ng-mouseover="image.showDeleteIcon=true" ng-mouseleave="image.showDeleteIcon=false">
        <span ng-if="$index == 3" ng-init="setImgCounter(post.postImages.length,$parent.$index+''+$index)"></span>
        <a id="{{$parent.$index}}{{$index}}" onclick="SetDataGallery(this.id)" ng-href="../upload/post-photos/{{image.attachmentURL}}">
            <img class="img-responsive feed-photo" ng-src="../upload/post-photos/{{image.attachmentURL}}" alt="Photo" style="display:inline;" ng-style="{ 'opacity' : ($index == 3) ? '0.5' : '1' }">
            <a href="#" class="imgDelete" ng-if="post.timelineStrore.hasControl" ng-show="image.showDeleteIcon" title="Delete Photo" ng-click="DeletePostAttachment(post.timelineStrore.id, image.postAttachmentId,'image')">
                <i class="fa fa-close"></i>
            </a>
        </a>
    </span>
</div>

Since the image is the first-child to anchor, it will only apply to image..but not i tag.

Note: If you wanted to apply it only for 3rd index, you can also use condition in ng-style. Angular is so flexible.

ng-style="{ 'opacity' : ($index == 3) ? '0.5' : '1' }"

I think this is your requirement.. pls ask me if any queries.


问:
Angular 2 - Observe result of firebase database
I'm new in angular, so be kind :)

Angular 2 ( 1.0.4 )
Angular Cli
NodeJs 7.9

i've try to make a centralized service that check if user is logged-in and, if it is retrive and send back data of User... i just try for 2 days to make this method works without success... any help will be appreciated :

```<code>    import { Injectable } from '@angular/core';
    import { Component, OnInit } from '@angular/core';
    import { AngularFireAuth } from 'angularfire2/auth';
    import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
    import { Observable } from 'rxjs/Rx';
    import { TipoUtente } from './tipidati' ;
    import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';

    import * as firebase from 'firebase';

    import 'rxjs/add/operator/toPromise' ;

    @Injectable()
    export class StatoutenteService implements OnInit {

constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {}

public getUserData() : Observable<any> {

  this.afAuth.authState.map( auth => {

        if (auth == null) {
          this.Logged = false ;
          this.Utente = new TipoUtente() ;
          this.UId = '' ;
          return undefined ;

        } else {
          this.Logged = true  ;
          this.UId = auth.uid ;

          return this.dbUserData().then(data => {
              console.log('leggo promessa') ;
              console.log(data) ;
              if (data.Livello != undefined) this.Utente = data ; else this.Utente = undefined ;
              console.log(this.Utente) ;
              if ( this.Utente == undefined ) { this.createNewUser() }
            } ) ;
        }
      } ) ;

} ;

private dbUserData() : Promise<TipoUtente> {

  // Controllo Utente
  console.log('Recupero dati utente!') ;
  console.log('UID :' + this.UId ) ;
  console.log(this.Logged) ;

  let utenteX = this.db.object('users/' + this.UId)
  return new Promise((resolve, reject) => {
    // must import 'rxjs/add/operator/first'; before using it here
    utenteX.subscribe( data  => {
      if ( data.$value == null ) resolve(undefined); else resolve(data) ;
    }, reject);
  });

}
</code>```

答:
Hello thanks for the answer :) i just edit a bit for make works for me and now the result is much better. then my previous code ( thankssss!! )

I just need now that listener receive back an "empty" user when is not auth... i try to edit your code as up but i get an exeption.

so i TRY to make this schema :

Menubar call the service asking for UserData

If User is Logged : Menubar get userdata and update buttons depending on Level

if User is not Logged : Menubar show "Login" button and hide menu.

this is edited code so far :

SERVICE :

```<code>      public getUserData() : Observable<any> {

        return this.afAuth.authState
           .flatMap( auth => {      //flatMap will resolve the returned observable (chaining observables)
               if ( auth == null ) {
                 this.Logged = false;
                 return undefined ;  // <<< Angular doesn't like this because it expect a stream
               } else {
               this.Logged = true;
               this.UId = auth.uid;
               return this.db.object('users/' + this.UId);
               }
          }).map(data => {
               console.log('sono dentro data') ;
               console.log(data) ;
               if (data.Livello != undefined) {
                   console.log('sono dentro if') ;
                   this.Utente = data;
               } else {
                   this.Utente = undefined; }
               console.log(this.Utente) ;
               if (this.Utente == undefined) return this.createNewUser(); else return data ;
          });
      }

private createNewUser() : Observable<any> {

  // Creo utente
  console.log('Creo Utente!') ;
  console.log(this.Logged) ;

  // se non sono loggato ritorno Livello 0
  if ( !this.Logged ) { return undefined } ;

  // carico dati in Utente :
  this.afAuth.authState.subscribe(auth => {
    if (auth != undefined) {
    console.log('sono in MAP') ;
  this.Utente = new TipoUtente() ;
  this.Utente.Cognome = auth.displayName.split(" ")[0] ;
  this.Utente.Nome    = auth.displayName.split(" ")[1] ;
  this.Utente.DisplayName = auth.displayName ;
  this.Utente.Immagine = auth.photoURL ;
  this.Utente.Livello = 1 ;
  this.UId = auth.uid ;

  // scrivo utente :
  console.log('chiamo DB') ;

  return this.db.database.ref('users/' + auth.uid).set(this.Utente) ;
  }
}) ;
</code>```

MENUBAR :

```<code>this.StatoUtente.getUserData().subscribe(data => {

    this.Utente = data ;
    console.log(data) ;

    if ( data != undefined ) {
        this.btntext = "Accedi" ;
        this.LevelMenu = 0 ;
        this.router.navigateByUrl('/') ;

      } else {
        this.btntext = "Logout" ;

        this.Utente = data ;
        this.LevelMenu = this.Utente.Livello ;
      }
    })
</code>```

Body:
I'm new in angular, so be kind :)

Angular 2 ( 1.0.4 )
Angular Cli
NodeJs 7.9

i've try to make a centralized service that check if user is logged-in and, if it is retrive and send back data of User... i just try for 2 days to make this method works without success... any help will be appreciated :

    import { Injectable } from '@angular/core';
    import { Component, OnInit } from '@angular/core';
    import { AngularFireAuth } from 'angularfire2/auth';
    import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
    import { Observable } from 'rxjs/Rx';
    import { TipoUtente } from './tipidati' ;
    import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';

    import * as firebase from 'firebase';

    import 'rxjs/add/operator/toPromise' ;

    @Injectable()
    export class StatoutenteService implements OnInit {

constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth, private router: Router) {}

public getUserData() : Observable<any> {

  this.afAuth.authState.map( auth => {

        if (auth == null) {
          this.Logged = false ;
          this.Utente = new TipoUtente() ;
          this.UId = '' ;
          return undefined ;

        } else {
          this.Logged = true  ;
          this.UId = auth.uid ;

          return this.dbUserData().then(data => {
              console.log('leggo promessa') ;
              console.log(data) ;
              if (data.Livello != undefined) this.Utente = data ; else this.Utente = undefined ;
              console.log(this.Utente) ;
              if ( this.Utente == undefined ) { this.createNewUser() }
            } ) ;
        }
      } ) ;

} ;

private dbUserData() : Promise<TipoUtente> {

  // Controllo Utente
  console.log('Recupero dati utente!') ;
  console.log('UID :' + this.UId ) ;
  console.log(this.Logged) ;

  let utenteX = this.db.object('users/' + this.UId)
  return new Promise((resolve, reject) => {
    // must import 'rxjs/add/operator/first'; before using it here
    utenteX.subscribe( data  => {
      if ( data.$value == null ) resolve(undefined); else resolve(data) ;
    }, reject);
  });

}

Body:
Hello thanks for the answer :) i just edit a bit for make works for me and now the result is much better. then my previous code ( thankssss!! )

I just need now that listener receive back an "empty" user when is not auth... i try to edit your code as up but i get an exeption.

so i TRY to make this schema :

Menubar call the service asking for UserData

If User is Logged : Menubar get userdata and update buttons depending on Level

if User is not Logged : Menubar show "Login" button and hide menu.

this is edited code so far :

SERVICE :

      public getUserData() : Observable<any> {

        return this.afAuth.authState
           .flatMap( auth => {      //flatMap will resolve the returned observable (chaining observables)
               if ( auth == null ) {
                 this.Logged = false;
                 return undefined ;  // <<< Angular doesn't like this because it expect a stream
               } else {
               this.Logged = true;
               this.UId = auth.uid;
               return this.db.object('users/' + this.UId);
               }
          }).map(data => {
               console.log('sono dentro data') ;
               console.log(data) ;
               if (data.Livello != undefined) {
                   console.log('sono dentro if') ;
                   this.Utente = data;
               } else {
                   this.Utente = undefined; }
               console.log(this.Utente) ;
               if (this.Utente == undefined) return this.createNewUser(); else return data ;
          });
      }

private createNewUser() : Observable<any> {

  // Creo utente
  console.log('Creo Utente!') ;
  console.log(this.Logged) ;

  // se non sono loggato ritorno Livello 0
  if ( !this.Logged ) { return undefined } ;

  // carico dati in Utente :
  this.afAuth.authState.subscribe(auth => {
    if (auth != undefined) {
    console.log('sono in MAP') ;
  this.Utente = new TipoUtente() ;
  this.Utente.Cognome = auth.displayName.split(" ")[0] ;
  this.Utente.Nome    = auth.displayName.split(" ")[1] ;
  this.Utente.DisplayName = auth.displayName ;
  this.Utente.Immagine = auth.photoURL ;
  this.Utente.Livello = 1 ;
  this.UId = auth.uid ;

  // scrivo utente :
  console.log('chiamo DB') ;

  return this.db.database.ref('users/' + auth.uid).set(this.Utente) ;
  }
}) ;

MENUBAR :

this.StatoUtente.getUserData().subscribe(data => {

    this.Utente = data ;
    console.log(data) ;

    if ( data != undefined ) {
        this.btntext = "Accedi" ;
        this.LevelMenu = 0 ;
        this.router.navigateByUrl('/') ;

      } else {
        this.btntext = "Logout" ;

        this.Utente = data ;
        this.LevelMenu = this.Utente.Livello ;
      }
    })


问:
Bing Maps v8 - Invoke Click Event on PushPin
Once i load the Bing map with multiple pushpin with infobox. I have added click Here anchor tag on HTML with specific pushpin index to display infobox on javascript click event. Somehow it's not working for me.

I do see Invoke event is being supported in v8

Here is the fiddle https://jsfiddle.net/pakpatel/9dc4oxfk/2/

var map, infobox;
  map = new Microsoft.Maps.Map('#myMap', {
    credentials: ''
  });

  //Create an infobox at the center of the map but don't show it.
  infobox = new Microsoft.Maps.Infobox(map.getCenter(), {
    visible: false
  });

  //Assign the infobox to a map instance.
  infobox.setMap(map);

  //Create random locations in the map bounds.
  var randomLocations = Microsoft.Maps.TestDataGenerator.getLocations(5, map.getBounds());

  for (var i = 0; i < randomLocations.length; i++) {
    var pin = new Microsoft.Maps.Pushpin(randomLocations[i]);

    //Store some metadata with the pushpin.
    pin.metadata = {
      title: 'Pin ' + i,
      description: 'Discription for pin' + i
    };

    //Add a click event handler to the pushpin.
    Microsoft.Maps.Events.addHandler(pin, 'click', pushpinClicked);

    //Add pushpin to the map.
    map.entities.push(pin);
  }

function pushpinClicked(e) {
  //Make sure the infobox has metadata to display.
  if (e.target.metadata) {
    //Set the infobox options with the metadata of the pushpin.
    infobox.setOptions({
      location: e.target.getLocation(),
      title: e.target.metadata.title,
      description: e.target.metadata.description,
      visible: true
    });
  }
}

function showInfoboxByKey(Key) {

  //Look up the  pushpin by gridKey.
  var selectedPin = map.entities.get(gridKey);
  //Show an infobox for the cluster or pushpin.
  Microsoft.Maps.Events.invoke(selectedPin, "click");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <script type='text/javascript'
        src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap'
        async defer></script>
 <div id="myMap" style="position:relative;width:600px;height:400px;"></div>
  Click Here </code>```

答:
The issue is you haven't passed in any event arguments when you invoked the event. As such the event handler doesn't get past your if statement and thus doesn't do anything. See the documentation here and you will notice that you need to provide the event arguments: https://msdn.microsoft.com/en-us/library/mt750279.aspx

That said, I'm not a fan of the approach being taken in your app here. If you simply want to get this working quick an easy, replace your invoke line of code with this:

```<code>pushpinClicked({e:{target: selectedPin }});
</code>```

I highly recommend adding your pushpins to a layer and adding your click event to the layer. This greatly reduces the complexity of the event system and has a small performance boast.

Body:
Once i load the Bing map with multiple pushpin with infobox. I have added click Here anchor tag on HTML with specific pushpin index to display infobox on javascript click event. Somehow it's not working for me.

I do see Invoke event is being supported in v8

Here is the fiddle https://jsfiddle.net/pakpatel/9dc4oxfk/2/

var map, infobox;
  map = new Microsoft.Maps.Map('#myMap', {
    credentials: ''
  });

  //Create an infobox at the center of the map but don't show it.
  infobox = new Microsoft.Maps.Infobox(map.getCenter(), {
    visible: false
  });

  //Assign the infobox to a map instance.
  infobox.setMap(map);

  //Create random locations in the map bounds.
  var randomLocations = Microsoft.Maps.TestDataGenerator.getLocations(5, map.getBounds());

  for (var i = 0; i < randomLocations.length; i++) {
    var pin = new Microsoft.Maps.Pushpin(randomLocations[i]);

    //Store some metadata with the pushpin.
    pin.metadata = {
      title: 'Pin ' + i,
      description: 'Discription for pin' + i
    };

    //Add a click event handler to the pushpin.
    Microsoft.Maps.Events.addHandler(pin, 'click', pushpinClicked);

    //Add pushpin to the map.
    map.entities.push(pin);
  }

function pushpinClicked(e) {
  //Make sure the infobox has metadata to display.
  if (e.target.metadata) {
    //Set the infobox options with the metadata of the pushpin.
    infobox.setOptions({
      location: e.target.getLocation(),
      title: e.target.metadata.title,
      description: e.target.metadata.description,
      visible: true
    });
  }
}

function showInfoboxByKey(Key) {

  //Look up the  pushpin by gridKey.
  var selectedPin = map.entities.get(gridKey);
  //Show an infobox for the cluster or pushpin.
  Microsoft.Maps.Events.invoke(selectedPin, "click");
}

  Click Here

Body:
The issue is you haven't passed in any event arguments when you invoked the event. As such the event handler doesn't get past your if statement and thus doesn't do anything. See the documentation here and you will notice that you need to provide the event arguments: https://msdn.microsoft.com/en-us/library/mt750279.aspx

That said, I'm not a fan of the approach being taken in your app here. If you simply want to get this working quick an easy, replace your invoke line of code with this:

pushpinClicked({e:{target: selectedPin }});

I highly recommend adding your pushpins to a layer and adding your click event to the layer. This greatly reduces the complexity of the event system and has a small performance boast.


问:
Advice to modify code to show multiple xpaths (PHP)
I'm using this test code on a site to learn how to do it. I'm attempting to basically web scrape everything contained in a specific div class, and echo it back on another site. This below is successfully accomplishing this with only the first div class displayed on the site, whereas I'd like it to display all. The below code spits out this result: string(107) " DJIA 21182.53 +8.84(0.04%) "

```<code><?php

 $doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;

$doc->loadHTMLFile('http://www.nbcnews.com/business');

$xpath = new DOMXPath($doc);

$query = "//div[@class='market']";

$entries = $xpath->query($query);
var_dump($entries->item(0)->textContent);

?>
</code>```

The source code however has these entries as well:

```<code>    <div class="market">
            <span class="market_item market_name">DJIA</span>
            <span class="market_item market_price">21182.53</span>
            <span class="market_item market_price  is-positive ">
            +8.84(0.04%)</span>
          </div>
          <div class="market">
            <span class="market_item market_name">NASDAQ</span>
            <span class="market_item market_price">6321.76</span>
            <span class="market_item market_price  is-positive ">
            +24.38(0.39%)</span>
          </div>
          <div class="market">
            <span class="market_item market_name">S&P 500</span>
            <span class="market_item market_price">2433.79</span>
            <span class="market_item market_price  is-positive ">
            +0.65(0.03%)</span>
          </div>
</code>```

Thoughts on what I need to modify in order to show all 3 of these? Guessing it could have something to do with the item(O), but when I modify that I break the code.
Second thing I'd like very much to change, is to stop the "string(___)" being displayed before the actual echo text.

Really appreciate it!! Thank you.

答:
$entries is object you can iterate over:

```<code>$entries = $xpath->query($query);
foreach ($entries as $entry) {
    echo trim($entry->textContent);  // use `trim` to eliminate spaces
}
</code>```

Body:
I'm using this test code on a site to learn how to do it. I'm attempting to basically web scrape everything contained in a specific div class, and echo it back on another site. This below is successfully accomplishing this with only the first div class displayed on the site, whereas I'd like it to display all. The below code spits out this result: string(107) " DJIA 21182.53 +8.84(0.04%) "

<?php

 $doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;

$doc->loadHTMLFile('http://www.nbcnews.com/business');

$xpath = new DOMXPath($doc);

$query = "//div[@class='market']";

$entries = $xpath->query($query);
var_dump($entries->item(0)->textContent);

?>

The source code however has these entries as well:

            DJIA
            21182.53

            +8.84(0.04%)

            NASDAQ
            6321.76

            +24.38(0.39%)

            S&P 500
            2433.79

            +0.65(0.03%)

Thoughts on what I need to modify in order to show all 3 of these? Guessing it could have something to do with the item(O), but when I modify that I break the code.
Second thing I'd like very much to change, is to stop the "string(___)" being displayed before the actual echo text.

Really appreciate it!! Thank you.

Body:
$entries is object you can iterate over:

$entries = $xpath->query($query);
foreach ($entries as $entry) {
    echo trim($entry->textContent);  // use `trim` to eliminate spaces
}


问:
Prevent search engines from indexing individual files in a member area
We've built a basic members area in WordPress that shows a list of PDF files to users when they are logged in, depending on their role. Incidentally the files can be accessed directly if you know the path to them, say https://example.com/wp-content/uploads/2017/the-file.pdf for example.

But we are now wondering if this is enough to prevent search engines from indexing the PDF files.

We know that if a search engine bot attempts to index the members page, it will not be able to because the bot is not authenticated.

But, if a logged in member accesses the PDF in the browser - again say https://example.com/wp-content/uploads/2017/the-file.pdf - can this file be indexed by a search engine and potentially be seen in search results? We are operating under the belief that the browser (Chrome) could potentially let Google know of the existence of these PDF files and then index them.

If so, what additional precautions should be taken to prevent potentially sensitive PDF files from being indexed by a search engine when logged in, and yet still allow them to be viewed in a browser?

答:
If you're dealing with sensitive data you'd also want to prevent users from guessing the url (either manually or via script)

Adding authentication when accessing the file should solve your problem and also prevent unauthorized users from getting it.

You can either only allow access to logged-in users or use a short-lived server-generated token that the user sends to the server when trying to access the file.

There are other methods as well.


答:
You need to call your hide/show code on page load alongwith tab click as</p>

```<code>jQuery(document).ready(function () {
            if($('#myTab').hasClass('overview active'))
            {
                jQuery('#rental').show(), jQuery('#homeo').hide();
            }else
            {
                jQuery('#rental').hide(), jQuery('#homeo').show();
            }
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

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

Title: Jquery not working to hide and show div until Bootstrap tab clicked

Body:
I have 2 different divs that need to appear depending on which tab is active.

If tab "#myTab class overview" is active then the "rental div" should show. If "#myTab class overview" is not active them the "homeo div" should show.

My function does not work on page load, on page load both divs appear. If i click either tab then only does my function work.

Do you know how to get my function to be working on page load.

jQuery(document).ready(function () {
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })

DOWNLOAD APPLICATION

Test

RENTAL

HOMEOWNER

Body:
You need to call your hide/show code on page load alongwith tab click as

jQuery(document).ready(function () {
            if($('#myTab').hasClass('overview active'))
            {
                jQuery('#rental').show(), jQuery('#homeo').hide();
            }else
            {
                jQuery('#rental').hide(), jQuery('#homeo').show();
            }
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })


问:
MySQL not using ports in xampp?
I installed Joomla and updated it to the latest version, but MySQL crashed, and when I start it back up it doesn't use any ports??

I've tried restarting xampp and it doesn't fix it. After a while of MySQL being opened, it crashes and windows gives me the error:

```<code>Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: mysqld.exe
  Application Version:  10.1.21.0
  Application Timestamp:    587e81ec
  Fault Module Name:    mysqld.exe
  Fault Module Version: 10.1.21.0
  Fault Module Timestamp:   587e81ec
  Exception Code:   80000003
  Exception Offset: 00463db0
  OS Version:   6.1.7601.2.1.0.256.1
  Locale ID:    1033
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt
</code>```

If i try going to PHPMyAdmin, it shows this :

Can I please get some help?

答: Just try to change the port no==> mysqli.default_port = 3306 in php.ini file and restart the system..Hope it will fix

Title: MySQL not using ports in xampp?

Body:
I installed Joomla and updated it to the latest version, but MySQL crashed, and when I start it back up it doesn't use any ports??

I've tried restarting xampp and it doesn't fix it. After a while of MySQL being opened, it crashes and windows gives me the error:

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: mysqld.exe
  Application Version:  10.1.21.0
  Application Timestamp:    587e81ec
  Fault Module Name:    mysqld.exe
  Fault Module Version: 10.1.21.0
  Fault Module Timestamp:   587e81ec
  Exception Code:   80000003
  Exception Offset: 00463db0
  OS Version:   6.1.7601.2.1.0.256.1
  Locale ID:    1033
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

If i try going to PHPMyAdmin, it shows this :

Can I please get some help?


答:
First of all create POJO model for saving objects and using them easily.

```<code>public class Contact {

    private String id;
    private String lastName;
    private String firstName;

    public Contact(String id, String lastName, String firstName) {
        this.id = id;
        this.lastName = lastName;
        this.firstName = firstName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}
</code>```

This is simply POJO model class, but if you want to get more information about this, you can follow this link!

Note : Variables should be private and methods should be public.

Then, it will be better if you create your own custom adapter.

```<code>public class ListAdapter extends ArrayAdapter<Item> {

    private List<Contact> contactList;

    public ListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public ListAdapter(Context context, int resource, List<Contact> contactList) {
        super(context, resource, contactList);
        this.contactList = contactList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.itemlistrow, null);
        }

        Item p = getItem(position);

        if (p != null) {
            TextView tvId = (TextView) v.findViewById(R.id.id);
            TextView tvLastName = (TextView) v.findViewById(R.id.lastName);
            TextView tvFirstName = (TextView) v.findViewById(R.id.firstName);

            tvId.setText(contactList.getId()); // this will show ID
            tvLastName.setText(contactList.getLastName());
            tvFirstName.setText(contactList.getFirstName());

        }

        return v;
    }

}
</code>```

Then, after getting all data from JSON link, send data to constructor.
I'll update your source:

```<code>      try {
                contactList = new ArrayList<Contact>;
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("drivers");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    Contact contact = new Contact();

                    JSONObject c = contacts.getJSONObject(i);

                    JSONObject user = c.getJSONObject("user");
                    contact.setId(c.getString("id"));
                    contact.setFirstName(user.getString("firstName"));
                    contact.setLastName(user.getString("lastName"));

                    contactList.add(contact);

                }
            }
</code>```

Update your onPostExecute() method also.

```<code>@Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            //System.out.println(contactList.size());

            /**
             * Updating parsed JSON data into ListView
             * */

            ListAdapter adapter = new ListAdapter(
                    getApplicationContext(), R.layout.list_item, contactList);
            lv.setAdapter(adapter);
        }
</code>```

If you get any error, comment here, and i'll update. Not tested yet, but i think this will helpful. Enjoy!

Title: how to get id value from listview on the ClickListener

Body:
I want to get the id from the listview, not the position. The id is in the JSON file so while I am displaying the data in a listview so when I click on it I get the id of that driver from JSON file.

[{lastName=wdkj fsj, firstName=jf jfn, id=1}, {lastName=singh,
  firstName=sunny, id=2}]

public class DriverData extends AppCompatActivity {
    private String TAG = DriverData.class.getSimpleName();

    ArrayAdapter<String> adapter;
    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://54.148.120.200:3000/getDrivers";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.driver_data);

        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.simpleListView);

        new DriverData.GetContacts().execute();

    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(DriverData.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("drivers");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");
                        JSONObject user = c.getJSONObject("user");
                        String firstName = user.getString("firstName");
                        String lastName = user.getString("lastName");

                        // Phone node is JSON Object

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("firstName", firstName);
                        contact.put("lastName", lastName);

                        // adding contact to contact list
                        contactList.add(contact);

                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
            System.out.println(contactList);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            /**
             * Updating parsed JSON data into ListView
             * */

            ListAdapter adapter = new SimpleAdapter(
                    DriverData.this, contactList,
                    R.layout.list_item, new String[]{"firstName", "lastName"
            }, new int[]{R.id.name, R.id.lastName});
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                }
            });

        }
    }
}

Body:
First of all create POJO model for saving objects and using them easily.

public class Contact {

    private String id;
    private String lastName;
    private String firstName;

    public Contact(String id, String lastName, String firstName) {
        this.id = id;
        this.lastName = lastName;
        this.firstName = firstName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

This is simply POJO model class, but if you want to get more information about this, you can follow this link!

Note : Variables should be private and methods should be public.

Then, it will be better if you create your own custom adapter.

public class ListAdapter extends ArrayAdapter<Item> {

    private List<Contact> contactList;

    public ListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public ListAdapter(Context context, int resource, List<Contact> contactList) {
        super(context, resource, contactList);
        this.contactList = contactList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.itemlistrow, null);
        }

        Item p = getItem(position);

        if (p != null) {
            TextView tvId = (TextView) v.findViewById(R.id.id);
            TextView tvLastName = (TextView) v.findViewById(R.id.lastName);
            TextView tvFirstName = (TextView) v.findViewById(R.id.firstName);

            tvId.setText(contactList.getId()); // this will show ID
            tvLastName.setText(contactList.getLastName());
            tvFirstName.setText(contactList.getFirstName());

        }

        return v;
    }

}

Then, after getting all data from JSON link, send data to constructor.
I'll update your source:

      try {
                contactList = new ArrayList<Contact>;
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("drivers");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    Contact contact = new Contact();

                    JSONObject c = contacts.getJSONObject(i);

                    JSONObject user = c.getJSONObject("user");
                    contact.setId(c.getString("id"));
                    contact.setFirstName(user.getString("firstName"));
                    contact.setLastName(user.getString("lastName"));

                    contactList.add(contact);

                }
            }

Update your onPostExecute() method also.

@Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            //System.out.println(contactList.size());

            /**
             * Updating parsed JSON data into ListView
             * */

            ListAdapter adapter = new ListAdapter(
                    getApplicationContext(), R.layout.list_item, contactList);
            lv.setAdapter(adapter);
        }

If you get any error, comment here, and i'll update. Not tested yet, but i think this will helpful. Enjoy!


问:
php regex mach before and after specific word
I have a string with data that looks like this:

```<code>$string = '
    foo=bar
    badge_name_foo=foo
    bar_badge_name=bar
    bar=baz
';
</code>```

I want to match all *_badge_name and badge_name_* strings.

The regex im using is this:
preg_match_all('~(?:(\w+)_)?badge_name(?:_(\w+))?~', $string, $matches, PREG_SET_ORDER);

The result is:

```<code>Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] =>
            [2] => foo
        )

    [1] => Array
        (
            [0] => bar_badge_name
            [1] => bar
        )

)
</code>```

The *_badge_name is working fine, but on badge_name_* there is every time a empty value? Now how can i remove that with preg_match_all

Expected result should be:

```<code>Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] => foo
        )

    [1] => Array
        (
            [0] => bar_badge_name
            [1] => bar
        )

)
</code>```

答:
It seems you need to use BRANCH RESET feature:

Alternatives inside a branch reset group share the same capturing groups. The syntax is (?|regex) where (?| opens the group and regex is any regular expression. If you don't use any alternation or capturing groups inside the branch reset group, then its special function doesn't come into play. It then acts as a non-capturing group.

Use

```<code>(?|(\w+)_badge_name|badge_name_(\w+))
^^^
</code>```

See the regex demo.

PHP demo:

```<code>$re = '/(?|(\w+)_badge_name|badge_name_(\w+))/';
$str = 'foo=bar
badge_name_foo=foo
bar_badge_name=bar
bar=baz';
preg_match_all($re, $str, $matches);
print_r($matches);
</code>```

Result:

```<code>Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] => bar_badge_name
        )

    [1] => Array
        (
            [0] => foo
            [1] => bar
        )

)
</code>```

Body:
I have a string with data that looks like this:

$string = '
    foo=bar
    badge_name_foo=foo
    bar_badge_name=bar
    bar=baz
';

I want to match all *_badge_name and badge_name_* strings.

The regex im using is this:
preg_match_all('~(?:(\w+)_)?badge_name(?:_(\w+))?~', $string, $matches, PREG_SET_ORDER);

The result is:

Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] =>
            [2] => foo
        )

    [1] => Array
        (
            [0] => bar_badge_name
            [1] => bar
        )

)

The *_badge_name is working fine, but on badge_name_* there is every time a empty value? Now how can i remove that with preg_match_all

Expected result should be:

Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] => foo
        )

    [1] => Array
        (
            [0] => bar_badge_name
            [1] => bar
        )

)

Body:
It seems you need to use BRANCH RESET feature:

Alternatives inside a branch reset group share the same capturing groups. The syntax is (?|regex) where (?| opens the group and regex is any regular expression. If you don't use any alternation or capturing groups inside the branch reset group, then its special function doesn't come into play. It then acts as a non-capturing group.

Use

(?|(\w+)_badge_name|badge_name_(\w+))
^^^

See the regex demo.

PHP demo:

$re = '/(?|(\w+)_badge_name|badge_name_(\w+))/';
$str = 'foo=bar
badge_name_foo=foo
bar_badge_name=bar
bar=baz';
preg_match_all($re, $str, $matches);
print_r($matches);

Result:

Array
(
    [0] => Array
        (
            [0] => badge_name_foo
            [1] => bar_badge_name
        )

    [1] => Array
        (
            [0] => foo
            [1] => bar
        )

)


问:
RabbitMQ take one message from queue on launch
I publish many messages to my queue in RabbitMQ when worker is off.
Then i start my worker and he takes all messages from queue and he is working fine but when i stop my worker proces before he ends, all messages are deleted from queue.
If i start second the same worker he has no messages to take.

```<code>$channel->queue_declare($action, false, false, false, false);

$channel->basic_qos(null, 1, null);
$channel->basic_consume($action, '', false, true, false, false, $callback);
</code>```

How can i do to my worker takes only one message on start from queue and when worker stops and starts he continue takes messages from queue where he stops ?

答:
If there are no messages left to take the messages have already been acknowledged.

"Auto acknowledgements" should be disabled so that an acknowledgement must be explicitly sent back manually (ie. after all work is done) to complete consuming the message.

```<code>$no_ack = false; # If no_ack is true the server does NOT expect a
                 # basic.ack response and will dequeue the message immediately!
$channel->basic_consume($action, '', false, $no_ack, false, false, $callback);
</code>```

The PHP tutorial on the RabbitMQ site shows how to send an ack from within the callback.

As long as the worker is killed before the ack has been sent the message will be made available again when the connection is closed - and can be picked up by other consumers. See Message Acknowledgements.

Specifically, wrt the no-ack bit:

If this field is set (true) the server does not expect acknowledgements for messages. That is, when a message is delivered to the client the server assumes the delivery will succeed and immediately dequeues it. This functionality may increase performance but at the cost of reliability. Messages can get lost if a client dies before they are delivered to the application.

Body:
I publish many messages to my queue in RabbitMQ when worker is off.
Then i start my worker and he takes all messages from queue and he is working fine but when i stop my worker proces before he ends, all messages are deleted from queue.
If i start second the same worker he has no messages to take.

$channel->queue_declare($action, false, false, false, false);

$channel->basic_qos(null, 1, null);
$channel->basic_consume($action, '', false, true, false, false, $callback);

How can i do to my worker takes only one message on start from queue and when worker stops and starts he continue takes messages from queue where he stops ?

Body:
If there are no messages left to take the messages have already been acknowledged.

"Auto acknowledgements" should be disabled so that an acknowledgement must be explicitly sent back manually (ie. after all work is done) to complete consuming the message.

$no_ack = false; # If no_ack is true the server does NOT expect a
                 # basic.ack response and will dequeue the message immediately!
$channel->basic_consume($action, '', false, $no_ack, false, false, $callback);

The PHP tutorial on the RabbitMQ site shows how to send an ack from within the callback.

As long as the worker is killed before the ack has been sent the message will be made available again when the connection is closed - and can be picked up by other consumers. See Message Acknowledgements.

Specifically, wrt the no-ack bit:

If this field is set (true) the server does not expect acknowledgements for messages. That is, when a message is delivered to the client the server assumes the delivery will succeed and immediately dequeues it. This functionality may increase performance but at the cost of reliability. Messages can get lost if a client dies before they are delivered to the application.


问:
What restricition imposed on cursor variable name in plsql?
I have executed following simple anonymous block in sql developer by expecting x number of rows to be deleted from "FOO" table however I ended up with unexpected outcome which in turn deleting entire rows.

```<code>DECLARE
  type pkarray IS VARRAY(3) OF RAW(16);
  ids pkarray;
BEGIN
  ids := pkarray('guid_value1','guid_value2','guid_value3');
  FOR i in 1 .. 3 LOOP
    FOR foo IN (SELECT FOO_ID FROM FOO WHERE BAR_ID = UPPER(ids(i))) LOOP
           DELETE FROM FOO WHERE FOO_ID = foo.FOO_ID;
    END LOOP;
  END LOOP;
END;
</code>```

However when I changed the cursor variable 'foo" to something else like "abc", the program worked correctly by deleting x number of rows. The number x I knew in ahead of time.

答:
Since PL/SQL is case insensitive for identifiers, foo and FOO are equvalent. Let's reproduce part of your code, setting off variable names in lower case for clarity:

```<code> FOR foo /*1*/ IN (SELECT foo_id FROM foo WHERE bar_id = UPPER(ids(i))) LOOP
     DELETE FROM foo /*2*/ WHERE foo_id = foo.foo_id;
 END LOOP;
</code>```

We are dealing here with name shadowing. When compiler evaluates this expression

```<code>DELETE FROM foo WHERE foo_id = foo.foo_id;
</code>```

it sees that needed identifiers foo and foo_id are known (in context of table definition). So there's no need to seek higher in syntax tree for definition of the utilized names. In other words the first foo (loop variable) is shadowed by table name and not used in compilation of the delete query, which is the same as

```<code>DELETE FROM foo WHERE foo_id = foo_id;
</code>```

and its filter condition is true for all foo_id except NULL, what leads to deleting entire rows.

Luckily this problem can be solved once and for all with naming conventions:  in PL/SQL blocks use names with special prefixes etc., protecting your code from accidental intersection with schema objects names.

ContentLicense: CC BY-SA 4.0

Body:
I have executed following simple anonymous block in sql developer by expecting x number of rows to be deleted from "FOO" table however I ended up with unexpected outcome which in turn deleting entire rows.

DECLARE
  type pkarray IS VARRAY(3) OF RAW(16);
  ids pkarray;
BEGIN
  ids := pkarray('guid_value1','guid_value2','guid_value3');
  FOR i in 1 .. 3 LOOP
    FOR foo IN (SELECT FOO_ID FROM FOO WHERE BAR_ID = UPPER(ids(i))) LOOP
           DELETE FROM FOO WHERE FOO_ID = foo.FOO_ID;
    END LOOP;
  END LOOP;
END;

However when I changed the cursor variable 'foo" to something else like "abc", the program worked correctly by deleting x number of rows. The number x I knew in ahead of time.

Body:
Since PL/SQL is case insensitive for identifiers, foo and FOO are equvalent. Let's reproduce part of your code, setting off variable names in lower case for clarity:

 FOR foo /*1*/ IN (SELECT foo_id FROM foo WHERE bar_id = UPPER(ids(i))) LOOP
     DELETE FROM foo /*2*/ WHERE foo_id = foo.foo_id;
 END LOOP;

We are dealing here with name shadowing. When compiler evaluates this expression

DELETE FROM foo WHERE foo_id = foo.foo_id;

it sees that needed identifiers foo and foo_id are known (in context of table definition). So there's no need to seek higher in syntax tree for definition of the utilized names. In other words the first foo (loop variable) is shadowed by table name and not used in compilation of the delete query, which is the same as

DELETE FROM foo WHERE foo_id = foo_id;

and its filter condition is true for all foo_id except NULL, what leads to deleting entire rows.

Luckily this problem can be solved once and for all with naming conventions:  in PL/SQL blocks use names with special prefixes etc., protecting your code from accidental intersection with schema objects names.


问:
Reference to an instance method of a particular object breaks the type-safety in Java?
Does the notion of a reference to an instance method of a particular object break the type-safety in Java?

According to

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

you can have a custom class ComparisonProvider  that DOES not implement the Comparator  interface, and still use an instance of this class as the second argument of the method

Arrays.sort(T[] a, Comparator c)

Sure, the implementation of your ComparisonProvider MUST have a method whose signature exactly matches the Comparator.compare() method, but that is still not an instance of Comparator, isn't it?

In essence, Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not.

This means, that we are loosing Type-safety in Java, do we?

答:
lambda expressions and method reference don't have a predefined type, they are poly expressions, as seen here. That means that their type is derived from the context in which they are used.

In your example these both would be legal for example:

```<code> BiFunction<Person, Person, Integer> biFun = myComparisonProvider::compareByName;

 Comparator<Person> comp = myComparisonProvider::compareByName;
</code>```

But at the same time you can't do:

```<code>Arrays.sort(pers, biFun);
</code>```

When you actually try to sort the array like this:

```<code>Arrays.sort(pers, myComparisonProvider::compareByName);
</code>```

At the bytecode level that is a Comparator:

```<code>// InvokeDynamic #0:compare:(LTest$ComparisonProvider;)Ljava/util/Comparator;
</code>```

Also notice that this would print true:

```<code>Comparator<Person> comp = myComparisonProvider::compareByName;
System.out.println(comp instanceof Comparator); // true
</code>```

You can enable a flag : -Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here

and look at what that method reference is transformed into:

```<code>final class Test$$Lambda$1 implements java.util.Comparator
</code>```

and inside it there's the compare method implementation(I've simplified it and removed some of it's code to make it a little more obvious):

```<code>public int compare(java.lang.Object, java.lang.Object);
Code:
     4: aload_1
     5: checkcast // class Test3$Person
     8: aload_2
     9: checkcast // class Test$Person
    12: invokevirtual Test$ComparisonProvider.compareByName:(Test$Person;Test$Person;)I
</code>```

Body:
lambda expressions and method reference don't have a predefined type, they are poly expressions, as seen here. That means that their type is derived from the context in which they are used.

In your example these both would be legal for example:

 BiFunction<Person, Person, Integer> biFun = myComparisonProvider::compareByName;

 Comparator<Person> comp = myComparisonProvider::compareByName;

But at the same time you can't do:

Arrays.sort(pers, biFun);

When you actually try to sort the array like this:

Arrays.sort(pers, myComparisonProvider::compareByName);

At the bytecode level that is a Comparator:

// InvokeDynamic #0:compare:(LTest$ComparisonProvider;)Ljava/util/Comparator;

Also notice that this would print true:

Comparator<Person> comp = myComparisonProvider::compareByName;
System.out.println(comp instanceof Comparator); // true

You can enable a flag : -Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here

and look at what that method reference is transformed into:

final class Test$$Lambda$1 implements java.util.Comparator

and inside it there's the compare method implementation(I've simplified it and removed some of it's code to make it a little more obvious):

public int compare(java.lang.Object, java.lang.Object);
Code:
     4: aload_1
     5: checkcast // class Test3$Person
     8: aload_2
     9: checkcast // class Test$Person
    12: invokevirtual Test$ComparisonProvider.compareByName:(Test$Person;Test$Person;)I


问:
Remote XML retrieval
I'm retrieving a remote XML file with wget -O remotefile localfile with a cron tab.

Every so often the local file becomes malformed probably because of double whitespace (according to firefox) between the CDATA tags.

Sometimes the parser gives an error for ' > ' missing, but upon checking the xml file the ' > ' exists...

The remote xml file never gives malformed errors when called in the url.

EDIT

It seems CDATA is not parsed by the xml parser. (w3schools)

Is there a way to set wget to retain wellformed XML?

If not wget, What is a good way to continously retrieve a remote XML file and keep it well formed?

答: Try using curl http://wherever.com/remote.xml > local.xml.

Title: Remote XML retrieval