问:
Remove image from cache in Glide library
I am using Glide in one of my projects to show image from file.

Below is my code how I am showing the image:

```<code>Glide.with(DemoActivity.this)
     .load(Uri.parse("file://" + imagePath))
     .into(mImage);
</code>```

The image at this location(imagePath) keeps on changing. By default Glide cache the image it shows in the ImageView. Because of this, the Glide was showing the first image from cache for new images at that location.

If I change the image at location imagePath with some other image having same name then the Glide is showing the first image instead of new one.

Two queries are:

Is it possible to always the image from File and not cache? This way problem will be solved.

Is it possible to clear image from cache before getting newly replaced image? This will also solve the problem.

答:
signature with GlideApp </p>

```<code>    GlideApp.with(imageView)
            .load(url)
            .signature(new ObjectKey(System.currentTimeMillis()))
            .placeholder(R.drawable.sky)
            .error(R.drawable.sky)
            .into(imageView);
</code>```

Body:
I am using Glide in one of my projects to show image from file.

Below is my code how I am showing the image:

Glide.with(DemoActivity.this)
     .load(Uri.parse("file://" + imagePath))
     .into(mImage);

The image at this location(imagePath) keeps on changing. By default Glide cache the image it shows in the ImageView. Because of this, the Glide was showing the first image from cache for new images at that location.

If I change the image at location imagePath with some other image having same name then the Glide is showing the first image instead of new one.

Two queries are:

Is it possible to always the image from File and not cache? This way problem will be solved.

Is it possible to clear image from cache before getting newly replaced image? This will also solve the problem.

Body:
signature with GlideApp

    GlideApp.with(imageView)
            .load(url)
            .signature(new ObjectKey(System.currentTimeMillis()))
            .placeholder(R.drawable.sky)
            .error(R.drawable.sky)
            .into(imageView);


来源: stackexchange

问:
jquery .on is not working
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

```<code>$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});
</code>```

答:
$(document).on('ready') is removed from jQuery 3.0 https://api.jquery.com/ready/

There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0.

ContentLicense: CC BY-SA 3.0

Title: jquery .on is not working

Body:
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});


问:
access inherited class properties from base class
I have base class and two inherited classes, these two inherited classes also share the two properties. I would like to access these properties from base class. How to do that? Example below. </p>

```<code>public abstract class ClientEngine
{
        public void SaveFile(string fileName);
        {
            //Not implemented, I get error here because I don't know how to access Inherited class properties
            if (FileStorage != null))
                File.WriteAllBytes(fileName, FileStorage);
        }
}

    public interface IEngineEntity
    {
        byte[] FileStorage { get; set; }
    }

public class MyEntity1 : ClientEngine, IEngineEntity
{

public string MyProperty1 {get; set;}
public string MyProperty2 {get; set;}

public byte[] FileStorage { get; set; }
}

public class MyEntity2 : ClientEngine, IEngineEntity
{

public string MyProperty3 {get; set;}
public string MyProperty4 {get; set;}

public byte[] FileStorage { get; set; }
}
</code>```

答:
Another functional alternative:</p>

```<code>var derivedType = Type.GetType(this.GetType().FullName);
var FileStorage = derivedType.GetProperty("FileStorage", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this) as byte[];
if (FileStorage != null)
{
    ...
}
</code>```

Body:
I have base class and two inherited classes, these two inherited classes also share the two properties. I would like to access these properties from base class. How to do that? Example below.

public abstract class ClientEngine
{
        public void SaveFile(string fileName);
        {
            //Not implemented, I get error here because I don't know how to access Inherited class properties
            if (FileStorage != null))
                File.WriteAllBytes(fileName, FileStorage);
        }
}

    public interface IEngineEntity
    {
        byte[] FileStorage { get; set; }
    }

public class MyEntity1 : ClientEngine, IEngineEntity
{

public string MyProperty1 {get; set;}
public string MyProperty2 {get; set;}

public byte[] FileStorage { get; set; }
}

public class MyEntity2 : ClientEngine, IEngineEntity
{

public string MyProperty3 {get; set;}
public string MyProperty4 {get; set;}

public byte[] FileStorage { get; set; }
}

Body:
Another functional alternative:

var derivedType = Type.GetType(this.GetType().FullName);
var FileStorage = derivedType.GetProperty("FileStorage", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this) as byte[];
if (FileStorage != null)
{
    ...
}


问:
Yii2 debug bar not showing on staging server even with allowedIP's entry
I'm trying to get the debug bar in Yii2 to show on my staging server but for some reason it isn't showing.

Here is code from my web.php config file:

```<code>if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
                                   'class' => 'yii\debug\Module',
                                   'allowedIPs' => ['127.0.0.1','::1','123.45.67.89']
                                   ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}
</code>```

123.45.67.89 obviously is just an example for the server's real IP.

I get the servers IP by doing:

```<code>$host = gethostname();
$server_ip = gethostbyname($host);
</code>```

If I try and access the debug page by going to:

http://www.example.com/debug/default/index

I get the message: You are not allowed to access this page.

I am sure I had this working before but now it's not working for some reason and I can't figure out why!?

I'm aware there are debug data files (not sure if they will contain any info on why I can't see it) but I am not sure how I can view the data properly?

答:
i know this is old but it may help someone now since this isn't very clear anywhere on the web.

We used to have this problem a lot when deploying to test and dev servers. Add this to your main-local.php

```<code>if (!YII_ENV_TEST) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'allowedIPs' => ['*']
    ];
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
    'class' => 'yii\gii\Module',
    ];
}
</code>```

DO NOT DO THIS ON A PRODUCTION SERVER!!!!

Body:
I'm trying to get the debug bar in Yii2 to show on my staging server but for some reason it isn't showing.

Here is code from my web.php config file:

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
                                   'class' => 'yii\debug\Module',
                                   'allowedIPs' => ['127.0.0.1','::1','123.45.67.89']
                                   ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

123.45.67.89 obviously is just an example for the server's real IP.

I get the servers IP by doing:

$host = gethostname();
$server_ip = gethostbyname($host);

If I try and access the debug page by going to:

http://www.example.com/debug/default/index

I get the message: You are not allowed to access this page.

I am sure I had this working before but now it's not working for some reason and I can't figure out why!?

I'm aware there are debug data files (not sure if they will contain any info on why I can't see it) but I am not sure how I can view the data properly?

Body:
i know this is old but it may help someone now since this isn't very clear anywhere on the web.

We used to have this problem a lot when deploying to test and dev servers. Add this to your main-local.php

if (!YII_ENV_TEST) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'allowedIPs' => ['*']
    ];
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
    'class' => 'yii\gii\Module',
    ];
}

DO NOT DO THIS ON A PRODUCTION SERVER!!!!


问:
change inline class Style property using javascript/jquery
How to change inline class Style property using javascript/jquery.
for example:

```<code><style>
.iexp-info-bar-body {
    background-color: #000000;
}
</style>
<div class="iexp-info-bar-body">
//data
</div>
</code>```

i want to change background-color property of a class .iexp-info-bar-body  #000000 to #C04848 .

Please not that i know inline css technique/using !important keyword to change color.

But i want to change all the occurance of a class .iexp-info-bar-body property
ie
i need a result like

```<code><style>
.iexp-info-bar-body {
    background-color: #C04848;
}
</style>
<div class="iexp-info-bar-body">
//data
</code>```

答:
I had a very good teacher that taught us to change the class :

First, it really helps to be fully aware of "what is my initial state" AND "what is my final state"

This is pretty useful if your design change and you have to implement some transitions. And you will never have to access your JavaScript files to change any css code.

Then think about conflicts

Today, you only have one element depending on that class, but what if you have 100 000 tomorrow ?

Maybe try to make another class is the simplest way to achieve what you want to do.

```<code><style>
    .iexp-info-bar-body {
        background-color: #000000;
    }
    .changed {
        background-color: #ff69b4;
    }
</style>

<div class="iexp-info-bar-body">
//data
</div>

<script>
    var all = document.querySelectorAll('.iexp-info-bar-body');
    for (var i = 0, length = all.length; i < length; i++) {
        all[i].classList.remove('iexp-info-bar-body');
        all[i].classList.add('changed');
    }
</script>
</code>```

Of course this is very primitive and you can improve it in many ways

Body:
How to change inline class Style property using javascript/jquery.
for example:

//data

i want to change background-color property of a class .iexp-info-bar-body  #000000 to #C04848 .

Please not that i know inline css technique/using !important keyword to change color.

But i want to change all the occurance of a class .iexp-info-bar-body property
ie
i need a result like

//data

Body:
I had a very good teacher that taught us to change the class :

First, it really helps to be fully aware of "what is my initial state" AND "what is my final state"

This is pretty useful if your design change and you have to implement some transitions. And you will never have to access your JavaScript files to change any css code.

Then think about conflicts

