问:
How to indent the first line of a paragraph in CKEditor
I'm using CKEditor and I want to indent just the first line of the paragraph. What I've done before is click "Source" and edit the
 style to include text-indent:12.7mm;, but when I click "Source" again to go back to the normal editor, my changes are gone and I have no idea why.

My preference would be to create a custom toolbar button, but I'm not sure how to do so or where to edit so that clicking a custom button would edit the
 with the style attribute I want it to have.

答:
I've got a way to indent the first line without using style, because I'm using iReport to generate automatic reports. Jasper does not understand styles. So I assign by jQuery an onkeydown method to the main iframe of CKEditor 4.6 and I check the TAB and Shift key to do and undo the first line indentation.</p>

```<code>// TAB
    $(document).ready(function(){
        startTab();
    });

    function startTab() {
        setTimeout(function(){
            var $iframe_document;
            var $iframe;
            $iframe_document = $('.cke_wysiwyg_frame').contents();
            $iframe = $iframe_document.find('body');

            $iframe.keydown(function(e){
                event_onkeydown(e);
            });

        },300);
    }

    function event_onkeydown(event){
        if(event.keyCode===9) { // key tab
            event.preventDefault();
            setTimeout(function(){
                var editor = CKEDITOR.instances['editor1'], //get your CKEDITOR instance here
                    range = editor.getSelection().getRanges()[0],
                    startNode = range.startContainer,
                    element = startNode.$,
                    parent;

                if(element.parentNode.tagName != 'BODY') // If you take an inner element of the paragraph, get the parentNode (P)
                    parent = element.parentNode;
                else // If it takes BODY as parentNode, it updates the inner element
                    parent = element;

                if(event.shiftKey) { // reverse tab
                    var res = parent.innerHTML.toString().split(' ');
                    var aux = [];
                    var count_space = 0;

                    for(var i=0;i<res.length;i++) {
                        // console.log(res[i]);
                        if(res[i] == "")
                            count_space++;
                        if(count_space > 8 || res[i] != "") {
                            if(!count_space > 8)
                                count_space = 9;
                            aux.push(res[i]);
                        }
                    }
                    parent.innerHTML = aux.join(' ');
                }
                else { // tab
                    var spaces = "        ";
                    parent.innerHTML = spaces + parent.innerHTML;
                }
            },200);
        }
    }
</code>```

Body:
I've got a way to indent the first line without using style, because I'm using iReport to generate automatic reports. Jasper does not understand styles. So I assign by jQuery an onkeydown method to the main iframe of CKEditor 4.6 and I check the TAB and Shift key to do and undo the first line indentation.

// TAB
    $(document).ready(function(){
        startTab();
    });

    function startTab() {
        setTimeout(function(){
            var $iframe_document;
            var $iframe;
            $iframe_document = $('.cke_wysiwyg_frame').contents();
            $iframe = $iframe_document.find('body');

            $iframe.keydown(function(e){
                event_onkeydown(e);
            });

        },300);
    }

    function event_onkeydown(event){
        if(event.keyCode===9) { // key tab
            event.preventDefault();
            setTimeout(function(){
                var editor = CKEDITOR.instances['editor1'], //get your CKEDITOR instance here
                    range = editor.getSelection().getRanges()[0],
                    startNode = range.startContainer,
                    element = startNode.$,
                    parent;

                if(element.parentNode.tagName != 'BODY') // If you take an inner element of the paragraph, get the parentNode (P)
                    parent = element.parentNode;
                else // If it takes BODY as parentNode, it updates the inner element
                    parent = element;

                if(event.shiftKey) { // reverse tab
                    var res = parent.innerHTML.toString().split('&nbsp;');
                    var aux = [];
                    var count_space = 0;

                    for(var i=0;i<res.length;i++) {
                        // console.log(res[i]);
                        if(res[i] == "")
                            count_space++;
                        if(count_space > 8 || res[i] != "") {
                            if(!count_space > 8)
                                count_space = 9;
                            aux.push(res[i]);
                        }
                    }
                    parent.innerHTML = aux.join('&nbsp;');
                }
                else { // tab
                    var spaces = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    parent.innerHTML = spaces + parent.innerHTML;
                }
            },200);
        }
    }


来源: stackexchange

问:
Get local time from different Timezone using batchfile
I do not want to use any scripting language, but just plain command line commands/scripting.

I can solve this using a (prepared) TZ table (e.g. format: UTC+06:00 + 'TZ name'), then use TZUTIL to collect their resp UTC values and calculate the Timezone's local time (preferably taking DST into account).

I am just hoping that somebody already did this in a more "proper" way. Searched this/other sites, but found nothing so far.

ps: no 'external' tools/etc, since the final batch-file needs to be distributed EMEA-wise.

答:
I had a need to obtain time zone information in a specific format from MS Windows systems via a batch file.  I could not find what I needed so I developed my own.  Thought I would share for others to use.  Use the code and adjust as necessary.   </p>

```<code>@echo off
REM Obtain the ActiveBias value and convert to decimal
for /f "tokens=3" %%a in ('reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation /v ActiveTimeBias ^| grep -i "ActiveTimeBias"') do set /a abias=%%a
for /f "tokens=3-8" %%n in ('reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation /v TimeZoneKeyName') do set tzn=%%n %%o %%p %%q %%r 2>NUL

REM Set the + or - sign variable to reflect the timezone offset
IF "%abias:~0,1%"=="-" (set si=+) ELSE (set si=-)
for /f "tokens=1 delims=-" %%t in ('echo %abias%') do set tzc=%%t

REM Calculate to obtain floating points (decimal values)
set /a tzd=100*%tzc%/60

REM Calculate the active bias to obtain the hour
set /a tze=%tzc%/60

REM Set the minutes based on the result of the floating point calculation
IF "%tzd%"=="0" (set en=00 && set si=)
IF "%tzd:~1%"=="00" (set en=00) ELSE IF "%tzd:~2%"=="00" (set en=00 && set tz=%tzd:~0,2%)
IF "%tzd:~1%"=="50" (set en=30) ELSE IF "%tzd:~2%"=="50" (set en=30 && set tz=%tzd:~0,2%)
IF "%tzd:~1%"=="75" (set en=45) ELSE IF "%tzd:~2%"=="75" (set en=45 && set tz=%tzd:~0,2%)

REM Adding a 0 to the beginning of a single digit hour value
IF %tze% LSS 10 (set tz=0%tze%)

REM Display timezone name and offset
echo %tzn% %si%%tz%%en%
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I had a need to obtain time zone information in a specific format from MS Windows systems via a batch file.  I could not find what I needed so I developed my own.  Thought I would share for others to use.  Use the code and adjust as necessary.

@echo off
REM Obtain the ActiveBias value and convert to decimal
for /f "tokens=3" %%a in ('reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation /v ActiveTimeBias ^| grep -i "ActiveTimeBias"') do set /a abias=%%a
for /f "tokens=3-8" %%n in ('reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation /v TimeZoneKeyName') do set tzn=%%n %%o %%p %%q %%r 2>NUL

REM Set the + or - sign variable to reflect the timezone offset
IF "%abias:~0,1%"=="-" (set si=+) ELSE (set si=-)
for /f "tokens=1 delims=-" %%t in ('echo %abias%') do set tzc=%%t

REM Calculate to obtain floating points (decimal values)
set /a tzd=100*%tzc%/60

REM Calculate the active bias to obtain the hour
set /a tze=%tzc%/60

REM Set the minutes based on the result of the floating point calculation
IF "%tzd%"=="0" (set en=00 && set si=)
IF "%tzd:~1%"=="00" (set en=00) ELSE IF "%tzd:~2%"=="00" (set en=00 && set tz=%tzd:~0,2%)
IF "%tzd:~1%"=="50" (set en=30) ELSE IF "%tzd:~2%"=="50" (set en=30 && set tz=%tzd:~0,2%)
IF "%tzd:~1%"=="75" (set en=45) ELSE IF "%tzd:~2%"=="75" (set en=45 && set tz=%tzd:~0,2%)

REM Adding a 0 to the beginning of a single digit hour value
IF %tze% LSS 10 (set tz=0%tze%)

REM Display timezone name and offset
echo %tzn% %si%%tz%%en%


问:
Modify QT Defines in .pro file from C++ file
Sorry, if this question doesn't make any sense but It just came to my mind, I was looking for a solution on this from quite long time but in the end I thought better to check with experts. :)

Below is a scenario:

Suppose In myProject.pro file, I have
      PATH = /home/local/Projects/
for which I created a QT DEFINE using below:
 DEFINES += PATH =\\"$${PATH}\\"

Now, I can use this "PATH" any where in my Project which is based on CPP file. This if perfectly fine.

Now, depending upon the input from user, I want to change this "PATH"
say, PATH can be:
    PATH = /home/local/Projects/TEST1/

```<code>PATH = /home/local/Projects/TEST2/

        and revert to

PATH = /home/local/Projects/
</code>```

So, that wherever I am using this "PATH" in my project will be changed automatically.

I know this is done at compile time. But came a thought. So wanted to get feedbacks from experts.

答:
One simple approach: use a global configuration object that takes the value of the PATH literal as the default value for its path member. That default value can be then changed by the user:

```<code>class Configuration {
  Q_DISABLE_COPY(Configuration)
  static Configuration * self;
public:
  static Configuration * instance() { return self; }
  Configuration() {
    Q_ASSERT(!self);
    self = this;
  }
  ~Configuration() { self = {}; }

  QString path{PATH};
};

Configuration * Configuration::self;

