问:
Portfolio Page Using MagnificPopup - Popup to link and popup to image on each portfolio item
I hope I can make this as clear as possible. I have a portfolio section on my one page scroll portfolio page, I want to have two links on each portfolio item div, which show when hovered over... one link which will trigger an image popup  will show an image of details of the individual project and one which will link to the url of the finished work I am showcasing. For MagnificPopup it seems that I can only have one trigger or the other. Thank you for the help! <img src="https://i.stack.imgur.com/ITbk4.png" alt="picture of ">    </p>

```<code>Javascript

  // Initialize MagnificPopup Plugin
    $('.filtr-container').magnificPopup({
        type:'inline',
        delegate: 'a',
        gallery:{enabled:true},
        zoom:{
            enabled:true,
            duration: 300,
            easing: 'ease-in-out'
        }
    });

HTML

    <!-- =============================
      5. Start Portfolio
    =============================== -->
    <div class="portfolio section" id="4">
      <div class="container-fluid">
        <div class="row portfolio-holder">
          <h1 class="wow fadeInUp" data-wow-duration="1.5s">PORTFOLIO</h1>
       <div class="col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1">
        <div class="row filtr-container wow fadeInUp" data-wow-duration="1.5s">

         <!-- ===== Single Portfolio Item Start ===== -->
              <div class="col-sm-4 col-xs-6 filtr-item" data-category="1">
                <div class="item-holder">

 <!-- ===== First Link I want ===== -->
<a href="https://www.testingtest.com/" target="blank" title="Project Title 04">

 <!-- ===== Second Link I want ===== -->
<a href="image/Portfolio/item3.jpg" title="Project Title 03">

                    <img src="image/Portfolio/item1.jpg" alt="item1">
                    <div class="item-caption">
                      <h2>Project <br> Title</h2>

                      <p>Graphic Design</p>
                          <p>Tools Used: HTML, CSS, JSS</p>
                      <div class="item-created">Jan 2017 </div>

                    </div>
<!-- item-caption -->
                  </a>
                </div> <!-- item-holder -->
              </div> <!-- filtr-item -->

              <!-- ===== Single Portfolio Item End ===== -->

            </div> <!-- filtr-container -->
          </div> <!-- col-sm-10 -->
        </div> <!-- row portfolio-holder -->
      </div> <!-- container-fluid -->
    </div> <!-- portfolio -->
</code>```

答:
So in reading over my question, I didn't clarify very well. Those of you who are curious. I just needed to create another initialization to have my logos pop up to an image modal and my websites go to a seperate url. </p>

```<code> // Initialize MagnificPopup Plugin
$('.filtr-container').magnificPopup({
    type:'div',
    delegate: 'button',
    gallery:{enabled:true},
    zoom:{
        enabled:true,
        duration: 300,
        easing: 'ease-in-out'
    }

        });

  $('.image-item').magnificPopup({

    type:'image',
    delegate: 'a',
    gallery:{enabled:true},
    zoom:{
        enabled:true,
        duration: 300,
        easing: 'ease-in-out'
    }

});
</code>```

Body:
I hope I can make this as clear as possible. I have a portfolio section on my one page scroll portfolio page, I want to have two links on each portfolio item div, which show when hovered over... one link which will trigger an image popup  will show an image of details of the individual project and one which will link to the url of the finished work I am showcasing. For MagnificPopup it seems that I can only have one trigger or the other. Thank you for the help!

Javascript

  // Initialize MagnificPopup Plugin
    $('.filtr-container').magnificPopup({
        type:'inline',
        delegate: 'a',
        gallery:{enabled:true},
        zoom:{
            enabled:true,
            duration: 300,
            easing: 'ease-in-out'
        }
    });

HTML

PORTFOLIO

Project
 Title

Graphic Design

Tools Used: HTML, CSS, JSS

Jan 2017

Body:
So in reading over my question, I didn't clarify very well. Those of you who are curious. I just needed to create another initialization to have my logos pop up to an image modal and my websites go to a seperate url.

 // Initialize MagnificPopup Plugin
$('.filtr-container').magnificPopup({
    type:'div',
    delegate: 'button',
    gallery:{enabled:true},
    zoom:{
        enabled:true,
        duration: 300,
        easing: 'ease-in-out'
    }

        });

  $('.image-item').magnificPopup({

    type:'image',
    delegate: 'a',
    gallery:{enabled:true},
    zoom:{
        enabled:true,
        duration: 300,
        easing: 'ease-in-out'
    }

});


来源: stackexchange

问:
Camera Plugin is not working on PhoneGap Build for Android
I am creating a PhoneGap app. I installed camera app with "phonegap plugin add cordova-plugin-camera". It works fine in phonegap aplication but after i do a successful build and upload it to phonegap build, none of these buttons are working on my android phone. I am posting my index, config and manifest below. Thank you for your help.

Index.html

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" href="jq/jquery.mobile-1.4.5.css" />
<script type="text/javascript" src="cordova.js"></script>
<script src="jq/jquery-3.2.1.js"></script>
<script src="jq/jquery.mobile-1.4.5.js"></script>
<title>Blank App</title>
<script type="text/javascript" charset="utf-8">
var pictureSource;
var destinationType;

document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}

function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}

function onPhotoURISuccess(imageURI) {
alert("inside large image")
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}

function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}

function capturePhotoEdit() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail,
{ quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}

function getPhoto(source) {
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}

function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
</code>```

Config.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.helloworld" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
<name>App005</name>
<description>
    A blank PhoneGap app.
</description>
<author email="support@phonegap.com" href="http://phonegap.com">
    PhoneGap Team
</author>
<content src="index.html" />
<access origin="*" />
<engine name="android" spec="~6.3.0" />
<plugin name="cordova-plugin-camera" spec="~3.0.0" />
</widget>
</code>```