Today, you only have one element depending on that class, but what if you have 100 000 tomorrow ?

Maybe try to make another class is the simplest way to achieve what you want to do.

<style>
    .iexp-info-bar-body {
        background-color: #000000;
    }
    .changed {
        background-color: #ff69b4;
    }
</style>

<div class="iexp-info-bar-body">
//data
</div>

<script>
    var all = document.querySelectorAll('.iexp-info-bar-body');
    for (var i = 0, length = all.length; i < length; i++) {
        all[i].classList.remove('iexp-info-bar-body');
        all[i].classList.add('changed');
    }
</script>

Of course this is very primitive and you can improve it in many ways


问:
Does change in package break existing clients using protobuf?
If I change,

```<code>syntax = "proto3";

package a.v0;

message HtmlStore{
    string html = 1;
}
</code>```

to

```<code>syntax = "proto3";

package a;

message HtmlStore{
    string html = 1;
}
</code>```

I have a python API which returns protobuf. There are existing clients consuming the API. I want to change protobuf definition of certain elements and I want to know if it will break the existing clients?

答:
Note: if you're using JSON encoding: all bets are off.

If you're using binary encoding, the package isn't usually part of the wire format - unless you've made use of the google.protobuf.Any feature.

So assuming you haven't used Any: changing the package will be completely invisible in terms of what is sent, and nobody will be impacted.

However! If they receive an updated version of the .proto and run the code-gen as part of their build, then their previously working code may cease to compile - requiring them to remove the .v0 from code that references those types.

The only things that are sent on the wire are the field-numbers (1 in the case of html), the wire-type (length-prefixed in the case of html - so: wire-type 2) and the actual values. You can also safely rename HtmlStore and html (under the same conditions re Any etc).

Body:
If I change,

syntax = "proto3";

package a.v0;

message HtmlStore{
    string html = 1;
}

to

syntax = "proto3";

package a;

message HtmlStore{
    string html = 1;
}

I have a python API which returns protobuf. There are existing clients consuming the API. I want to change protobuf definition of certain elements and I want to know if it will break the existing clients?


问:
Failed to resolve: junit:junit: 4.12
Failed to resolve: junit:junit:4.12

What is the solution to this problem
I have tried several solutions

答:
You can simply remove that from Gradle and download this file http://www.java2s.com/Code/JarDownload/junit/junit-4.9.jar.zip or latest version found on there site and add it as library to Gradle and again build the project and it's all done.

This problem may be because. Gradle may be unable to find that, but after adding that downloaded file to your project. You are good to go.

Title: Failed to resolve: junit:junit: 4.12


问:
How to restrict serialization for the property type Guid?
```<code>    public class Pet
    {
      // The default value for the Animal field is "Dog".
      [DefaultValue(0)]
      public int testinteger { get; set; }

      [DefaultValue (00000000 - 0000 - 0000 - 0000 - 000000000000)]
      public Guid testbool { get; set; }
    }

    public class Run
   {
    public static void Main()
    {
        Run test = new Run();

        test.SerializeObject("OverrideDefaultValue.xml");
    }

    public void SerializeObject(string filename)
    {
        XmlSerializer mySerializer = new XmlSerializer(typeof(Pet));
        TextWriter writer = new StreamWriter(filename);
        Pet myPet = new Pet();
        myPet.testinteger = 10;
        mySerializer.Serialize(writer, myPet);
        writer.Close();
    }
  }
</code>```

Here i have used Id property for serialization. I have used the attribute default value. But serialization is not restricted for Id property.

答:
You can mark the property as internal(Only public property are Serialized)if attributes is not working.

Try checking if the correct attribute is set set an XML attribute above the property to not serialize the property.
    [XmlIgnore]
   or
    [NonSerialized]

Body:
    public class Pet
    {
      // The default value for the Animal field is "Dog".
      [DefaultValue(0)]
      public int testinteger { get; set; }

      [DefaultValue (00000000 - 0000 - 0000 - 0000 - 000000000000)]
      public Guid testbool { get; set; }
    }

    public class Run
   {
    public static void Main()
    {
        Run test = new Run();

        test.SerializeObject("OverrideDefaultValue.xml");
    }

    public void SerializeObject(string filename)
    {
        XmlSerializer mySerializer = new XmlSerializer(typeof(Pet));
        TextWriter writer = new StreamWriter(filename);
        Pet myPet = new Pet();
        myPet.testinteger = 10;
        mySerializer.Serialize(writer, myPet);
        writer.Close();
    }
  }

Here i have used Id property for serialization. I have used the attribute default value. But serialization is not restricted for Id property.


问:
How can I access another drive in my computer using PHP
My xampp was installed in c:/xampp.when my c:/ drive filled So I would like to access E:/ drive using PHP anybody give me some suggestions?</p>

答:
First you need to store the current path, before changing dirs:</p>

```<code>echo chdir(dirname(__FILE__));

$oldPath = getcwd();
chdir('/your_new_path');
include(./your_file.php);
chdir($oldPath);
</code>```

Body:
First you need to store the current path, before changing dirs:

echo chdir(dirname(__FILE__));

$oldPath = getcwd();
chdir('/your_new_path');
include(./your_file.php);
chdir($oldPath);


问:
gitlab ci: Run build job when manual or when master only
Is it possible to have a gitlab-ci file wheres a build job defined with the following requirements:

get executed when manual
OR

get executed by master push

I thought of something like this, but this is poorly false:

```<code>build_jar:
stage: build
script:
  - echo "build jar"
artifacts:
  paths:
    - jar/path/*.jar
only:
  - master
when: manual
</code>```

Only solution for me is to have two jobs, one for the master push and one a manual input. But the disadvantage is, that in gitlab it becomes confusingly