int main(int argc, char ** argv) {
  Configuration configuration;
  QApplication app{argc, argv};
  ...
  qDebug() << Configuration::instance()->path;
}
</code>```

Whenever you wish to access configuration globally, use the Configuration::instance() static method to obtain the instance, then use its path member. It will be set to the hardcoded PATH by default, but you can change it at any time.

The Configuration::instance() implements the same idiom as QCoreApplication::instance(): it lets you access a globally unique value, without suffering from the static initialization order fiasco.

Body:
Sorry, if this question doesn't make any sense but It just came to my mind, I was looking for a solution on this from quite long time but in the end I thought better to check with experts. :)

Below is a scenario:

Suppose In myProject.pro file, I have
      PATH = /home/local/Projects/
for which I created a QT DEFINE using below:
 DEFINES += PATH =\\"$${PATH}\\"

Now, I can use this "PATH" any where in my Project which is based on CPP file. This if perfectly fine.

Now, depending upon the input from user, I want to change this "PATH"
say, PATH can be:
    PATH = /home/local/Projects/TEST1/

PATH = /home/local/Projects/TEST2/

        and revert to

PATH = /home/local/Projects/

So, that wherever I am using this "PATH" in my project will be changed automatically.

I know this is done at compile time. But came a thought. So wanted to get feedbacks from experts.

Body:
One simple approach: use a global configuration object that takes the value of the PATH literal as the default value for its path member. That default value can be then changed by the user:

class Configuration {
  Q_DISABLE_COPY(Configuration)
  static Configuration * self;
public:
  static Configuration * instance() { return self; }
  Configuration() {
    Q_ASSERT(!self);
    self = this;
  }
  ~Configuration() { self = {}; }

  QString path{PATH};
};

Configuration * Configuration::self;

int main(int argc, char ** argv) {
  Configuration configuration;
  QApplication app{argc, argv};
  ...
  qDebug() << Configuration::instance()->path;
}

Whenever you wish to access configuration globally, use the Configuration::instance() static method to obtain the instance, then use its path member. It will be set to the hardcoded PATH by default, but you can change it at any time.

The Configuration::instance() implements the same idiom as QCoreApplication::instance(): it lets you access a globally unique value, without suffering from the static initialization order fiasco.


问:
view-source: having the incorrect JSON rendering ToString() C# MVC
While trying to fetch the db table column value which looks like:

```<code>{   "@context":        }
</code>```

The front end web application  view source is rendering as

```<code>{   "@context":   }
</code>```

which should be like

```<code>{   "@context":        }
</code>```

In Visual Studio Quick watch I could see the fetched value is looking good.
But while rending it is having hyper text characters.

Below is the Front end code,

```<code>agentModel.JSON = Convert.ToString(agentItem.GetValue("JSON"));
ViewBag.JSON = agentModel.JSON;
<script type="application/ld+json">
    @ViewBag.JSON
</script>
</code>```

Have also tried agentItem.GetValue("JSON").ToString(), but no help.

Please advise how to fix this so that it prints the correct character quot in the front end view source.

答:
To display the data without the HTML encoding, you can use @Html.Raw( ), which is part of the HTML Helper:

https://msdn.microsoft.com/en-us/library/gg480740(v=vs.118).aspx

In your case, try writing: @Html.Raw(ViewBag.JSON)

Body:
While trying to fetch the db table column value which looks like:

{   "@context":        }

The front end web application  view source is rendering as

{   "@context":   }

which should be like

{   "@context":        }

In Visual Studio Quick watch I could see the fetched value is looking good.
But while rending it is having hyper text characters.

Below is the Front end code,

agentModel.JSON = Convert.ToString(agentItem.GetValue("JSON"));
ViewBag.JSON = agentModel.JSON;

Have also tried agentItem.GetValue("JSON").ToString(), but no help.

Please advise how to fix this so that it prints the correct character quot in the front end view source.


问:
how to retrieve data from JSON into list?
I have a simple JSON with 4 items. I want to just import item 2,3,4 into li in html. With my code imported all items. I am new in JavaScript.

can you please give me some possible way to solve ?

item.json:

```<code>[
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
]
</code>```

HTML:

```<code><div>
    <ul>

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

script:

```<code><script>
$(document).ready( function(){

        $.getJSON('item.json', function(data) {
            $.each(data, function (i, f) {
                $("ul").append("<li><img src=" + f.content + "/></li>");
            });
  });
});
</script>
</code>```

答:
Your code looks fine. If you are looking for a way to skip first record and only display 2,3 and 4 then make this change:</p>

```<code>$.getJSON('item.json', function(data) {
        $.each(data, function (i, f) {
            if(i>0){
                $("ul").append("<li><img src=" + f.content + "/></li>");
            }

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

Body:
I have a simple JSON with 4 items. I want to just import item 2,3,4 into li in html. With my code imported all items. I am new in JavaScript.

can you please give me some possible way to solve ?

item.json:

[
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
]

HTML:

script:

Body:
Your code looks fine. If you are looking for a way to skip first record and only display 2,3 and 4 then make this change:

$.getJSON('item.json', function(data) {
        $.each(data, function (i, f) {
            if(i>0){
                $("ul").append("<li><img src=" + f.content + "/></li>");
            }

        });
   });
});


问:
How do I apply the style of all TextInputEditText of android application
I want to set custom font size of hint of TextInputEditText. I have an style which I want to apply to my all TextInputEditText.

It is not applying on my TextInputEditText. Can anyone help me where I am missing something ?

styles.xml

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Widget.Design.TextInputLayout" parent="AppTheme">
        <item name="hintTextAppearance">@style/AppTheme.TextFloatLabelAppearance</item>
    </style>

    <style name="AppTheme.TextFloatLabelAppearance" parent="TextAppearance.Design.Hint">
        <item name="android:textSize">18sp</item>
    </style>

</resources>
</code>```

AndroidManifest.xml

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".login.AuthenticationActivity"
        android:label="@string/login_screen_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

layout.xml

```<code><android.support.design.widget.TextInputLayout
    android:id="@+id/access_code_input_layout"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="@+id/guideline"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/login_participation_access_code"
        android:inputType="textPassword" />

</android.support.design.widget.TextInputLayout>
</code>```

答:
You can either directly apply app:hintTextAppearance to TextInputLayout:

```<code><android.support.design.widget.TextInputLayout
    ...
    app:hintTextAppearance="@style/AppTheme.TextFloatLabelAppearance"
    ...
    >
</code>```

Or change your activity's or application's theme in AndroidManifest.xml:

```<code>android:theme="@style/Widget.Design.TextInputLayout"
</code>```

Body:
I want to set custom font size of hint of TextInputEditText. I have an style which I want to apply to my all TextInputEditText.

It is not applying on my TextInputEditText. Can anyone help me where I am missing something ?

styles.xml

<resources>

</resources>

AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".login.AuthenticationActivity"
        android:label="@string/login_screen_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

layout.xml

<android.support.design.widget.TextInputLayout
    android:id="@+id/access_code_input_layout"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="@+id/guideline"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/login_participation_access_code"
        android:inputType="textPassword" />

</android.support.design.widget.TextInputLayout>

Body:
You can either directly apply app:hintTextAppearance to TextInputLayout:

<android.support.design.widget.TextInputLayout
    ...
    app:hintTextAppearance="@style/AppTheme.TextFloatLabelAppearance"
    ...
    >

Or change your activity's or application's theme in AndroidManifest.xml:

android:theme="@style/Widget.Design.TextInputLayout"


问:
Is there any way to insert an ImageSpan in a TextView without disrupting the text?
It seems that in order to add an ImageSpan to a Spannable in Android, I have to actually replace some text with the Image. For example:

```<code>Spannable span = new SpannableString("Foo imageplace Bar!");
Drawable android = context.getResources().getDrawable(R.drawable.android);
android.setBounds(0, 0, 32,32);
ImageSpan image = new ImageSpan(android, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 4, 14, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
</code>```

This will replace "imageplace" with the image. Because I'm dealing with complex multi-span text and reiteration, it's a bit of a headache to insert meaningless text at each place I want the android icon. But it looks like if start and end of span are the same, the image won't be included. Is there any way around this?

答:
You have to know the length of the text, the one after you want to add the image. For example..</p>

```<code>Drawable image = ContextCompat.getDrawable(mContext, android.R.drawable.presence_offline);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
// Replace blank spaces with image icon
String myText = "myText";
int textLength = myText.length();
SpannableString sb = new SpannableString(myText + "   " + "This is another text");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, textLength, textLength + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
</code>```

Body:
It seems that in order to add an ImageSpan to a Spannable in Android, I have to actually replace some text with the Image. For example:

Spannable span = new SpannableString("Foo imageplace Bar!");
Drawable android = context.getResources().getDrawable(R.drawable.android);
android.setBounds(0, 0, 32,32);
ImageSpan image = new ImageSpan(android, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 4, 14, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

This will replace "imageplace" with the image. Because I'm dealing with complex multi-span text and reiteration, it's a bit of a headache to insert meaningless text at each place I want the android icon. But it looks like if start and end of span are the same, the image won't be included. Is there any way around this?

Body:
You have to know the length of the text, the one after you want to add the image. For example..

Drawable image = ContextCompat.getDrawable(mContext, android.R.drawable.presence_offline);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
// Replace blank spaces with image icon
String myText = "myText";
int textLength = myText.length();
SpannableString sb = new SpannableString(myText + "   " + "This is another text");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, textLength, textLength + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


问:
MSDE backup file is appending
I have an MSDE 2000 database backup file which is appending rather than deleting or renaming.  I am using this command:
BACKUP DATABASE [SPSDB] TO  DISK = 'E:\Program Files\Microsoft SQL Server\MSSQL\BACKUP\SPSbackup\spsdb.bak' with retaindays = 1

I am using a maintenance plan on my full SQL version databases, and they create a new file everyday with the date in the file name.

The backup file size creeps up on me if I don't monitor it. Is there a way to have MSDE make a uniue file with the daily backup job I created?

Thanks,
Chad

答:
Take a look at http://msdn.microsoft.com/en-us/library/ms186865.aspx for the BACKUP command. Did you try using INIT option?

I noticed the question is very old, but maybe my answer can help somenone.

OwnerDisplayName: Chad

ContentLicense: CC BY-SA 2.5

Title: MSDE backup file is appending


问:
How to avoid deadlock when the called method uses the same lock that the caller already locked?
How to avoid deadlock when the called method uses the same lock that the caller already locked?

I have and method called closeUnusedConnections(), that creates a std::unique_lock but its caller already created a std::unique_lock with the same std::mutex: Foo::m_myMutex.

Do I have to release the lock before calling the subroutine?

Obs.: I can't integrate both methods because the  closeUnusedConnections is also called independently.

Some code:

```<code>void Foo::closeUnusedConnections()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
}

Foo::CommNodePtr Foo::getConnection()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
   if( true /*some condition*/ )
   {
      lock.unlock();     // The goal is to avoid this unlock
                         // someone could get the lock between
                         // this unlock until closeUnusedConnections's lock.
      closeUnusedConnections();
   }
   // etc
}
</code>```

答:
Create a private function that does the work without grabbing the lock

```<code>//call with m_mtx locked
void Foo::unlockedCloseUnusedConnections()
{
   // do stuff
}
</code>```

Your public function just becomes

```<code> void Foo::closeUnusedConnections()
 {
     std::unique_lock< std::mutex > lock( m_mtx );
     unlockedCloseUnusedConnections();
 }
</code>```

Your Foo::getConnection() function calls unlockedCloseUnusedConnections() , since it has already taken the lock.

Body:
How to avoid deadlock when the called method uses the same lock that the caller already locked?

I have and method called closeUnusedConnections(), that creates a std::unique_lock but its caller already created a std::unique_lock with the same std::mutex: Foo::m_myMutex.

Do I have to release the lock before calling the subroutine?

Obs.: I can't integrate both methods because the  closeUnusedConnections is also called independently.

Some code:

void Foo::closeUnusedConnections()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
}

Foo::CommNodePtr Foo::getConnection()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
   if( true /*some condition*/ )
   {
      lock.unlock();     // The goal is to avoid this unlock
                         // someone could get the lock between
                         // this unlock until closeUnusedConnections's lock.
      closeUnusedConnections();
   }
   // etc
}

Body:
Create a private function that does the work without grabbing the lock

//call with m_mtx locked
void Foo::unlockedCloseUnusedConnections()
{
   // do stuff
}

Your public function just becomes

 void Foo::closeUnusedConnections()
 {
     std::unique_lock< std::mutex > lock( m_mtx );
     unlockedCloseUnusedConnections();
 }

Your Foo::getConnection() function calls unlockedCloseUnusedConnections() , since it has already taken the lock.


问:
amazon redshift copy command json format
I'm trying to copy into Redshift some json files with the following structure:

```<code>{
"data": [{
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3",
},
{
    "attr1": "value4",
    "attr2": "value5",
    "attr3": "value6",
}]
}
</code>```

The number of array elements is variable.

I've tried using the following jsonpath, but it doesn't work:

```<code>{
"jsonpaths": [
    "$.data[*].attr1",
    "$.data[*].attr2",
    "$.data[*].attr3"
]
}
</code>```

If I use the following jsonpath, it only loads the first object in the array:

```<code>{
"jsonpaths": [
    "$.data[0].attr1",
    "$.data[0].attr2",
    "$.data[0].attr3"
]
}
</code>```

Is there a way to do this?

Thanks!

答:
Your data structure is not quite right. For jsonpaths loading Redshift does not actually want the entire file to be one json structure. Each record is its own structure. So no commas separate records.

The top level elements for each record can either be all objects{} or arrays [], but the records are complete json structures and are separated by newlines and not commas. Check out this page for examples.

For your example like this:

```<code>{"data": {
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
}}
{"data": {
    "attr1": "value4",
    "attr2": "value5",
    "attr3": "value6"
}}
</code>```

{"jsonpaths": ["$.data.attr1", "$.data.attr2", "$.data.attr3"]}

or just:

```<code>{
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
}
{
    "attr1": "value4",
    "attr2": "value5",
    "attr3": "value6"
}
</code>```

{"jsonpaths": ["$.attr1", "$.attr2", "$.attr3"]}

Body:
I'm trying to copy into Redshift some json files with the following structure:

{
"data": [{
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3",
},
{
    "attr1": "value4",
    "attr2": "value5",
    "attr3": "value6",
}]
}

The number of array elements is variable.

I've tried using the following jsonpath, but it doesn't work:

{
"jsonpaths": [
    "$.data[*].attr1",
    "$.data[*].attr2",
    "$.data[*].attr3"
]
}

If I use the following jsonpath, it only loads the first object in the array:

{
"jsonpaths": [
    "$.data[0].attr1",
    "$.data[0].attr2",
    "$.data[0].attr3"
]
}

Is there a way to do this?

Thanks!

Body:
Your data structure is not quite right. For jsonpaths loading Redshift does not actually want the entire file to be one json structure. Each record is its own structure. So no commas separate records.

The top level elements for each record can either be all objects{} or arrays [], but the records are complete json structures and are separated by newlines and not commas. Check out this page for examples.

For your example like this:

{"data": {
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
}}
{"data": {
    "attr1": "value4",
    "attr2": "value5",
    "attr3": "value6"
}}

{"jsonpaths": ["$.data.attr1", "$.data.attr2", "$.data.attr3"]}

or just:

{
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
}
{
    "attr1": "value4",
    "attr2": "value5",
    "attr3": "value6"
}

{"jsonpaths": ["$.attr1", "$.attr2", "$.attr3"]}


问:
What to do when package version cannot be found however I can see it on nuget.org?
I have a project where I need Microsoft.TeamFoundation.DistributedTask.Common.Contracts. According to nuget.org there is a 15.114.0-preview package. But, Visual Studio says that there is no package like this.

I clean all local cache and doesn't help.

How can I solve it? Generally, how much time is needed for a package to go through the spreading process if there is any?

答:
You seem to be looking at the wrong package in Visual Studio Package manager window.

Microsoft.TeamFoundation.DistributedTask.Common.Contracts has latest version as 15.114.0-preview

while Microsoft.TeamFoundation.DistributedTask.Common has latest version as 15.112.1

Hope this helps.

-AG.


问:
trying to update a row from one table to another
```<code>UPDATE customer_service.batch_status.cust_nm
SET batch_status.cust_nm
SELECT customer_service.batch_detail.cust_nm
FROM   customer_service.batch_detail
LEFT JOIN customer_service.batch_status
    ON customer_service.batch_detail.cust_nm = customer_service.batch_status.cust_nm;
</code>```

答:
Your syntax is off.

Instead:

```<code>UPDATE customer_service.batch_status.cust_nm
FROM customer_service.batch_detail csbd
SET cust_nm = csbd.cust_nm
WHERE csbd.cust_nm = customer_service.batch_status.cust_nm;
</code>```

Body:
Your syntax is off.

Instead:

UPDATE customer_service.batch_status.cust_nm
FROM customer_service.batch_detail csbd
SET cust_nm = csbd.cust_nm
WHERE csbd.cust_nm = customer_service.batch_status.cust_nm;


问:
jboss-cli : How do I read one specific system property using jboss-cli?
I'm new to jboss-cli and working through the 'jboss-cli recipes'.

Question

How do I read one specific property using jboss-cli? E.g.

jboss.home.dir (e.g. "-Djboss.home.dir=/path/to/my/jboss")

Xmx ("-Xmx=4G")

Context

The "CLI Recipes" documentation has this helpful example to get all system properties. However its 'too much infomration'. I want to script reading one specific property.

https://docs.jboss.org/author/display/WFLY10/CLI+Recipes#CLIRecipes-

Overview of all system properties in JBoss AS7+ including OS system
  properties and properties specified on command line using -D, -P or
  --properties arguments.

```<code>Standalone
[standalone@IP_ADDRESS:9999 /] /core-service=platform-mbean/type=runtime:read-attribute(name=system-properties)
</code>```

Thanks in advance

答:
You could do a :

:resolve-expression(expression=${jboss.home.dir})

Body:
I'm new to jboss-cli and working through the 'jboss-cli recipes'.

Question

How do I read one specific property using jboss-cli? E.g.

jboss.home.dir (e.g. "-Djboss.home.dir=/path/to/my/jboss")

Xmx ("-Xmx=4G")

Context

The "CLI Recipes" documentation has this helpful example to get all system properties. However its 'too much infomration'. I want to script reading one specific property.

https://docs.jboss.org/author/display/WFLY10/CLI+Recipes#CLIRecipes-

Overview of all system properties in JBoss AS7+ including OS system
  properties and properties specified on command line using -D, -P or
  --properties arguments.

Standalone
[standalone@IP_ADDRESS:9999 /] /core-service=platform-mbean/type=runtime:read-attribute(name=system-properties)

Thanks in advance


问:
How to debug Gitlab LDAP authentication?
I am trying to configure LDAP authentication with gitlab. My configuration is someting like:

```<code>ldap:
    enabled: true
    host: 'ldap.example.com'
    base: 'ou=People,o=example.com'
    port: 636
    uid: 'uid'
    method: 'ssl' # "ssl" or "plain"
    bind_dn: 'cn=gitlab,ou=Apps,o=example.com'
    password: 'password'
    allow_username_or_email_login: true
</code>```

I tested it with the following :

```<code>ldapsearch  -b "ou=People,o=example.com" -s sub -D "cn=gitlab,ou=Apps,o=example.com" -H ldaps://ldap.example.com:636 -w "password" -x "(uid=myname@example.com)"
</code>```

The line above works, but when I try to log in using LDAP, I always got "invalid credentials".

How can I troubleshoot this and narrow down the root cause f this problem?