AndroidManifest.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="com.phonegap.helloworld" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
<intent-filter android:label="@string/launcher_name">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="android.support.v4.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
</application>
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
</code>```

答: I was having the similar issue on Android with Phonegap version 7.0.1 and cordova-plugin-camera. It was working as expected on iOS. Updating the plugin to older version have fixed the issue. Thanks</p>

ContentLicense: CC BY-SA 3.0

Body:
I am creating a PhoneGap app. I installed camera app with "phonegap plugin add cordova-plugin-camera". It works fine in phonegap aplication but after i do a successful build and upload it to phonegap build, none of these buttons are working on my android phone. I am posting my index, config and manifest below. Thank you for your help.

Index.html

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" href="jq/jquery.mobile-1.4.5.css" />

<title>Blank App</title>

<button onclick="capturePhoto();">Capture Photo</button>

<button onclick="capturePhotoEdit();">Capture Editable Photo</button>

<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button>

<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button>

Config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.helloworld" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
<name>App005</name>
<description>
    A blank PhoneGap app.
</description>
<author email="support@phonegap.com" href="http://phonegap.com">
    PhoneGap Team
</author>
<content src="index.html" />
<access origin="*" />
<engine name="android" spec="~6.3.0" />
<plugin name="cordova-plugin-camera" spec="~3.0.0" />
</widget>

AndroidManifest.xml

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="com.phonegap.helloworld" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
<intent-filter android:label="@string/launcher_name">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="android.support.v4.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
</application>
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>


问:
IIS 10.0 AppPool crashing (causing 503 error)
Situation

After the latest Windows 10 updates (Nov 2017) were installed, the Application Pool required by a local web application keeps stopping/crashing displaying the message below in Event Viewer:

The worker process for application pool 'SrvAppPoolv4.0'
  encountered an error 'Cannot read configuration file ' trying to read
  configuration data from file '\\?\<EMPTY>', line number '0'.  The data
  field contains the error code.

Setup

Windows 10

Internet Information Services (Version 10.0.16299.15)

What I've tried

I've tried a few things that I've found via Google, both here on Stackoverflow and other sites, nothing has helped so far. Some of what I've tried:

Changed the AppPool Identity to a different user (Right-click, Advanced Settings).

Checked the permissions on the machine.config (all four of them in the various \Windows\Microsoft.NET\Framework\.. and ..\Framework64\.. folders).

Unchecked the IIS and .NET features (Control Panel / Windows Features) and then added them back in again.

Uninstalled the application in question, cleared everything, then re-installed it.

Nothing has helped.

Besides reinstalling the entire machine, what else can I try?

Also, besides the Event Viewer, are there any other logs I can review to get more details? I read something about an application log, but nothing as to where to find it?

Update:

I just tried what user3739842 suggested Add/Remove Programs, selecting IIS Express and then Repair - issue remains.

Solution

For me the solution was the following (thanks rusware):

Go to the drive your IIS is installed on, eg. C:\inetpub\temp\appPools\

Delete the directory (or virtual directory) with the same name as your app pool.

Recycle/Start your app pool again.

In my case, it was a virtual directory which was corrupted.

答:
Hi the answer to your problem can be found here. It worked for me and same error

Cannot read configuration file ' trying to read configuration data from file '\\?\<EMPTY>', line number '0'.


问:
How to set conditional breakpoint in anonymous inner class depending on final local variable?
suppose I have the following class and want to set a conditional breakpoint on arg==null at the marked location. This won't work in eclipse and gives the error "conditional breakpoint has compilation error(s). Reason: arg cannot be resolved to a variable".

I found some related information here, but even if I change the condition to "val$arg==null" (val$arg is the variable name displayed in the debugger's variable view), eclipse gives me the same error.

```<code>public abstract class Test {

    public static void main(String[] args) {
        Test t1 = foo("123");
        Test t2 = foo(null);
        t1.bar();
        t2.bar();
    }

    abstract void bar();

    static Test foo(final String arg) {
        return new Test() {
            @Override
                void bar() {
                // I want to set a breakpoint here with the condition "arg==null"
                System.out.println(arg);
            }
        };
    }
}
</code>```

答:
You could try placing the argument as a field in the local class.</p>

```<code>static Test foo(final String arg) {
    return new Test() {
        private final String localArg = arg;
        @Override
            void bar() {
            // I want to set a breakpoint here with the condition "arg==null"
            System.out.println(localArg);
        }
    };
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
suppose I have the following class and want to set a conditional breakpoint on arg==null at the marked location. This won't work in eclipse and gives the error "conditional breakpoint has compilation error(s). Reason: arg cannot be resolved to a variable".

I found some related information here, but even if I change the condition to "val$arg==null" (val$arg is the variable name displayed in the debugger's variable view), eclipse gives me the same error.

public abstract class Test {

    public static void main(String[] args) {
        Test t1 = foo("123");
        Test t2 = foo(null);
        t1.bar();
        t2.bar();
    }

    abstract void bar();

    static Test foo(final String arg) {
        return new Test() {
            @Override
                void bar() {
                // I want to set a breakpoint here with the condition "arg==null"
                System.out.println(arg);
            }
        };
    }
}

Body:
You could try placing the argument as a field in the local class.

static Test foo(final String arg) {
    return new Test() {
        private final String localArg = arg;
        @Override
            void bar() {
            // I want to set a breakpoint here with the condition "arg==null"
            System.out.println(localArg);
        }
    };
}


问:
how to mapping hibernate entity to db view
Could you help me how can I mapping to any entity to db view?

Scenario is here, We create a view on db with native sql we have to do like this and we want to mapping this view to ours entity.

How can we do that? We try to create an entity with same columns on view but it doesn't work?

答:
Hibernate-specific @Immutable annotation which I use in the following code snippet.
View can be mapped as like below....

```<code>@Entity
@Immutable
public class <NAME>View {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Version
@Column(name = "version")
private int version;
</code>```

The @Immutable annotation tells Hibernate to ignore all changes on this entity, but you can use it to retrieve data from the database.

List<View> views = em.createQuery("SELECT v FROM View v", View.class).getResultList();

Body:
Hibernate-specific @Immutable annotation which I use in the following code snippet.
View can be mapped as like below....

@Entity
@Immutable
public class <NAME>View {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Version
@Column(name = "version")
private int version;

The @Immutable annotation tells Hibernate to ignore all changes on this entity, but you can use it to retrieve data from the database.

List<View> views = em.createQuery("SELECT v FROM View v", View.class).getResultList();


问:
Accessing AJAX JSON properties with index gives undefined in the promise
So I have quiz app which is talking to my API on the server with MongoDB.

I want to access its response indexes like so:

```<code>setTimeout(() => {

  axios.get('/api/ninjas')
    .then(function (questions) {
      var data = questions.data;

  $.each(data, function(index, value) {
    /*thequestion = [
      new Question(value.the_question[index], value.the_choices[index], value.the_answer[index])

    ]*/
    console.log(value[index].the_question);
    quiz = new Quiz(thequestion)
    populate()
  })
}), 2000});
</code>```

But I get Uncaught (in promise) TypeError: Cannot read property 'the_question' of undefined

If I remove the [index] then I get the question text out in the console. I also tried putting [index] in the end like so console.log(value.the_question[index]); but then I just get one letter at the time in the screen.

So basically I have two objects in my MongoDB collection. Each contains the_question string, the_choices array and the_answer string. I want to output one question at a time in the screen and its answer choices, but when I reload the page I get only the last question in the DB collection and all answer choices at a time stacked right after each other, even tho there should be no more than 3 buttons for each question. When there is only one question in DB it works fine.

One question in DB:

More than one question in DB collection:

So I want to use indexes to output one question at a time, but I get error when using them. What's wrong?

I have to mention that it was working fine I wasn't using DB for this. Just globals in javascript. Like this, I was getting one question at a time

```<code>let thequestion = [
  new Question("Which one of the three is a programming language?", ["Javascript", "HTML", "CSS"], "Javascript"),
  new Question("Is NodeJS is a front end or back end framework?", ["Back end", "Front End"], "Back end"),
  new Question("Is JAVA object oriented language?", ["Yes", "No"], "Yes")
]
</code>```

My DB looks like this:

EDIT: The whole front-end source code:

https://codepen.io/Limpuls/pen/rYYLro?editors=1010

答:
You could try the following, if that doesn't work could you please update your question with the output of the console log so we can see the format of the questions received by your API?

```<code>setTimeout(() => {
  axios.get('/api/ninjas')
  .then(function (questions) {
    console.log(
      "received questions:"
      ,JSON.stringify(questions,undefined,2)
    );
    quiz = new Quiz(//create a quiz
      (questions.data || [])//map question data to Question type
      .map(
        function (question) {
          return new Question(
            question.the_question,
            question.the_choices,
            question.the_answer
          );
        }
      )
    );
    populate()
  })
  , 2000
});
</code>```

Why are you waiting 2 seconds to get the data? If this is on page load then you could try $(document).ready but I don't think you have to wait for document ready to start fetching the questions (maybe  only populate):

```<code>$(document).ready(x=>populate());
</code>```

Body:
So I have quiz app which is talking to my API on the server with MongoDB.

I want to access its response indexes like so:

setTimeout(() => {

  axios.get('/api/ninjas')
    .then(function (questions) {
      var data = questions.data;

  $.each(data, function(index, value) {
    /*thequestion = [
      new Question(value.the_question[index], value.the_choices[index], value.the_answer[index])

    ]*/
    console.log(value[index].the_question);
    quiz = new Quiz(thequestion)
    populate()
  })
}), 2000});

But I get Uncaught (in promise) TypeError: Cannot read property 'the_question' of undefined

If I remove the [index] then I get the question text out in the console. I also tried putting [index] in the end like so console.log(value.the_question[index]); but then I just get one letter at the time in the screen.

So basically I have two objects in my MongoDB collection. Each contains the_question string, the_choices array and the_answer string. I want to output one question at a time in the screen and its answer choices, but when I reload the page I get only the last question in the DB collection and all answer choices at a time stacked right after each other, even tho there should be no more than 3 buttons for each question. When there is only one question in DB it works fine.

One question in DB:

More than one question in DB collection:

So I want to use indexes to output one question at a time, but I get error when using them. What's wrong?

I have to mention that it was working fine I wasn't using DB for this. Just globals in javascript. Like this, I was getting one question at a time

let thequestion = [
  new Question("Which one of the three is a programming language?", ["Javascript", "HTML", "CSS"], "Javascript"),
  new Question("Is NodeJS is a front end or back end framework?", ["Back end", "Front End"], "Back end"),
  new Question("Is JAVA object oriented language?", ["Yes", "No"], "Yes")
]

My DB looks like this:

EDIT: The whole front-end source code:

https://codepen.io/Limpuls/pen/rYYLro?editors=1010

Body:
You could try the following, if that doesn't work could you please update your question with the output of the console log so we can see the format of the questions received by your API?

setTimeout(() => {
  axios.get('/api/ninjas')
  .then(function (questions) {
    console.log(
      "received questions:"
      ,JSON.stringify(questions,undefined,2)
    );
    quiz = new Quiz(//create a quiz
      (questions.data || [])//map question data to Question type
      .map(
        function (question) {
          return new Question(
            question.the_question,
            question.the_choices,
            question.the_answer
          );
        }
      )
    );
    populate()
  })
  , 2000
});

Why are you waiting 2 seconds to get the data? If this is on page load then you could try $(document).ready but I don't think you have to wait for document ready to start fetching the questions (maybe  only populate):

$(document).ready(x=>populate());


问:
Disable touch on scroll, enable gestures on its subviews?
I have to disable scrolling on scrollview, so it can be scrolled only by software and not by the user.

```<code>scrollView.isUserInteractionEnabled = false
</code>```

This scrollview has some views, and they have TapGesture on them, I enabled their interaction :

```<code>        view.isUserInteractionEnabled=true
</code>```

But it will not work unless I enable the interaction on the scroller.
Is there any other way to achieve my goal ?

答:
Set isScrollEnabled to false instead of userInteractionEnabled.

```<code>scrollView.isScrollEnabled = false
</code>```

isScrollEnabled

If the value of this property is true , scrolling is enabled, and if
  it is false , scrolling is disabled. The default is true. When
  scrolling is disabled, the scroll view does not accept touch events;
  it forwards them up the responder chain.

Body:
I have to disable scrolling on scrollview, so it can be scrolled only by software and not by the user.

scrollView.isUserInteractionEnabled = false

This scrollview has some views, and they have TapGesture on them, I enabled their interaction :

        view.isUserInteractionEnabled=true

But it will not work unless I enable the interaction on the scroller.
Is there any other way to achieve my goal ?

Body:
Set isScrollEnabled to false instead of userInteractionEnabled.

scrollView.isScrollEnabled = false

isScrollEnabled

If the value of this property is true , scrolling is enabled, and if
  it is false , scrolling is disabled. The default is true. When
  scrolling is disabled, the scroll view does not accept touch events;
  it forwards them up the responder chain.


问:
embed code loop not working
```<code><embed
    id="audio_1"
    src="website.com/music.mp3"
    loop=TRUE
    autoplay="true"
    PLAYCOUNT="3">
</code>```

This embed code loop isn't working. I tried using loop and playcount but none of the attributes are working for me, autoplay is working fine though. This doesn't works in Chrome or Firefox.

答:
I just figured out: you need to have playlist="" to use loop</p>

```<code>src="https://www.youtube.com/embed/peSfCy7HFrM?playlist=peSfCy7HFrM&loop=1;rel=0&autoplay=1&controls=0&showinfo=0" frameborder="0" allowfullscreen>
</code>```

Title: embed code loop not working

Body:
<embed
    id="audio_1"
    src="website.com/music.mp3"
    loop=TRUE
    autoplay="true"
    PLAYCOUNT="3">

This embed code loop isn't working. I tried using loop and playcount but none of the attributes are working for me, autoplay is working fine though. This doesn't works in Chrome or Firefox.

Body:
I just figured out: you need to have playlist="" to use loop

src="https://www.youtube.com/embed/peSfCy7HFrM?playlist=peSfCy7HFrM&loop=1;rel=0&amp;autoplay=1&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen>


问:
Tweepy returns 414 error retrieving status of only most recent tweet
My code looks like:

```<code>user = api.get_user('any_user_you_like')
for status in api.user_timeline(user, count=1, trim_user=1):
    status = str(status.id)
</code>```

When I run this on my own twitter account it returns my latest tweet ID with no issue.  However when I run this on the twitter account of someone with a lot of tweets, like a celebrity I receive the error:

```<code>tweepy.error.TweepError: Twitter error response: status code = 414
</code>```

It looks like something is coming back too large to be parsed, however I'm only asking for 1 tweet and it works on my own user and those of my friends who have roughly 1300 tweets or less.

Any suggestions, or is there a better way to get just the last tweet of a specific user?  The script continues by comparing the tweet ID received to the last tweet by that user to determine if it is new, however there may be a better way to do this.

答:
I solved the issue.  api.get_user returns a ton of data for the user that isn't necessarily their user ID or anything relevant.  You can forgo the user = api.get_user('name')  bit entirely and just do:

```<code>for status in api.user_timeline(screen_name='any_name_you_like', count=1, trimuser=1):
    status = str(status.id)
</code>```

Body:
My code looks like:

user = api.get_user('any_user_you_like')
for status in api.user_timeline(user, count=1, trim_user=1):
    status = str(status.id)

When I run this on my own twitter account it returns my latest tweet ID with no issue.  However when I run this on the twitter account of someone with a lot of tweets, like a celebrity I receive the error:

tweepy.error.TweepError: Twitter error response: status code = 414

It looks like something is coming back too large to be parsed, however I'm only asking for 1 tweet and it works on my own user and those of my friends who have roughly 1300 tweets or less.

Any suggestions, or is there a better way to get just the last tweet of a specific user?  The script continues by comparing the tweet ID received to the last tweet by that user to determine if it is new, however there may be a better way to do this.

Body:
I solved the issue.  api.get_user returns a ton of data for the user that isn't necessarily their user ID or anything relevant.  You can forgo the user = api.get_user('name')  bit entirely and just do:

for status in api.user_timeline(screen_name='any_name_you_like', count=1, trimuser=1):
    status = str(status.id)


问:
Jenkins: You have not accepted the license agreements of the following SDK components
I have downloaded the adt-bundle-windows-x86_64-20130219 and apply $ANDROID_HOME/sdk in Android SDK root at Configure System in Jenkins.

My error is:

```<code> * What went wrong:
 A problem occurred configuring project ':app'.
 > You have not accepted the license agreements of the following SDK
 components:
 [Android SDK Build-Tools 25.0.2, Android SDK Platform 25].
 Before building your project, you need to accept the license agreements and
 complete the installation of the missing components using the Android
 Studio SDK Manager.
 Alternatively, to learn how to transfer the license agreements from one
 workstation to another, go to http://d.android.com/r/studio-ui/export-
 licenses.html
</code>```

I have seen a lot of tutorials that i need to run ./sdkmanager --licenses
 at $ANDROID_HOME/tools/bin. But the real problem is i dont have BIN in my adt-bundle. Here is my directory: C:\Users\user\Desktop\Gradle\adt-bundle-windows-x86_64-20130219\sdk\tools. The bin folder is missing and i dont have it. Did i download the wrong sdk tools? I also run the SDK Manager, unfortunately the bin folder is missing in tools.

ADDITIONAL INFORMATION IN JENKINS JOB:
I just invoke the gradle script and add tasks: packageDebug

答:
This is solved.

Steps:

Download sdk tools in android studio website

Create a folder then extract the sdk into that folder

Go to tools/bin directory

Go to CMD in that directory then type ./sdkmanager.bat --licenses

Just press y everytime they ask you for the licenese

Body:
I have downloaded the adt-bundle-windows-x86_64-20130219 and apply $ANDROID_HOME/sdk in Android SDK root at Configure System in Jenkins.

My error is:

 * What went wrong:
 A problem occurred configuring project ':app'.
 > You have not accepted the license agreements of the following SDK
 components:
 [Android SDK Build-Tools 25.0.2, Android SDK Platform 25].
 Before building your project, you need to accept the license agreements and
 complete the installation of the missing components using the Android
 Studio SDK Manager.
 Alternatively, to learn how to transfer the license agreements from one
 workstation to another, go to http://d.android.com/r/studio-ui/export-
 licenses.html

I have seen a lot of tutorials that i need to run ./sdkmanager --licenses
 at $ANDROID_HOME/tools/bin. But the real problem is i dont have BIN in my adt-bundle. Here is my directory: C:\Users\user\Desktop\Gradle\adt-bundle-windows-x86_64-20130219\sdk\tools. The bin folder is missing and i dont have it. Did i download the wrong sdk tools? I also run the SDK Manager, unfortunately the bin folder is missing in tools.

ADDITIONAL INFORMATION IN JENKINS JOB:
I just invoke the gradle script and add tasks: packageDebug


答:
Don't use isUserInteractionEnabled to disable scroll on your tableView. Use isScrollEnabled instead of isUserInteractionEnabled and you don't need to change anything of your view

```<code>scrollView?.isScrollEnabled = false;
</code>```

If you set isUserInteractionEnabled to false, it will ignore touchs on subviews of tableView, doesn't matter isUserInteractionEnabled of the subview is true or false.

Title: Disable touch on scroll, enable gestures on its subviews?

Body:
Don't use isUserInteractionEnabled to disable scroll on your tableView. Use isScrollEnabled instead of isUserInteractionEnabled and you don't need to change anything of your view

scrollView?.isScrollEnabled = false;

If you set isUserInteractionEnabled to false, it will ignore touchs on subviews of tableView, doesn't matter isUserInteractionEnabled of the subview is true or false.


问:
Framework recommendation needed on .NET or JAVA for Volunteer computing (internet nodes)
I want client machines on internet who subscribe to my server to donate their idle cpu cycles.(Like SETI@Home)

They would take jobs(work-units) from server to process, and send back results to the server. (This is the most simple description). The framework i need should allow me to define a job/task. Rest of things like communication, job execution/tracking, client binaries update etc. should be managed by framework.

I evaluated Alchemi.NET a bit, but its not actively maintained, seems half-baked.

BOINC has API in C, but i want a .NET or JAVA framework.

I am looking at Manjrasoft's ANEKA , but it seems to work only for LAN clouds.

There must be some such frameworks available. I need expert recommendations!

答:
How about .net's ClickOnce installer to manage auto updated client binaries.
http://msdn.microsoft.com/en-us/library/t71a733d.aspx

I'm not sure of a "jobs framework" per-say, but  Microsoft's Sync framework to support rolling your own jobs syncing with clients?

http://msdn.microsoft.com/en-us/sync/default


问:
How to check whether a character comes before another character in a string in Python
I'm writing a program that determines whether a math equation input by user has matching parentheses. I have it to where it counts whether the amount of right parentheses are equal to the amount of left parentheses, but the user could input 2)(3+x)(4+x)(6. To avoid telling the user his parentheses match in this case, I want to check if a ')' comes before a '('.

```<code>left_parenth = math.count("(")
right_parenth = math.count(")")

total_parenth = right_parenth + left_parenth

if total_parenth % 2 != 0:
    if right_parenth > left_parenth:
        print("\nYou are missing a left parentheses '('")
    elif right_parenth < left_parenth:
        print("\nYou are missing a right parentheses ')'")

elif total_parenth % 2 == 0:
    print("\nYour equation has the correct amount of parentheses")
</code>```

答:
Using a stack is definitely not necessary. Just keep a count of how many parentheses are open. If that count ever is negative, then they aren't matched, and if the count ends up positive, they aren't matched:

```<code>def valid_parens(string):
    open_count = 0
    for char in string:
        if char == "(":
            open_count += 1
        elif char == ")":
            open_count -= 1
            if open_count < 0:
                return False
    return open_count == 0
</code>```

Test cases:

```<code>assert valid_parens("((2+2)-4)*2") == True
assert valid_parens(")(2/2)(") == False
assert valid_parens("()()()") == True
assert valid_parens("((())") == False
</code>```

Body:
I'm writing a program that determines whether a math equation input by user has matching parentheses. I have it to where it counts whether the amount of right parentheses are equal to the amount of left parentheses, but the user could input 2)(3+x)(4+x)(6. To avoid telling the user his parentheses match in this case, I want to check if a ')' comes before a '('.

left_parenth = math.count("(")
right_parenth = math.count(")")

total_parenth = right_parenth + left_parenth

if total_parenth % 2 != 0:
    if right_parenth > left_parenth:
        print("\nYou are missing a left parentheses '('")
    elif right_parenth < left_parenth:
        print("\nYou are missing a right parentheses ')'")

elif total_parenth % 2 == 0:
    print("\nYour equation has the correct amount of parentheses")

Body:
Using a stack is definitely not necessary. Just keep a count of how many parentheses are open. If that count ever is negative, then they aren't matched, and if the count ends up positive, they aren't matched:

def valid_parens(string):
    open_count = 0
    for char in string:
        if char == "(":
            open_count += 1
        elif char == ")":
            open_count -= 1
            if open_count < 0:
                return False
    return open_count == 0

Test cases:

assert valid_parens("((2+2)-4)*2") == True
assert valid_parens(")(2/2)(") == False
assert valid_parens("()()()") == True
assert valid_parens("((())") == False


问:
Set empty value on number column using SharePoint Designer
I am trying to assign "Column A" value to "Column B" in another list. Both columns are of "Number" data type.

When nothing is entered in Column A, Column is getting set as "0". How can I show empty in Column B also.

Thanks in Advance.

答:
Why not add a condition before assigning "Column A" value to "Column B".
when "Column A" is not empty,assign "Column A" value to "Column B". Therefore, when "Column A" is empty, we do not need do anything.</p>


问:
Spring SimpleFormController in 3.0
i notice that this controller has now been deprecated in the latest spring and was wondering what the alternative controller is?</p>

答:
In Spring 3.0, your Controllers should no longer inherit from a base class.
The standard way is to use annotated controllers.</p>

Title: Spring SimpleFormController in 3.0


问:
my aem instance became inaccessible after configuring referrer filter
I configured the referrer filter and I added get method also as filter method and saved. After that, my aem instance became inaccessible. Im not even able to access the url localhost:4503/system/console/configMgr to modify the referrer filter. May I know what can be done now.

答:
If you have post requests working as expected you can try curling a correct config-

```<code>curl  -F "jcr:primaryType=sling:OsgiConfig"  -F filter.methods=[ \"POST\", \"PUT\", \"DELETE\"] -u admin:admin  http://localhost:4502/apps/system/config/org.apache.sling.security.impl.ReferrerFilter
</code>```

Also, If you have access to file system, you can go to crx-quickstart/launchpad/config/org/apache/sling/security/impl and delete the file ReferrerFilter.config and restart your AEM instance. Default ReferrerFilter config  will be restored.

Body:
If you have post requests working as expected you can try curling a correct config-

curl  -F "jcr:primaryType=sling:OsgiConfig"  -F filter.methods=[ \"POST\", \"PUT\", \"DELETE\"] -u admin:admin  http://localhost:4502/apps/system/config/org.apache.sling.security.impl.ReferrerFilter

Also, If you have access to file system, you can go to crx-quickstart/launchpad/config/org/apache/sling/security/impl and delete the file ReferrerFilter.config and restart your AEM instance. Default ReferrerFilter config  will be restored.


问:
Declare dynamic variable from array list angular js
I created an array.

JS code

```<code>$scope.type = ["status", "category", "subCategory", "room"];
</code>```

I want to use array item as variable. I have to create dynamically. Later I will add a dynamic value. For example when I use $scope.type[0]
variable have to be $scope.status How can I do?

答:
Is this your need ?</p>

```<code>$scope[$scope.type[0]]
</code>```

Body:
I created an array.

JS code

$scope.type = ["status", "category", "subCategory", "room"];

I want to use array item as variable. I have to create dynamically. Later I will add a dynamic value. For example when I use $scope.type[0]
variable have to be $scope.status How can I do?

Body:
Is this your need ?

$scope[$scope.type[0]]


问:
Call Parent Activity method from Child Activity
I have Activity A that starts Activity B. Let me start by saying that I believe that Activity A can't use "startActivityForResult()" because Activity B can replace himself for another Activity B (this means, starting another activity and finishing himself), and if that happened Activity A wouldn't be expecting a result anymore and that second Activity B couldn't pass Activity A the result.

Activity A has the instance of the Model. Is there anyway I can get access to the Model from Activity B?

答:
In ActivityA You have to implements Serializable and using Intent.
Try it.

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Go to Activity B
    Intent gotoActivityB = new Intent(this, ActivityB.class);
    gotoActivityB.putExtra("ACTIVITY_A", this);
    startActivity(gotoActivityB);
}
</code>```

In Activity B You can get Activity A from Intent

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    // get Activity A
    if (getIntent() != null){
        AcitivityA acitivityA = (AcitivityA) getIntent().getSerializableExtra("ACTIVITY_A");
    }
}
</code>```

Sorry for my bad english :(

ContentLicense: CC BY-SA 4.0

Body:
In ActivityA You have to implements Serializable and using Intent.
Try it.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Go to Activity B
    Intent gotoActivityB = new Intent(this, ActivityB.class);
    gotoActivityB.putExtra("ACTIVITY_A", this);
    startActivity(gotoActivityB);
}

In Activity B You can get Activity A from Intent

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    // get Activity A
    if (getIntent() != null){
        AcitivityA acitivityA = (AcitivityA) getIntent().getSerializableExtra("ACTIVITY_A");
    }
}

Sorry for my bad english :(


问:
OpenCV get pixel channel value from Mat image
Maybe I'm not looking hard enough, but everything seems to want me to use an array. Thus, how do I get the channel value for a particular pixel for foo if foo is something like Mat foo = imread("bar.png")?

答:
The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

```<code>Mat foo;
int x=100, y=50;
</code>```

Solution 1:

Create a macro function that obtains the pixel from the array.

```<code>#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R
</code>```

Solution 2:

Get's the pixel using the method ptr.

```<code>unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R
</code>```

Body:
The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R


问:
Help regarding a shell script
I was creating a init.d service, and was reading a few scripts for reference. I found this one in a skeleton:

What does this snippet do? I get that this is a switch:case. I am asking about the case within the case.

```<code>case "$1" in
  start)
        echo test
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
</code>```

PS: Excuse the title, I couldn't think of a better name

Thanks.

答:
$? holds the exit code of the last executed command.
If 0 - there were no errors.</p>

Title: Help regarding a shell script

Body:
I was creating a init.d service, and was reading a few scripts for reference. I found this one in a skeleton:

What does this snippet do? I get that this is a switch:case. I am asking about the case within the case.

case "$1" in
  start)
        echo test
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac

PS: Excuse the title, I couldn't think of a better name

Thanks.


问:
Youtube iframe "loop" doesn't work
I tried to use the YouTube player demo to generate the code necessary for my video to autoplay and loop itself.
But only the autoplay works, it doesn't loop, and the demo-video doesn't work either. Here is the code I've used.</p>

```<code><iframe class="embed-responsive-item" id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/M7lc1UVf-VE?&autoplay=1&loop=1&rel=0&showinfo=0&color=white&iv_load_policy=3" frameborder="0" allowfullscreen>
</iframe>
</code>```

答:
I just figured out you need to have playlist="" to use loop.

```<code><iframe src="https://www.youtube.com/embed/peSfCy7HFrM?playlist=peSfCy7HFrM&loop=1;rel=0&autoplay=1&controls=0&showinfo=0" frameborder="0" allowfullscreen>
</code>```

Title: Youtube iframe "loop" doesn't work

Body:
I just figured out you need to have playlist="" to use loop.

<iframe src="https://www.youtube.com/embed/peSfCy7HFrM?playlist=peSfCy7HFrM&loop=1;rel=0&autoplay=1&controls=0&showinfo=0" frameborder="0" allowfullscreen>


问:
Android Device Screen Size compared to emulator
I'm new to android and now I'm calculating some of the coordinates based on the screen size of my emulator in android studio, whose width is 1080. Can I assume that other devices also have this size or close to 1080?</p>

答:
You cannot assume that any two Android devices will have the same or similar screen dimensions, even newer phones, for example:

Pixel XL: 1440 x 2560
Pixel: 1080 x 1920

You should look at this: https://developer.android.com/guide/practices/screens_support.html

It will introduce you to the techniques used to have items be the same size regardless of screen dimensions or pixel density.


问:
Quora Python library not installing
I am using macOS 10.13.1 (which is the latest version at this moment) on a MacBook Pro 13" Early 2015, and am trying to install the "quora" library for python 3.6.1. I am trying to install it by typing this into the terminal:

```<code>pip install quora
</code>```

When I do so, it says it is already installed. Then when I type into the python IDLE IDE:

```<code>import quora
</code>```

As a single line program, it says that no module named quora is found, yet when my terminal specifically says it has already been installed.
Any information about how I can fix this will greatly be appreciated. Thank-you.

Edit #1:
When I input in terminal:

```<code>pip3 install quora
</code>```

And I run the import in IDLE, it gives this error message:
Traceback (most recent call last):

File "/Users/Hussein/Downloads/quora_install.py", line 1, in
    import quora
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/quora/init.py", line 8, in
    from user import User, Activity
ModuleNotFoundError: No module named 'user'

Edit #2:
Up until this point I have been using the IDE for Python 3.6. I tried to run the import in Python 2.7, which is the default for the Mac, and works fine. But I do not know if there are functions that I need that may have been added to Python after the 2.7 release. I still wish to continue trying to get it work for v3.6.1.

答: Do you have multiple Python versions on your machine? Try pip3 install quora? </p>

Title: Quora Python library not installing

Body:
I am using macOS 10.13.1 (which is the latest version at this moment) on a MacBook Pro 13" Early 2015, and am trying to install the "quora" library for python 3.6.1. I am trying to install it by typing this into the terminal:

pip install quora

When I do so, it says it is already installed. Then when I type into the python IDLE IDE:

import quora

As a single line program, it says that no module named quora is found, yet when my terminal specifically says it has already been installed.
Any information about how I can fix this will greatly be appreciated. Thank-you.

Edit #1:
When I input in terminal:

pip3 install quora

And I run the import in IDLE, it gives this error message:
Traceback (most recent call last):

File "/Users/Hussein/Downloads/quora_install.py", line 1, in
    import quora
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/quora/init.py", line 8, in
    from user import User, Activity
ModuleNotFoundError: No module named 'user'

Edit #2:
Up until this point I have been using the IDE for Python 3.6. I tried to run the import in Python 2.7, which is the default for the Mac, and works fine. But I do not know if there are functions that I need that may have been added to Python after the 2.7 release. I still wish to continue trying to get it work for v3.6.1.


问:
Regex for range 7.2-80.0, decimal length not required
Anyone see what's wrong with the below query? Trying to confirm a number is between or equal to 7.2 and 80 in regex. Multiple decimals don't matter for example 8.999 is fine. </p>

```<code>^(?:80(?:\.0)?|[8-79](?:\.[0-9])?|7?:\.[2-9])$
</code>```

答:
Your character class [8-79] is not a valid way of matching integers 8 through 79. An integer range in a character class must be a range of one-digit integers. A proper way to match integers 8 through 79 would be:

```<code>(?:[89]|[1-7][0-9])
</code>```

Also, you are only matching up to one decimal place. For example,

```<code>80(?:\.0)?
</code>```

will match 80 and 80.0, but not 80.00. If this could cause a problem for your application, you would instead want to use

```<code>80(?:\.0+)?
</code>```

Using these concepts, I think this regex should do what you want:

```<code>^(?:80(?:\.0+)?|(?:[89]|[1-7][0-9])(?:\.[0-9]+)?|7(?:\.[2-9][0-9]*)?)$
</code>```

Body:
Anyone see what's wrong with the below query? Trying to confirm a number is between or equal to 7.2 and 80 in regex. Multiple decimals don't matter for example 8.999 is fine.

^(?:80(?:\.0)?|[8-79](?:\.[0-9])?|7?:\.[2-9])$

Body:
Your character class [8-79] is not a valid way of matching integers 8 through 79. An integer range in a character class must be a range of one-digit integers. A proper way to match integers 8 through 79 would be:

(?:[89]|[1-7][0-9])

Also, you are only matching up to one decimal place. For example,

80(?:\.0)?

will match 80 and 80.0, but not 80.00. If this could cause a problem for your application, you would instead want to use

80(?:\.0+)?

Using these concepts, I think this regex should do what you want:

^(?:80(?:\.0+)?|(?:[89]|[1-7][0-9])(?:\.[0-9]+)?|7(?:\.[2-9][0-9]*)?)$


答:
Although the problem can be solved with a stack, it's a little wasteful of memory.  In normal-sized inputs this wouldn't ever be a problem, but in really large sequences it would become a problem.  You don't need to keep track of the parens themselves, but just a count of how many open ones there are -- total memory usage is a single integer, rather than one entry on a stack per paren encountered.</p>

```<code>def proper_paren(seq):
    open_parens = 0
    for char in seq:
        if char == '(':
            open_parens += 1
        elif char == ')':
            open_parens -= 1
            if open_parens < 0:
                return False
    return open_parens == 0
</code>```

Title: How to check whether a character comes before another character in a string in Python

Body:
Although the problem can be solved with a stack, it's a little wasteful of memory.  In normal-sized inputs this wouldn't ever be a problem, but in really large sequences it would become a problem.  You don't need to keep track of the parens themselves, but just a count of how many open ones there are -- total memory usage is a single integer, rather than one entry on a stack per paren encountered.

def proper_paren(seq):
    open_parens = 0
    for char in seq:
        if char == '(':
            open_parens += 1
        elif char == ')':
            open_parens -= 1
            if open_parens < 0:
                return False
    return open_parens == 0


问:
Swift 3.0 Dynamically Change Font of a Label
I am using a label to display text that the user has entered so the length of the label is variable. I am wondering if there is a way to dynamically change the font size of my text. Currently, I have constraint the vertical length of the label to 120, and checked off the "Automatically Adjust Font" in the Attributes Inspector but it doesn't scale it like I want. Not sure whether this is a programmatic or design method to do this.

Here's an example of the text being cut off:

答:
You can try this below;</p>

```<code>yourLabel.numberOfLines = 0;
yourLabel.minimumScaleFactor = 0.7;
yourLabel.adjustsFontSizeToFitWidth = true;
</code>```

Body:
You can try this below;

yourLabel.numberOfLines = 0;
yourLabel.minimumScaleFactor = 0.7;
yourLabel.adjustsFontSizeToFitWidth = true;


问:
Generalization vs Specialization of DB table
When I want to design database tables that model a finite parent-child relationship, for e.g., computer as parent, and the components inside as the child; or a simple organizational hierarchy, I am usually torn at which approach to use -

A 'specialized table' approach, in which I create a table for each of the possible entity. In the computer component example, I would have a Computer table and a Component table, with the ComputerID as FK in the Component table referencing back to Computer.ComputerID.
or

A 'generalized table approach, in which I have one table table called Component, with ComponentID as PK, and a ParentComponentID as FK referencing to its parent's ComponentID.

答: In my experience, a Generalized table approach is tempting, because it gives you more power, but in the long term you will find it is complicated to follow and maintain.</p>

OwnerDisplayName: Eduardo Molteni


问:
Spring Boot: Re-use code in another project
I am building a project (Parrent) that use mysql data. Instead of writing new code for that, I want to re-use code in another project (SQLConnection) that I have finished before.

Normally, I will import SQLConnection to Parrent:

```<code>Java Build Path => Project => Add
</code>```

But when I do that and call function from SQLConnection, it shows error

```<code>Cannot determine embedded database driver class for database type NONE
</code>```

I know someone who achieved the same by using the Maven build, but I have no idea how to do it with Maven.

If someone have ever faced this situation, please leave me a comment.

Thank you!

答:
I hope u already have a piece of java code that access MySQL data in SQLconnection project . Create a jar of SQLconnection , use it as maven dependency (Pom.xml)in your Parrent project. Once dependency is injected , import the java class of SQLconnection in Parrent class for access purpose . </p>

<p>Basically I’m asking make SQLconnection as a library for Parrent project . </p>

Body:
I am building a project (Parrent) that use mysql data. Instead of writing new code for that, I want to re-use code in another project (SQLConnection) that I have finished before.

Normally, I will import SQLConnection to Parrent:

Java Build Path => Project => Add

But when I do that and call function from SQLConnection, it shows error

Cannot determine embedded database driver class for database type NONE

I know someone who achieved the same by using the Maven build, but I have no idea how to do it with Maven.

If someone have ever faced this situation, please leave me a comment.

Thank you!

Body:
I hope u already have a piece of java code that access MySQL data in SQLconnection project . Create a jar of SQLconnection , use it as maven dependency (Pom.xml)in your Parrent project. Once dependency is injected , import the java class of SQLconnection in Parrent class for access purpose .

Basically I’m asking make SQLconnection as a library for Parrent project .


问:
What's the proper way to grab an object from my Entities dictionary in a Normalized state and pass it to a component?
I have a state that looks like:

```<code>entities: {
  pageDict: {
   ['someId1']: { name: 'page1', id: 'someId1' },
   ['someId2']: { name: 'page2', id: 'someId2' },
   ['someId3']: { name: 'page3', id: 'someId3' }
  }
}
lists: {
  pageIdList: ['someId1', 'someId2', 'someId3']
}
</code>```

And a Component that looks like:

```<code>const Pages = ( props ) => {
  return (
    <div>
       props.pageIdList.map(( pageId, key ) => {
         return (
           <Page
             key={ key }
             pageObj={ somethingHere }  // What to do here?
           />
         );
       })
    </div>
  );
}
</code>```

To grab the object, I would need to do:

```<code>let pageObj = state.entities.pageDict[ pageId ];
</code>```

I guess I can pass the state.entities.pageDict as props from the Containers.. but I'm trying to look at the selectors pattern and looking at this:

https://redux.js.org/docs/recipes/ComputingDerivedData.html

and I'm wondering if I'm doing this wrong, can someone give me some insight?  I just want to make sure I'm doing this correctly.

EDIT: I got the idea of using Entities from the https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html and the SoundCloud Redux project

EDIT2: I'm looking at things online like this https://github.com/reactjs/redux/issues/584 but I'm questioning if I'm using this incorrectly and I'm not sure how to apply this to my own project

EDIT3: I'm leaning on creating a selector that will get the pageIdList and return a list of the pageobjects from the pageDict.. that way I already have the object to pass into my Page component.

答:
I think I follow what you're trying to do here. With Redux try thinking of your user interface as always displaying something immutable: rather than "passing something to it" it is "reading something from the state". That when when your state changes your user interface is updated (it isn't always this simple but it is a pretty good start).

If I read your answer correctly you have a Map of pages:

```<code>//data
{
  id1: {...pageProperties} },
  id2: {...pageProperties} },
  id3: {...pageProperties} },
}
</code>```

and your page list is the order these are displayed in:

ex:

```<code>[id2, id3, id1]
</code>```

Your page object might look something like this:

```<code>//Page.js
class Page extends React.Component {
  render() {
    const { pageIdList, pageEntities } = this.props //note I'm using props because this is connected via redux
    return (
      <div>
        { pageIdList.map((pageId, index)=>{
          return <Page key={index} pageEntity={pageEntities[pageId]} />  //I'm just pulling the object from the map here
        }}
      </div>
    )
  }
}
//connect is the Redux connect function
export default connect((store)=> { //most examples use "state" here, but it is the redux store
  return {
    pageEntities: store.pageEntities,
    pageIdList: store.pageList
  }
})(Page)
</code>```

Now when we want to change something you update the state via a dispatch / action. That is reduced in the reducer to display the new state. There are a lot of example out there on how this works but the general idea is update the state and the components take care of displaying it.

The result of this code (and there might be some typeos) is that you should see:

Page id: 2, Page id: 3, Page id: 1 because the list of the pages in the state is 2, 3, 1 in the example I gave.

To answer your question specifically what the entity I'm pulling is the global Redux Store (not the internal component state). 'Map State to Props' is really 'Map Store to Props' as the 'state' is part of React and the 'store' is your Redux store.

Does that help? React+Redux is really nice once you figure it out, it took me a solid month to understand all the ins and outs but it really does simplify things in the long run.

Body:
I have a state that looks like:

entities: {
  pageDict: {
   ['someId1']: { name: 'page1', id: 'someId1' },
   ['someId2']: { name: 'page2', id: 'someId2' },
   ['someId3']: { name: 'page3', id: 'someId3' }
  }
}
lists: {
  pageIdList: ['someId1', 'someId2', 'someId3']
}

And a Component that looks like:

const Pages = ( props ) => {
  return (

       props.pageIdList.map(( pageId, key ) => {
         return (
           <Page
             key={ key }
             pageObj={ somethingHere }  // What to do here?
           />
         );
       })

  );
}

To grab the object, I would need to do:

let pageObj = state.entities.pageDict[ pageId ];

I guess I can pass the state.entities.pageDict as props from the Containers.. but I'm trying to look at the selectors pattern and looking at this:

https://redux.js.org/docs/recipes/ComputingDerivedData.html

and I'm wondering if I'm doing this wrong, can someone give me some insight?  I just want to make sure I'm doing this correctly.

EDIT: I got the idea of using Entities from the https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html and the SoundCloud Redux project

EDIT2: I'm looking at things online like this https://github.com/reactjs/redux/issues/584 but I'm questioning if I'm using this incorrectly and I'm not sure how to apply this to my own project

EDIT3: I'm leaning on creating a selector that will get the pageIdList and return a list of the pageobjects from the pageDict.. that way I already have the object to pass into my Page component.

Body:
I think I follow what you're trying to do here. With Redux try thinking of your user interface as always displaying something immutable: rather than "passing something to it" it is "reading something from the state". That when when your state changes your user interface is updated (it isn't always this simple but it is a pretty good start).

