问:
android constrain layout support different screen size
Dears am trying to use constrain layout with percentage to support different screen sizes its working fine if am only using pictures or button but when i add text its not appearing on small screen even though i add it as match parent with center gravity.
i added the xml code..
can you help me if i can use this method to support different screen sizes or i have to create different xml files.

EDIT I

The screen sizes is LDPI API 22 240 × 320: ldpi 22 Android 5.1 (Google APIs) and MDPI Small API 22 320 × 480: mdpi 22 Android 5.1 (Google APIs)

The Layout:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/green_background"
tools:context="com.yaacoach.gymapp.StartExercise">

<android.support.constraint.Guideline
    android:id="@+id/guideline16"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.18" />

<android.support.constraint.Guideline
    android:id="@+id/guideline36"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.2" />

<android.support.constraint.Guideline
    android:id="@+id/guideline37"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.8" />

<android.support.constraint.Guideline
    android:id="@+id/guideline38"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.03" />

<android.support.constraint.Guideline
    android:id="@+id/guideline40"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.08" />

<android.support.constraint.Guideline
    android:id="@+id/guideline41"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.92" />

<android.support.constraint.Guideline
    android:id="@+id/guideline42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.27" />

<Button
    android:id="@+id/btn_start"
    style="@style/Base.TextAppearance.AppCompat.Medium"
    android:gravity="center"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="start"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.833" />

<android.support.constraint.Guideline
    android:id="@+id/guideline43"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.93" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_startExercise_information"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline39"
    app:layout_constraintEnd_toStartOf="@+id/guideline41"
    app:layout_constraintStart_toStartOf="@+id/guideline40"
    app:layout_constraintTop_toTopOf="@+id/guideline42" />

<android.support.constraint.Guideline
    android:id="@+id/guideline39"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86" />

<android.support.constraint.Guideline
    android:id="@+id/guideline45"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.25" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/CL_stopWatch"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@drawable/stopwatchstyle"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:foregroundGravity="center"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38"
    app:layout_constraintVertical_bias="1.0">

</android.support.constraint.ConstraintLayout>

<Chronometer
    android:id="@+id/chronometer2"
    style="@android:style/TextAppearance.DeviceDefault.Medium"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@color/btnbrainiac"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/guideline46"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38" />

<android.support.constraint.Guideline
    android:id="@+id/guideline46"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.11" />

<android.support.constraint.Guideline
    android:id="@+id/guideline47"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_start_exercise_weight_rep"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView2"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/Weight"
    app:layout_constraintBottom_toTopOf="@+id/guideline16"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView4"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/repetition"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline16" />

<Button
    android:id="@+id/btn_StartExercies_Pause"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="Button"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.0" />
</code>```

Body:
Dears am trying to use constrain layout with percentage to support different screen sizes its working fine if am only using pictures or button but when i add text its not appearing on small screen even though i add it as match parent with center gravity.
i added the xml code..
can you help me if i can use this method to support different screen sizes or i have to create different xml files.

EDIT I

The screen sizes is LDPI API 22 240 × 320: ldpi 22 Android 5.1 (Google APIs) and MDPI Small API 22 320 × 480: mdpi 22 Android 5.1 (Google APIs)

The Layout:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/green_background"
tools:context="com.yaacoach.gymapp.StartExercise">

<android.support.constraint.Guideline
    android:id="@+id/guideline16"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.18" />

<android.support.constraint.Guideline
    android:id="@+id/guideline36"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.2" />

<android.support.constraint.Guideline
    android:id="@+id/guideline37"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.8" />

<android.support.constraint.Guideline
    android:id="@+id/guideline38"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.03" />

<android.support.constraint.Guideline
    android:id="@+id/guideline40"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.08" />

<android.support.constraint.Guideline
    android:id="@+id/guideline41"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.92" />

<android.support.constraint.Guideline
    android:id="@+id/guideline42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.27" />

<Button
    android:id="@+id/btn_start"
    style="@style/Base.TextAppearance.AppCompat.Medium"
    android:gravity="center"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="start"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.833" />

<android.support.constraint.Guideline
    android:id="@+id/guideline43"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.93" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_startExercise_information"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline39"
    app:layout_constraintEnd_toStartOf="@+id/guideline41"
    app:layout_constraintStart_toStartOf="@+id/guideline40"
    app:layout_constraintTop_toTopOf="@+id/guideline42" />

<android.support.constraint.Guideline
    android:id="@+id/guideline39"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86" />

<android.support.constraint.Guideline
    android:id="@+id/guideline45"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.25" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/CL_stopWatch"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@drawable/stopwatchstyle"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:foregroundGravity="center"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38"
    app:layout_constraintVertical_bias="1.0">

</android.support.constraint.ConstraintLayout>

<Chronometer
    android:id="@+id/chronometer2"
    style="@android:style/TextAppearance.DeviceDefault.Medium"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@color/btnbrainiac"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/guideline46"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38" />

<android.support.constraint.Guideline
    android:id="@+id/guideline46"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.11" />

<android.support.constraint.Guideline
    android:id="@+id/guideline47"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_start_exercise_weight_rep"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView2"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/Weight"
    app:layout_constraintBottom_toTopOf="@+id/guideline16"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView4"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/repetition"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline16" />

<Button
    android:id="@+id/btn_StartExercies_Pause"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="Button"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.0" />


来源: stackexchange

问:
.map() is not a function Error on Mapping Dynamically created Object
I am trying to map a dynamically created Object to an Array like this

```<code>          params.junctionBarriers = dojo.toJson(junctionBarriers);
          // printing the object in the console (Please look at attached image)
          console.log(params.junctionBarriers);

          var value = [];
          var data = params.junctionBarriers.map(function (s) {
             value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
              return s;
          })
</code>```

but I am getting this error

params.junctionBarriers.map is not a function

As you can see from the image the params.junctionBarriers is dynamically loaded but the .map() is not valid. Why is this, and how I can fix it?

答:
Option 1: Don't use dojo.ToJson.

Option 2: If you need to conovert your object to JSON string for some reason you will need to parse it back to an object before using .map

```<code>      // Option 1 params.junctionBarriers = junctionBarriers;
      // Option 2 params.junctionBarriers = JSON.parse(params.junctionBarriers);
       // printing the object in the console (Please look at attached image)
      console.log(params.junctionBarriers);

      var value = [];
      var data = params.junctionBarriers.map(function (s) {
         value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
          return s;
      })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to map a dynamically created Object to an Array like this

          params.junctionBarriers = dojo.toJson(junctionBarriers);
          // printing the object in the console (Please look at attached image)
          console.log(params.junctionBarriers);

          var value = [];
          var data = params.junctionBarriers.map(function (s) {
             value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
              return s;
          })

but I am getting this error

params.junctionBarriers.map is not a function

As you can see from the image the params.junctionBarriers is dynamically loaded but the .map() is not valid. Why is this, and how I can fix it?

Body:
Option 1: Don't use dojo.ToJson.

Option 2: If you need to conovert your object to JSON string for some reason you will need to parse it back to an object before using .map

      // Option 1 params.junctionBarriers = junctionBarriers;
      // Option 2 params.junctionBarriers = JSON.parse(params.junctionBarriers);
       // printing the object in the console (Please look at attached image)
      console.log(params.junctionBarriers);

      var value = [];
      var data = params.junctionBarriers.map(function (s) {
         value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
          return s;
      })

ContentLicense: CC BY-SA 3.0


问:
No ASP.NET control intellisense in Win2K8 server (not R2) x64, VS2008 SP1
This is a new install of Visual Studio 2008 SP1 on Windows 2008 (original) SP1.  I have opened up projects I have previously had intellisense in in VS2008 on different machines, but I don't get intellisense for any asp: server control.

I have intellisense for HTML markup, and I have it for the vsdoc version of jQuery on the same page that I don't have it for any asp:control named control.  I have this standard tag definition in web.config:

I have tried ScottGu's hotfix rollup and many hours of things to get it to work.  No Google, Bing or StackOverflow search has shown me anyone with exactly the same problem.  Does anyone have any suggestions for what to try to get intellisense to work for asp controls?

答:
You might have followed this during you search. If not have a look at
http://social.msdn.microsoft.com/Forums/en/vsdebug/thread/383dc775-5577-4cfd-80c8-b21c85a93fdb</p>

ContentLicense: CC BY-SA 2.5


问:
How to change array shape of list array in python?
I have (808,1,22,2000) list array which load from json file.

It has 808 number of (22,2000) arrays.

so i want to make this to (22,2000,808).

Can you let me know how to do it?

Body:
Although there is an ambiguity here because it's not clear why you want to change the shape, if I'm right, numpy.reshape should be your answer.
Look at this example:

>> a = np.array([[[[0,1,2,3],[4,5,6,7]]],[[[8,9,10,11],[12,13,14,15]]],[[[16,17,18,19],[20,21,22,23]]]])
>> a
array([[[[ 0,  1,  2,  3],
     [ 4,  5,  6,  7]]],

   [[[ 8,  9, 10, 11],
     [12, 13, 14, 15]]],

   [[[16, 17, 18, 19],
     [20, 21, 22, 23]]]])

>> a.shape
(3, 1, 2, 4)

>> b = a.reshape((a.shape[2],a.shape[3],a.shape[0]))
>> b
array([[[ 0,  1,  2],
    [ 3,  4,  5],
    [ 6,  7,  8],
    [ 9, 10, 11]],

   [[12, 13, 14],
    [15, 16, 17],
    [18, 19, 20],
    [21, 22, 23]]])

>> b.shape
(2, 4, 3)


问:
TypeError: db.collection is not a function
I am trying to post data to database that I have created on mLab and I am getting this error but I don't know whats going wrong.I also have read previously asked question on this topic but I am not able to solve my error as I am new to this. So here I am posting the code which I am trying to implement and It is taken from this tutorial https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2.

server.js

```<code>const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');

const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extened:true}));

MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    require('./app/routes')(app,{});
    app.listen(port,() => {
        console.log("We are live on"+port);
    });

})
</code>```

db.js

```<code>module.exports = {
  url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};
</code>```

index.js

```<code>const noteroutes = require('./note_routes');

module.exports = function(app,db)
{
    noteroutes(app,db);

};
</code>```

note_routes.js

```<code>module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) {
        res.send({ 'error': 'An error has occurred' });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};
</code>```

答:
The error is in the mongodb library. Try to install version 2.2.33 of mongodb. Delete your node_modules directory and add

```<code>"dependencies": {
   "mongodb": "^2.2.33"
}
</code>```

Then

```<code>npm install
</code>```

and there you are

Body:
I am trying to post data to database that I have created on mLab and I am getting this error but I don't know whats going wrong.I also have read previously asked question on this topic but I am not able to solve my error as I am new to this. So here I am posting the code which I am trying to implement and It is taken from this tutorial https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2.

server.js

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');

const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extened:true}));

MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    require('./app/routes')(app,{});
    app.listen(port,() => {
        console.log("We are live on"+port);
    });

})

db.js

module.exports = {
  url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};

index.js

const noteroutes = require('./note_routes');

module.exports = function(app,db)
{
    noteroutes(app,db);

};

note_routes.js

module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) {
        res.send({ 'error': 'An error has occurred' });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

Body:
The error is in the mongodb library. Try to install version 2.2.33 of mongodb. Delete your node_modules directory and add

"dependencies": {
   "mongodb": "^2.2.33"
}

Then

npm install

and there you are


问:
Displaying results in subform only works for first query
I am trying to build the front end for a Mysql database application using linked tables in MS Access. Currently, I have a button on a form which executes a query that allows the user to search for records by a person's name. On the form, there is a subform which displays the results of the executed query.

My problem is that whenever I open the form, the subform only displays the query results for the first time the query is executed. If I try to search for another name, it will open the results set in a separate sheet and not update my subform.

How can I get the subform to update on every search?

Disclaimer: I am new to Access and do not know any VBA code.

Query:

```<code>SELECT employees.FNAME, employees.LNAME, access.NAME, access.USERNAME, access.CREATED_BY, access.ACCESS_GRANTED, access.ACCESS_TERMINATED, access.ADMIN
FROM employees INNER JOIN access ON EMPLOYEES.ID = ACCESS.ID
WHERE (((employees.FNAME) Like "*" & Forms![Form1]!FNameTxt & "*"));
</code>```

Picture of my form after query with name "chase" is executed

答:
I never use dynamic parameterized query. I would use VBA code to set Filter and FilterOn properties, like:

Me.Filter = "[FName] LIKE '*" & Me.cbxFNames & "*'"
Me.FilterOn = True

If you prefer dynamic parameterized query the VBA would be: Me.Requery

If code is behind the main form then need to reference subform through container control. Recommend giving the container control a name different from the object it holds, like ctrEmps

Me.ctrEmps.Requery

The real trick is figuring out what event to put code into.

Body:
I am trying to build the front end for a Mysql database application using linked tables in MS Access. Currently, I have a button on a form which executes a query that allows the user to search for records by a person's name. On the form, there is a subform which displays the results of the executed query.

My problem is that whenever I open the form, the subform only displays the query results for the first time the query is executed. If I try to search for another name, it will open the results set in a separate sheet and not update my subform.

How can I get the subform to update on every search?

Disclaimer: I am new to Access and do not know any VBA code.

Query:

SELECT employees.FNAME, employees.LNAME, access.NAME, access.USERNAME, access.CREATED_BY, access.ACCESS_GRANTED, access.ACCESS_TERMINATED, access.ADMIN
FROM employees INNER JOIN access ON EMPLOYEES.ID = ACCESS.ID
WHERE (((employees.FNAME) Like "*" & Forms![Form1]!FNameTxt & "*"));

Picture of my form after query with name "chase" is executed


问:
Render reactjs component in multiple div tags
I want to create a React.JS component which can be rendered in multiple places using the classname of div elements instead of an id.

The regular way to render a component is this:

```<code>React.render(<Component/>, document.getElementById('id'))
</code>```

while I wonder if it' possible to do this:

```<code>React.render(<Component/>, document.getElementsByClassName)?
</code>```

答:
Just adding onto @Michelle Tilley's answer, I really wanted to do this technique while grabbing a dataset from each element to pass in as a prop. The key was to pass the ComponentName without quotes or brackets and then to createElement with it :

```<code>let elems = document.getElementsByClassName("class_name");

function renderToElements(toRender, elements, dataset) {
  for (var i = 0; i < elements.length; i++) {
    let passId = elements[i].dataset[dataset];
    let renderEl = React.createElement(toRender, {id: passId})
    ReactDOM.render(renderEl, elements[i]);
  }
}

renderToElements(ComponentName, elems, 'id')
</code>```

Body:
I want to create a React.JS component which can be rendered in multiple places using the classname of div elements instead of an id.

The regular way to render a component is this:

React.render(<Component/>, document.getElementById('id'))

while I wonder if it' possible to do this:

React.render(<Component/>, document.getElementsByClassName)?

Body:
Just adding onto @Michelle Tilley's answer, I really wanted to do this technique while grabbing a dataset from each element to pass in as a prop. The key was to pass the ComponentName without quotes or brackets and then to createElement with it :

let elems = document.getElementsByClassName("class_name");

function renderToElements(toRender, elements, dataset) {
  for (var i = 0; i < elements.length; i++) {
    let passId = elements[i].dataset[dataset];
    let renderEl = React.createElement(toRender, {id: passId})
    ReactDOM.render(renderEl, elements[i]);
  }
}

renderToElements(ComponentName, elems, 'id')


问:
Maven: How to create a correct JDBC driver dependency, if I don't know which database the client will use?
I'm currently learning to use maven, I understood how to create a maven project using dependencies from maven repository - and now I have the following question:

If I have an application which uses a database access, for example via Hibernate, then I need to add a dependency representing the corresponding database driver, for example mysql-connector-java for MySql, ojdbc for Oracle and so on.

But what if I want the program to run on a different machine and I don't know what database engine it uses? What is the common way to solve this? Just import all possible drivers as dependencies? Or is there a more elegant way?

答:
I assume that you want everything to happen automagically and you're not too eager to instruct each user/machine admin how to configure system to have your app working. I am afraid it is not possible in the way you might have hoped.

The standalone database solution that Kayaman suggested might be the best solution in your case but hard to say without knowing further.

However here are some aspects regarding using maven and possible difficulties with some notes.

If I have an application which uses a database access, for example via
  Hibernate, then I need to add a dependency representing the
  corresponding database driver, for example mysql-connector-java for
  MySql, ojdbc for Oracle and so on.

Yes. And you also would need to tell hibernate about this Driver and perhaps other stuff related. It is not just adding dependency but also filtering some prop file or persistence.xml. That might be a job for maven and some of its plugins. But still it would require knowledge about all the  possible db alternatives and maven profiles for each of those to handle them.

But what if I want the program to run on a different machine and I
  don't know what databse it uses? What is the common way to solve this?
  What options do I have? Just import all possible drivers as
  dependencies? Is there a more elegant way?

All programs have dependencies. Was it related to DB or not. In a sense as other answers suggest this is not maven specific (but quite related still! ) thing. You need to be aware of the requirements of any environment if you really want to develop on the level of JDBC drivers.

This specific question of yours is something that  - I believe - is the motivation to develop things like:

ODBC

JNDI

NOTE 1 even similar naming ODBC & JDBC are totally in different level (I mean how JDBC drivers are found which actually might be the main problem...)

NOTE 2 JNDI is not restricted to DataSources

However maven can be a great help depending on what you need and finally decide to do. But not in so big role if you can use ODBC / JNDI.


问:
How to write a function where the original list of integers is changed without using return?
Let us say we have a list of integers:

list = [6, 4, 1, 4, 4, 4, 4, 4, 2, 1]

I now wrote a function which returns another list with all the integers from the list above without repeats.

```<code>def no_repeats(s):
    new_list = []
    for number in s:
        if new_list.count(number) < 1:
            new_list.append(number)
    return(new_list)
</code>```

The new_list returns [6, 4, 1, 2] which is good! My question is how I would now write two similar functions:

A function clean(s) which does not return a new list like the function above, but changes the original list by deleting all the numbers that repeat. Thus, the result has to be the same and the function must not include "return" or create a new list. It must only clean the original list.

A function double(s) which, again, changes the original list (does not return a new list!) but this time, by doubling every number in the original list. Thus, double(list) should change the original list above to:

[6, 6, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1]

Thank you for all the help!

答:
Removing duplicates inplace without preserving the order:

```<code>def no_repeats(L):
    L[:] = set(L)
</code>```

There are several variations possible (preserve order, support non-hashable items, support item that do not define total ordering) e.g., to preserve order:

```<code>from collections import OrderedDict

def no_repeats(L):
    L[:] = OrderedDict.fromkeys(L)
</code>```

To double each element's value inplace:

```<code>def double(L):
    for i in range(len(L)):
        L[i] *= 2
</code>```

To duplicate each element:

```<code>def duplicate_elements(L):
    L[:] = [x for x in L for _ in range(2)]
</code>```

Body:
Let us say we have a list of integers:

list = [6, 4, 1, 4, 4, 4, 4, 4, 2, 1]

I now wrote a function which returns another list with all the integers from the list above without repeats.

def no_repeats(s):
    new_list = []
    for number in s:
        if new_list.count(number) < 1:
            new_list.append(number)
    return(new_list)

The new_list returns [6, 4, 1, 2] which is good! My question is how I would now write two similar functions:

A function clean(s) which does not return a new list like the function above, but changes the original list by deleting all the numbers that repeat. Thus, the result has to be the same and the function must not include "return" or create a new list. It must only clean the original list.

A function double(s) which, again, changes the original list (does not return a new list!) but this time, by doubling every number in the original list. Thus, double(list) should change the original list above to:

[6, 6, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1]

Thank you for all the help!

Body:
Removing duplicates inplace without preserving the order:

def no_repeats(L):
    L[:] = set(L)

There are several variations possible (preserve order, support non-hashable items, support item that do not define total ordering) e.g., to preserve order:

from collections import OrderedDict

def no_repeats(L):
    L[:] = OrderedDict.fromkeys(L)

To double each element's value inplace:

def double(L):
    for i in range(len(L)):
        L[i] *= 2

To duplicate each element:

def duplicate_elements(L):
    L[:] = [x for x in L for _ in range(2)]


问:
Delete Duplicates VBA
I am trying to erase duplicate rows starting from bottom, but it isnt working. It keeps two copies but deletes other duplicate items.

```<code>With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    wb_DST.Sheets(sWs_DST).Range(("A13:A" & lncheckduplicatescolumn - 2 & ":" & "AW13:AW" & lncheckduplicatescolumn - 2)).Sort key1:=wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2), order1:=xlDescending, Header:=xlNo

    Dim row As Range
    Dim rng As Range
    Dim cell As Range
    Dim i As Integer
    Set rng = wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2)
    For Each cell In rng
        If cell.Value = cell.Offset(-1, 0).Value Then
            .cell.Offset(-1, 0).EntireRow.Delete
        End If
    Next
End with
</code>```

If Excel shows

```<code>Column A       Column B
A                 1
A                 2
A                 3
</code>```

I want the code to retain the last row, and delete the ones above it.

The result should be

```<code>Column A            Column B
A                    3
</code>```

Thanks,

答:
Work from the bottom up and loop until all 'higher' (i.e. in a row less than current) are removed.

```<code>dim dup as variant, r as long, lncheckduplicatescolumn as long
With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    for r = lncheckduplicatescolumn  to 2 step -1
        dup = application.match(.cells(r, "A").value, .columns(1), 0)
        if dup < r then .rows(dup).delete
    next r
end with
</code>```

This will take a few more cycles than is absolutely necessary but the operation is efficient enough that it should not make a significant difference.

Title: Delete Duplicates VBA

Body:
I am trying to erase duplicate rows starting from bottom, but it isnt working. It keeps two copies but deletes other duplicate items.

With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    wb_DST.Sheets(sWs_DST).Range(("A13:A" & lncheckduplicatescolumn - 2 & ":" & "AW13:AW" & lncheckduplicatescolumn - 2)).Sort key1:=wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2), order1:=xlDescending, Header:=xlNo

    Dim row As Range
    Dim rng As Range
    Dim cell As Range
    Dim i As Integer
    Set rng = wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2)
    For Each cell In rng
        If cell.Value = cell.Offset(-1, 0).Value Then
            .cell.Offset(-1, 0).EntireRow.Delete
        End If
    Next