Edit 26/09:

Here are some things I found on production.log:

```<code>Started GET "/users/sign_in" for 127.0.0.1 at 2013-09-23 17:42:58 -0300
Processing by Devise::SessionsController#new as HTML
  Rendered devise/sessions/_new_ldap.html.haml (1.7ms)
  Rendered devise/sessions/_new_base.html.haml (1.8ms)
  Rendered devise/sessions/_oauth_providers.html.haml (0.0ms)
  Rendered devise/sessions/new.html.haml within layouts/devise (4.2ms)
  Rendered layouts/_head.html.haml (1.6ms)
  Rendered layouts/_flash.html.haml (0.1ms)
Completed 200 OK in 9ms (Views: 6.9ms | ActiveRecord: 0.0ms)
Started POST "/users/auth/ldap/callback" for 127.0.0.1 at 2013-09-23 17:43:00 -0300
Processing by OmniauthCallbacksController#failure as HTML
  Parameters: {"utf8"=>"â", "authenticity_token"=>"AwqZsVHRqOeZr+GLWWeGM7MyOAdk7cFl8/rZgbVRU+8=", "username"=>"name@example.com", "password"=>"[FILTERED]"}
Redirected to http://example.com/users/sign_in
Completed 302 Found in 3ms (ActiveRecord: 0.0ms)
Started GET "/users/sign_in" for 127.0.0.1 at 2013-09-23 17:43:00 -0300
Processing by Devise::SessionsController#new as HTML
  Rendered devise/sessions/_new_base.html.haml (2.8ms)
  Rendered devise/sessions/_oauth_providers.html.haml (0.1ms)
  Rendered devise/sessions/new.html.haml within layouts/devise (3.7ms)
  Rendered layouts/_head.html.haml (1.7ms)
  Rendered layouts/_flash.html.haml (0.1ms)
Completed 200 OK in 9ms (Views: 6.6ms | ActiveRecord: 0.0ms)
Started GET "/" for 127.0.0.1 at 2013-09-23 18:50:08 -0300
Processing by DashboardController#show as HTML
Completed 401 Unauthorized in 1ms
</code>```

Edit: I finally got the answer: a configuration on devise was stripping everyting after the "@". I can't recall the exact name, but I can post as soon as I got access to the machine. I discovered this by adding logs to the ldap oauth login.

答:
I see you found the solution for your scenario, but I thought I'd include some additional troubleshooting steps for others who run into authentication issues with GitLab & LDAP.

Run GitLab's LDAP rake check to localize the problem. https://docs.gitlab.com/ce/administration/raketasks/ldap.html#check. There's also a more comprehensive one that's listed in the GitLab install document you're using.

If using SELinux, set it to permissive mode.

If using Apache with GitLab: Install LDAP - Apache Directory Studio
and try to establish a connection. If you can't then something is
probably wrong in your config.yml file. I'd start by looking at the
base.

Run tcpdump and import the .pcap file into WireShark for inspection.

Review logs on your LDAP server and your GitLab server

Body:
I am trying to configure LDAP authentication with gitlab. My configuration is someting like:

ldap:
    enabled: true
    host: 'ldap.example.com'
    base: 'ou=People,o=example.com'
    port: 636
    uid: 'uid'
    method: 'ssl' # "ssl" or "plain"
    bind_dn: 'cn=gitlab,ou=Apps,o=example.com'
    password: 'password'
    allow_username_or_email_login: true

I tested it with the following :

ldapsearch  -b "ou=People,o=example.com" -s sub -D "cn=gitlab,ou=Apps,o=example.com" -H ldaps://ldap.example.com:636 -w "password" -x "(uid=myname@example.com)"

The line above works, but when I try to log in using LDAP, I always got "invalid credentials".

How can I troubleshoot this and narrow down the root cause f this problem?

Edit 26/09:

Here are some things I found on production.log:

Started GET "/users/sign_in" for 127.0.0.1 at 2013-09-23 17:42:58 -0300
Processing by Devise::SessionsController#new as HTML
  Rendered devise/sessions/_new_ldap.html.haml (1.7ms)
  Rendered devise/sessions/_new_base.html.haml (1.8ms)
  Rendered devise/sessions/_oauth_providers.html.haml (0.0ms)
  Rendered devise/sessions/new.html.haml within layouts/devise (4.2ms)
  Rendered layouts/_head.html.haml (1.6ms)
  Rendered layouts/_flash.html.haml (0.1ms)
Completed 200 OK in 9ms (Views: 6.9ms | ActiveRecord: 0.0ms)
Started POST "/users/auth/ldap/callback" for 127.0.0.1 at 2013-09-23 17:43:00 -0300
Processing by OmniauthCallbacksController#failure as HTML
  Parameters: {"utf8"=>"â", "authenticity_token"=>"AwqZsVHRqOeZr+GLWWeGM7MyOAdk7cFl8/rZgbVRU+8=", "username"=>"name@example.com", "password"=>"[FILTERED]"}
Redirected to http://example.com/users/sign_in
Completed 302 Found in 3ms (ActiveRecord: 0.0ms)
Started GET "/users/sign_in" for 127.0.0.1 at 2013-09-23 17:43:00 -0300
Processing by Devise::SessionsController#new as HTML
  Rendered devise/sessions/_new_base.html.haml (2.8ms)
  Rendered devise/sessions/_oauth_providers.html.haml (0.1ms)
  Rendered devise/sessions/new.html.haml within layouts/devise (3.7ms)
  Rendered layouts/_head.html.haml (1.7ms)
  Rendered layouts/_flash.html.haml (0.1ms)
Completed 200 OK in 9ms (Views: 6.6ms | ActiveRecord: 0.0ms)
Started GET "/" for 127.0.0.1 at 2013-09-23 18:50:08 -0300
Processing by DashboardController#show as HTML
Completed 401 Unauthorized in 1ms

Edit: I finally got the answer: a configuration on devise was stripping everyting after the "@". I can't recall the exact name, but I can post as soon as I got access to the machine. I discovered this by adding logs to the ldap oauth login.

ContentLicense: CC BY-SA 4.0


问:
A cross platform process manager tool
I need a program that is able to launch a set of processes according to a schedule/configuration; the program would run in the background and restart the processes in case they crash.

There are standard tools for this kind of task on both windows and unix - what I need is a cross platform program which could run on different operating systems using the same configuration.

Any portable C/C++ library which implements the basic functionality (i.e. create processes, signal process termination events etc) would be ok too.

答:
What about installing ssh servers on all those platforms and handle the start/stop of processes by means of every platform own command line tools?

To be able to access without prompt authentication I would use asymmetric key authentication without password so access would be immediate from a controlling machine to all the hosts managed.

So my solution would be a home-made one consisting of a bunch of scripts (.bat or .sh or whatever scripting language you want) and several ssh servers.

OwnerDisplayName: lvlv

Title: A cross platform process manager tool

OwnerDisplayName: Fernando Miguélez


答:
Use array shift() or if statement

```<code><script>
    $(document).ready( function(){

    $.getJSON('item.json', function(data) {
        data.shift();
        $.each(data, function (i, f) {
            $("ul").append("<li><img src=" + f.content + "/></li>");
        });
     });
   });
</script>
</code>```

if statement

```<code>$.each(data, function (i, f) {
   if(f.content != "nopic"){
      $("ul").append("<li><img src=" + f.content + "/></li>");
   }
});
</code>```

Title: how to retrieve data from JSON into list?

Body:
Use array shift() or if statement

<script>
    $(document).ready( function(){

    $.getJSON('item.json', function(data) {
        data.shift();
        $.each(data, function (i, f) {
            $("ul").append("<li><img src=" + f.content + "/></li>");
        });
     });
   });
</script>

if statement

$.each(data, function (i, f) {
   if(f.content != "nopic"){
      $("ul").append("<li><img src=" + f.content + "/></li>");
   }
});


问:
Displaying values above certain number in array and counting how many values there are
Need to count how many values that are equal or above 5. This is my best guess, but it's not even close to working.</p>

```<code>$array = array(1,4,8,1,4,10,5,6,2,4,6);
$x=0;

while ($x < count($array)){
    if($array[$x]>=5){
        $amount = array_count_values($array[$x]);
        echo $amout;
    }
    $x += 1;
}
</code>```

答:
Replace your loop with</p>

```<code>foreach($array as $thing)
    if($thing >=5){
            $x += 1;
    }
}
</code>```

Body:
Need to count how many values that are equal or above 5. This is my best guess, but it's not even close to working.

$array = array(1,4,8,1,4,10,5,6,2,4,6);
$x=0;

while ($x < count($array)){
    if($array[$x]>=5){
        $amount = array_count_values($array[$x]);
        echo $amout;
    }
    $x += 1;
}

Body:
Replace your loop with

foreach($array as $thing)
    if($thing >=5){
            $x += 1;
    }
}


问:
fabric8 springboot full example
I am trying to figure out how to build a spring boot docker image using fabric8 docker-maven-plugin. The documentation contains bit and bytes and I'm obviously missing something. Does anyone have a full pom.xml example for it?</p>

答:
The fabric8-maven-plugin documentation is pretty hard to dig through if you just want to get started quickly, so here's a quick example for everything you need to get a Docker image built.

First, make sure docker is on your path and the Docker daemon is running. Run docker ps and ensure a response like this:

```<code>CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
</code>```

Add this to your pom.xml and run this with mvn clean package docker:build