If I read your answer correctly you have a Map of pages:

//data
{
  id1: {...pageProperties} },
  id2: {...pageProperties} },
  id3: {...pageProperties} },
}

and your page list is the order these are displayed in:

ex:

[id2, id3, id1]

Your page object might look something like this:

//Page.js
class Page extends React.Component {
  render() {
    const { pageIdList, pageEntities } = this.props //note I'm using props because this is connected via redux
    return (
      <div>
        { pageIdList.map((pageId, index)=>{
          return <Page key={index} pageEntity={pageEntities[pageId]} />  //I'm just pulling the object from the map here
        }}
      </div>
    )
  }
}
//connect is the Redux connect function
export default connect((store)=> { //most examples use "state" here, but it is the redux store
  return {
    pageEntities: store.pageEntities,
    pageIdList: store.pageList
  }
})(Page)

Now when we want to change something you update the state via a dispatch / action. That is reduced in the reducer to display the new state. There are a lot of example out there on how this works but the general idea is update the state and the components take care of displaying it.

The result of this code (and there might be some typeos) is that you should see:

Page id: 2, Page id: 3, Page id: 1 because the list of the pages in the state is 2, 3, 1 in the example I gave.

To answer your question specifically what the entity I'm pulling is the global Redux Store (not the internal component state). 'Map State to Props' is really 'Map Store to Props' as the 'state' is part of React and the 'store' is your Redux store.

Does that help? React+Redux is really nice once you figure it out, it took me a solid month to understand all the ins and outs but it really does simplify things in the long run.


问:
Javascript keyup call other table value
I have a table like this:

```<code><tbody id="invoice_item">
<tr>
<td><input name='qty[]' type='text' class='form-control form-control-sm qty' value='0'></td>
        <td><input name='price[]' type='text' class='form-control form-control-sm price' value='0'></td>
        <td><input name='sub_total[]' type='text' class='form-control form-control-sm sub_total' value='0' readonly></td>
</tr>
</tbody>
</code>```

I want to make Javascript when qty/price change subtotal changed too.
My js:

```<code> $("#invoice_item").delegate(".qty","keyup",function(){
    var qty = $(this).val();
    var price = tr.find(".price").val();
    alert(price);
    var sub_total = qty * price;
    alert(sub_total);
    tr.find(".sub_total").html(sub_total);

    })
    $("#invoice_item").delegate(".price","keyup",function(){
      var price = $(this).val();
      var qty = tr.find(".qty").val();
      alert(qty);

      })
</code>```

It seems the trouble is tr.find(".").val();.
I try to alert it, but no use.. anyone can help? How I can call the other input?
$(this).val(); is no problem.

答:
i solved it,
i must define it by
var tr = $(this).parent().parent();

thanks all!

Title: Javascript keyup call other table value

Body:
I have a table like this:

<input name='qty[]' type='text' class='form-control form-control-sm qty' value='0'>
        <input name='price[]' type='text' class='form-control form-control-sm price' value='0'>
        <input name='sub_total[]' type='text' class='form-control form-control-sm sub_total' value='0' readonly>

I want to make Javascript when qty/price change subtotal changed too.
My js:

 $("#invoice_item").delegate(".qty","keyup",function(){
    var qty = $(this).val();
    var price = tr.find(".price").val();
    alert(price);
    var sub_total = qty * price;
    alert(sub_total);
    tr.find(".sub_total").html(sub_total);

    })
    $("#invoice_item").delegate(".price","keyup",function(){
      var price = $(this).val();
      var qty = tr.find(".qty").val();
      alert(qty);

      })

It seems the trouble is tr.find(".").val();.
I try to alert it, but no use.. anyone can help? How I can call the other input?
$(this).val(); is no problem.


问:
Match OOXML paragraph with string
I have OOXML document, i need replace paragraph inside it, to insert table in it place, in my case it simple string $(test)

Here i prepare regex https://regex101.com/r/ZTMlEc/2/

I try to make it but without any luck, it matches from first

I need match block that starts with :

```<code><w:p w:rsidR="0035180D" w:rsidRDefault="00C7412B" w:rsidP="00945FB5">
</code>```

and ends

```<code></w:p>
</code>```

for later replace

problem is there may many other paragraphs in documents, and i try, but cant create regexp to match exactly this one, couse it internal tags may differs.

I need work with this XML like as string, and cant use XML libs for it.

答:
I solve this problem other way.

I just select all <w:p> tags and then made preg_match on each of them to find first one that have right string. And then just use str_replace.

```<code>   public function insertTable($blockname, $tableText) {

    $pregstr = '/<w:p .*?>([^<]*)<\/w:p>/i';
    preg_match_all(
            $pregstr, $this->tempDocumentMainPart, $matches
    );

    $replacematch = "";

    foreach ($matches[0] as $m) {
        preg_match(
                '/<w:p .*?>.*?<w:t>\$.*?' . $blockname . '.*?<\/w:p>/ims', $m, $amatches
        );
        if (count($amatches) > 0) {
            $replacematch = $amatches[0];
        }
    }

    $this->tempDocumentMainPart = str_replace(
            $replacematch, $tableText, $this->tempDocumentMainPart
    );
}
</code>```

Title: Match OOXML paragraph with string

Body:
I have OOXML document, i need replace paragraph inside it, to insert table in it place, in my case it simple string $(test)

Here i prepare regex https://regex101.com/r/ZTMlEc/2/

I try to make it but without any luck, it matches from first

I need match block that starts with :

<w:p w:rsidR="0035180D" w:rsidRDefault="00C7412B" w:rsidP="00945FB5">

and ends

</w:p>

for later replace

problem is there may many other paragraphs in documents, and i try, but cant create regexp to match exactly this one, couse it internal tags may differs.

I need work with this XML like as string, and cant use XML libs for it.

Body:
I solve this problem other way.

I just select all <w:p> tags and then made preg_match on each of them to find first one that have right string. And then just use str_replace.