答:
The exact thing you want is not possible at the moment. Though the 2 jobs (one with only: master and the other with when: manual should provide an alternative.

If you put them in the same stage it shouldn't be that confusing I guess.

You could also use some special yaml features like anchors to stay DRY.

Body:
Is it possible to have a gitlab-ci file wheres a build job defined with the following requirements:

get executed when manual
OR

get executed by master push

I thought of something like this, but this is poorly false:

build_jar:
stage: build
script:
  - echo "build jar"
artifacts:
  paths:
    - jar/path/*.jar
only:
  - master
when: manual

Only solution for me is to have two jobs, one for the master push and one a manual input. But the disadvantage is, that in gitlab it becomes confusingly


问:
How do I see the list of open files within Emacs?  Or browse a directory within Emacs?
Most text editors have a navigation pane that lets you see all the files you currently have open.  Or a pane that lets you browse a file directory.

How do I do this in Emacs?

答: You could try the sidebar package</p>

OwnerDisplayName: someguy

Body: You could try the sidebar package


问:
Passing extra Intent information from Activity to View
I have an activity that is launched from another activity through an intent. The intent carries an extra "id" information. Now, the launched activity has a custom view (actually, a extension of LinearLayout class). I want to access the "id" information in the custom view. Can the activity pass that value to its contained view? Or can the view get a handle to the activity?</p>

答: Yes, your custom View class can get a reference to the Activity it is contained in. Every View has a getContext() method which returns the Context the View is running in (i.e. your Activity).</p>

ContentLicense: CC BY-SA 2.5


问:
how to use the hook processUpload_postProcessAction in my extension?
Can anyone here know how to use the processUpload_postProcessAction hook in my extension?

I have created a hook folder and added a php file named class.tx_lms_tcemain.php

I have added the following lines in my extension's ext_localconf.php

```<code>$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUploadClass'][] = 'EXT:wr_dw_lms/hooks/class.tx_lms_tcemain.php:tx_lms_tcemain';
</code>```

In the PHP file inside hooks folder contains following code:

```<code>    <?php
class tx_lms_tcemain {
            function processUpload_postProcessAction (&$filename, t3lib_TCEmain
$parentObject) {
$this->addFlashMessage(
'Blog created successfully!',
'Status',
\TYPO3\CMS\Core\Messaging\AbstractMessage::OK,TRUE
);
           }

    }
?>
</code>```

This one does not work. My code is not getting executed. Can anyone here help me?

答:
Try to write this in your ext_localconf.php

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'][] = 'Vendor\WrDwLms\Hooks\Tcemain\';

Body:
Can anyone here know how to use the processUpload_postProcessAction hook in my extension?

I have created a hook folder and added a php file named class.tx_lms_tcemain.php

I have added the following lines in my extension's ext_localconf.php

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUploadClass'][] = 'EXT:wr_dw_lms/hooks/class.tx_lms_tcemain.php:tx_lms_tcemain';

In the PHP file inside hooks folder contains following code:

    <?php
class tx_lms_tcemain {
            function processUpload_postProcessAction (&$filename, t3lib_TCEmain
$parentObject) {
$this->addFlashMessage(
'Blog created successfully!',
'Status',
\TYPO3\CMS\Core\Messaging\AbstractMessage::OK,TRUE
);
           }

    }
?>

This one does not work. My code is not getting executed. Can anyone here help me?


答:
The error is pointing to this:

```<code>tabs[i].on(...
</code>```

Not the use on the document.ready event.

Because .on() is a function on the jQuery object, not on any HTML element in JavaScript.  And when you loop through the results of a jQuery object, HTML elements are exactly what you're getting.

You don't need to loop in the first place.  You already have a jQuery object:

```<code>$("ul.nav-tabs > li")
</code>```

You can simply call .on() on that object:

```<code>$(document).ready(function() {
    $("ul.nav-tabs > li").on("click", switchTab);

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});
</code>```

Title: jquery .on is not working

Body:
The error is pointing to this:

tabs[i].on(...

Not the use on the document.ready event.

Because .on() is a function on the jQuery object, not on any HTML element in JavaScript.  And when you loop through the results of a jQuery object, HTML elements are exactly what you're getting.

You don't need to loop in the first place.  You already have a jQuery object:

$("ul.nav-tabs > li")

You can simply call .on() on that object:

$(document).ready(function() {
    $("ul.nav-tabs > li").on("click", switchTab);

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});


问:
Default Option not selected dropdown in angularjs
I am struggling with dropdown list, Please refer bellow code

My Controller

```<code>(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);
</code>```

My UI

```<code><body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>
</code>```

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

答:
Your object IDs are string whereas your data.model is number.

Uniform your data type and it will work.

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model='1';

 }]);
})(window.angular);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-select-ngrepeat-production</title>

  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="app.js"></script>

</head>
<body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>
</html></code>```

See example on AngularJS official documentation

Body:
I am struggling with dropdown list, Please refer bellow code

My Controller

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);

My UI

  <form name="myForm">
     Repeat select:
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>

  <tt>model = {{data.model}}</tt>

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

Body:
Your object IDs are string whereas your data.model is number.

Uniform your data type and it will work.

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model='1';

 }]);
})(window.angular);

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-select-ngrepeat-production</title>

  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="app.js"></script>

</head>
<body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>
</html>

See example on AngularJS official documentation


问:
Run Laravel Dusk on multiple web domains
I have multiple websites.

en.web-site.com/pages/faqs

fr.web-site.com/pages/faqs

ar.web-site.com/pages/faqs

br.web-site.com/pages/faqs

... 30 more websites that have the same URI structure

I want to run a browser test on each of these websites.

I've updated the emails on the faqs pages of all my websites and I want to test if all of them have the changes.

```<code><?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;

class UpdatedEmailTest extends DuskTestCase
{
    public function testUpdatedEmail()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/pages/faqs')
                ->assertPathIs('/pages/faqs')
                ->assertSee('new_email@sample.com')
                ->assertDontSee('old_email@sample.com');
        });
    }
}
</code>```

This test will absolutely work fine on any of my websites, but I have to edit the .env file every time I have to run it.

What can I do that will allow me to test on all of these websites without having to edit the .env file?

答:
To achieve this, you may need a loop over all the 30+ website domains.

```<code>public function testUpdatedEmail()
{
    $websites = .... //array with full urls and emails

    foreach ($websites as $website)

      $this->browse(function (Browser $browser) use ($website) {
          $browser->visit($website["url"])
            ->assertPathIs(parse_url($website["url"], PHP_URL_PATH))
            ->assertSee($website["new_email"])
            ->assertDontSee($website["old_email"]);
    });
}
</code>```

Refer to Browers.php https://github.com/laravel/dusk/blob/bcb05e6fe29817bbf04574f68996312a296bb366/src/Browser.php#L119

Body:
I have multiple websites.

en.web-site.com/pages/faqs

fr.web-site.com/pages/faqs

ar.web-site.com/pages/faqs

br.web-site.com/pages/faqs

... 30 more websites that have the same URI structure

I want to run a browser test on each of these websites.

I've updated the emails on the faqs pages of all my websites and I want to test if all of them have the changes.

<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;

class UpdatedEmailTest extends DuskTestCase
{
    public function testUpdatedEmail()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/pages/faqs')
                ->assertPathIs('/pages/faqs')
                ->assertSee('new_email@sample.com')
                ->assertDontSee('old_email@sample.com');
        });
    }
}

This test will absolutely work fine on any of my websites, but I have to edit the .env file every time I have to run it.

What can I do that will allow me to test on all of these websites without having to edit the .env file?

Body:
To achieve this, you may need a loop over all the 30+ website domains.

public function testUpdatedEmail()
{
    $websites = .... //array with full urls and emails

    foreach ($websites as $website)

      $this->browse(function (Browser $browser) use ($website) {
          $browser->visit($website["url"])
            ->assertPathIs(parse_url($website["url"], PHP_URL_PATH))
            ->assertSee($website["new_email"])
            ->assertDontSee($website["old_email"]);
    });
}

Refer to Browers.php https://github.com/laravel/dusk/blob/bcb05e6fe29817bbf04574f68996312a296bb366/src/Browser.php#L119


问:
DateTimePicker like reservation system
I need to prepare an input for date and time which can disable time in the specific date. I prepared a Bootstrap 3 DateTimePicker for that:

```<code>$('#ScheduledAt').datetimepicker({
    format: 'YYYY-MM-DD HH:mm',
    disabledDates: [
         moment("2017-12-05 9:00"),
    ],
    daysOfWeekDisabled: [0, 7],
    stepping: 30,
    enabledHours: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
})
</code>```

The stepping is 30 minutes, so on 2017-12-05 at 9:00 someone reserved something, but on 2017-12-05 at 9:30 I can create a reservation. When I will set up like upper I can't click this specific date and choose another time. Is there any possibility to do that? Or another plugin?

答:
Have you tried with disabledtimeintervals option of eonasdan bootstrap-datetimepicker?

Here is a CodePen: https://codepen.io/beaver71/pen/gXyrwR
showing this functionality.

$('#ScheduledAt').datetimepicker({
    format: 'YYYY-MM-DD HH:mm',
    toolbarPlacement: 'top',
  showClear: true,
  showClose: true,
  sideBySide: true,
    disabledTimeIntervals: [
      [moment("2017-12-05 8:40"),moment("2017-12-05 9:20")],
    ],
    daysOfWeekDisabled: [0, 7],
    stepping: 30,
    enabledHours: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js?ver=1"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.0/moment-with-locales.js"></script>
<script src="https://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/5a991bff/src/js/bootstrap-datetimepicker.js"></script>
<link href="https://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/master/build/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
    <div class="col-md-4">
      <div class="panel-body">
        <form id="srcForm">
          <div class="row">
            <div class="form-group col-xs-12">
              <label>Date</label>
              <div id="ScheduledAt" class="input-group">
                <input type="text" class="form-control" name="from">
                <span class="input-group-addon">
                  <span class="glyphicon glyphicon-calendar"></span>
                </span>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
</div></code>```

The interval [moment("2017-12-05 8:40"),moment("2017-12-05 9:20")] is used to disable 2017-12-05 9:00 datetime.

Title: DateTimePicker like reservation system

Body:
I need to prepare an input for date and time which can disable time in the specific date. I prepared a Bootstrap 3 DateTimePicker for that:

$('#ScheduledAt').datetimepicker({
    format: 'YYYY-MM-DD HH:mm',
    disabledDates: [
         moment("2017-12-05 9:00"),
    ],
    daysOfWeekDisabled: [0, 7],
    stepping: 30,
    enabledHours: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
})

The stepping is 30 minutes, so on 2017-12-05 at 9:00 someone reserved something, but on 2017-12-05 at 9:30 I can create a reservation. When I will set up like upper I can't click this specific date and choose another time. Is there any possibility to do that? Or another plugin?

Body:
Have you tried with disabledtimeintervals option of eonasdan bootstrap-datetimepicker?

Here is a CodePen: https://codepen.io/beaver71/pen/gXyrwR
showing this functionality.

$('#ScheduledAt').datetimepicker({
    format: 'YYYY-MM-DD HH:mm',
    toolbarPlacement: 'top',
  showClear: true,
  showClose: true,
  sideBySide: true,
    disabledTimeIntervals: [
      [moment("2017-12-05 8:40"),moment("2017-12-05 9:20")],
    ],
    daysOfWeekDisabled: [0, 7],
    stepping: 30,
    enabledHours: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js?ver=1"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.0/moment-with-locales.js"></script>
<script src="https://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/5a991bff/src/js/bootstrap-datetimepicker.js"></script>
<link href="https://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/master/build/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
    <div class="col-md-4">
      <div class="panel-body">
        <form id="srcForm">
          <div class="row">
            <div class="form-group col-xs-12">
              <label>Date</label>
              <div id="ScheduledAt" class="input-group">
                <input type="text" class="form-control" name="from">
                <span class="input-group-addon">
                  <span class="glyphicon glyphicon-calendar"></span>
                </span>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
</div>

The interval [moment("2017-12-05 8:40"),moment("2017-12-05 9:20")] is used to disable 2017-12-05 9:00 datetime.


问:
Docker compose v3 specify network to be ingress?
I have docker-compose file for my docker swarm stack.I want my stack services to be deployed on specific network and that network i want to be ingress network so that i can use DNSRR of docker.

```<code>version: "3"
services:
 a:
  image: xyz/a:dev
  ports:
   - "80:80"
   - "443:443"
  networks:
   -my_network
b:
  image: xyz/b:dev
  ports:
  - "5000:5000"
  networks:
   -my_network

networks:
  my_network:
    driver:overlay
    ipam:
     driver: default
     config:
       -subnet: 10.0.1.0/24
</code>```

here, where can i specify that this network should be ingress network? plus how can i specify ip-range same as specified here in cli : here

答:
Apparently, these options are not exposed in the composefile. The documentation doesn't mention them and to be sure you can check the source code, in particular the latest compose schema.

The only option is to create the ingress network on the command line and reference it from the compose file as an external network.

Body:
I have docker-compose file for my docker swarm stack.I want my stack services to be deployed on specific network and that network i want to be ingress network so that i can use DNSRR of docker.

version: "3"
services:
 a:
  image: xyz/a:dev
  ports:
   - "80:80"
   - "443:443"
  networks:
   -my_network
b:
  image: xyz/b:dev
  ports:
  - "5000:5000"
  networks:
   -my_network

networks:
  my_network:
    driver:overlay
    ipam:
     driver: default
     config:
       -subnet: 10.0.1.0/24

here, where can i specify that this network should be ingress network? plus how can i specify ip-range same as specified here in cli : here


问:
Windows 10 Task Scheduler: Execute bash script without showing up cmd
I have a task on my computer downloading a daily backup from my server. Basically it's:

```<code>bash.exe -c "cd /mnt/d/server_backups && ./download_backup.sh"
</code>```

This does work, however it always pops up the cmd window, which wouldn't actually bother me, if it wasn't because it interrupts whatever I'm doing (gaming, watching a movie, working) and just throws me to desktop.

Changing task to "Run whether user is logged or not" doesn't work because apparently windows session zero (whatever that is) can't initiate calls with bash.

Is there another way to either not show up the cmd window or doing it without the SO deciding on its own that I want to have it main focused and everything else minimized?

答:
You could use a VBS script to launch bash without a cmd.exe window, as follow :

hidden_launcher.vbs

```<code>Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run WScript.Arguments(0), 0
Set WinScriptHost = Nothing
</code>```

Here, we run the 1st argument received, and 0 means start the program hidden.

Now set up your task in the task scheduler :

Program to launch : C:\Path\to\hidden_launcher.vbs

Arguments: "bash.exe -c 'cd /mnt/d/server_backups && ./download_backup.sh' "

This should do the trick !!

Body:
I have a task on my computer downloading a daily backup from my server. Basically it's:

bash.exe -c "cd /mnt/d/server_backups && ./download_backup.sh"

This does work, however it always pops up the cmd window, which wouldn't actually bother me, if it wasn't because it interrupts whatever I'm doing (gaming, watching a movie, working) and just throws me to desktop.

Changing task to "Run whether user is logged or not" doesn't work because apparently windows session zero (whatever that is) can't initiate calls with bash.

Is there another way to either not show up the cmd window or doing it without the SO deciding on its own that I want to have it main focused and everything else minimized?

Body:
You could use a VBS script to launch bash without a cmd.exe window, as follow :

hidden_launcher.vbs

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run WScript.Arguments(0), 0
Set WinScriptHost = Nothing

Here, we run the 1st argument received, and 0 means start the program hidden.

Now set up your task in the task scheduler :

Program to launch : C:\Path\to\hidden_launcher.vbs

Arguments: "bash.exe -c 'cd /mnt/d/server_backups && ./download_backup.sh' "

This should do the trick !!


问:
SQL Query to calculate the difference of a number of fields and passing to ASP script
My query as it stands at the moment:

```<code>SELECT RemainingCapacityBytes
  FROM [Check].[dbo].[tbl_BackupChecks_MediaInfo]
  WHERE Company = 'Company Name' and ModifiedDateTime >= dateadd(d,-7,GETDATE())
</code>```

This returns a number of results that are integer values. I'm not sure if this is possible but what I would like to do is have SQL calculate the difference of the above returned results (by taking the highest and lowest value)  and then pass the caluclated answer variable back to the ASP script the query is running in. I will put an example below

```<code>RemainingCapacityBytes
----------------------
500293821
920392832
192837282
192837283
010299999
</code>```

The query would calculate the highest number 500293821 - the lowest 010299999 and then return the answer.

I don't think this is possible and I think I will probably end up just doing it in the ASP script but I thought I'd ask the experts first.

答:
Try this:</p>

```<code>SELECT MAX(RemainingCapacityBytes) - MIN(RemainingCapacityBytes) DiffCapacityBytes
   FROM [Check].[dbo].[tbl_BackupChecks_MediaInfo]
 WHERE Company = 'Company Name' and ModifiedDateTime >= dateadd(d,-7,GETDATE())
</code>```

Body:
My query as it stands at the moment:

SELECT RemainingCapacityBytes
  FROM [Check].[dbo].[tbl_BackupChecks_MediaInfo]
  WHERE Company = 'Company Name' and ModifiedDateTime >= dateadd(d,-7,GETDATE())

This returns a number of results that are integer values. I'm not sure if this is possible but what I would like to do is have SQL calculate the difference of the above returned results (by taking the highest and lowest value)  and then pass the caluclated answer variable back to the ASP script the query is running in. I will put an example below

RemainingCapacityBytes
----------------------
500293821
920392832
192837282
192837283
010299999

The query would calculate the highest number 500293821 - the lowest 010299999 and then return the answer.

I don't think this is possible and I think I will probably end up just doing it in the ASP script but I thought I'd ask the experts first.

Body:
Try this:

SELECT MAX(RemainingCapacityBytes) - MIN(RemainingCapacityBytes) DiffCapacityBytes
   FROM [Check].[dbo].[tbl_BackupChecks_MediaInfo]
 WHERE Company = 'Company Name' and ModifiedDateTime >= dateadd(d,-7,GETDATE())


问:
How to display sum of row data in view using codeigniter?
This is my view. How can I calculate sum of rows using view without using model and controller</p>

```<code>foreach($requests as $request):
<?php echo SUM($request->unit_price) ?>
<?php  endforeach; ?>
</code>```

答:
```<code>foreach($requests as $request){
$data[]=$request->unit_price;
}
</code>```

now $data array contains all the unit prices.

```<code>echo array_sum($data);
</code>```

and you get your answer.

Body:
This is my view. How can I calculate sum of rows using view without using model and controller

foreach($requests as $request):
<?php echo SUM($request->unit_price) ?>
<?php  endforeach; ?>

Body:
foreach($requests as $request){
$data[]=$request->unit_price;
}

now $data array contains all the unit prices.

echo array_sum($data);

and you get your answer.


问:
how to import intellij idea keymap to a text file (like csv)
I need to obtain a list of registered keybinding in the installed IntelliJ Idea. Existing way (File -> Settings -> Keymap) does not meet the use cases I interested to. For example,

Find a function for certain keyboard shortcut

Look for vacant keyboard shortcuts

The formatted list of keyboard shortcuts could be imported in spreadsheet software, R etc. What is the best way to obtain the mentioned list?

答:
There ia a KeyMap exporter plugin I cannot force to perform. Same project was placed to github:
intellij-plugin-export-keymap. So one can see through the code and try to find them own way.</p>


问:
How can I use RegularExpressions to replace a match based on a pattern, but keep the value?
I want to replace all 'm's in my strings by 'meter'. The Problem is that I have to find the correct pattern, since it is possible to have a number in combination of a space in front of the unit symbol.

I already tried the following pattern: [1-9][0-9]*\\s?m": "[1-9][0-9]*\\s?Meter with the following code:

```<code>static let patterns = [
    "[1-9][0-9]*\\s?m": "[1-9][0-9]*\\s?Meter"
];

static public func prepareText(input: String) -> String {
    var modifiedInput = input;

    for pattern in patterns.keys {
        let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive);
        modifiedInput = regex.stringByReplacingMatches(
            in: modifiedInput, options: [], range: NSMakeRange(0, modifiedInput.count),
            withTemplate: patterns[pattern]!);
    }

    return modifiedInput;
}
</code>```

But now I have the problem that the value of my parameter is also changed:

```<code>800 m -> [1-9][0-9]*s?Meter
</code>```

So how can I keep the 800 in front of the unit symbol?

答:
You need to use

```<code>static let patterns = [
    "([1-9][0-9]*\\s?)m": "$1Meter"
];
</code>```

The "([1-9][0-9]*\\s?)m" pattern will match and capture into Group 1 a digit from 1 to 9, any 0+ digits and then an optional whitespace, then just matches m. The $1Meter replacement will replace with the contents of Group 1 and then add Meter.

If you need to make sure the m is not followed with a word char, use "([1-9][0-9]*\\s?)m\\b" regex (that is, add \\b, a word boundary, after m).

Body:
I want to replace all 'm's in my strings by 'meter'. The Problem is that I have to find the correct pattern, since it is possible to have a number in combination of a space in front of the unit symbol.

I already tried the following pattern: [1-9][0-9]*\\s?m": "[1-9][0-9]*\\s?Meter with the following code:

static let patterns = [
    "[1-9][0-9]*\\s?m": "[1-9][0-9]*\\s?Meter"
];

static public func prepareText(input: String) -> String {
    var modifiedInput = input;

    for pattern in patterns.keys {
        let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive);
        modifiedInput = regex.stringByReplacingMatches(
            in: modifiedInput, options: [], range: NSMakeRange(0, modifiedInput.count),
            withTemplate: patterns[pattern]!);
    }

    return modifiedInput;
}

But now I have the problem that the value of my parameter is also changed:

800 m -> [1-9][0-9]*s?Meter

So how can I keep the 800 in front of the unit symbol?

Body:
You need to use

static let patterns = [
    "([1-9][0-9]*\\s?)m": "$1Meter"
];

The "([1-9][0-9]*\\s?)m" pattern will match and capture into Group 1 a digit from 1 to 9, any 0+ digits and then an optional whitespace, then just matches m. The $1Meter replacement will replace with the contents of Group 1 and then add Meter.

If you need to make sure the m is not followed with a word char, use "([1-9][0-9]*\\s?)m\\b" regex (that is, add \\b, a word boundary, after m).


问:
Using an external jar in a Scala.js project
I have a library in a jar that I would like to use in a Scala.js project.
Is any jar usable as a dependency of a Scala.js project?
Or should the jar have been compiled in a specific way?</p>

答:
It depends on the library, and exactly how you're trying to use it -- there are some macro libraries that work, for example, and you can technically put anything in a jar -- but usually this doesn't make sense. Jars are usually composed mainly of JVM classes, which aren't compatible with Scala.js' JavaScript environment.

This is really the biggest practical difference between ScalaJVM and Scala.js -- while the language is identical, the libraries are entirely separate...


问:
jquery .on is not working
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

```<code>$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});
</code>```

答:
You don't need the for loop:</p>

```<code>$(document).ready(function() {
    var tabs = $("ul.nav-tabs > li");

    tabs.on('click', switchTab)

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});
</code>```

Title: jquery .on is not working

Body:
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});

Body:
You don't need the for loop:

$(document).ready(function() {
    var tabs = $("ul.nav-tabs > li");

    tabs.on('click', switchTab)

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});


问:
Android: Synchronized scrolling of two different views
I have a tricky problem related to synchronized scrolling of two
different views.
I've made my own custom grid view widget, which has "sticky" views to
the left and top that only in one direction with the grid. Think of a
calendar where you have times at the top, dates at the left, and when
you scroll horizontally through time, the date view should stay put,
and when you scroll vertically through the dates, the time view should
stay put.

The grid itself is implemented using a nested horizontal scrollview in
a vertical scrollview. The grid is working great, so no problem there.
Since the sticky views are not in the actual grid, I have overriden
onScrollChanged in the grid scrollviews and programatically call
scrollTo on the sticky views when the user scrolls the grid.

That works as expected, except that there is a slight time offset as
to when the two different views start scrolling and ends scrolling. It
makes sense when you consider that the scrolling likely is executed
linearly on the UI thread I suppose..

All the views are scroll views, and I have enabled smooth scrolling
and used smoothScrollTo, etc, instead to try to improve this, but it's
the same problem nonetheless. The problem is especially noticeable on
larger screens, such as the Samsung Galaxy Tab, whereas it's hardly
noticeable on small-medium screen devices.

Any help is appreciated! If there is an easy fix, great..if it means
new design (that meets the sticky view usecase above), then so be it.

Code to trigger prog. scroll, same for horizontal

```<code>@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
   mListener.onScrollY(y);
   super.onScrollChanged(x, y, oldx, oldy);
}
// which leads to,
// Handle vertical scroll
public void onScrollY(final int y) {
   mCurrentY = y;
   mVerticalScroll.smoothScrollTo(0, y);
}
</code>```

XML layouts below, if that's of any help

The actual grid, which is a horizontal scroll view wrapped in a vertical scroll view and the grid items are added vertically in the nested linearlayout

    >

```<code>  < com.....VerticalScrollView
    android:id="@+id/gridscroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/timescroll"
    android:layout_toRightOf="@id/vertscroll"
    android:layout_alignTop="@id/vertscroll"
    android:layout_marginLeft="2dp" android:scrollbars="none"
    android:fadingEdge="none">

    < com....HorizScrollView
    android:id="@+id/horizscroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none"
    android:fadingEdge="none">

    < LinearLayout android:id="@+id/grid"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical">

      < /LinearLayout>

      < /com.....HorizScrollView>

      < /com.....VerticalScrollView>
</code>```

The horizontal sticky view

```<code> < com.....GridTimeScrollView
    android:id="@+id/timescroller"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none"
    android:fadingEdge="none">

    < LinearLayout android:id="@+id/timelist"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" />
    < /com.....GridTimeScrollView>
</code>```

The vertical sticky view

```<code>< com....GridVertListScrollView
android:id="@+id/vertscroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
android:fadingEdge="none">

< LinearLayout
android:id="@+id/vertitemlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" />
< /com.....GridVertListScrollView>
</code>```

答: Don't use smoothScrollTo, use scrollTo instead. smoothScrollTo will animate a scroll from its current position to the position you want, because you want them to be synced, you want the other scrollview to be instantly exactly where the other scrollview is, scrollTo does that.</p>

Body:
I have a tricky problem related to synchronized scrolling of two
different views.
I've made my own custom grid view widget, which has "sticky" views to
the left and top that only in one direction with the grid. Think of a
calendar where you have times at the top, dates at the left, and when
you scroll horizontally through time, the date view should stay put,
and when you scroll vertically through the dates, the time view should
stay put.

The grid itself is implemented using a nested horizontal scrollview in
a vertical scrollview. The grid is working great, so no problem there.
Since the sticky views are not in the actual grid, I have overriden
onScrollChanged in the grid scrollviews and programatically call
scrollTo on the sticky views when the user scrolls the grid.

That works as expected, except that there is a slight time offset as
to when the two different views start scrolling and ends scrolling. It
makes sense when you consider that the scrolling likely is executed
linearly on the UI thread I suppose..

All the views are scroll views, and I have enabled smooth scrolling
and used smoothScrollTo, etc, instead to try to improve this, but it's
the same problem nonetheless. The problem is especially noticeable on
larger screens, such as the Samsung Galaxy Tab, whereas it's hardly
noticeable on small-medium screen devices.

Any help is appreciated! If there is an easy fix, great..if it means
new design (that meets the sticky view usecase above), then so be it.

Code to trigger prog. scroll, same for horizontal

@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
   mListener.onScrollY(y);
   super.onScrollChanged(x, y, oldx, oldy);
}
// which leads to,
// Handle vertical scroll
public void onScrollY(final int y) {
   mCurrentY = y;
   mVerticalScroll.smoothScrollTo(0, y);
}

XML layouts below, if that's of any help

The actual grid, which is a horizontal scroll view wrapped in a vertical scroll view and the grid items are added vertically in the nested linearlayout

    >

  < com.....VerticalScrollView
    android:id="@+id/gridscroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/timescroll"
    android:layout_toRightOf="@id/vertscroll"
    android:layout_alignTop="@id/vertscroll"
    android:layout_marginLeft="2dp" android:scrollbars="none"
    android:fadingEdge="none">

    < com....HorizScrollView
    android:id="@+id/horizscroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none"
    android:fadingEdge="none">

    < LinearLayout android:id="@+id/grid"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical">

      < /LinearLayout>

      < /com.....HorizScrollView>

      < /com.....VerticalScrollView>

The horizontal sticky view

 < com.....GridTimeScrollView
    android:id="@+id/timescroller"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none"
    android:fadingEdge="none">

    < LinearLayout android:id="@+id/timelist"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" />
    < /com.....GridTimeScrollView>

The vertical sticky view

< com....GridVertListScrollView
android:id="@+id/vertscroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
android:fadingEdge="none">

< LinearLayout
android:id="@+id/vertitemlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" />
< /com.....GridVertListScrollView>


问:
Fill image into table cell without resizing and overflowing

I want to put image to my table cell without resizing but cropping overflow part. Now I've got only resized image as maximum or cropped only by horizontal

Want:

Got:

Got:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>title</title>
   <link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon">

```

答:
Use background-image instead of simple image like this :

.tablemap {
  table-layout: fixed;
}

.pixelblock {
  padding: 1px;
  width: 120px;
  height: 120px;
  background-color: lightgrey;
  overflow: hidden;
  background-repeat:no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="tablemap">
  <tr>
    <td class="pixelblock" style="background-image:url(https://www.destinationweddings.com/Portals/0/PropertyAgent/446/Images/27082.jpg)">
    </td>
  </tr>
  <!--%TABLE%-->
</table></code>```

Or make the image absolute position and don't forget the relative position for the td :

.tablemap {
  table-layout: fixed;
}

.pixelblock {
  padding: 1px;
  width: 120px;
  height: 120px;
  background-color: lightgrey;
  overflow: hidden;
  position:relative;
}

.pixelblockimage {
  position:absolute;
  top:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="tablemap">
  <tr>
    <td class="pixelblock">
      <img class="pixelblockimage" src="https://www.destinationweddings.com/Portals/0/PropertyAgent/446/Images/27082.jpg" />
    </td>
  </tr>
  <!--%TABLE%-->
</table></code>```

Body:
Use background-image instead of simple image like this :

.tablemap {
  table-layout: fixed;
}

.pixelblock {
  padding: 1px;
  width: 120px;
  height: 120px;
  background-color: lightgrey;
  overflow: hidden;
  background-repeat:no-repeat;
}

<table class="tablemap">
  <tr>
    <td class="pixelblock" style="background-image:url(https://www.destinationweddings.com/Portals/0/PropertyAgent/446/Images/27082.jpg)">
    </td>
  </tr>
  <!--%TABLE%-->
</table>

Or make the image absolute position and don't forget the relative position for the td :

.tablemap {
  table-layout: fixed;
}

.pixelblock {
  padding: 1px;
  width: 120px;
  height: 120px;
  background-color: lightgrey;
  overflow: hidden;
  position:relative;
}

.pixelblockimage {
  position:absolute;
  top:0;
}

<table class="tablemap">
  <tr>
    <td class="pixelblock">
      <img class="pixelblockimage" src="https://www.destinationweddings.com/Portals/0/PropertyAgent/446/Images/27082.jpg" />
    </td>
  </tr>
  <!--%TABLE%-->
</table>


问:
Windows Store App drag and drop between ListViews
I am building a Windows Store App / Universal App targeting Windows 8.1 and Windows 10 and I would like to be able to drag and drop items between ListViews and be able to position the item in a specific spot in the ListView. The main problem I'm having is that I can't find a good way to determine the list index of where the item was dropped.

I found a sample (XAML ListView reorder) but an important difference is that the items in my list have variable heights so the simple calculation this sample project uses to infer the index won't work for me.

I am able to get the x,y position of where within the ListView the item was dropped, but I'm having trouble using that position to figure out the index. I've found mentions of people using ListView.GetItemAt(x, y) or ListView.HitTest(x, y) but as other have found, those methods don't seem to exist in Windows Universal apps. I've also tried using VisualTreeHelper.FindElementsInHostCoordinates() but I'm either not using it properly or I'm not understanding its purpose because I can't get it to return results.

Here is some example code that I've tried:

```<code>private void ListView_OnDrop(object sender, DragEventArgs e)
{
    var targetListView = (ListView)sender;

    var positionRelativeToTarget = e.GetPosition(targetListView);

    var rect = new Rect(positionRelativeToTarget, new Size(10, 15));
    var elements = VisualTreeHelper.FindElementsInHostCoordinates(rect, targetListView);

    // Trying to get the index in the list where the item was dropped
    // 'elements' is always empty
}
</code>```

For reference, I'm using C#, XAML, and Visual Studio 2013.

Thanks!

答:
I'm doing this to get the target listviewItem on the drag over event. It should work for both list and grid views</p>

```<code>private YOURITEMCLASS _dragTarget;

private void ItemListView_OnDragOver(object sender, DragEventArgs e)
{
   var pos = e.GetPosition(this);
   // Offset position by left and top borders if in split view control

   var elements = VisualTreeHelper.FindElementsInHostCoordinates(pos, this);
   foreach (var element in elements)
   {
       var cellItem = element as ContentControl;
       var item = cellItem?.Content as YOURITEMCLASS;
       if (item == null) continue;
       _dragTarget = item;
       break;
   }
}
</code>```

Body:
I am building a Windows Store App / Universal App targeting Windows 8.1 and Windows 10 and I would like to be able to drag and drop items between ListViews and be able to position the item in a specific spot in the ListView. The main problem I'm having is that I can't find a good way to determine the list index of where the item was dropped.

I found a sample (XAML ListView reorder) but an important difference is that the items in my list have variable heights so the simple calculation this sample project uses to infer the index won't work for me.

I am able to get the x,y position of where within the ListView the item was dropped, but I'm having trouble using that position to figure out the index. I've found mentions of people using ListView.GetItemAt(x, y) or ListView.HitTest(x, y) but as other have found, those methods don't seem to exist in Windows Universal apps. I've also tried using VisualTreeHelper.FindElementsInHostCoordinates() but I'm either not using it properly or I'm not understanding its purpose because I can't get it to return results.

Here is some example code that I've tried:

private void ListView_OnDrop(object sender, DragEventArgs e)
{
    var targetListView = (ListView)sender;

    var positionRelativeToTarget = e.GetPosition(targetListView);

    var rect = new Rect(positionRelativeToTarget, new Size(10, 15));
    var elements = VisualTreeHelper.FindElementsInHostCoordinates(rect, targetListView);

    // Trying to get the index in the list where the item was dropped
    // 'elements' is always empty
}

For reference, I'm using C#, XAML, and Visual Studio 2013.

Thanks!

Body:
I'm doing this to get the target listviewItem on the drag over event. It should work for both list and grid views

private YOURITEMCLASS _dragTarget;

private void ItemListView_OnDragOver(object sender, DragEventArgs e)
{
   var pos = e.GetPosition(this);
   // Offset position by left and top borders if in split view control

   var elements = VisualTreeHelper.FindElementsInHostCoordinates(pos, this);
   foreach (var element in elements)
   {
       var cellItem = element as ContentControl;
       var item = cellItem?.Content as YOURITEMCLASS;
       if (item == null) continue;
       _dragTarget = item;
       break;
   }
}


问:
Pimcore installation - ajax calls from install.php 403 forbidden
I am trying to install pimcore 5 with php 7.

When i enter the data to the install form (db name, user, pass.. etc) and press check requirements or install two different ajax post calls happen. When i get the result from both post calls i get 403 forbidden error, ther response is only "Forbidden".

Don't know what to change, and what caused the error.
My server has php 7.1, all the minimum requirements are sufficient.

Please help, regards Dejan

答: Solved. Obviusly my host doesn work with tmp subdomains. Sorry i bothered.</p>


问:
how to omit a file if it does not exist - openpyxl, os
i am using openpyxl to help bulk copy particular filoes from a list within Excel. currently the process being followed is:
Search a worksheet for a particular filename prefix
if file name is found in list, and begins with specific prefix, copy from folder:

```<code>#Import required modules
from openpyxl import load_workbook
import os
import shutil
# Enter source folder

source = ("C:\\Users\\alec.litchfield\\Desktop\\Resized images\\")
# Enter destiantion folder - this must exist.
destination = ("C:\\Users\\alec.litchfield\\Desktop\\Stripped Blackpool Photos\\")
# Enter the name of your Excel Workbook (including the extension):
workBookName = ("C:\\Users\\alec.litchfield\\Desktop\\2017.11.22 Point Data - Master.xlsx") #input("Enter the name of your Excel Workbook (including the extension): ")
workSheetName = ("Point data") #input("Enter the name of the work sheet to read from: ")
RowRange = int(input ("add total number of rows to check: "))
workBook = load_workbook(filename = workBookName, read_only=True,data_only=True)
workSheet = workBook[workSheetName]
#filepath = ("C:\\Users\\alec.litchfield\\Desktop\\My Personal Folder\\Python lessons\\Photo copy paste\\")
for x in range(2, RowRange):
    file = str (workSheet["j" + str(x)].value)
          if file.startswith(('P1010','P1020', 'P1070','P1060','P1050' 'P1040' 'P1020' )):
        shutil.copyfile (source + file, destination + file)
</code>```

The problem i am getting, is that if the file does not exist, then the process stops. this only takes one to cause the stoppage, and is problematic when dealing with the numebr of files that we are copying (4000)

is there a simple addition to the code in order to tell it 'if the file doesnt exist, ignore and move on'

Many thanks in advance!

Alec

答:
Check out the python exceptions functions (try, except, finally)

For example:

```<code>try:
    #do stuff with the file here
except FileNotFoundError:
    #do nothing if the file is not found
    pass
</code>```

Body:
i am using openpyxl to help bulk copy particular filoes from a list within Excel. currently the process being followed is:
Search a worksheet for a particular filename prefix
if file name is found in list, and begins with specific prefix, copy from folder:

#Import required modules
from openpyxl import load_workbook
import os
import shutil
# Enter source folder

source = ("C:\\Users\\alec.litchfield\\Desktop\\Resized images\\")
# Enter destiantion folder - this must exist.
destination = ("C:\\Users\\alec.litchfield\\Desktop\\Stripped Blackpool Photos\\")
# Enter the name of your Excel Workbook (including the extension):
workBookName = ("C:\\Users\\alec.litchfield\\Desktop\\2017.11.22 Point Data - Master.xlsx") #input("Enter the name of your Excel Workbook (including the extension): ")
workSheetName = ("Point data") #input("Enter the name of the work sheet to read from: ")
RowRange = int(input ("add total number of rows to check: "))
workBook = load_workbook(filename = workBookName, read_only=True,data_only=True)
workSheet = workBook[workSheetName]
#filepath = ("C:\\Users\\alec.litchfield\\Desktop\\My Personal Folder\\Python lessons\\Photo copy paste\\")
for x in range(2, RowRange):
    file = str (workSheet["j" + str(x)].value)
          if file.startswith(('P1010','P1020', 'P1070','P1060','P1050' 'P1040' 'P1020' )):
        shutil.copyfile (source + file, destination + file)

The problem i am getting, is that if the file does not exist, then the process stops. this only takes one to cause the stoppage, and is problematic when dealing with the numebr of files that we are copying (4000)

is there a simple addition to the code in order to tell it 'if the file doesnt exist, ignore and move on'

Many thanks in advance!

Alec

Body:
Check out the python exceptions functions (try, except, finally)

For example:

try:
    #do stuff with the file here
except FileNotFoundError:
    #do nothing if the file is not found
    pass


问:
Can't get any values in the cursor
I'm confused why I can't get any values in the cursor.
What's wrong in my code..

here's the code..

```<code> sqLiteDatabase = getReadableDatabase();
 Cursor cursor = sqLiteDatabase.query("bank",new String[]{"name", "acno", "available"},"bank_index = ?",new String[]{String.valueOf(bank_index)},null,null,null);
 cursor.moveToFirst();
 String name = cursor.getString(cursor.getColumnIndex("name"));
 String acno = cursor.getString(cursor.getColumnIndex("acno"));
 contentValues.put("bank", name + " Account number: " + acno);
</code>```

I got error of CursorOutOfBoundsException on last third line of the above code..

query of the table:

```<code> sqLiteDatabase.execSQL("create table bank(bank_index integer primary key,name text,acno text,branch text,available text)");
</code>```

答:
Before performing any operation on cursor, you must check </p>

```<code>if(cursor != null && cursor.getCount() > 0 ) {
   //go ahead
}

//You can also try
String query = "SELECT name, acno, available FROM bank WHERE bank_index = '"+String.valueOf(bank_index)+"'";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
</code>```

Title: Can't get any values in the cursor

Body:
I'm confused why I can't get any values in the cursor.
What's wrong in my code..

here's the code..

 sqLiteDatabase = getReadableDatabase();
 Cursor cursor = sqLiteDatabase.query("bank",new String[]{"name", "acno", "available"},"bank_index = ?",new String[]{String.valueOf(bank_index)},null,null,null);
 cursor.moveToFirst();
 String name = cursor.getString(cursor.getColumnIndex("name"));
 String acno = cursor.getString(cursor.getColumnIndex("acno"));
 contentValues.put("bank", name + " Account number: " + acno);

I got error of CursorOutOfBoundsException on last third line of the above code..

query of the table:

 sqLiteDatabase.execSQL("create table bank(bank_index integer primary key,name text,acno text,branch text,available text)");

Body:
Before performing any operation on cursor, you must check

if(cursor != null && cursor.getCount() > 0 ) {
   //go ahead
}

//You can also try
String query = "SELECT name, acno, available FROM bank WHERE bank_index = '"+String.valueOf(bank_index)+"'";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);


问:
Custom UIView without Storyboard
Now I'm practicing build IOS app without using storyboard , but I have a problem want to solve , I created a custom UIView called BannerView and added a background(UIView) and a title(UILabel) , and called this BannerView in the MainVC , but run this app , it crashes at the function setupSubviews() and I don't know why.

```<code>import UIKit
import SnapKit

class BannerView: UIView {

    var background: UIView!
    var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }

    func setupSubviews() {
        background.backgroundColor = .gray
        title.text = "INHEART"

        self.addSubview(background)
        self.addSubview(title)
    }

    override func layoutSubviews() {
        background.snp.makeConstraints { make in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(BannerHeight)
            make.left.top.right.equalTo(0)
        }

        title.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.center.equalTo(background.snp.center)
        }
    }

}

class MainVC: UIViewController {

    var bannerView:BannerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bannerView = BannerView(frame: CGRect.zero)
        view.addSubview(bannerView)
    }

}
</code>```

答:
You are not initialised the background view please initialised them

```<code>self.background = UIView()
self.title = UILabel()
</code>```

and if you want to create custom view by use of xib the follow them Custum View

Title: Custom UIView without Storyboard

Body:
Now I'm practicing build IOS app without using storyboard , but I have a problem want to solve , I created a custom UIView called BannerView and added a background(UIView) and a title(UILabel) , and called this BannerView in the MainVC , but run this app , it crashes at the function setupSubviews() and I don't know why.

import UIKit
import SnapKit

class BannerView: UIView {

    var background: UIView!
    var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }

    func setupSubviews() {
        background.backgroundColor = .gray
        title.text = "INHEART"

        self.addSubview(background)
        self.addSubview(title)
    }

    override func layoutSubviews() {
        background.snp.makeConstraints { make in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(BannerHeight)
            make.left.top.right.equalTo(0)
        }

        title.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.center.equalTo(background.snp.center)
        }
    }

}

class MainVC: UIViewController {

    var bannerView:BannerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bannerView = BannerView(frame: CGRect.zero)
        view.addSubview(bannerView)
    }

}

Body:
You are not initialised the background view please initialised them

self.background = UIView()
self.title = UILabel()

and if you want to create custom view by use of xib the follow them Custum View


问:
Can not put single artist in more than one figure
Here is my issue.

I create a function that plot a list of circles.
I need to plot my circle C1 first with a circle C2 then with C3.... until C40.

```<code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle

def plot_circle(Liste_circles):

    fig = plt.figure(figsize=(5,5))
    ax = fig.add_subplot(111)

    # On définie un fond blanc
    ax.set_facecolor((1, 1, 1))

    ax.set_xlim(-5, 15)
    ax.set_ylim(-6, 12)

    for c in Liste_circles:
        ax.add_patch(c)

    plt.show()
</code>```

Now I create C1:

```<code>C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
</code>```

An finally I try to plot it.

The first plot worked:

```<code>C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
plot_circle([C1,C2])
</code>```

The second one failed:

```<code>C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])
</code>```

with the error:

RuntimeError: Can not put single artist in more than one figure

I can make it worked by doing:

```<code>C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])
</code>```

How can I do to plot my circle C1 with 40 other circles without having to recreate C1 each time? (My program took 10min to create C1 throught a complicated algorithme, I cannot recreate it at each of the 40 plot....).

答:
Here is how to make it work: just do a copy of the circle and plot the copy:

First import copy:

```<code>from copy import copy
</code>```

then, instead of doing:

```<code>for c in Liste_circles:
    ax.add_patch(c)
</code>```

we have to do:

```<code>for c in Liste_circles:
   new_c=copy(c)
   ax.add_patch(new_c)
</code>```

This way we won't plot the same circle (= the same artist) but its copy

Body:
Here is my issue.

I create a function that plot a list of circles.
I need to plot my circle C1 first with a circle C2 then with C3.... until C40.

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

def plot_circle(Liste_circles):

    fig = plt.figure(figsize=(5,5))
    ax = fig.add_subplot(111)

    # On définie un fond blanc
    ax.set_facecolor((1, 1, 1))

    ax.set_xlim(-5, 15)
    ax.set_ylim(-6, 12)

    for c in Liste_circles:
        ax.add_patch(c)

    plt.show()

Now I create C1:

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')

An finally I try to plot it.

The first plot worked:

C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
plot_circle([C1,C2])

The second one failed:

C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])

with the error:

RuntimeError: Can not put single artist in more than one figure

I can make it worked by doing:

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])

How can I do to plot my circle C1 with 40 other circles without having to recreate C1 each time? (My program took 10min to create C1 throught a complicated algorithme, I cannot recreate it at each of the 40 plot....).

Body:
Here is how to make it work: just do a copy of the circle and plot the copy:

First import copy:

from copy import copy

then, instead of doing:

for c in Liste_circles:
    ax.add_patch(c)

we have to do:

for c in Liste_circles:
   new_c=copy(c)
   ax.add_patch(new_c)

This way we won't plot the same circle (= the same artist) but its copy


问:
Automatic manipulation of data in Oracle with Jupyter Notebook (Windows & OS X)
I have a table with 5 columns and an empty column in oracle. I am searching for a way to pull that table from Oracle, use it in the Jupyter Notebook to add data in that empty column (through executing the python script) and then INSERT the table into Oracle again.

I know i could just export the table from Oracle manually, run it through the notebook and use the import in Oracle manually, but i am searching for a way that i could do all those steps as an automatic daily job.

I am using both windows and OS x, so it would be cool if there would be both solutions to this problem.

Best regards & thank you in advance

答:
Did you try using 'cx_Oracle' module.

Below link has the example usage:

http://www.oracle.com/technetwork/articles/dsl/python-091105.html


问:
Don't drop dimensions when subseting 3-dimensional array
Let A be a 1 x 2 x 2-array:

```<code>> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0
</code>```

Then A[,,1] is dimensionless:

```<code>> A[,,1]
[1] 0 0
</code>```

I would like to have:

```<code>     [,1] [,2]
[1,]    0    0
</code>```

The drop argument does not yield what I want:

```<code>> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0
</code>```

I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.

Of course I could do matrix(A[,,1], 1, 2). Is there a more convenient way?

答:
```<code>t(A[,,1])
 [,1] [,2]
[1,]    0    0
</code>```

I though of it from your comment that R identifies vector to column matrix. I think transpose it gives what you want, and is a bit more convenient.

Body:
Let A be a 1 x 2 x 2-array:

> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0

Then A[,,1] is dimensionless:

> A[,,1]
[1] 0 0

I would like to have:

     [,1] [,2]
[1,]    0    0

The drop argument does not yield what I want:

> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0

I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.

Of course I could do matrix(A[,,1], 1, 2). Is there a more convenient way?

Body:
t(A[,,1])
 [,1] [,2]
[1,]    0    0

I though of it from your comment that R identifies vector to column matrix. I think transpose it gives what you want, and is a bit more convenient.


问:
How to get the load time of a web page using chrome console window and console commands?
How can I get the load time of a web page in Chrome's JavaScript console?

I openede google.com and tried the following commands: console.time, console.loadTime. Is there a specific command which I can use to obtain the full load time of a given page?

答:
You can use the deprecated window.performance.timing API to see different events and their timestamps. To calculate the load time for a page in milliseconds, get the time difference between the loadEventEnd and navigationStart like this:

window.performance.timing.loadEventEnd - window.performance.timing.navigationStart
```

ContentLicense: CC BY-SA 4.0


问:
Multi-threading in Android
I'm new to Android and Java. I'm trying to download 1000 plus images. I don't want to do that serially in a UI thread as that will be slow. Hence, I implemented multi-threading using thread and runnable in the below manner.

The for-loop will be called 1000 plus times. So is it an efficient way of achieving it? Will the OS manage the thread pool by its own?

```<code>private void syncS3Data() {
    tStart = System.currentTimeMillis();
    try {
        for (final AWSSyncFile f : awsSyncData.getFiles()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    beginDownload(f);
                }

            }).start();
        }
    } catch (Exception ex) {
        progressDialog.dismiss();
        showMessage("Error:" + ex.getStackTrace().toString());
    }
}
</code>```

答:
for Sure you can't do that in MainThread (UI Thread) because if you did, the application will not be responding.. and then it will be killed by system, you can use AsyncTask class in order to do what do you need but i prefer to use intentservice
However you have to use Intentservice it's a worker thread (long operation) but be noted intentservice will not execute anything until it finish the current task, if you need to download it in parallel then you have to use Service it works with UI Thread so you need asyncTask in order to perform the action but make sure of calling stopSelf() unlike intentService it will be stopped once it finish</p>

Title: Multi-threading in Android

Body:
I'm new to Android and Java. I'm trying to download 1000 plus images. I don't want to do that serially in a UI thread as that will be slow. Hence, I implemented multi-threading using thread and runnable in the below manner.

The for-loop will be called 1000 plus times. So is it an efficient way of achieving it? Will the OS manage the thread pool by its own?

private void syncS3Data() {
    tStart = System.currentTimeMillis();
    try {
        for (final AWSSyncFile f : awsSyncData.getFiles()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    beginDownload(f);
                }

            }).start();
        }
    } catch (Exception ex) {
        progressDialog.dismiss();
        showMessage("Error:" + ex.getStackTrace().toString());
    }
}


问:
Where can i get a wiki formatting widget for my django application?
Am looking for a wiki formatting widget for my django application, just like the one am using to type this question in stackoverflow?</p>

答:
There are two parts to this question.  If you're looking for the client-side Javascript WYSIWYG (or WYSIWYM) editor widget, that's unrelated to Django and WMD is a fine choice (though personally I prefer MarkItUp!).

If you're looking for the server-side (Django) piece of the equation, you might check into django-markitup.

OwnerDisplayName: gath

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Carl Meyer


问:
Android: saving application state when going to the "background"
I have a complex Android app with a decent amount of application state that needs to be persisted (in a specific format). Writing out the data is not an instantaneous operation and so it would be ideal to minimize persisting it unnecessarily.

Because of the persistence overhead it is not practical to persist the state every time it is changed. Ideally, persisting state would be triggered when the app is "backgrounded" by the user tapping the 'home' button or tapping the 'back' button on the app's root Activity (or by an incoming call, etc.). This minimizes persistence overhead while maintaining state consistency from the user's perspective. The question is how can you detect if the app is being "backgrounded"?

The Activity lifecycle calls (onStart, onResume, onPause and friends) don't help as the app has many different activities, any one of which could be active when the user taps 'home'. Furthermore, the calls get called when Activities get pushed, popped (and bottom killed) on the Activity stack and so they don't reflect if the app is going away or not.

So how does an app detect when it is going to the background?

答:
I suggest managing your data on an activity-by-activity basis.  This is suggested in the android docs.

For any activity that alters your persistent state, save that state when leaving the activity.

From http://developer.android.com/reference/android/app/Activity.html

onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).


问:
How to insert with table creation
I am looking for a more appropriate way to execute several inserts into a nonexistent table.
To create the table beforehand is not easily possible, as I don't know the data type of the selected column.
An "insert with create" would do, but I don't think there is anything like that.

Is there any better way to do so than to select into and then to insert?

Here is the "bad" way I do it, in an example very much stripped down to demonstrate the problem.

```<code>set nocount on

declare
    @name sysname = '',
    @i int = 0,
    @sql nvarchar(4000) = ''

declare test cursor for
    select top 10 a.name from sys.tables a inner join sys.columns b on a.object_id = b.object_id --and b.name = 'description'
open test
fetch next from test into @name
while (@@FETCH_STATUS <> -1)
begin

    if @i = 0 begin

        set @sql = 'select distinct top 10 description into #t1 from ' + @name + ''
        select @sql
        --  exec sp_executesql @sql

    end
    else begin

        set @sql = 'insert #t1 select distinct top 10 description into #t1 from ' + @name + ''
        select @sql
        --  exec sp_executesql @sql

    end
    set @i = @i + 1
    fetch next from test into @name
end
close test
deallocate test

if object_id ('tempdb..#t1') is not null select * from #t1
</code>```

This solution is "bad" as you need the statement at two positions. In the case shown here this is trivial, but when the statement gets more complex this can become an issue.

答:
The SELECT INTO statement copies data from one table into a new table, this might help you.

Example:-

SELECT *
INTO newtable
FROM oldtable
WHERE condition

The above also supports joins.

Title: How to insert with table creation

Body:
I am looking for a more appropriate way to execute several inserts into a nonexistent table.
To create the table beforehand is not easily possible, as I don't know the data type of the selected column.
An "insert with create" would do, but I don't think there is anything like that.

Is there any better way to do so than to select into and then to insert?

Here is the "bad" way I do it, in an example very much stripped down to demonstrate the problem.

set nocount on

declare
    @name sysname = '',
    @i int = 0,
    @sql nvarchar(4000) = ''

declare test cursor for
    select top 10 a.name from sys.tables a inner join sys.columns b on a.object_id = b.object_id --and b.name = 'description'
open test
fetch next from test into @name
while (@@FETCH_STATUS <> -1)
begin

    if @i = 0 begin

        set @sql = 'select distinct top 10 description into #t1 from ' + @name + ''
        select @sql
        --  exec sp_executesql @sql

    end
    else begin

        set @sql = 'insert #t1 select distinct top 10 description into #t1 from ' + @name + ''
        select @sql
        --  exec sp_executesql @sql

    end
    set @i = @i + 1
    fetch next from test into @name
end
close test
deallocate test

if object_id ('tempdb..#t1') is not null select * from #t1

This solution is "bad" as you need the statement at two positions. In the case shown here this is trivial, but when the statement gets more complex this can become an issue.