<build>
    <plugins>
        <plugin>
            <groupId>io.fabric8</groupId>
            <artifactId>fabric8-maven-plugin</artifactId>
            <configuration>
                <verbose>true</verbose>
                <images>
                    <image>

                        <name>your-project-name:${project.version}</name>

                        <build>

                            <from>vixns/java8</from>

                            <entryPoint>
                                <exec>
                                    <arg>java</arg>

                                    <arg>-Djava.security.egd=file:/dev/./urandom</arg>
                                    <arg>-jar</arg>

                                    <arg>/maven/${project.artifactId}.${project.packaging}</arg>
                                </exec>
                            </entryPoint>

                            <assembly>

                                <descriptorRef>artifact</descriptorRef>
                            </assembly>
                        </build>
                    </image>
                </images>
            </configuration>
        </plugin>
    </plugins>
</build>
```

Note: you'll need additional setup if you want to use the mvn docker:start command. You don't have to use it, you can use the standard docker command if you'd like.

Title: fabric8 springboot full example

Body:
The fabric8-maven-plugin documentation is pretty hard to dig through if you just want to get started quickly, so here's a quick example for everything you need to get a Docker image built.

First, make sure docker is on your path and the Docker daemon is running. Run docker ps and ensure a response like this:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

Add this to your pom.xml and run this with mvn clean package docker:build

<build>
    <plugins>
        <plugin>
            <groupId>io.fabric8</groupId>
            <artifactId>fabric8-maven-plugin</artifactId>
            <configuration>
                <verbose>true</verbose>
                <images>
                    <image>
                        <!-- Replace your-project-name -->
                        <name>your-project-name:${project.version}</name>

                        <build>

                            <!-- This is the same FROM used in a Dockerfile -->
                            <from>vixns/java8</from>

                            <!-- This is the same ENTRYPOINT used in a Dockerfile -->
                            <entryPoint>
                                <exec>
                                    <arg>java</arg>
                                    <!-- This extra argument is so Tomcat can start faster due to lack of entropy -->
                                    <arg>-Djava.security.egd=file:/dev/./urandom</arg>
                                    <arg>-jar</arg>
                                    <!-- /maven/ is the default dir that the plugin copies your artifact to -->
                                    <arg>/maven/${project.artifactId}.${project.packaging}</arg>
                                </exec>
                            </entryPoint>

                            <assembly>
                                <!-- This is a predefined assembly.xml that will only copy your final artifact to the Docker image -->
                                <descriptorRef>artifact</descriptorRef>
                            </assembly>
                        </build>
                    </image>
                </images>
            </configuration>
        </plugin>
    </plugins>
</build>

Note: you'll need additional setup if you want to use the mvn docker:start command. You don't have to use it, you can use the standard docker command if you'd like.


问:
Bootstrap 4 align elements right inside a col div
My question is pretty simple but I don't find a proper way (I mean not use absolute positionning of sub elements inside a relative position container) to achieve this in Bootstrap 4.

I have a row with a col-8 and a col-4. My content in col-4 must be right aligned so its content is at the right border.

```<code><h1 class="col-md-8">Applications portfolio</h1>

  <div class="btn-group col-md-4" role="group">
    <p class="float-right">
      <a class="btn btn-secondary btn-md" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
    </p>
  </div>
</code>```

Here is a codepen:

https://codepen.io/anon/pen/QpzVgJ

I want my two buttons to right align within the col-4.

How in Bootstrap 4 to properly align right elements within a col?

答:
Use ml-auto to push the buttons to the right...

https://codepen.io/anon/pen/evbLQN

```<code><div class="btn-group col-md-4" role="group">
    <p class="ml-auto">
      <a class="btn btn-secondary btn-md" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
    </p>
</div>
</code>```

Another option is to remove the btn-group from the col-md-4, and then float-right will work as expected. The pull-right class was replaced by float-right in Bootstrap 4.

```<code><section class="row">
  <h1 class="col-md-8">Applications portfolio</h1>

  <div class="col-md-4" role="group">
    <p class="float-right">
      <a class="btn btn-secondary btn-md" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
    </p>
  </div>
</section>
</code>```

PS - To prevent the horizontal scrollbar visible in your Codepen, make sure the .row is placed inside a container-fluid. Also, generally col-* are used to contain content, and shouldn't be applied to other components/elements. So, for example if you wanted to use the btn-group..

```<code><div class="container-fluid">
    <section class="row">
        <div class="col-md-8">
            <h1>Applications portfolio</h1>
        </div>
        <div class="col-md-4">
            <div class="btn-group float-right mt-2" role="group">
                <a class="btn btn-secondary btn-md" href="#">
                    <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
                <a class="btn btn-md btn-secondary" href="#">
                    <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
            </div>
        </div>
    </section>
</div>
</code>```

http://www.codeply.com/go/8OYDK5D8Db

Related: Right align element in div class with bootstrap 4

Body:
My question is pretty simple but I don't find a proper way (I mean not use absolute positionning of sub elements inside a relative position container) to achieve this in Bootstrap 4.

I have a row with a col-8 and a col-4. My content in col-4 must be right aligned so its content is at the right border.

Applications portfolio

         Creation

         Report

Here is a codepen:

https://codepen.io/anon/pen/QpzVgJ

I want my two buttons to right align within the col-4.

How in Bootstrap 4 to properly align right elements within a col?

Body:
Use ml-auto to push the buttons to the right...

https://codepen.io/anon/pen/evbLQN

<div class="btn-group col-md-4" role="group">
    <p class="ml-auto">
      <a class="btn btn-secondary btn-md" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
    </p>
</div>

Another option is to remove the btn-group from the col-md-4, and then float-right will work as expected. The pull-right class was replaced by float-right in Bootstrap 4.

<section class="row">
  <h1 class="col-md-8">Applications portfolio</h1>

  <div class="col-md-4" role="group">
    <p class="float-right">
      <a class="btn btn-secondary btn-md" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
    </p>
  </div>
</section>

PS - To prevent the horizontal scrollbar visible in your Codepen, make sure the .row is placed inside a container-fluid. Also, generally col-* are used to contain content, and shouldn't be applied to other components/elements. So, for example if you wanted to use the btn-group..

<div class="container-fluid">
    <section class="row">
        <div class="col-md-8">
            <h1>Applications portfolio</h1>
        </div>
        <div class="col-md-4">
            <div class="btn-group float-right mt-2" role="group">
                <a class="btn btn-secondary btn-md" href="#">
                    <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
                <a class="btn btn-md btn-secondary" href="#">
                    <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
            </div>
        </div>
    </section>
</div>

http://www.codeply.com/go/8OYDK5D8Db

Related: Right align element in div class with bootstrap 4


问:
Get option value from select tag in jQuery
I have a select tag on my page. I want to get the value 1 from <option value="1"> here using jquery to process an ajax request. How can I get so?

Here is a sample code

```<code><select name="duration">
    <option value='01'>This is Value 1</option>
    <option value='02'>This is Value 2</option>
    <option value='03'>This is Value 3</option>
    <option value='04'>This is Value 4</option>
</select>
</code>```

I want to get the 01, 02, 03 or 04 (whichever is selected in case) from the select tag. How can I do so?

I tried using $("select[name='duration'] option:selected").text() but this returns me This is Value 1 instead of 01 (the actual field value). Please help.

Body:
I have a select tag on my page. I want to get the value 1 from <option value="1"> here using jquery to process an ajax request. How can I get so?

Here is a sample code

<select name="duration">
    <option value='01'>This is Value 1</option>
    <option value='02'>This is Value 2</option>
    <option value='03'>This is Value 3</option>
    <option value='04'>This is Value 4</option>
</select>

I want to get the 01, 02, 03 or 04 (whichever is selected in case) from the select tag. How can I do so?

I tried using $("select[name='duration'] option:selected").text() but this returns me This is Value 1 instead of 01 (the actual field value). Please help.

Body: $("select[name='duration']").val()


问:
Read and write file over SSH in python 3.5
I have been unsuccessful in finding a way to read a file from a remote server over ssh and then writing a similar file in the same way. Paramiko doesn't seem to work with 3.5 and i'm not sure what else i can do.

Example of what i'm trying to do:

```<code>from shutil import copyfile
copyfile('10.1.1.5:v3/ec/s//01_inventory.txt', '10.1.1.5:v3/ec/s//01_inventory_Bkup.txt')
</code>```

答:
You could use scp I suppose (https://ss64.com/bash/scp.html). You would have something like this to replace your copyfile call:

```<code>import subprocess

subprocess.call("scp 10.1.1.5:v3/ec/s/01_inventory.txt 10.1.1.5:v3/ec/s/01_inventory_Bkup.txt", shell=True)
</code>```

You could also use scp to copy to your local host, modify it as you would normally and then replace the original.

Body:
I have been unsuccessful in finding a way to read a file from a remote server over ssh and then writing a similar file in the same way. Paramiko doesn't seem to work with 3.5 and i'm not sure what else i can do.

Example of what i'm trying to do:

from shutil import copyfile
copyfile('10.1.1.5:v3/ec/s//01_inventory.txt', '10.1.1.5:v3/ec/s//01_inventory_Bkup.txt')

Body:
You could use scp I suppose (https://ss64.com/bash/scp.html). You would have something like this to replace your copyfile call:

import subprocess

subprocess.call("scp 10.1.1.5:v3/ec/s/01_inventory.txt 10.1.1.5:v3/ec/s/01_inventory_Bkup.txt", shell=True)

You could also use scp to copy to your local host, modify it as you would normally and then replace the original.


问:
Suppressing SUCCESS alert boxes?
I have three functions that called as shown below (Functions not included):

Code:

```<code>$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSourcepData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSpouseData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSpousData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllDividentData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveDividentData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
</code>```

When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".

This forces user to have to close three popup boxes.

Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?

答:
You could also simplified your code by using Promise.all:</p>

```<code>$("#btnSubmit").click(function() {

     var allSourcepData = JSON.stringify(getAllSourcepData());
     var allSpouseData = JSON.stringify(getAllSpouseData());
     var allDividentData = JSON.stringify(getAllDividentData());

     Promise.all([

        getData('closures.aspx/SaveSourceData', allSourcepData),
        getData('closures.aspx/SaveSpousData', allSpouseData),
        getData('closures.aspx/SaveDividentData', allDividentData)
      ])
      .then( alert )
      .catch( alert )
});