   public function insertTable($blockname, $tableText) {

    $pregstr = '/<w:p .*?>([^<]*)<\/w:p>/i';
    preg_match_all(
            $pregstr, $this->tempDocumentMainPart, $matches
    );

    $replacematch = "";

    foreach ($matches[0] as $m) {
        preg_match(
                '/<w:p .*?>.*?<w:t>\$.*?' . $blockname . '.*?<\/w:p>/ims', $m, $amatches
        );
        if (count($amatches) > 0) {
            $replacematch = $amatches[0];
        }
    }

    $this->tempDocumentMainPart = str_replace(
            $replacematch, $tableText, $this->tempDocumentMainPart
    );
}


问:
How to make Ansible run one certain task only on one host?
The playbook looks like:

```<code>- hosts: all
  tasks:
    - name: "run on all hosts,1"
      shell: something1
    - name: "run on all hosts,2"
      shell: something2
    - name: "run on one host, any host would do"
      shell: this_command_should_run_on_one_host
    - name: "run on all hosts,3"
      shell: something3
</code>```

I know with command line option --limit, I can limit to one host, is it possible to do it in playbook?

答:
For any host (with defaults it will match the first on the list):

```<code>- name: "run on first found host"
  shell: this_command_should_run_on_one_host
  run_once: true
</code>```

For a specific host:

```<code>- name: "run on that_one_host host"
  shell: this_command_should_run_on_one_host
  when: ansible_hostname == 'that_one_host'
</code>```

Or inventory_hostname (hostname as defined in the Ansible inventory) instead of ansible_hostname (hostname as defined on the target machine), depending on which name you want to use.

Body:
The playbook looks like:

- hosts: all
  tasks:
    - name: "run on all hosts,1"
      shell: something1
    - name: "run on all hosts,2"
      shell: something2
    - name: "run on one host, any host would do"
      shell: this_command_should_run_on_one_host
    - name: "run on all hosts,3"
      shell: something3

I know with command line option --limit, I can limit to one host, is it possible to do it in playbook?

Body:
For any host (with defaults it will match the first on the list):

- name: "run on first found host"
  shell: this_command_should_run_on_one_host
  run_once: true

For a specific host:

- name: "run on that_one_host host"
  shell: this_command_should_run_on_one_host
  when: ansible_hostname == 'that_one_host'

Or inventory_hostname (hostname as defined in the Ansible inventory) instead of ansible_hostname (hostname as defined on the target machine), depending on which name you want to use.


问:
Which event is fired when releasing a HTML input range (slider) on touch device?
In my Angular 2 app I use a plain vanilla HTML5 input type "range" to provide the user a simple slider component.

```<code><input type="range" [min]="x" [max]="y" (mouseup)="onReleased()" />
</code>```

I need to know when the user released the slider. Releasing means that using a mouse the dragging is finished and the mouse button has been released. For that purpose I hook into the OnMouseUp event. However, this does not apply in case I use a touch device.

On my tablet I can drag the slider aroun, but when releasing it with my finger the event is no fired.

I know, this is not a mouse, but what event is equivalent to on mouse up and works on touch devices?

答:
The answer to your question would appear to be the touchend event.

I assume there is a way to make the slider a touch surface within the wider Touch Events Web API

Body:
In my Angular 2 app I use a plain vanilla HTML5 input type "range" to provide the user a simple slider component.

<input type="range" [min]="x" [max]="y" (mouseup)="onReleased()" />

I need to know when the user released the slider. Releasing means that using a mouse the dragging is finished and the mouse button has been released. For that purpose I hook into the OnMouseUp event. However, this does not apply in case I use a touch device.

On my tablet I can drag the slider aroun, but when releasing it with my finger the event is no fired.

I know, this is not a mouse, but what event is equivalent to on mouse up and works on touch devices?


问:
Deploy Springboot TCP APP on PWS
Trying to deploy SpringBoot TCP server application on Pivotal Web Service(Cloud Foundry)

The following is in manifest.yml file

```<code>applications:
- name: myapp-api
  path: target/myapp-api-0.0.1-SNAPSHOT.jar
  host: app
  domain: cf-tcpapps.io
  memory: 1G
  instances: 1
</code>```

When i cf push i get this error

```<code>FAILED
Server error, status code: 400, error code: 310009, message: You have exceeded the total reserved route ports for your organization's quota.
</code>```

when i cf router-groups i get

```<code>FAILED
Failed fetching router groups.
Server error, status code: 401, error code: UnauthorizedError, message: You are not authorized to perform the requested action
</code>```

How can one deploy a spring mvc api that exposes a TCP port

答:
The PWS docs indicate:

```<code>Note: By default, PWS only supports routing of HTTP requests to applications.
</code>```

This implies maybe they do, if you get a special dispensation? May be worth contacting PWS support.

Title: Deploy Springboot TCP APP on PWS

Body:
Trying to deploy SpringBoot TCP server application on Pivotal Web Service(Cloud Foundry)

The following is in manifest.yml file

applications:
- name: myapp-api
  path: target/myapp-api-0.0.1-SNAPSHOT.jar
  host: app
  domain: cf-tcpapps.io
  memory: 1G
  instances: 1

When i cf push i get this error

FAILED
Server error, status code: 400, error code: 310009, message: You have exceeded the total reserved route ports for your organization's quota.

when i cf router-groups i get

FAILED
Failed fetching router groups.
Server error, status code: 401, error code: UnauthorizedError, message: You are not authorized to perform the requested action

How can one deploy a spring mvc api that exposes a TCP port

Body:
The PWS docs indicate:

Note: By default, PWS only supports routing of HTTP requests to applications.

This implies maybe they do, if you get a special dispensation? May be worth contacting PWS support.


问:
ORDER_BY in codeigniter query builder
I am trying to order the result based on status column tinyint(4) which is 0 and 1.

In this is query:

```<code>$query = $this->db->order_by('status','DESC')->get('subjects');
</code>```

The expected results are status with a of 1 first but the result query is still following the default database rows. How do I make it so that the status column should be descending?

答: My jquery data table is auto sorting a certain column. That's why.</p>

Title: ORDER_BY in codeigniter query builder

Body:
I am trying to order the result based on status column tinyint(4) which is 0 and 1.

In this is query:

$query = $this->db->order_by('status','DESC')->get('subjects');

The expected results are status with a of 1 first but the result query is still following the default database rows. How do I make it so that the status column should be descending?


问:
How to capitalise the first letter of each word after reversing a string
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.</p>

```<code>function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}
</code>```

答:
here now it will work</p>

```<code> function titleCase(str) {
    var reversed = str.toLowerCase().split(' ').reverse();
    var newArr = [];
    for (var i = 0; i < reversed.length; i++) {
            reversed[i]=reversed[i].split("").reverse().join("");

    var firstLetter = reversed[i].charAt(0).toUpperCase();
        var restOfWord = reversed[i].slice(1);
            newArr[i] = firstLetter + restOfWord;
     }
     return newArr.join(' ');
    }
</code>```

Body:
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.

function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}