End with

If Excel shows

Column A       Column B
A                 1
A                 2
A                 3

I want the code to retain the last row, and delete the ones above it.

The result should be

Column A            Column B
A                    3

Thanks,

Body:
Work from the bottom up and loop until all 'higher' (i.e. in a row less than current) are removed.

dim dup as variant, r as long, lncheckduplicatescolumn as long
With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    for r = lncheckduplicatescolumn  to 2 step -1
        dup = application.match(.cells(r, "A").value, .columns(1), 0)
        if dup < r then .rows(dup).delete
    next r
end with

This will take a few more cycles than is absolutely necessary but the operation is efficient enough that it should not make a significant difference.


问:
jQuery checkbox disable and add class
I have a table which have list of rows and every row have two checkboxes
what I am trying to do is when someone check on check box it send request to server using ajax and reponsev with data if it pass it change the tr color to green if fail it change to red..I am done with this step

Now I want when it is success it should enable other check box which is on the same tr so now user can process with the second step.

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

  var selected = "";
  $('.ReviewForm').each(function() {
    selected = selected + "," + $(this).attr('id');
  });

  $.ajax({
    url: '@Url.Action("VerifyFormRquest", "Results")',
    type: "POST",
    data: {
      scanid: selected
    },
    success: function(data, textStatus, jqXHR) {
      alert(data.success);

      data.success.split(',').forEach(function(c) {
        if (c != "") {
          var m = $('#example tr:has(td:contains(' + c + '))').css('background-color', 'lightgreen');
        }
      });
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="example">
  <tr id="1000000107">
    <td>
      <input type="checkbox" id="J15000001" scanid="1000000103" onclick="call()" disabled="disabled" value="1000000103" class="ELOchecked">
    </td>
  </tr>
  <tr id="1000000107">
    <td>
      <input type="checkbox" id="J15000012" scanid="1000000107" disabled="disabled" value="1000000107" class="ELR">
    </td>
  </tr>
</table></code>```

答:
Since you already have the pattern to get the td you could get the next one using next('td'):

```<code>var current_td = $('#example td:contains('+ c +')');

//If the current td found get the next one and remove the disabled property
if( current_td.length > 0 ){
    current_td.next('td').prop('checked',false);
}
</code>```

Title: jQuery checkbox disable and add class

Body:
I have a table which have list of rows and every row have two checkboxes
what I am trying to do is when someone check on check box it send request to server using ajax and reponsev with data if it pass it change the tr color to green if fail it change to red..I am done with this step

Now I want when it is success it should enable other check box which is on the same tr so now user can process with the second step.

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

  var selected = "";
  $('.ReviewForm').each(function() {
    selected = selected + "," + $(this).attr('id');
  });

  $.ajax({
    url: '@Url.Action("VerifyFormRquest", "Results")',
    type: "POST",
    data: {
      scanid: selected
    },
    success: function(data, textStatus, jqXHR) {
      alert(data.success);

      data.success.split(',').forEach(function(c) {
        if (c != "") {
          var m = $('#example tr:has(td:contains(' + c + '))').css('background-color', 'lightgreen');
        }
      });
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });
});

      <input type="checkbox" id="J15000001" scanid="1000000103" onclick="call()" disabled="disabled" value="1000000103" class="ELOchecked">

      <input type="checkbox" id="J15000012" scanid="1000000107" disabled="disabled" value="1000000107" class="ELR">

Body:
Since you already have the pattern to get the td you could get the next one using next('td'):

var current_td = $('#example td:contains('+ c +')');

//If the current td found get the next one and remove the disabled property
if( current_td.length > 0 ){
    current_td.next('td').prop('checked',false);
}


问:
Weird: C# Type or Namespace name could not be found - Builds successfully
I have a weird error showing up in my project when it is open in the VS2012 IDE. Everywhere where I make use of another referenced project it suddenly says "Type or Namespace name could not be found". And by "says", I mean it has the text underlined in red with the error when I hover over it. The intellisense doesn't work for that code. BUT (and here's the weird part), the errors do not show up in the error console and the project builds and runs fine.

I can even debug and step through the code and it works perfectly fine. So at runtime the project is referenced fine but at design time the IDE can't find it. This worked for the past 2 weeks, and only then suddenly went a little bonkers. It's really annoying because I am rubbish at coding without intellisense!

Has anybody ever seen anything like this or have any suggestions?

答:
I had the same problem, where it would build and run fine, it just would always show that error and I couldn't use intellisense with the class.

I actually used the automatic method of creating the class in a new file to resolve the issue, then just copied the code over from the real class. I deleted the old file, renamed the new file, and now it works.


问:
Using property from pom to run test @FitNesseRunner.Suite
How can I use the settings in the POM for running tests from FitNesseRunner:

```<code><systemPropertyVariables>
     <fitnesseSuiteToRun>${fitnesseSuiteToRun}</fitnesseSuiteToRun>
     <seleniumDefaultTimeout>${seleniumDefaultTimeout}</seleniumDefaultTimeout>
     <seleniumGridUrl>${seleniumGridUrl}</seleniumGridUrl>
     <seleniumBrowser>${seleniumBrowser}</seleniumBrowser>
     <seleniumDriverClass>${seleniumDriverClass}</seleniumDriverClass>
     <seleniumCapabilities>${seleniumCapabilities}</seleniumCapabilities>
     <seleniumJsonCapabilities>${seleniumJsonCapabilities}</seleniumJsonCapabilities>
</systemPropertyVariables>
</code>```

I want to use fitnesseSuiteToRun in myTests.myTest like this :

@FitNesseRunner.Suite("myTests.myTest")

答:
To override the @Suite in your code you can specify add a value for fitnesseSuiteToRun as system property on the maven command line. So the command to run the tests becomes something like:

mvn clean test-compile failsafe:integration-test -DfitnesseSuiteToRun=myTests.myTest

Body:
How can I use the settings in the POM for running tests from FitNesseRunner:

<systemPropertyVariables>
     <fitnesseSuiteToRun>${fitnesseSuiteToRun}</fitnesseSuiteToRun>
     <seleniumDefaultTimeout>${seleniumDefaultTimeout}</seleniumDefaultTimeout>
     <seleniumGridUrl>${seleniumGridUrl}</seleniumGridUrl>
     <seleniumBrowser>${seleniumBrowser}</seleniumBrowser>
     <seleniumDriverClass>${seleniumDriverClass}</seleniumDriverClass>
     <seleniumCapabilities>${seleniumCapabilities}</seleniumCapabilities>
     <seleniumJsonCapabilities>${seleniumJsonCapabilities}</seleniumJsonCapabilities>
</systemPropertyVariables>

I want to use fitnesseSuiteToRun in myTests.myTest like this :

@FitNesseRunner.Suite("myTests.myTest")


问:
How application folder should be properly shared between nginx and php-fpm containers in kubernetes?
I have php application with public folder, that contains as index.php that handles php requests as static files.

I would like to deliver static files via nginx container directly, and use php-fpm only for delivering dynamic requests.

How that can be achieved? As i understand, there are two ways:

create two separate containers with same application folder: the first will be with nginx, that serves static and delegates dynamic requests to the second, where php-fpm would be located.

Second solution is to use persistentVolumeClaim, but that also requires some kind of magic for synchronization (initContainers).

What is the best practice?

答:
Let's begin by saying that there are 2 pods which are Nginx Pod and Php pod.
Now There are two things need to be associated with these pods.

Static files (Public folder)

Configuration file (nginx.conf)

I would prefer to use Persistent Volume claim for static files and ConfigMap for the configuration file.

Solutions to your issue.

Php pod will have following k8s resources

Deployment( containers )

Service (to expose it internal)

PersistentVolumeClaim (for public folder)

ConfigMap ( Environment Variable such as information about database )

Nginx pod will have following k8s resources

Deployment (Container)

Service (to expose it internal or external)

ConfigMap (customised nginx.conf)

Now Deployment Resouces will have a relationship with other resources such as Persistent volume claim and configmap etc.

As I understand by InitContainer, It helps Pod to have a consistent Network Namespace as well as organise file system for the main container it provides all the necessary resources to the main container such as service account, pvc, configmap.

For example, If the main container restart then init container make sure that IP address does not change.However, if you create pod again it means you are creating initcontainer  again then Pod will have new IP address.


问:
In Java, do methods that don't use static or class variables need to be synchronized?
Do methods that only use local variables inside suffer any threading issues ?. Somewhere it was mentioned that the method with local variables are copied to each thread stack frame to work with and do not need to synchronized for multithreaded implementation unless it uses class level or static references/variables ?</p>

答:
If your method only operates on parameters and locally-defined (as opposed to class member) variables then there are zero synchronization problems to worry about.

But...

This means any mutable reference types you use must live and die only within the scope of your method.  (Immutable reference types aren't a problem here.)  For example this is no problem:

```<code>int doSomething(int myParameter)
{
  MyObject working_set = new MyObject();
  interim = working_set.doSomethingElse(myParameter);
  return working_set.doSomethingElseAgain(interim);
}
</code>```

A MyObject instance is created within your method, does all of its work in your method and is coughing up blood, waiting to be culled by the GC when you exit your method.

This, on the other hand, can be a problem:

```<code>int doSomething(int myParameter)
{
  MyObject working_set = new MyObject();
  interim = working_set.doSomethingElse(myParameter);
  another_interim = doSomethingSneaky(working_set);
  return working_set.doSomethingElseAgain(another_interim);
}
</code>```

Unless you know for sure what's going on in doSomethingSneaky(), you may have a need for synchronization somewhere.  Specifically you may have to do synchronization on the operations on working_set because doSomethingSneaky() could possibly store the reference to your local working_set object and pass that off to another thread while you're still doing stuff in your method or in the working_set's methods.  Here you'll have to be more defensive.

If, of course, you're only working with primitive types, even calling out to other methods, passing those values along, won't be a problem.

Body:
If your method only operates on parameters and locally-defined (as opposed to class member) variables then there are zero synchronization problems to worry about.

But...

This means any mutable reference types you use must live and die only within the scope of your method.  (Immutable reference types aren't a problem here.)  For example this is no problem:

int doSomething(int myParameter)
{
  MyObject working_set = new MyObject();
  interim = working_set.doSomethingElse(myParameter);
  return working_set.doSomethingElseAgain(interim);
}

A MyObject instance is created within your method, does all of its work in your method and is coughing up blood, waiting to be culled by the GC when you exit your method.

This, on the other hand, can be a problem:

int doSomething(int myParameter)
{
  MyObject working_set = new MyObject();
  interim = working_set.doSomethingElse(myParameter);
  another_interim = doSomethingSneaky(working_set);
  return working_set.doSomethingElseAgain(another_interim);
}

Unless you know for sure what's going on in doSomethingSneaky(), you may have a need for synchronization somewhere.  Specifically you may have to do synchronization on the operations on working_set because doSomethingSneaky() could possibly store the reference to your local working_set object and pass that off to another thread while you're still doing stuff in your method or in the working_set's methods.  Here you'll have to be more defensive.

If, of course, you're only working with primitive types, even calling out to other methods, passing those values along, won't be a problem.


问:
cytoscape.js redundant edges
cytoscape.js to fails to render the graph if the graph has redundant edges/arcs. Why is this happening?

Example:

https://jsfiddle.net/smiccke/mq5t1rw9/4/

$(function() {
  var cy = window.cy = cytoscape({
    container: document.getElementById('cy'),
    ready: function() {},
    style: [{
      selector: 'node',
      css: {
        'content': 'data(name)'
      }
    }, {
      selector: 'edge',
      css: {
        'target-arrow-shape': 'triangle'
      }
    }],
    elements: {
      nodes: [{
        data: {
          id: 'j',
          name: 'Jerry'
        }
      }, {
        data: {
          id: 'e',
          name: 'Elaine'
        }
      }, {
        data: {
          id: 'k',
          name: 'Kramer'
        }
      },
      ],
      edges: [{
        data: {
          source: 'j',
          target: 'e'
        }
      }, {
        data: {
          source: 'j',
          target: 'k'
        }
      }
      ]
    }
  });
});```

The graph works if you remove the two redundant edges from the end (j->e, j->e).

It seems like one redundant edge is ok, but two or more is a problem. Any clues why this is so?

As workaround, any nice short-cuts to remove redundant edges from the graph?

答:
All the edges are there.  You've rendered all parallel edges on top of one another, because that's how your edge style is specified.

Use appropriate style for the type of graph you're rendering.  E.g., a multigraph should probably use haystack edges with a non-zero haystack radius or bundled bezier edges.

Refer to curve-style etc. in the docs: http://js.cytoscape.org/#style/edge-line

Title: cytoscape.js redundant edges

Body:
cytoscape.js to fails to render the graph if the graph has redundant edges/arcs. Why is this happening?

Example:

https://jsfiddle.net/smiccke/mq5t1rw9/4/

$(function() {
  var cy = window.cy = cytoscape({
    container: document.getElementById('cy'),
    ready: function() {},
    style: [{
      selector: 'node',
      css: {
        'content': 'data(name)'
      }
    }, {
      selector: 'edge',
      css: {
        'target-arrow-shape': 'triangle'
      }
    }],
    elements: {
      nodes: [{
        data: {
          id: 'j',
          name: 'Jerry'
        }
      }, {
        data: {
          id: 'e',
          name: 'Elaine'
        }
      }, {
        data: {
          id: 'k',
          name: 'Kramer'
        }
      },
      ],
      edges: [{
        data: {
          source: 'j',
          target: 'e'
        }
      }, {
        data: {
          source: 'j',
          target: 'k'
        }
      }
      ]
    }
  });
});

The graph works if you remove the two redundant edges from the end (j->e, j->e).

It seems like one redundant edge is ok, but two or more is a problem. Any clues why this is so?

As workaround, any nice short-cuts to remove redundant edges from the graph?


问:
Source Tree connecting to VSTS GIT Could not read from remote repository. Please make sure you have the correct access rights
I'm Trying to connect to VSTS Online GIT via SourceTree i get following error. Funny thing is VisualStudio 2017 and GIt bash could connect to the repo without issues. What's wrong with SourceTree setup??

git -c diff.mnemonicprefix=false -c core.quotepath=false fetch --prune --tags origin
FATAL ERROR: Server sent disconnect message
type 2 (protocol error):
"Invalid packet"
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Completed with errors, see above.

答:
Real issue was there is a outbound proxy stop communication in cycles. Sometimes work sometimes dont. fix was to

#

```<code> Get system value
$ git config --system --get https.proxy
$ git config --system --get http.proxy

# Get global value
 $ git config --global --get https.proxy
 $ git config --global --get http.proxy
</code>```

explained here

https://confluence.atlassian.com/bitbucketserverkb/can-t-clone-or-pull-due-to-a-git-outbound-proxy-779171769.html

Body:
Real issue was there is a outbound proxy stop communication in cycles. Sometimes work sometimes dont. fix was to

#

 Get system value
$ git config --system --get https.proxy
$ git config --system --get http.proxy

# Get global value
 $ git config --global --get https.proxy
 $ git config --global --get http.proxy

explained here

https://confluence.atlassian.com/bitbucketserverkb/can-t-clone-or-pull-due-to-a-git-outbound-proxy-779171769.html


问:
JSF 2 -- Composite component with optional listener attribute on f:ajax
I have a composite component that looks something like this:

```<code><!DOCTYPE html>
<html
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:dm="http://davemaple.com/dm-taglib"
    xmlns:rich="http://richfaces.org/rich"
    xmlns:cc="http://java.sun.com/jsf/composite"
    xmlns:fn="http://java.sun.com/jsp/jstl/functions"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:a4j="http://richfaces.org/a4j">

<cc:interface>
    <cc:attribute name="styleClass" />
    <cc:attribute name="textBoxStyleClass" />
    <cc:attribute name="inputTextId" />
    <cc:attribute name="labelText" />
    <cc:attribute name="tabindex" />
    <cc:attribute name="required" default="false" />
    <cc:attribute name="requiredMessage" />
    <cc:attribute name="validatorId" />
    <cc:attribute name="converterId" />
    <cc:attribute name="title"/>
    <cc:attribute name="style"/>
    <cc:attribute name="unicodeSupport" default="false"/>
    <cc:attribute name="tooltip" default="false"/>
    <cc:attribute name="tooltipText" default=""/>
    <cc:attribute name="tooltipText" default=""/>
    <cc:attribute name="onfail" default=""/>
    <cc:attribute name="onpass" default=""/>
</cc:interface>

<cc:implementation>

        <ui:param name="converterId" value="#{! empty cc.attrs.converterId ? cc.attrs.converterId : 'universalConverter'}" />
        <ui:param name="validatorId" value="#{! empty cc.attrs.validatorId ? cc.attrs.validatorId : 'universalValidator'}" />
        <ui:param name="component" value="#{formFieldBean.getComponent(cc.attrs.inputTextId)}" />
        <ui:param name="componentValid" value="#{((facesContext.maximumSeverity == null and empty component.valid) or component.valid) ? true : false}" />
        <ui:param name="requiredMessage" value="#{! empty cc.attrs.requiredMessage ? cc.attrs.requiredMessage : msg['validation.generic.requiredMessage']}" />
        <ui:param name="clientIdEscaped" value="#{fn:replace(cc.clientId, ':', '\\\\\\\\:')}" />

        <h:panelGroup layout="block" id="#{cc.attrs.inputTextId}ValidPanel" style="display:none;">
            <input type="hidden" id="#{cc.attrs.inputTextId}Valid" value="#{componentValid}" />
        </h:panelGroup>

        <dm:outputLabel for="#{cc.clientId}:#{cc.attrs.inputTextId}" id="#{cc.attrs.inputTextId}Label">#{cc.attrs.labelText}</dm:outputLabel>
        <dm:inputText
            styleClass="#{cc.attrs.textBoxStyleClass}"
               tabindex="#{cc.attrs.tabindex}"
               id="#{cc.attrs.inputTextId}"
               required="#{cc.attrs.required}"
               requiredMessage="#{requiredMessage}"
               title="#{cc.attrs.title}"
               unicodeSupport="#{cc.attrs.unicodeSupport}">
            <f:validator validatorId="#{validatorId}" />
            <f:converter converterId="#{converterId}" />
            <cc:insertChildren />
            <f:ajax
                event="blur"
                execute="@this"
                render="#{cc.attrs.inputTextId}ValidPanel #{cc.attrs.inputTextId}Msg"
                onevent="on#{cc.attrs.inputTextId}Event" />
        </dm:inputText>
        <rich:message for="#{cc.clientId}:#{cc.attrs.inputTextId}" id="#{cc.attrs.inputTextId}Msg" style="display: none;" />
        <script>
            function on#{cc.attrs.inputTextId}Event(e) {
                if(e.status == 'success') {
                    $('##{clientIdEscaped}\\:#{cc.attrs.inputTextId}').trigger($('##{cc.attrs.inputTextId}Valid').val()=='true'?'pass':'fail');
                }
            }
            $('##{clientIdEscaped}\\:#{cc.attrs.inputTextId}').bind('fail', function() {
                $('##{clientIdEscaped}\\:#{cc.attrs.inputTextId}, ##{clientIdEscaped}\\:#{cc.attrs.inputTextId}Label, ##{cc.attrs.inputTextId}Msg, ##{cc.id}Msg').addClass('error');
                $('##{cc.id}Msg').html($('##{clientIdEscaped}\\:#{cc.attrs.inputTextId}Msg').html());
                #{cc.attrs.onfail}
            }).bind('pass', function() {
                $('##{clientIdEscaped}\\:#{cc.attrs.inputTextId}, ##{clientIdEscaped}\\:#{cc.attrs.inputTextId}Label, ##{cc.attrs.inputTextId}Msg, ##{cc.id}Msg').removeClass('error');
                $('##{cc.id}Msg').html($('##{clientIdEscaped}\\:#{cc.attrs.inputTextId}Msg').html());
                #{cc.attrs.onpass}
            });
        </script>
        <a4j:region rendered="#{facesContext.maximumSeverity != null and !componentValid}">
            <script>
                $(document).ready(function() {
                    $('##{clientIdEscaped}\\:#{cc.attrs.inputTextId}').trigger('fail');
                });
            </script>
        </a4j:region>
</cc:implementation>

</html>
</code>```

I'd like to be able to add an optional "listener" attribute which if defined would add an event listener to my f:ajax but I'm having trouble figuring out how to accomplish this. Any help would be appreciated.

答:
All of the above didn't work for me unfortunately, so I fiddled around and came up with the following solution.

```<code><cc:interface type="someComponent">
    <cc:attribute name="listener" method-signature="void listener()" />
</cc:interface>
<cc:implementation>
    <h:someComponent>
        <p:ajax listener="#{cc.attrs.listener}" onstart="#{cc.attrs.containsKey('listener') ? '' : 'return false'}" />
    </h:someComponent>
</cc:implementation>
</code>```

This will always bind the ajax behavior, but only execute it if there actually is a listener.

Body:
I have a composite component that looks something like this:

<!DOCTYPE html>

<cc:interface>
    <cc:attribute name="styleClass" />
    <cc:attribute name="textBoxStyleClass" />
    <cc:attribute name="inputTextId" />
    <cc:attribute name="labelText" />
    <cc:attribute name="tabindex" />
    <cc:attribute name="required" default="false" />
    <cc:attribute name="requiredMessage" />
    <cc:attribute name="validatorId" />
    <cc:attribute name="converterId" />
    <cc:attribute name="title"/>
    <cc:attribute name="style"/>
    <cc:attribute name="unicodeSupport" default="false"/>
    <cc:attribute name="tooltip" default="false"/>
    <cc:attribute name="tooltipText" default=""/>
    <cc:attribute name="tooltipText" default=""/>
    <cc:attribute name="onfail" default=""/>
    <cc:attribute name="onpass" default=""/>
</cc:interface>

<cc:implementation>

        <ui:param name="converterId" value="#{! empty cc.attrs.converterId ? cc.attrs.converterId : 'universalConverter'}" />
        <ui:param name="validatorId" value="#{! empty cc.attrs.validatorId ? cc.attrs.validatorId : 'universalValidator'}" />
        <ui:param name="component" value="#{formFieldBean.getComponent(cc.attrs.inputTextId)}" />
        <ui:param name="componentValid" value="#{((facesContext.maximumSeverity == null and empty component.valid) or component.valid) ? true : false}" />
        <ui:param name="requiredMessage" value="#{! empty cc.attrs.requiredMessage ? cc.attrs.requiredMessage : msg['validation.generic.requiredMessage']}" />
        <ui:param name="clientIdEscaped" value="#{fn:replace(cc.clientId, ':', '\\\\\\\\:')}" />

        <h:panelGroup layout="block" id="#{cc.attrs.inputTextId}ValidPanel" style="display:none;">
            <input type="hidden" id="#{cc.attrs.inputTextId}Valid" value="#{componentValid}" />
        </h:panelGroup>

        <dm:outputLabel for="#{cc.clientId}:#{cc.attrs.inputTextId}" id="#{cc.attrs.inputTextId}Label">#{cc.attrs.labelText}</dm:outputLabel>
        <dm:inputText
            styleClass="#{cc.attrs.textBoxStyleClass}"
               tabindex="#{cc.attrs.tabindex}"
               id="#{cc.attrs.inputTextId}"
               required="#{cc.attrs.required}"
               requiredMessage="#{requiredMessage}"
               title="#{cc.attrs.title}"
               unicodeSupport="#{cc.attrs.unicodeSupport}">
            <f:validator validatorId="#{validatorId}" />
            <f:converter converterId="#{converterId}" />
            <cc:insertChildren />
            <f:ajax
                event="blur"
                execute="@this"
                render="#{cc.attrs.inputTextId}ValidPanel #{cc.attrs.inputTextId}Msg"
                onevent="on#{cc.attrs.inputTextId}Event" />
        </dm:inputText>
        <rich:message for="#{cc.clientId}:#{cc.attrs.inputTextId}" id="#{cc.attrs.inputTextId}Msg" style="display: none;" />

        <a4j:region rendered="#{facesContext.maximumSeverity != null and !componentValid}">

        </a4j:region>
</cc:implementation>

I'd like to be able to add an optional "listener" attribute which if defined would add an event listener to my f:ajax but I'm having trouble figuring out how to accomplish this. Any help would be appreciated.

Body:
All of the above didn't work for me unfortunately, so I fiddled around and came up with the following solution.

<cc:interface type="someComponent">
    <cc:attribute name="listener" method-signature="void listener()" />
</cc:interface>
<cc:implementation>
    <h:someComponent>
        <p:ajax listener="#{cc.attrs.listener}" onstart="#{cc.attrs.containsKey('listener') ? '' : 'return false'}" />
    </h:someComponent>
</cc:implementation>

This will always bind the ajax behavior, but only execute it if there actually is a listener.


问:
I got this error when I wanted to update my application
I have uploaded an application to my store and when I wanted to update it, I got this error</p>

答: Looks like your app was signed with a different key than the one that it was uploaded with. Either sign the apk with the same key or change the package name of the app create a new key and sign it again and reupload it to the Google Play Store.</p>


问:
Python Script Read TXT and create new
I have this script for creating 'acl' to add all IP's of server to squid config

```<code>file = open("ip.txt", "r")
ip_list = [line for line in file]

for acl, tcp in zip(ip_list[::2], ip_list[1::2]):
    print "acl ip" + str(ip_list.index(acl) + 1) + " myip " + acl.strip()
    print  "tcp_outgoing_address " + tcp.strip() + " ip" + str(ip_list.index(acl) + 1)
</code>```

My problem is that when script read IP from ip.txt I need to enter 2 times the same IP cause I need the same IP 2 times in my final paste.

My friend told me to create double loop but I have no idea how to do it.

ip.txt looks like this

```<code>1.1.1.1
2.2.2.2
3.3.3.3
</code>```

Final paste should looked like this

```<code>acl ip1 myip 1.1.1.1
tcp_outgoing_address 1.1.1.1 ip1
acl ip2 myip 2.2.2.2
tcp_outgoing_address 2.2.2.2 ip2
acl ip3 myip 3.3.3.3
tcp_outgoing_address 3.3.3.3 ip3
acl ip4 myip 4.4.4.4
tcp_outgoing_address 4.4.4.4 ip4
</code>```

答:
I've made also this with input from user and saving to TXT</p>

```<code>file1 = open("iplist.txt","w")

ip = raw_input("Enter IP list:").split(" ")

tpl = """acl ip{index} myip {ip}
tcp_outgoing_address {ip} ip{index}
"""

for index, line in enumerate(ip):
    file1.write(tpl.format(index=index, ip=line.strip()))
</code>```

Title: Python Script Read TXT and create new

Body:
I have this script for creating 'acl' to add all IP's of server to squid config

file = open("ip.txt", "r")
ip_list = [line for line in file]

for acl, tcp in zip(ip_list[::2], ip_list[1::2]):
    print "acl ip" + str(ip_list.index(acl) + 1) + " myip " + acl.strip()
    print  "tcp_outgoing_address " + tcp.strip() + " ip" + str(ip_list.index(acl) + 1)

My problem is that when script read IP from ip.txt I need to enter 2 times the same IP cause I need the same IP 2 times in my final paste.

My friend told me to create double loop but I have no idea how to do it.

ip.txt looks like this

1.1.1.1
2.2.2.2
3.3.3.3

Final paste should looked like this

acl ip1 myip 1.1.1.1
tcp_outgoing_address 1.1.1.1 ip1
acl ip2 myip 2.2.2.2
tcp_outgoing_address 2.2.2.2 ip2
acl ip3 myip 3.3.3.3
tcp_outgoing_address 3.3.3.3 ip3
acl ip4 myip 4.4.4.4
tcp_outgoing_address 4.4.4.4 ip4

Body:
I've made also this with input from user and saving to TXT

file1 = open("iplist.txt","w")

ip = raw_input("Enter IP list:").split(" ")

tpl = """acl ip{index} myip {ip}
tcp_outgoing_address {ip} ip{index}
"""

for index, line in enumerate(ip):
    file1.write(tpl.format(index=index, ip=line.strip()))


问:
Unwanted MSI appearance after installation
I used windows installer (msi project) and actually I have the msi file after installation it throws a shortcuts to the desktop.

My problem is when i double-click on the shortcut for my application, it displays somthing like the installation then it runs my application. I don't want the installtion windows to appear where my application doesn't need to throw any file or to install something before running all pre-requests are installed through the msi file. I want that when the end-user clicks on the shortcut, it runs the application directly ...

I hope I explained my problem well.

One additional note i'm using VS 2005, C#

What if i want to remove this action where it always happens. everytime i double click on the exe file it appears this window . my application is not so complicated to so.

EDIT: where can i find the log file ?!?

please help.
thnx indavence

答: That quick installer operations you saw is very often issue. I think it appears only on first run and never again. Never mind. Maybe Windows Installer service makes some registration, etc.</p>

LastEditorDisplayName: moocha

OwnerDisplayName: abatishchev

LastEditorDisplayName: abatishchev


问:
Python tkinter multiple commands for one button
I am trying to make a program with tkinter that shows different words when a button is pressed. So my question is the following: say there is a button next question and whenever it is pressed the question that is currently on screen changes to the next one( current one is Q1 -- > button is pressed -- > Q2 replaced Q1), and I only want to have one singe button, not different ones for each question. What should I use to accomplish this? I tried using lists but it didn't work out.

Thank you guys in advance!

答:
The simplest solution is to put the questions in a list, and use a global variable to track the index of the current question. The "next question" button needs to simply increment the index and then show the next question.

Using classes would be better than global variables, but to keep the example short I won't use classes.

Example:

```<code>import Tkinter as tk

current_question = 0
questions = [
    "Shall we play a game?",
    "What's in the box?",
    "What is the airspeed velocity of an unladen swallow?",
    "Who is Keyser Soze?",
]

def next_question():
    show_question(current_question+1)

def show_question(index):
    global current_question
    if index >= len(questions):
        # no more questions; restart at zero
        current_question = 0
    else:
        current_question = index

    # update the label with the new question.
    question.configure(text=questions[current_question])

root = tk.Tk()
button = tk.Button(root, text="Next question", command=next_question)
question = tk.Label(root, text="", width=50)

button.pack(side="bottom")
question.pack(side="top", fill="both", expand=True)

show_question(0)

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

Body:
The simplest solution is to put the questions in a list, and use a global variable to track the index of the current question. The "next question" button needs to simply increment the index and then show the next question.

Using classes would be better than global variables, but to keep the example short I won't use classes.

Example:

import Tkinter as tk

current_question = 0
questions = [
    "Shall we play a game?",
    "What's in the box?",
    "What is the airspeed velocity of an unladen swallow?",
    "Who is Keyser Soze?",
]

def next_question():
    show_question(current_question+1)

def show_question(index):
    global current_question
    if index >= len(questions):
        # no more questions; restart at zero
        current_question = 0
    else:
        current_question = index

    # update the label with the new question.
    question.configure(text=questions[current_question])

root = tk.Tk()
button = tk.Button(root, text="Next question", command=next_question)
question = tk.Label(root, text="", width=50)

button.pack(side="bottom")
question.pack(side="top", fill="both", expand=True)

show_question(0)

root.mainloop()


问:
How to write a script for delete all the logs everytime macos shutdown?
I knew how to delete all the log files with terminal command "sudo rm -r /var/log" but how to set it up for system events, therefore, clear up everytime system shutdown?</p>

答:
We can execute commands or script at startup or shutdown,

see the links below for details,

unix.stackexchange.com or ccm or opensource.com


问:
How to set child control viewmodel property from the parent control's xmal
I'm not sure how to set a child control's viewmodel property from the parent. Below I'm trying to access IntValue, but I get an error saying it doesn't exist in the user control. That's because it exists in the viewmodel that is tied to the user control.

ChildViewModel.cs

```<code>public class ChildViewModel : ViewModelBase
{
    public ChildModel Model { get; private set; }

    public int IntValue
    {
        get
        {
            return Model.IntValue;
        }
        set
        {
            Model.IntValue = value;
            OnPropertyChanged();
        }
    }

    public ChildViewModel()
    {
        Model = new ChildModel();
    }
}
</code>```

ParentControl.xaml

```<code><UserControl
    x:Class="EmbeddedControls.ParentControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:EmbeddedControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">

    <Grid>
        <local:ChildControl IntValue="4">
    </Grid>
</UserControl>
</code>```

So what I would like to do here is to update the IntValue inline when creating the control in xaml. Is there a way to do this? Thanks in advance.

答:
There are some ways to achieve that:

Declare a Dependency property in your user control. Here you can find an example.

Communicate both ViewModels, here you can find some examples.

I hope this can help you.

Body:
I'm not sure how to set a child control's viewmodel property from the parent. Below I'm trying to access IntValue, but I get an error saying it doesn't exist in the user control. That's because it exists in the viewmodel that is tied to the user control.

ChildViewModel.cs

public class ChildViewModel : ViewModelBase
{
    public ChildModel Model { get; private set; }

    public int IntValue
    {
        get
        {
            return Model.IntValue;
        }
        set
        {
            Model.IntValue = value;
            OnPropertyChanged();
        }
    }

    public ChildViewModel()
    {
        Model = new ChildModel();
    }
}

ParentControl.xaml

<UserControl
    x:Class="EmbeddedControls.ParentControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:EmbeddedControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">

    <Grid>
        <local:ChildControl IntValue="4">
    </Grid>
</UserControl>

So what I would like to do here is to update the IntValue inline when creating the control in xaml. Is there a way to do this? Thanks in advance.


问:
Check subgraph based in vertex attributes(name) and edges colors/weight
Is there some way to check in R/igraph if a graph m is subgraph of another graph g, based on attributes vertices (name) and weight or colors of the edges?

The funtcion is_subgraphic_isomomorphic_to(m,g, method=vf2) does not work, because it uses vertex id (and I need to use attributes(name/color))

example:
graph m

graph g

答: UPDATE: is_subgraphic_isomomorphic_to(m,g, method=vf2) uses colors (vertex/edge), and i need to use both the names of the vertices and weight/colors edges, as in the example figures.


问:
How to pass object data to a window.open()
Is there anyway to pass JavaScript objects to a window.open() without having the objects in a URL. I know i can do this when loading a url into a div:

```<code>$("#myDiv").load(urlForWindow, { data: data });
</code>```

But is there a way i can do this for a window:

```<code>var win = window.open(urlForWindow, '_blank', { data: data });
</code>```

答: Ok i realized, why make this harder. just use ajax post to an api.</p>

Body:
Is there anyway to pass JavaScript objects to a window.open() without having the objects in a URL. I know i can do this when loading a url into a div:

$("#myDiv").load(urlForWindow, { data: data });

But is there a way i can do this for a window:

var win = window.open(urlForWindow, '_blank', { data: data });


问:
How to rotate my image using Keys in pygame?
I'm trying to let an image (transparent image) Rotate on the keys that I press. I.E. I want to rotate my player's head up and down(he is shooting from his head), but I don't really have a decent guideline on how to code this. If anyone could help me it would be greatly appreciated. Also I wanted the head just to smoothly rotate(aim) up and down when I hold the keys down. Code below: </p>

```<code>import pygame

pygame.init()

white = (255,255,255)
BLACK = (0,0,0)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((640,360))

background = pygame.image.load('background.jpg').convert()

player = pygame.image.load('BigShagHoofdz.png') #this must be rotateable

pygame.display.set_caption('Leslie is Lauw')
clock = pygame.time.Clock()

gameDisplay.blit(background, [0,0])
gameDisplay.blit(player, [-1,223])
pygame.display.update()

FPS = 60

direction = "Down"

def head():
    if direction == "Down":
        playerhead = player
    if direction == "Up":
        playerhead = pygame.transform.rotate(player, 60)

def gameLoop():
    global direction
    gameExit = False

    while gameExit==False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            gameExit = True

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            gameExit = True

            if event.key == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                direction = "Up"
                elif event.key == pygame.K_DOWN:
                direction = "Down"

clock.tick(60)
pygame.quit()
quit()
</code>```

<p>It should only rotate up or down when I press the up or down key, maybe let it go smooth when it's held down or up. </p>

答:
If you just want to switch between a normal and a rotated image, you can create the rotated version before the while loop and then just switch the image if a key gets pressed.</p>

```<code>import pygame

pygame.init()

gameDisplay = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
# The normal image/pygame.Surface.
player_image = pygame.Surface((30, 50), pygame.SRCALPHA)
player_image.fill((0, 100, 200))
pygame.draw.circle(player_image, (0, 50, 100), (15, 20), 12)
# The rotated image.
player_rotated = pygame.transform.rotate(player_image, 60)

FPS = 60

def gameLoop():
    player = player_image
    player_pos = [100, 223]
    gameExit = False

    while gameExit == False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            elif event.type == pygame.KEYDOWN:
                # Assign the current image to the `player` variable.
                if event.key == pygame.K_UP:
                    player = player_image
                elif event.key == pygame.K_DOWN:
                    player = player_rotated

        gameDisplay.fill((30, 30, 30))
        gameDisplay.blit(player, player_pos)

        pygame.display.flip()
        clock.tick(60)

gameLoop()
pygame.quit()
</code>```

Body:
I'm trying to let an image (transparent image) Rotate on the keys that I press. I.E. I want to rotate my player's head up and down(he is shooting from his head), but I don't really have a decent guideline on how to code this. If anyone could help me it would be greatly appreciated. Also I wanted the head just to smoothly rotate(aim) up and down when I hold the keys down. Code below:

import pygame

pygame.init()

white = (255,255,255)
BLACK = (0,0,0)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((640,360))

background = pygame.image.load('background.jpg').convert()

player = pygame.image.load('BigShagHoofdz.png') #this must be rotateable

pygame.display.set_caption('Leslie is Lauw')
clock = pygame.time.Clock()

gameDisplay.blit(background, [0,0])
gameDisplay.blit(player, [-1,223])
pygame.display.update()

FPS = 60

direction = "Down"

def head():
    if direction == "Down":
        playerhead = player
    if direction == "Up":
        playerhead = pygame.transform.rotate(player, 60)

def gameLoop():
    global direction
    gameExit = False

    while gameExit==False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            gameExit = True

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            gameExit = True

            if event.key == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                direction = "Up"
                elif event.key == pygame.K_DOWN:
                direction = "Down"

clock.tick(60)
pygame.quit()
quit()

It should only rotate up or down when I press the up or down key, maybe let it go smooth when it's held down or up.

Body:
If you just want to switch between a normal and a rotated image, you can create the rotated version before the while loop and then just switch the image if a key gets pressed.

import pygame

pygame.init()

gameDisplay = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
# The normal image/pygame.Surface.
player_image = pygame.Surface((30, 50), pygame.SRCALPHA)
player_image.fill((0, 100, 200))
pygame.draw.circle(player_image, (0, 50, 100), (15, 20), 12)
# The rotated image.
player_rotated = pygame.transform.rotate(player_image, 60)

FPS = 60

def gameLoop():
    player = player_image
    player_pos = [100, 223]
    gameExit = False

    while gameExit == False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            elif event.type == pygame.KEYDOWN:
                # Assign the current image to the `player` variable.
                if event.key == pygame.K_UP:
                    player = player_image
                elif event.key == pygame.K_DOWN:
                    player = player_rotated

        gameDisplay.fill((30, 30, 30))
        gameDisplay.blit(player, player_pos)

        pygame.display.flip()
        clock.tick(60)

gameLoop()
pygame.quit()


问:
Two Columns Auto Height Background Colour
I'm probably missing something really simple here. I have two columns which keep the same height, depending on which div has more content inside of it, however the background colour does not extend on the shorter column; the columns change to a vertical layout when the display is smaller with the use of media queries. How can I get the background colour of the left column to extend to the bottom of the div?

#pageContainer {
        width: 100%;
        text-align: center;
    }

    #pageContainer p {
        line-height: 10px;
    }

    .sectionContainer {
        width: 80%;
        margin: 0 auto;
        display: table;
    }

    .leftColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #4F4F4F;
        color: #FFFFFF;
    }

    .rightColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #EEEEEE;
        color: #000000;

    }

    @media all and (max-width: 768px) {
        .sectionContainer {
            width: 100%;
        }

        .leftColumn {
            width: 100%;
        }

        .rightColumn {
            width: 100%;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pageContainer">
  <div class="sectionContainer">
    <div class="leftColumn">
      <h1>Left Column</h1>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
    </div>
    <div class="rightColumn">
      <h1>Right Column</h1>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
    </div>
  </div>
</div></code>```

I have included a CodePen to show the problem: https://codepen.io/Macast/pen/ZaZrNz

Thanks!

答:
Erase the floats (make no sense in a table) to fix the height problem. Then in the media query, change display to block for the container and to inline-block for the two inner elements:

#pageContainer {
  width: 100%;
  text-align: center;
}

#pageContainer p {
  line-height: 10px;
}

.sectionContainer {
  width: 80%;
  margin: 0 auto;
  display: table;
}

.leftColumn {
  display: table-cell;
  width: 50%;
  background-color: #4F4F4F;
  color: #FFFFFF;
}

.rightColumn {
  display: table-cell;
  width: 50%;
  background-color: #EEEEEE;
  color: #000000;
}

@media all and (max-width: 768px) {
  .sectionContainer {
    display: block;
    width: 100%;
  }
  .leftColumn {
    display: inline-block;
    width: 100%;
  }
  .rightColumn {
    display: inline-block;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pageContainer">
  <div class="sectionContainer">
    <div class="leftColumn">
      <h1>Left Column</h1>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
    </div>
    <div class="rightColumn">
      <h1>Right Column</h1>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
    </div>
  </div>
</div></code>```

Body:
I'm probably missing something really simple here. I have two columns which keep the same height, depending on which div has more content inside of it, however the background colour does not extend on the shorter column; the columns change to a vertical layout when the display is smaller with the use of media queries. How can I get the background colour of the left column to extend to the bottom of the div?

#pageContainer {
        width: 100%;
        text-align: center;
    }

    #pageContainer p {
        line-height: 10px;
    }

    .sectionContainer {
        width: 80%;
        margin: 0 auto;
        display: table;
    }

    .leftColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #4F4F4F;
        color: #FFFFFF;
    }

    .rightColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #EEEEEE;
        color: #000000;

    }

    @media all and (max-width: 768px) {
        .sectionContainer {
            width: 100%;
        }

        .leftColumn {
            width: 100%;
        }

        .rightColumn {
            width: 100%;
        }
    }

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

I have included a CodePen to show the problem: https://codepen.io/Macast/pen/ZaZrNz

Thanks!

Body:
Erase the floats (make no sense in a table) to fix the height problem. Then in the media query, change display to block for the container and to inline-block for the two inner elements:

#pageContainer {
  width: 100%;
  text-align: center;
}

#pageContainer p {
  line-height: 10px;
}

.sectionContainer {
  width: 80%;
  margin: 0 auto;
  display: table;
}

.leftColumn {
  display: table-cell;
  width: 50%;
  background-color: #4F4F4F;
  color: #FFFFFF;
}

.rightColumn {
  display: table-cell;
  width: 50%;
  background-color: #EEEEEE;
  color: #000000;
}

@media all and (max-width: 768px) {
  .sectionContainer {
    display: block;
    width: 100%;
  }
  .leftColumn {
    display: inline-block;
    width: 100%;
  }
  .rightColumn {
    display: inline-block;
    width: 100%;
  }
}

<div id="pageContainer">
  <div class="sectionContainer">
    <div class="leftColumn">
      <h1>Left Column</h1>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
    </div>
    <div class="rightColumn">
      <h1>Right Column</h1>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
    </div>
  </div>
</div>


问:
How can i convert a DBQuery<T> to an ObjectQuery<T>?
I've got a DBQuery<T> which converts to an IQueryable<T> (this bit works fine). But then I'm trying to convert the IQueryable to an ObjectQuery .. which fails :-

```<code>public void Foo(this IQueryable<T> source)
{
    // ... snip ...

    ObjectQuery<T> objectQuery = source as ObjectQuery<T>;
    if (objectQuery != null)
    {
        // ... do stuff ...
    }
}
</code>```

This used to work before I changed over to Entity-Framework 4 CTP5 Magic Unicorn blah blah blah. Now, it's not working - ie. objectQuery is null.

Now, DBQuery<T> inherits IQueryable<T> .. so I thought this should work.

If i change the code to ..

```<code>var x = (ObjectQuery<T>) source;
</code>```

then the following exception is thrown :-

System.InvalidCastException: Unable to
  cast object of type
  'System.Data.Entity.Infrastructure.DbQuery1[Tests.Models.Order]'
  to type
  'System.Data.Objects.ObjectQuery1[Tests.Models.Order]'.

Any suggestions?

答:
Not sure what you're trying to do with it, but would a dynamic variable help?

Using Type dynamic (C# Programming Guide)

Body:
I've got a DBQuery<T> which converts to an IQueryable<T> (this bit works fine). But then I'm trying to convert the IQueryable to an ObjectQuery .. which fails :-

public void Foo(this IQueryable<T> source)
{
    // ... snip ...

    ObjectQuery<T> objectQuery = source as ObjectQuery<T>;
    if (objectQuery != null)
    {
        // ... do stuff ...
    }
}

This used to work before I changed over to Entity-Framework 4 CTP5 Magic Unicorn blah blah blah. Now, it's not working - ie. objectQuery is null.

Now, DBQuery<T> inherits IQueryable<T> .. so I thought this should work.

If i change the code to ..

var x = (ObjectQuery<T>) source;

then the following exception is thrown :-

System.InvalidCastException: Unable to
  cast object of type
  'System.Data.Entity.Infrastructure.DbQuery1[Tests.Models.Order]'
  to type
  'System.Data.Objects.ObjectQuery1[Tests.Models.Order]'.

Any suggestions?