function getData(url, data)
{
     return new Promise((resolve, reject){
        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({
                'empdata': data
            }),
            success: () => { resolve("Data Added Successfully") },
            error: () => { reject("Error while inserting data"); }

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

Title: Suppressing SUCCESS alert boxes?

Body:
I have three functions that called as shown below (Functions not included):

Code:

$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSourcepData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSpouseData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSpousData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllDividentData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveDividentData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});

When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".

This forces user to have to close three popup boxes.

Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?

Body:
You could also simplified your code by using Promise.all:

$("#btnSubmit").click(function() {

     var allSourcepData = JSON.stringify(getAllSourcepData());
     var allSpouseData = JSON.stringify(getAllSpouseData());
     var allDividentData = JSON.stringify(getAllDividentData());

     Promise.all([

        getData('closures.aspx/SaveSourceData', allSourcepData),
        getData('closures.aspx/SaveSpousData', allSpouseData),
        getData('closures.aspx/SaveDividentData', allDividentData)
      ])
      .then( alert )
      .catch( alert )
});

function getData(url, data)
{
     return new Promise((resolve, reject){
        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({
                'empdata': data
            }),
            success: () => { resolve("Data Added Successfully") },
            error: () => { reject("Error while inserting data"); }

        });
    })
  }


问:
Anaconda is not creating full environment

I'm trying to create a conda environment using git-bash and win10. I ran:

```<code>$ conda create --name my_env
</code>```

The result looks like the screenshot above.

Looking at other environments , I can see they normally look like:

How can I fix this?

答:
You have to use this to get all of the Anaconda default packages:

```<code>conda create --name my_env anaconda
</code>```

Otherwise, it doesn't install everything.

Body:
I'm trying to create a conda environment using git-bash and win10. I ran:

$ conda create --name my_env

The result looks like the screenshot above.

Looking at other environments , I can see they normally look like:

How can I fix this?

Body:
You have to use this to get all of the Anaconda default packages:

conda create --name my_env anaconda

Otherwise, it doesn't install everything.


问:
Maven assembly : add different version of the same artifact
I create my application archive with the maven assembly plugin.
All the dependency present in my pom are included without any problem.

Now I need to include two or more version of the same artifact.

If in my pom I put

```<code><dependencies>
        [...]
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.1.0</version>
        </dependency>
</dependencies>
</code>```

Of source the dependenvcy resolver remove the old version and only the 1.1.0 is packaged in the archive

I try to include the jar by using assembly xml descriptor file. And I didn't find any solution.

A possible solution will be to manually put all the needed model.jar inside a folder and tell the assembly to copy it in the archive. But I'm looking for a more configurable solution.

Any idea ?

答:
I found a solution by using maven-dependency-plugin to copy resolved pom dependencies and additional jar.

```<code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
    <execution>
        <id>copy-dependencies</id>
        <phase>package</phase>
        <goals>
            <goal>copy-dependencies</goal>
        </goals>
        <configuration>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
            <overWriteReleases>false</overWriteReleases>
            <overWriteSnapshots>false</overWriteSnapshots>
            <overWriteIfNewer>true</overWriteIfNewer>
            <includeScope>runtime</includeScope>
        </configuration>
    </execution>
    <execution>
        <id>copy-model</id>
        <phase>package</phase>
        <goals>
            <goal>copy</goal>
        </goals>
        <configuration>
            <artifactItems>
                <artifactItem>
                    <groupId>my.test.pkg</groupId>
                    <artifactId>my-model</artifactId>
                    <classifier>server</classifier>
                    <version>1.0.3</version>
                    <type>jar</type>
                </artifactItem>
                <artifactItem>
                    <groupId>my.test.pkg</groupId>
                    <artifactId>my-model</artifactId>
                    <classifier>server</classifier>
                    <version>1.1.0</version>
                    <type>jar</type>
                </artifactItem>
            </artifactItems>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
        </configuration>
    </execution>
</executions>
</code>```

Now I just have to add the following lines in my assembly xml

```<code>    <fileSet>
        <directory>${project.build.directory}/lib</directory>
        <outputDirectory>/lib</outputDirectory>
        <filtered>false</filtered>
        <includes>
            <include>*.jar</include>
        </includes>
        <fileMode>0600</fileMode>
    </fileSet>
</code>```

Body:
I create my application archive with the maven assembly plugin.
All the dependency present in my pom are included without any problem.

Now I need to include two or more version of the same artifact.

If in my pom I put

<dependencies>
        [...]
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.1.0</version>
        </dependency>
</dependencies>

Of source the dependenvcy resolver remove the old version and only the 1.1.0 is packaged in the archive

I try to include the jar by using assembly xml descriptor file. And I didn't find any solution.

A possible solution will be to manually put all the needed model.jar inside a folder and tell the assembly to copy it in the archive. But I'm looking for a more configurable solution.

Any idea ?

Body:
I found a solution by using maven-dependency-plugin to copy resolved pom dependencies and additional jar.

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
    <execution>
        <id>copy-dependencies</id>
        <phase>package</phase>
        <goals>
            <goal>copy-dependencies</goal>
        </goals>
        <configuration>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
            <overWriteReleases>false</overWriteReleases>
            <overWriteSnapshots>false</overWriteSnapshots>
            <overWriteIfNewer>true</overWriteIfNewer>
            <includeScope>runtime</includeScope>
        </configuration>
    </execution>
    <execution>
        <id>copy-model</id>
        <phase>package</phase>
        <goals>
            <goal>copy</goal>
        </goals>
        <configuration>
            <artifactItems>
                <artifactItem>
                    <groupId>my.test.pkg</groupId>
                    <artifactId>my-model</artifactId>
                    <classifier>server</classifier>
                    <version>1.0.3</version>
                    <type>jar</type>
                </artifactItem>
                <artifactItem>
                    <groupId>my.test.pkg</groupId>
                    <artifactId>my-model</artifactId>
                    <classifier>server</classifier>
                    <version>1.1.0</version>
                    <type>jar</type>
                </artifactItem>
            </artifactItems>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
        </configuration>
    </execution>
</executions>

Now I just have to add the following lines in my assembly xml

    <fileSet>
        <directory>${project.build.directory}/lib</directory>
        <outputDirectory>/lib</outputDirectory>
        <filtered>false</filtered>
        <includes>
            <include>*.jar</include>
        </includes>
        <fileMode>0600</fileMode>
    </fileSet>


问:
Eclipse Compare Dialog
I wrote a plugin for Eclipse that need to compare two existing .java files.
I want to open a "Compare with Other Resources" dialog from code, but i cant find any tutorials for that.
Can anyone help me?</p>

答:
```<code>FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.html"});
dialog.setFilterPath("c:\\temp");
String result = dialog.open();
</code>```

https://wiki.eclipse.org/FAQ_How_do_I_prompt_the_user_to_select_a_file_or_a_directory%3F

But how is your plugin structured? Extends a view? Are you using the jdt classes to select resources from a project?

EDIT

http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fcompare%2FCompareUI.html

This class is probably a good starting point. A search on bugzilla in eclipse:

https://bugs.eclipse.org/bugs/attachment.cgi?id=108951

states this class as internal. It may not be wise to use it

Title: Eclipse Compare Dialog

Body:
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.html"});
dialog.setFilterPath("c:\\temp");
String result = dialog.open();

https://wiki.eclipse.org/FAQ_How_do_I_prompt_the_user_to_select_a_file_or_a_directory%3F

But how is your plugin structured? Extends a view? Are you using the jdt classes to select resources from a project?

EDIT

http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fcompare%2FCompareUI.html

This class is probably a good starting point. A search on bugzilla in eclipse:

https://bugs.eclipse.org/bugs/attachment.cgi?id=108951

states this class as internal. It may not be wise to use it


问:
Writing javascript in the codemirror source view of froala, then switching back to visual mode, causes the javascript to execute
When using froala 2.3.4, I found some issues where it stripped out a bunch of valid code such as

答:
On summernote.js search the line:

```<code>$editable.html(dom.html($note) || dom.emptyPara);
</code>```

and replace it with:

```<code>var str = dom.html($note) || dom.emptyPara;
str = str.replace('<script>', '<scriptfalse>');
str = str.replace('<script ', '<scriptfalse ');
str = str.replace('</script>', '</scriptfalse>');
$editable.html(str);
</code>```

And also search the line:

```<code>$note.val(context.invoke('code'));
</code>```

and replace it with:

```<code>var str = context.invoke('code');
str = str.replace('<scriptfalse>', '<script>');
str = str.replace('<scriptfalse ', '<script ');
str = str.replace('</scriptfalse>', '</script>');
$note.val(str);
</code>```

Body:
On summernote.js search the line:

$editable.html(dom.html($note) || dom.emptyPara);

and replace it with:

var str = dom.html($note) || dom.emptyPara;
str = str.replace('<script>', '<scriptfalse>');
str = str.replace('<script ', '<scriptfalse ');
str = str.replace('</script>', '</scriptfalse>');
$editable.html(str);

And also search the line:

$note.val(context.invoke('code'));

and replace it with:

var str = context.invoke('code');
str = str.replace('<scriptfalse>', '<script>');
str = str.replace('<scriptfalse ', '<script ');
str = str.replace('</scriptfalse>', '</script>');
$note.val(str);


问:
How to display custom attribute in cart (Magento)
I have tried a lot of stuf but none of them work. I think I can get the custom attributes on the product page, but I was wondering: how to get them in shopping cart page? (the attribute is just a simple written text)</p>

答:
Following all the contributions I've taken the 1st answer and wondered arround magento.