Body:
here now it will work

 function titleCase(str) {
    var reversed = str.toLowerCase().split(' ').reverse();
    var newArr = [];
    for (var i = 0; i < reversed.length; i++) {
            reversed[i]=reversed[i].split("").reverse().join("");

    var firstLetter = reversed[i].charAt(0).toUpperCase();
        var restOfWord = reversed[i].slice(1);
            newArr[i] = firstLetter + restOfWord;
     }
     return newArr.join(' ');
    }


问:
Print keys and values from dictionary in descending order without importing operator(Python)
For my assignment I'm writing a program that will take the contents of a file, store it into a dictionary, count and output the number of occurrences of each word in the file, and output the ten most frequently occurring words in descending order.

Here is my code. I didn't want to use import operator, but I'm trying to sort the contents in my dictionary. Right now I have the values printing in sorted order but not with the key in front. How do I print the key words from the dictionary, with the number of occurrences attached, in descending order?

```<code>done = False
while not done:
    try:
        print("ENTER A FILE NAME, IF NOT IN SAME FILE LOCATION AS PROGRAM, SPECIFY PATH")
        input_file_name = input("Please Enter the name of your text file: ")
        infile = open(input_file_name, "r")
        done = True

    except FileNotFoundError:
        done = False
        print("File not Found")

myDict = {}
file = infile.read()
line = file.split()
unwanted_chars = ".,!-_)(*&^%$#@:;'<>?/\{}[]|+=~`"

for symbol in line:
    word = symbol.strip(unwanted_chars)
    if word not in myDict:
        myDict[word] = 0
    myDict[word] = myDict[word] + 1

sortedValues = sorted(myDict.values())

print(myDict)
print(sortedValues)

infile.close()
</code>```

答:
Something like this?

```<code>sortedKeysAndValues = sorted(myDict.items(), key=lambda kv: -kv[1])
</code>```

And then to print,

```<code>for k, v in sortedKeysAndValues:
    print(k, v)
</code>```

Body:
For my assignment I'm writing a program that will take the contents of a file, store it into a dictionary, count and output the number of occurrences of each word in the file, and output the ten most frequently occurring words in descending order.

Here is my code. I didn't want to use import operator, but I'm trying to sort the contents in my dictionary. Right now I have the values printing in sorted order but not with the key in front. How do I print the key words from the dictionary, with the number of occurrences attached, in descending order?

done = False
while not done:
    try:
        print("ENTER A FILE NAME, IF NOT IN SAME FILE LOCATION AS PROGRAM, SPECIFY PATH")
        input_file_name = input("Please Enter the name of your text file: ")
        infile = open(input_file_name, "r")
        done = True

    except FileNotFoundError:
        done = False
        print("File not Found")

myDict = {}
file = infile.read()
line = file.split()
unwanted_chars = ".,!-_)(*&^%$#@:;'<>?/\{}[]|+=~`"