I found a solution that I didn't have to make the load() again. I've edited the file config.xml on the following path,

```<code>app/code/core/Mage/Sales/etc/config.xml
</code>```

and on the item / product attributes I've added the custom attribute

```<code><item>
    <product attributes>
        <sku/>
        <type_id/>
        <my_custom_attribute_id/>
</code>```

then on my cart.phtml file I was able to get the attribute just by using:

```<code>$_item->getProduct()->getmy_custom_attribute_id();
</code>```

I don't know if this is the best or the correct thing to do, but it sure solved the problem.

Cheers

Body:
Following all the contributions I've taken the 1st answer and wondered arround magento.

I found a solution that I didn't have to make the load() again. I've edited the file config.xml on the following path,

app/code/core/Mage/Sales/etc/config.xml

and on the item / product attributes I've added the custom attribute

<item>
    <product attributes>
        <sku/>
        <type_id/>
        <my_custom_attribute_id/>

then on my cart.phtml file I was able to get the attribute just by using:

$_item->getProduct()->getmy_custom_attribute_id();

I don't know if this is the best or the correct thing to do, but it sure solved the problem.

Cheers


问:
How to send data to php from angularjs and ionic
I am an angular begginer, and I am currently trying to save some data in a data base with the $http() service, but it does not work. Could you help me, please? This is what I am trying to do:

Form:

<form name="form">
  <input ng-model="model.text" type="text" name="text">
  <button class="button" ng-click="saveData()"> Save </button>
</form>
```

<p>Controller of that page:</p>

<pre class="lang-js prettyprint-override"><code>.controller('pagCtrl', function ($scope, $http) {
  $scope.saveData = function () {

    $http ({
        url : 'http://localhost/prueba/www/php/enviar_datos.php',
        method : 'POST',
        data : { text : $scope.form.text.value }
    }).then (function (response) {

    }, function (response) {

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

PHP:

<?php
    $link = mysqli_connect("localhost", "root", "", "testDB");

    if (mysqli_connect_errno()) {
        die("Error de conexión: " . mysqli_connect_error());
    }

    mysqli_set_charset($link, 'utf8');
    mysqli_query($link, "INSERT INTO tabla_prueba (texto) VALUES ('" . $_POST['text'] . "')");
    mysqli_close($link);
?>
```

I think the problem is that it does not connect correctly to the php url.
I am working with Ionic. Thank you for your attention!

答:
Use the variable defined by the ng-model attribute.

```<code><form name="form">
  <input ng-model="model.text" type="text" name="text">
  <button class="button" ng-click="saveData()"> Save </button>
</form>
</code>```

```<code>app.controller('pagCtrl', function ($scope, $http) {
  //INITIALIZE model object
  $scope.model = {};
  $scope.saveData = function () {

    $http ({
        url : 'http://localhost/prueba/www/php/enviar_datos.php',
        method : 'POST',
        //data : { text : $scope.form.text.value }
        //POST model object
        data: $scope.model

    }).then (function successHandler(response) {

    }, function rejectHandler(response) {

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

More inputs can be easily added with no change to the controller:

```<code><form name="form">
  <input ng-model="model.text" type="text" name="text">
  <input ng-model="model.name" type="text" name="name">
  <input ng-model="model.id" type="text" name="id">
  <button class="button" ng-click="saveData()"> Save </button>
</form>
</code>```

All inputs will be serialized and sent as a JSON string text.

Body:
I am an angular begginer, and I am currently trying to save some data in a data base with the $http() service, but it does not work. Could you help me, please? This is what I am trying to do:

Form:

<form name="form">
  <input ng-model="model.text" type="text" name="text">
  <button class="button" ng-click="saveData()"> Save </button>
</form>

Controller of that page:

.controller('pagCtrl', function ($scope, $http) {
  $scope.saveData = function () {

    $http ({
        url : 'http://localhost/prueba/www/php/enviar_datos.php',
        method : 'POST',
        data : { text : $scope.form.text.value }
    }).then (function (response) {

    }, function (response) {

    });
  }
})

PHP:

<?php
    $link = mysqli_connect("localhost", "root", "", "testDB");

    if (mysqli_connect_errno()) {
        die("Error de conexión: " . mysqli_connect_error());
    }

    mysqli_set_charset($link, 'utf8');
    mysqli_query($link, "INSERT INTO tabla_prueba (texto) VALUES ('" . $_POST['text'] . "')");
    mysqli_close($link);
?>

I think the problem is that it does not connect correctly to the php url.
I am working with Ionic. Thank you for your attention!

Body:
Use the variable defined by the ng-model attribute.

<form name="form">
  <input ng-model="model.text" type="text" name="text">
  <button class="button" ng-click="saveData()"> Save </button>
</form>

app.controller('pagCtrl', function ($scope, $http) {
  //INITIALIZE model object
  $scope.model = {};
  $scope.saveData = function () {

    $http ({
        url : 'http://localhost/prueba/www/php/enviar_datos.php',
        method : 'POST',
        //data : { text : $scope.form.text.value }
        //POST model object
        data: $scope.model

    }).then (function successHandler(response) {

    }, function rejectHandler(response) {

    });
  }
})

More inputs can be easily added with no change to the controller:

<form name="form">
  <input ng-model="model.text" type="text" name="text">
  <input ng-model="model.name" type="text" name="name">
  <input ng-model="model.id" type="text" name="id">
  <button class="button" ng-click="saveData()"> Save </button>
</form>

All inputs will be serialized and sent as a JSON string text.


答:
The following is the code that will add all the numbers greater than 5, and also store them in a separate array;</p>

```<code><?php
$array = array(1,4,8,1,4,10,5,6,2,4,6);
$count=0;
$arr2 = [];
foreach($array as $arr)
{
    if($arr >= 5)
    {
        $count++;
        $arr2[] = $arr;
    }
}

echo "Total Greater than 5 = ".$count;
echo "Greater than 5 values:";
print_r($arr2);
echo "Total less than 5 = ".(count($array)-count($arr2));
</code>```

Title: Displaying values above certain number in array and counting how many values there are

Body:
Need to count how many values that are equal or above 5. This is my best guess, but it's not even close to working.

$array = array(1,4,8,1,4,10,5,6,2,4,6);
$x=0;

while ($x < count($array)){
    if($array[$x]>=5){
        $amount = array_count_values($array[$x]);
        echo $amout;
    }
    $x += 1;
}

Body:
The following is the code that will add all the numbers greater than 5, and also store them in a separate array;

<?php
$array = array(1,4,8,1,4,10,5,6,2,4,6);
$count=0;
$arr2 = [];
foreach($array as $arr)
{
    if($arr >= 5)
    {
        $count++;
        $arr2[] = $arr;
    }
}

echo "Total Greater than 5 = ".$count;
echo "Greater than 5 values:";
print_r($arr2);
echo "Total less than 5 = ".(count($array)-count($arr2));


答:
Just for fun:

```<code>$count = count(array_filter($array, function($v){ return ($v >= 5); }));
</code>```

filter out values < 5

count the remaining ones

Or if you want to loop and echo:

```<code>$result = array_filter($array, function($v){ return ($v >= 5); });

foreach($result as $number) {
    echo "$number<br>";
}
</code>```

Body:
Just for fun:

$count = count(array_filter($array, function($v){ return ($v >= 5); }));

filter out values < 5

count the remaining ones

Or if you want to loop and echo:

$result = array_filter($array, function($v){ return ($v >= 5); });

foreach($result as $number) {
    echo "$number<br>";
}


问:
Change placeholder when browser is resized
Im looking to add a placeholder to a textbox when the browser has a smaller width than 800 and im not sure where im going wrong.

```<code><form class="info">
            <script>add();</script>
            <label>Name</label> <input type="text" class="box" name="name" placeholder="" size="40"><br><br>
</form>
</code>```

And the JS

```<code><script>
function add(){
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (w < 800) {
    document.getElementsByName('name')[0].placeholder='Name';
} else
{
}}
</script>
</code>```

答:
In your above code you defined a function that will execute some javascript when called.

But where are you calling your add function?  You should be doing it on the window resize event, if you want it executed each time the browser window is resized.

Example:

```<code><script>
    window.onresize = function(event) {
        var w = $(window).width();
        if (w < 800) {
           document.getElementsByName('name')[0].placeholder='Name';
        } else {
           document.getElementsByName('name')[0].placeholder='';
        }
    };
</script>
</code>```

Body:
Im looking to add a placeholder to a textbox when the browser has a smaller width than 800 and im not sure where im going wrong.

<form class="info">

            Name <input type="text" class="box" name="name" placeholder="" size="40">

</form>

And the JS

Body:
In your above code you defined a function that will execute some javascript when called.

But where are you calling your add function?  You should be doing it on the window resize event, if you want it executed each time the browser window is resized.

Example:

<script>
    window.onresize = function(event) {
        var w = $(window).width();
        if (w < 800) {
           document.getElementsByName('name')[0].placeholder='Name';
        } else {
           document.getElementsByName('name')[0].placeholder='';
        }
    };
</script>


问:
NSMutableDictionary & dispatch_async Native Objects C# equivalent or similar
I'm fairly new to xamarin and mobile dev. I'm currently migrating geofire library by Firebase to xamarin.ios. I came across the following objective-c code and trying to figure out what is actually doing? and its c# equivalent:

```<code>@property (nonatomic, strong) NSMutableDictionary *keyEnteredObservers;
</code>```

...

```<code>GFQueryLocationInfo *info = self.locationInfos[key];

[self.keyEnteredObservers enumerateKeysAndObjectsUsingBlock:^(id observerKey,
                                                                      GFQueryResultBlock block,
                                                                      BOOL *stop) {
        dispatch_async(self.geoFire.callbackQueue, ^{         // the callbackQueue is of type @property (nonatomic, strong) dispatch_queue_t callbackQueue;
            block(key, info.location);
        });
    }];