for symbol in line:
    word = symbol.strip(unwanted_chars)
    if word not in myDict:
        myDict[word] = 0
    myDict[word] = myDict[word] + 1

sortedValues = sorted(myDict.values())

print(myDict)
print(sortedValues)

infile.close()

Body:
Something like this?

sortedKeysAndValues = sorted(myDict.items(), key=lambda kv: -kv[1])

And then to print,

for k, v in sortedKeysAndValues:
    print(k, v)


问:
Moving Node with JavaFX DropShadow leaves trail
In a game I am working on in JavaFX, I have cards (Labels) with DropShadows. The cards can move, and, when they do, the shadow leaves behind a faint trail. I've tried using Node#setCache(boolean), which works, but blurs the text in the label.

Are there any other ways to prevent a DropShadow from leaving a trail?

Here is a MCVE with the result:

```<code>public class DropShadowTest extends Application {

    @Override
    public void start(final Stage stage) throws Exception {
        final Label label = new Label("Hello, world!");
        label.setBackground(new Background(new BackgroundFill(Color.LIGHTGRAY, new CornerRadii(10), Insets.EMPTY)));
        label.setEffect(new DropShadow(3, 0, 1, Color.BLACK));
        label.setMaxSize(100, 100);
        label.setMinSize(100, 100);

        stage.setScene(new Scene(new StackPane(label), 640, 480));
        stage.show();

        label.setOnMouseClicked(event -> {
            final TranslateTransition anim = new TranslateTransition(Duration.seconds(1), label);
            anim.setToX(Math.random() * 500 - 250);
            anim.setToY(Math.random() * 300 - 150);
            anim.play();
        });
    }

    public static void main(final String[] args) {
        Application.launch(args);
    }

}
</code>```

Result:

Thanks!

答:
Try using Caching  with the Cache hints , For example before you start animating you set the cache hint to SPEED
Once you are done with Animation you switch back to QUALITY , it will re-render your Node (like repaint() in swing)

Body:
In a game I am working on in JavaFX, I have cards (Labels) with DropShadows. The cards can move, and, when they do, the shadow leaves behind a faint trail. I've tried using Node#setCache(boolean), which works, but blurs the text in the label.

Are there any other ways to prevent a DropShadow from leaving a trail?

Here is a MCVE with the result:

public class DropShadowTest extends Application {

    @Override
    public void start(final Stage stage) throws Exception {
        final Label label = new Label("Hello, world!");
        label.setBackground(new Background(new BackgroundFill(Color.LIGHTGRAY, new CornerRadii(10), Insets.EMPTY)));
        label.setEffect(new DropShadow(3, 0, 1, Color.BLACK));
        label.setMaxSize(100, 100);
        label.setMinSize(100, 100);

        stage.setScene(new Scene(new StackPane(label), 640, 480));
        stage.show();

        label.setOnMouseClicked(event -> {
            final TranslateTransition anim = new TranslateTransition(Duration.seconds(1), label);
            anim.setToX(Math.random() * 500 - 250);
            anim.setToY(Math.random() * 300 - 150);
            anim.play();
        });
    }

    public static void main(final String[] args) {
        Application.launch(args);
    }

}

Result:

Thanks!


问:
Why does PIR sensor stay high with nodeMCU/ESP8266 board?
I have a PIR sensor attached to a Amica nodeMCU board routing 5v from VIN and attached via USB port for testing. When motion is deteted it connects to the internet and sends data to IFTTT which i receive a notification on my phone.

When I power up, the PIR pauses for calibration and then immediately goes HIGH and fires the motion detected call which i receive on my phone. However From then on it never goes LOW but every 5-8 minutes sends another HIGH call through even if there is no motion.

Testing

Tried using separate 5v supply to PIR same thing happens

I have tried both retrigger modes (H & L) and experienced the same result

The same happens with the Adafruit featherwing huzzah board.

I have tested the PIR without a micro-controller and can confirm that it functions correctly -lighting an led

I have tested with an Arduino Nano with the same code and it functions correctly - lighting an led

My Code modified version of Arduino Playground PIR Project

```<code>//Sends IFTTT every 5 minutes it detects motion

#include <ESP8266WiFi.h>
//WiFi Settings

// Set up macros for wifi and connection.
#define SSID "my-network"    // SSID
#define PASS "mypassphrase"      // Network Password
#define HOST "maker.ifttt.com"  // Webhost
//-------------------------------
const char* streamId   = "test";
const char* privateKey = "mysecretkey";

//PIR Settings
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

int  interval = 1000; // Wait between dumps
boolean lockLow = true;
boolean takeLowTime;
int ledPin = 1;
int pirPin = 2;    //the digital pin connected to the PIR sensor's output
int nPIR_detect;
int motion = 2;

int minSecsBetweenUpdates = 300; // 5 minutes
long lastSend = -minSecsBetweenUpdates * 1000l;
//-------------------------------

// Begin Setup
void setup(){
  Serial.begin(115200);
  pinMode(pirPin, INPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for(int i = 0; i < calibrationTime; i++){
    Serial.print(".");
    delay(1000);
    }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
   nPIR_detect = 0;

  // Test ESP8266 module.
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
 if(digitalRead(pirPin) == HIGH){
       digitalWrite(BUILTIN_LED, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec");
         sendData(String(motion));
         delay(50);
         }
         takeLowTime = true;
       }

     if(digitalRead(pirPin) == LOW){
       digitalWrite(BUILTIN_LED, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause,
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){
           //makes sure this block of code is only executed again after
           //a new motion sequence has been detected
           lockLow = true;
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
}

void sendData(String motion){

  //Send the motion to IFTTT value1
  Serial.print("connecting to ");
  Serial.println(HOST);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(HOST, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/trigger/";
  url += streamId;
  url += "/with/key/";
  url += privateKey;
  url += "?value1=";
  url += "motion";

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + HOST + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");

}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Connection");
    return true;
  }
  else{
    Serial.println("No Connection");
    return false;
  }
}
</code>```

Why does a PIR sensor stay high with nodeMCU/ESP8266 board?

In essence, I never see the serial message "motion ended at.."

答: Just able to solve the problem by plugging in V_in of Node MCU with V_cc of PIR. It seems PIR needs ~5V and only V_in could provide that kind of voltage. Earlier I was getting a series of HIGH after every x seconds, when plugged to 3.3v.</p>

Body:
I have a PIR sensor attached to a Amica nodeMCU board routing 5v from VIN and attached via USB port for testing. When motion is deteted it connects to the internet and sends data to IFTTT which i receive a notification on my phone.

When I power up, the PIR pauses for calibration and then immediately goes HIGH and fires the motion detected call which i receive on my phone. However From then on it never goes LOW but every 5-8 minutes sends another HIGH call through even if there is no motion.

Testing

Tried using separate 5v supply to PIR same thing happens

I have tried both retrigger modes (H & L) and experienced the same result

The same happens with the Adafruit featherwing huzzah board.

I have tested the PIR without a micro-controller and can confirm that it functions correctly -lighting an led

I have tested with an Arduino Nano with the same code and it functions correctly - lighting an led

My Code modified version of Arduino Playground PIR Project

//Sends IFTTT every 5 minutes it detects motion

#include <ESP8266WiFi.h>
//WiFi Settings

// Set up macros for wifi and connection.
#define SSID "my-network"    // SSID
#define PASS "mypassphrase"      // Network Password
#define HOST "maker.ifttt.com"  // Webhost
//-------------------------------
const char* streamId   = "test";
const char* privateKey = "mysecretkey";

//PIR Settings
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

int  interval = 1000; // Wait between dumps
boolean lockLow = true;
boolean takeLowTime;
int ledPin = 1;
int pirPin = 2;    //the digital pin connected to the PIR sensor's output
int nPIR_detect;
int motion = 2;

int minSecsBetweenUpdates = 300; // 5 minutes
long lastSend = -minSecsBetweenUpdates * 1000l;
//-------------------------------

// Begin Setup
void setup(){
  Serial.begin(115200);
  pinMode(pirPin, INPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for(int i = 0; i < calibrationTime; i++){
    Serial.print(".");
    delay(1000);
    }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
   nPIR_detect = 0;

  // Test ESP8266 module.
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
 if(digitalRead(pirPin) == HIGH){
       digitalWrite(BUILTIN_LED, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec");
         sendData(String(motion));
         delay(50);
         }
         takeLowTime = true;
       }

     if(digitalRead(pirPin) == LOW){
       digitalWrite(BUILTIN_LED, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause,
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){
           //makes sure this block of code is only executed again after
           //a new motion sequence has been detected
           lockLow = true;
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
}

void sendData(String motion){

  //Send the motion to IFTTT value1
  Serial.print("connecting to ");
  Serial.println(HOST);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(HOST, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/trigger/";
  url += streamId;
  url += "/with/key/";
  url += privateKey;
  url += "?value1=";
  url += "motion";

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + HOST + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");

}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Connection");
    return true;
  }
  else{
    Serial.println("No Connection");
    return false;
  }
}

Why does a PIR sensor stay high with nodeMCU/ESP8266 board?

In essence, I never see the serial message "motion ended at.."