</code>```

for the callbackQueue I am currently using type BlockingCollection<'Task>

Any help is greatly appreciated.

答:
A NSMutableDictionary.enumerateKeysAndObjectsUsingBlock in this context is doing two basic things.

It filters the dictionary based on an key. (A Linq Where would work as a C# replacement)

The filtered elements of the dictionary are available to a "block" of code as it is executed asynchronously(dispatch_async) via GCD (Grand Central Dispatch). So you are already using a BlockingCollection as a Task pump, so pass the key string that is a parameter to updateLocationInfo and the CLLocation to your Task...

Note: The stop boolean will cause an early exit from the enumerator, so a C# break as a replacement, but it is not used in this context...

If you are still using a NSMutableDictionary for your observers, you can filter via KeysForObject. In my version of GeoFire, I used a BlockingCollection<Action> vs. Tasks thus added the lambdas directly to the work queue.

Something like:

```<code>foreach (var info in keyEnteredObservers.KeysForObject(firebaseHandle))
{
    var nonCapturedLocation = info.location.Copy(); // location = CLLocation, do not capture entire dictionary by ref in lambda
    callbackQueue.Add(() =>
    {
        GFQueryResultBlock(key, nonCapturedLocation);
    });
}
</code>```

Body:
I'm fairly new to xamarin and mobile dev. I'm currently migrating geofire library by Firebase to xamarin.ios. I came across the following objective-c code and trying to figure out what is actually doing? and its c# equivalent:

@property (nonatomic, strong) NSMutableDictionary *keyEnteredObservers;

...

GFQueryLocationInfo *info = self.locationInfos[key];

[self.keyEnteredObservers enumerateKeysAndObjectsUsingBlock:^(id observerKey,
                                                                      GFQueryResultBlock block,
                                                                      BOOL *stop) {
        dispatch_async(self.geoFire.callbackQueue, ^{         // the callbackQueue is of type @property (nonatomic, strong) dispatch_queue_t callbackQueue;
            block(key, info.location);
        });
    }];

for the callbackQueue I am currently using type BlockingCollection<'Task>

Any help is greatly appreciated.

Body:
A NSMutableDictionary.enumerateKeysAndObjectsUsingBlock in this context is doing two basic things.

It filters the dictionary based on an key. (A Linq Where would work as a C# replacement)

The filtered elements of the dictionary are available to a "block" of code as it is executed asynchronously(dispatch_async) via GCD (Grand Central Dispatch). So you are already using a BlockingCollection as a Task pump, so pass the key string that is a parameter to updateLocationInfo and the CLLocation to your Task...

Note: The stop boolean will cause an early exit from the enumerator, so a C# break as a replacement, but it is not used in this context...

If you are still using a NSMutableDictionary for your observers, you can filter via KeysForObject. In my version of GeoFire, I used a BlockingCollection<Action> vs. Tasks thus added the lambdas directly to the work queue.

Something like:

foreach (var info in keyEnteredObservers.KeysForObject(firebaseHandle))
{
    var nonCapturedLocation = info.location.Copy(); // location = CLLocation, do not capture entire dictionary by ref in lambda
    callbackQueue.Add(() =>
    {
        GFQueryResultBlock(key, nonCapturedLocation);
    });
}


问:
Find text in webview page using swift?
How can I find text in uiwebview page and highlight it and go to its position in the page using swift ?

For example chrome find text :

search example

But I'm using alert view instead :

my search example in my app !!!

答:
Here is the swift code:

1) add UIWebViewSearch.js file to your project

```<code>func highlightAllOccurencesOfString(str:String) -> Int {

    let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js")

    var jsCode = ""

    do{

        jsCode = try String(contentsOfFile: path!)

    }catch
    {
    // do something

    }

    self.newsWebView.stringByEvaluatingJavaScript(from: jsCode)

    let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(str)')"

    self.newsWebView .stringByEvaluatingJavaScript(from: startSearch)

    let  result = self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_SearchResultCount")

    return  Int(result!)!

}

func scrollTo(index:Int)  {

    self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_ScrollTo('\(index)')")

}

func removeAllHighlights() {

self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_RemoveAllHighlights()")

}
</code>```

Title: Find text in webview page using swift?

Body:
Here is the swift code:

1) add UIWebViewSearch.js file to your project

func highlightAllOccurencesOfString(str:String) -> Int {

    let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js")

    var jsCode = ""

    do{

        jsCode = try String(contentsOfFile: path!)

    }catch
    {
    // do something

    }

    self.newsWebView.stringByEvaluatingJavaScript(from: jsCode)

    let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(str)')"

    self.newsWebView .stringByEvaluatingJavaScript(from: startSearch)

    let  result = self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_SearchResultCount")

    return  Int(result!)!

}

func scrollTo(index:Int)  {

    self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_ScrollTo('\(index)')")

}

func removeAllHighlights() {

self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_RemoveAllHighlights()")

}


问:
Swift getter + array initialization
How can I do this right? (Error: Variable used within its own initial value):

```<code>private var cars = [Car]() {
    get { return cars }
}
</code>```

...works for:

```<code>private var connection:Bool! {
    get { return connection }
}
</code>```

答:
Your variable

```<code>cars
</code>```

is a computed property. That been said, it doesnt store any value. For your example you will need to create a variable. Lest called it

```<code>private var localCars = [Car]()
</code>```

This variable is the one that will store all the values you need and then you can use the computed property to get all the information you need from cars like this.

```<code>private var cars:Cars! {
    get { return localCars }
}
</code>```

You can also use the set in your computed propert to store the value to localCars

```<code>private var cars:Cars! {
    get { return localCars }
    set { localCars = newValue }
}
</code>```

If you want to learn what its a computer property check this page. It explains them really well.

Title: Swift getter + array initialization

Body:
How can I do this right? (Error: Variable used within its own initial value):

private var cars = [Car]() {
    get { return cars }
}

...works for:

private var connection:Bool! {
    get { return connection }
}

Body:
Your variable

cars

is a computed property. That been said, it doesnt store any value. For your example you will need to create a variable. Lest called it

private var localCars = [Car]()

This variable is the one that will store all the values you need and then you can use the computed property to get all the information you need from cars like this.

private var cars:Cars! {
    get { return localCars }
}

You can also use the set in your computed propert to store the value to localCars

private var cars:Cars! {
    get { return localCars }
    set { localCars = newValue }
}

If you want to learn what its a computer property check this page. It explains them really well.


问:
Easy way to mention all the objects inside a function without explicitly writing all of them
Suppose I have created 100 data frames by the name of v1, v2, v3, v4, v5,...,v99,v100.
All these data frames are of the same size, I mean they all have the same set of columns.
I now want to export all these data frames appended in a single csv file using rbind within write.csv.
So I am using the function

```<code>write.csv(rbind(v1, v2, v3,v4,v5), "myfilename.csv")
</code>```

The above command does the job but as you can see only 5 data frames are appended. I want to append all the data frames i.e. from v1 to v100 (in a sequential order ) but writing all of their names individually can be a painful task. Is there an easy way to mention all the object names without writing all of their names. Thanking in anticipation.

答:
If you must have separate objects then get the names and order them by number. Then copy them into list L and rbind them together

```<code>nms <- ls(pattern = "^v\\d+$")
nms <- nms[order(as.numeric(sub("v", "", nms)))]
L <- mget(nms)
DF <- do.call("rbind", L)
</code>```

however, as @MrFlick mentioned it would have been better to create them in a list L in the first place in which case only the last statement would be needed.

Body:
Suppose I have created 100 data frames by the name of v1, v2, v3, v4, v5,...,v99,v100.
All these data frames are of the same size, I mean they all have the same set of columns.
I now want to export all these data frames appended in a single csv file using rbind within write.csv.
So I am using the function

write.csv(rbind(v1, v2, v3,v4,v5), "myfilename.csv")

The above command does the job but as you can see only 5 data frames are appended. I want to append all the data frames i.e. from v1 to v100 (in a sequential order ) but writing all of their names individually can be a painful task. Is there an easy way to mention all the object names without writing all of their names. Thanking in anticipation.

Body:
If you must have separate objects then get the names and order them by number. Then copy them into list L and rbind them together

nms <- ls(pattern = "^v\\d+$")
nms <- nms[order(as.numeric(sub("v", "", nms)))]
L <- mget(nms)
DF <- do.call("rbind", L)

however, as @MrFlick mentioned it would have been better to create them in a list L in the first place in which case only the last statement would be needed.


问:
Convert list of lists with different lengths to a numpy array
I have list of lists with different lengths (e.g. [[1, 2, 3], [4, 5], [6, 7, 8, 9]]) and want to convert it into a numpy array of integers. I understand that 'sub' arrays in numpy multidimensional array must be the same length. So what is the most efficient way to convert such a list as in example above into a numpy array like this [[1, 2, 3, 0], [4, 5, 0, 0], [6, 7, 8, 9]], i.e. completed with zeros?

答:
you could make a numpy array with np.zeros and fill them with your list elements as shown below.

```<code>a = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
import numpy as np
b = np.zeros([len(a),len(max(a,key = lambda x: len(x)))])
for i,j in enumerate(a):
    b[i][0:len(j)] = j
</code>```

results in

```<code>[[ 1.  2.  3.  0.]
 [ 4.  5.  0.  0.]
 [ 6.  7.  8.  9.]]
</code>```

Body:
you could make a numpy array with np.zeros and fill them with your list elements as shown below.

a = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
import numpy as np
b = np.zeros([len(a),len(max(a,key = lambda x: len(x)))])
for i,j in enumerate(a):
    b[i][0:len(j)] = j

results in

[[ 1.  2.  3.  0.]
 [ 4.  5.  0.  0.]
 [ 6.  7.  8.  9.]]