问:
c# object does not contain definition error
I'm creating a winform which can read data from another winform but i receive some errors in my functions : </p>

```<code>namespace stackkcw
  {
    public partial class Form1 : Form
    {
        public TcpClient client;
        private object datgdStock;
        private object lablUpdates;
        private object lablTime;
        private int countOfData;

        public Form1()
        {

            InitializeComponent();
        }
       private void UpdateGrid(StockDetails data)
        {

            datgdStock.Rows[data.StockId].Cells[0].Value = data.StockName;
            datgdStock.Rows[data.StockId].Cells[1].Value = data.StockPrice;
            datgdStock.Rows[data.StockId].Cells[2].Value = data.StockChange;

        }
        private void UpdateLbl(StockDetails data)
        {
            countOfData++;

            lablUpdates.Invoke(new Action(() => lablUpdates.Text =          countOfData.ToString()));
            lablTime.Invoke(new Action(() => lablTime.Text = data.Time.ToString()));

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataReceiver data = new DataReceiver();

            data.connect(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
            // Pass input in txtIP as an IPAddress and the input in txtPort as an int.
            button1.Enabled = false; // Disable button connect on valid data sending to data reciever class.
            textBox1.Enabled = false; // Disable ip text box on valid data sending to data receiver class
            textBox2.Enabled = false; // disable port text box on valid data sending to data receiver class
            data.dataRecieved += new DataReceiver.DataRecived(UpdateGrid);

            data.dataRecieved += new DataReceiver.DataRecived(UpdateLbl);

        }
        public struct StockDetails
        {

            public int StockId;
            public string StockName;
            public double StockPrice;
            public double StockChange;
            public DateTime Time;
        }
        class DataReceiver
        {
            public delegate void DataRecived(StockDetails stockData);
            public event DataRecived dataRecieved;
            StockDetails data;

            private TcpClient StockClient;

            private Thread listeningThread = null;

            public void connect(IPAddress ip, int port)
            {
                StockClient = new TcpClient();
                StockClient.Connect(ip, port);

                MessageBox.Show("Connected to: " + ip.ToString());

                listeningThread = new Thread(new ThreadStart(listen));
                listeningThread.Start();
            }

            public void listen()
            {
                NetworkStream stream = StockClient.GetStream();

                while (true)
                {
                    byte[] buffer = new byte[256];
                    int no_of_bytes = stream.Read(buffer, 0, 256);

                    JavaScriptSerializer Serializer = new  JavaScriptSerializer();
                    data = Serializer.Deserialize<StockDetails>(Encoding.ASCII.GetString(buffer, 0, no_of_bytes));

                    OnDataRecived();
                }

            }

            protected virtual void OnDataRecived()
            {
                dataRecieved(data);
            }
        }

    }
}
</code>```

答:
D not use object for these properties</p>

```<code> private DataGridView datgdStock;
        private TextBox lablUpdates;
        private TextBox lablTime;
</code>```

Body:
I'm creating a winform which can read data from another winform but i receive some errors in my functions :

namespace stackkcw
  {
    public partial class Form1 : Form
    {
        public TcpClient client;
        private object datgdStock;
        private object lablUpdates;
        private object lablTime;
        private int countOfData;

        public Form1()
        {

            InitializeComponent();
        }
       private void UpdateGrid(StockDetails data)
        {

            datgdStock.Rows[data.StockId].Cells[0].Value = data.StockName;
            datgdStock.Rows[data.StockId].Cells[1].Value = data.StockPrice;
            datgdStock.Rows[data.StockId].Cells[2].Value = data.StockChange;

        }
        private void UpdateLbl(StockDetails data)
        {
            countOfData++;

            lablUpdates.Invoke(new Action(() => lablUpdates.Text =          countOfData.ToString()));
            lablTime.Invoke(new Action(() => lablTime.Text = data.Time.ToString()));

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataReceiver data = new DataReceiver();

            data.connect(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
            // Pass input in txtIP as an IPAddress and the input in txtPort as an int.
            button1.Enabled = false; // Disable button connect on valid data sending to data reciever class.
            textBox1.Enabled = false; // Disable ip text box on valid data sending to data receiver class
            textBox2.Enabled = false; // disable port text box on valid data sending to data receiver class
            data.dataRecieved += new DataReceiver.DataRecived(UpdateGrid);

            data.dataRecieved += new DataReceiver.DataRecived(UpdateLbl);

        }
        public struct StockDetails
        {

            public int StockId;
            public string StockName;
            public double StockPrice;
            public double StockChange;
            public DateTime Time;
        }
        class DataReceiver
        {
            public delegate void DataRecived(StockDetails stockData);
            public event DataRecived dataRecieved;
            StockDetails data;

            private TcpClient StockClient;

            private Thread listeningThread = null;

            public void connect(IPAddress ip, int port)
            {
                StockClient = new TcpClient();
                StockClient.Connect(ip, port);

                MessageBox.Show("Connected to: " + ip.ToString());

                listeningThread = new Thread(new ThreadStart(listen));
                listeningThread.Start();
            }

            public void listen()
            {
                NetworkStream stream = StockClient.GetStream();

                while (true)
                {
                    byte[] buffer = new byte[256];
                    int no_of_bytes = stream.Read(buffer, 0, 256);

                    JavaScriptSerializer Serializer = new  JavaScriptSerializer();
                    data = Serializer.Deserialize<StockDetails>(Encoding.ASCII.GetString(buffer, 0, no_of_bytes));

                    OnDataRecived();
                }

            }

            protected virtual void OnDataRecived()
            {
                dataRecieved(data);
            }
        }

    }
}

Body:
D not use object for these properties

 private DataGridView datgdStock;
        private TextBox lablUpdates;
        private TextBox lablTime;


来源: stackexchange

问:
Guice with parents
What do I do with Guice when I need to call a parent constructor that is also injectable? e.g. I have an abstract parent class that has a constructor that is injected with an object shared by all derived children and each child also has an injectable constructor.

Calling super() wont work because Java wants me to pass in the object as a paremeter rather than have Guice inject.

Thanks

EDIT: I am wondering if maybe I need to use method injection instead?

答:
You'd need to do the exact same thing you do if you weren't using Guice... declare any parameters the parent constructor requires as parameters to each child's constructor as well, and pass those to super.

So if your abstract parent class's constructor takes a Foo, a child class's constructor needs to look like:

```<code>@Inject public ChildClass(Foo foo, Bar bar) {
  super(foo);
  this.bar = bar;
  ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Guice with parents

Body:
You'd need to do the exact same thing you do if you weren't using Guice... declare any parameters the parent constructor requires as parameters to each child's constructor as well, and pass those to super.

So if your abstract parent class's constructor takes a Foo, a child class's constructor needs to look like:

@Inject public ChildClass(Foo foo, Bar bar) {
  super(foo);
  this.bar = bar;
  ...
}


问:
ko.computed property to determine visibility not working
In my KncokoutJS ViewModel, I have the follow computed property:

```<code>self.SelectedUserHasRoles = ko.computed(function () {
  if (self.isLoaded()) {
    return self.selectedUser().roles().length > 0;
  }
  return false;
});
</code>```

And in my HTML, I have the following:

```<code><!-- ko if: isLoaded() -->
  <!-- ko if: !SelectedUserHasRoles -->
  <div>
    <p>User has no Roles.</p>
  </div>
  <!-- /ko -->
  <!-- ko if: SelectedUserHasRoles -->
  <div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
    <div class="role-token" data-bind="text: Name"></div>
  </div>
  <!-- /ko -->
<!-- /ko -->
</code>```

In my code, I was to say this:

If data from AJAX call has finished loading (isLoaded is true), then for the currently selected user, check and see if he/she has any roles. If yes, then loop through them and show them, if not, show a bit of text saying 'User has no Roles.'

All seems to work, except for the showing User has no Roles text snippet. I've no idea why that isn't showing! I'm putting breakpoints into my computed property and can see that when I select a user with no roles, the expression (in console window) is false, and I'm negating that, so I should see that text snippet!

What am I doing wrong? I've created a screencast to make things easier to understand.

答:
You have the same check for isLoaded() twice, actually

```<code><!-- ko if: isLoaded() -->
  <!-- ko if: !SelectedUserHasRoles -->
</code>```

if isLoaded() evalutes to false, your SelectedUserHasRoles() won't even be evaluated.

ContentLicense: CC BY-SA 3.0

Body:
In my KncokoutJS ViewModel, I have the follow computed property:

self.SelectedUserHasRoles = ko.computed(function () {
  if (self.isLoaded()) {
    return self.selectedUser().roles().length > 0;
  }
  return false;
});

And in my HTML, I have the following:

User has no Roles.

In my code, I was to say this:

If data from AJAX call has finished loading (isLoaded is true), then for the currently selected user, check and see if he/she has any roles. If yes, then loop through them and show them, if not, show a bit of text saying 'User has no Roles.'

All seems to work, except for the showing User has no Roles text snippet. I've no idea why that isn't showing! I'm putting breakpoints into my computed property and can see that when I select a user with no roles, the expression (in console window) is false, and I'm negating that, so I should see that text snippet!

What am I doing wrong? I've created a screencast to make things easier to understand.

Body:
You have the same check for isLoaded() twice, actually

<!-- ko if: isLoaded() -->
  <!-- ko if: !SelectedUserHasRoles -->

if isLoaded() evalutes to false, your SelectedUserHasRoles() won't even be evaluated.


问:
req.flash is not a function - Initialization order
I am using node.js with Express 4. I have problem with connect-flash initialization. I looked at many questions with different answers and I still can't solve my problem. I tried many combinations of app.use() order and still getting TypeError req.flash is not a function

Here is my current initialization order:

```<code>var app = express();
var index = require('./routes/index');
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(sassMiddleware({
    src: __dirname + '/public/sass',
    dest: path.join(__dirname, 'public/css'),
    debug: true,
    outputStyle: 'compressed',
    prefix:  '/css'
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));
app.use(i18n({
  translationsPath: path.join(__dirname, './locales'),
  siteLangs: ["es","en"]
}));
app.use(function (res,req,next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
});

app.use('/', index);
app.use('/users', users);
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
</code>```

Thank you for your help.

答:
```<code>app.use(function (res,req,next) {
    //...
})
</code>```

Your req and res parameters in this function is in the wrong order.

Body:
I am using node.js with Express 4. I have problem with connect-flash initialization. I looked at many questions with different answers and I still can't solve my problem. I tried many combinations of app.use() order and still getting TypeError req.flash is not a function

Here is my current initialization order:

var app = express();
var index = require('./routes/index');
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(sassMiddleware({
    src: __dirname + '/public/sass',
    dest: path.join(__dirname, 'public/css'),
    debug: true,
    outputStyle: 'compressed',
    prefix:  '/css'
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));
app.use(i18n({
  translationsPath: path.join(__dirname, './locales'),
  siteLangs: ["es","en"]
}));
app.use(function (res,req,next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
});

app.use('/', index);
app.use('/users', users);
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

Thank you for your help.

Body:
app.use(function (res,req,next) {
    //...
})

Your req and res parameters in this function is in the wrong order.


问:
What are the chronological steps in building a cross browser compatible site?
I am working on my first project that requires me to worry about cross browser compatibility.  Since this is my first time doing so, I dont know how to go about completing the project.  I am specifically worried about IE.  Should I complete my project in a more graceful browser then hack it to work in IE, or should I simultaneously build my program up in both environments?</p>

答: Also you should focus on resetting css like this</p>


问:
Mongoose open connection issue with Supertest
I am unable to run multiple Supertest/Mocha tests as I get an error Error: Trying to open unclosed connection. - I found this post which suggest looping and checking connection status. Wondering if there is a better way? perhaps something that was added in Supertest recently to handle this.

答:
```<code>// Also you can use the 'open' event to call the 'done' callback
// inside the 'before' Mocha hook.

    before((done) => {
        mongoose.connect('mongodb://localhost/test_db');
        mongoose.connection
            .once('open', () => {
                done();
            })
            .on('error', (err) => {
                console.warn('Problem connecting to mongo: ', error);
                done();
            });

    });
</code>```


问:
Not using the url from a header redirection
I am using a header redirection to go back to a pagejump spot at my webpage. I did this with header('Location: index.php#contact');.

The problem I have now is that it says

www.pagename/index.php#contact

The problem is that I don't want to see the #contact in my url, how can I fix this?

Btw, the page were I use header('Location: index.php#contact'); is a different page as the one were I have the anchor.

答:
I suggest that you add some javascript code at [index.php] to change the URL. Like this:

```<code>echo "<script type='text/javascript' language='javascript'>
    history.pushState({},\"index.php#contact\",\"index.php\");
</script>";
</code>```

The second parameter is the original URL, and the third parameter is the URL you want to display.

That's all.O(∩_∩)O~

Body:
I suggest that you add some javascript code at [index.php] to change the URL. Like this:

echo "<script type='text/javascript' language='javascript'>
    history.pushState({},\"index.php#contact\",\"index.php\");
</script>";

The second parameter is the original URL, and the third parameter is the URL you want to display.

That's all.O(∩_∩)O~


问:
Merging two objects in javascript without overwriting users progress in a game
Background: Making a little incremental/idle game and It's got auto clickers and upgrades etc and I'm saving the data in localStorage. At the minute I've got the data stored in an object and I want to be able to add more clickers/upgrades without having to reset the users progress. Here is currently how it is (hopefully not too buggy) - http://johnth.com/

I have an object defined as user which is like a template so when the user first loads the website if there's no local storage it will save user and then the next time they visit it will be loaded into a variable called x and melons and melons per second will be filled with data. Say if I added an upgrade to the melons section then it would be undefined if I tried loading it in so I need to merge the x (which has the users progress) and user (which has the new upgrades). I don't really know the best way to go about this I'm aware of jQuery's .extend and Object.assign and I can't really figure out how to do it.

```<code>var user = {
  "name": "",
  "stats": {
    "click": 1,
    "level": 1,
    "xp": 0,
    "melons": 0,
    "mps": 0,
  },
  "upgrades": {
    "melons": {
      "mash": {
        "name": "Mash - 1MPS",
        "cost": 50,
        "value": 1,
        "owned": 0,
        "scale": costScaling
      },
      "masher": {
        "name": "Masher - 5MPS",
        "cost": 500,
        "value": 5,
        "owned": 0,
        "scale": costScaling
      },
      "mashing": {
        "name": "Mashing - 25MPS",
        "cost": 2500,
        "value": 25,
        "owned": 0,
        "scale": costScaling
      },
      "mashmonster": {
        "name": "MashMonster - 100MPS",
        "cost": 250000,
        "value": 100,
        "owned": 0,
        "scale": costScaling
      }
    },
    "other": {
      "click": {
        "name": "Double Clicks",
        "cost": 1000,
        "value": 1,
        "owned": 0,
        "scale": costScaling
      },
      "a30secboost": {
        "name": "30 Second Boost - 2.5x MPS",
        "cost": 25000,
        "value": 2.5,
        "owned": 0,
        "scale": costScaling
      }
    }
  }
};
</code>```

答:
Basically you need a recursive version of $.extend and Object.assign that recursively merges values of two objects. Fortunately, Lodash has such the function you need.

Check out lodash's merge. It enables you to overwrite values that are in the same key "path", or add on if they don't already exist in the first object.

For example:

```<code>var foo = {
  a: {
    b: 1
  },
  c: 2
}

var bar = {
  a: {
    b: 2
  },
  d: 3
}

console.log(_.merge(foo, bar)) =>

{
  a: {
    b: 2 // overwritten by value in bar
  },
  c: 2,
  d: 3   // added by bar
}
</code>```

Body:
Background: Making a little incremental/idle game and It's got auto clickers and upgrades etc and I'm saving the data in localStorage. At the minute I've got the data stored in an object and I want to be able to add more clickers/upgrades without having to reset the users progress. Here is currently how it is (hopefully not too buggy) - http://johnth.com/

I have an object defined as user which is like a template so when the user first loads the website if there's no local storage it will save user and then the next time they visit it will be loaded into a variable called x and melons and melons per second will be filled with data. Say if I added an upgrade to the melons section then it would be undefined if I tried loading it in so I need to merge the x (which has the users progress) and user (which has the new upgrades). I don't really know the best way to go about this I'm aware of jQuery's .extend and Object.assign and I can't really figure out how to do it.

var user = {
  "name": "",
  "stats": {
    "click": 1,
    "level": 1,
    "xp": 0,
    "melons": 0,
    "mps": 0,
  },
  "upgrades": {
    "melons": {
      "mash": {
        "name": "Mash - 1MPS",
        "cost": 50,
        "value": 1,
        "owned": 0,
        "scale": costScaling
      },
      "masher": {
        "name": "Masher - 5MPS",
        "cost": 500,
        "value": 5,
        "owned": 0,
        "scale": costScaling
      },
      "mashing": {
        "name": "Mashing - 25MPS",
        "cost": 2500,
        "value": 25,
        "owned": 0,
        "scale": costScaling
      },
      "mashmonster": {
        "name": "MashMonster - 100MPS",
        "cost": 250000,
        "value": 100,
        "owned": 0,
        "scale": costScaling
      }
    },
    "other": {
      "click": {
        "name": "Double Clicks",
        "cost": 1000,
        "value": 1,
        "owned": 0,
        "scale": costScaling
      },
      "a30secboost": {
        "name": "30 Second Boost - 2.5x MPS",
        "cost": 25000,
        "value": 2.5,
        "owned": 0,
        "scale": costScaling
      }
    }
  }
};

Body:
Basically you need a recursive version of $.extend and Object.assign that recursively merges values of two objects. Fortunately, Lodash has such the function you need.

Check out lodash's merge. It enables you to overwrite values that are in the same key "path", or add on if they don't already exist in the first object.

For example:

var foo = {
  a: {
    b: 1
  },
  c: 2
}

var bar = {
  a: {
    b: 2
  },
  d: 3
}

console.log(_.merge(foo, bar)) =>

{
  a: {
    b: 2 // overwritten by value in bar
  },
  c: 2,
  d: 3   // added by bar
}


问:
Camera Preview black in Android 7
I'm using a straight forwards Camera API, for backwards compatibility. The camera view itself is overlayed slightly by an imageview and my surfaceChanged does this:

```<code>camera.setPreviewCallback((data, arg1) -> LiveView.this.invalidate());
camera.setPreviewDisplay(mHolder);
camera.startPreview();
</code>```

which works fine on all older devices. I set the preview size to the largest available  size earlier in surfaceCreated.
However on Android 7.1, it's suddenly black (on a Nexus 6 and Moto X Play, probably others - so on different devices).
The SurfaceView itself is greyed out in the Layout Inspector (willNotDraw = true), but VISIBLE (and hardware accelerated).
Strangely, I'm still able to take photos, event without preview, and the data in the preview callback contains an image.

At the same time I get the following log

```<code>E/mm-camera: mct_pipeline_send_ctrl_events: Send Set Parm events
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
D/QCameraParameters: setSnapshotSkipHint: preview hint 3 fps 15.019738
</code>```

Has anybody else experienced a completely black image in Android 7? Are there any easy fixes? (Like drawing the content of data directly?)

答:
Like @apk has said before, black screen is appearing because you are not handling permissions in your code. If you are working with targetSdkVersion 23 (and above) you will have to requests permissions from the user at run-time.

Previous comment explains you how to resolve it through SDK's operations directly, but I prefer use a great third party library for these cases: Karumi/Dexter

Title: Camera Preview black in Android 7

Body:
I'm using a straight forwards Camera API, for backwards compatibility. The camera view itself is overlayed slightly by an imageview and my surfaceChanged does this:

camera.setPreviewCallback((data, arg1) -> LiveView.this.invalidate());
camera.setPreviewDisplay(mHolder);
camera.startPreview();

which works fine on all older devices. I set the preview size to the largest available  size earlier in surfaceCreated.
However on Android 7.1, it's suddenly black (on a Nexus 6 and Moto X Play, probably others - so on different devices).
The SurfaceView itself is greyed out in the Layout Inspector (willNotDraw = true), but VISIBLE (and hardware accelerated).
Strangely, I'm still able to take photos, event without preview, and the data in the preview callback contains an image.

At the same time I get the following log

E/mm-camera: mct_pipeline_send_ctrl_events: Send Set Parm events
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
D/QCameraParameters: setSnapshotSkipHint: preview hint 3 fps 15.019738

Has anybody else experienced a completely black image in Android 7? Are there any easy fixes? (Like drawing the content of data directly?)


问:
What are the best wiki engine with good authorization features?
What is the best wiki engine with good authorization features?</p>

答:
DokuWiki is a great open source PHP Wiki, clean syntax, straightforward install, simple report for read-only and private pages, plus a full ACL system, and a active community of plugin developers.

MediaWiki is amazing from a feature stand point, if you need SVG and MathML support, but I find it too hard to customize and hack on personally.

OwnerDisplayName: kellan

LastEditorDisplayName: VonC


问:
Images taken with ACTION_IMAGE_CAPTURE always returns 1 for ExifInterface.TAG_ORIENTATION on some Gingerbread devices
I had the orientation issue when working with ACTION_IMAGE_CAPTURE activity. I have used the TAG_ORIENTATION so that I would rotate the picture accordingly. But now we found that on some newer devices this doesn't work. In fact it returns 1 for all orientations.

Here's the list of devices we observed this on;

Samsung Infuse 4G (2.3.3)

Samsung Galaxy SII X (2.3.5)

Sony Xperia Arc (2.3.3)

Interesting thing is that once this image is the gallery it shows up properly and if I select it, the TAG_ORIENTATION is populated properly. So somehow the OS fills this information properly but not on ActivityResult.

What's the most reliable way to figure the orientation? Someone on another question suggested comparing height and width but when getting these, they are properly switched based on orientation (another mystery)

EDIT: It seems that this could be connected to another bug where the OS duplicates the image taken in the gallery (it's only supposed to save the image in the URL specified by us), the thing is this image in gallery has the ORIENTATION information while the one in the specified location doesn't.

This is the bug; http://code.google.com/p/android/issues/detail?id=19268

EDIT-2: I've filed a new bug with Android. I'm pretty sure this is an OS bug related the aforementioned bug.
http://code.google.com/p/android/issues/detail?id=22822

答:
My solution for this. Tested on LG G2 mobile. I noticed that when I use camera and take new picture everything works fine. ExifInterface returns right orientation. So it must be something in the path because my path was null in this line of code:

```<code>exif = new ExifInterface(path);
</code>```

but when i used absolute path my app crash. But the solution is in this method below, because it depends on your sdk version. One more note to mention I used absolute path only for selecting gallery picture because if i used it for Camera my app crashed. Im new in programing and just lost 2 days to solve this. Hope it will help someone.

```<code>   public String getRealPathFromURI(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = uri.getLastPathSegment().split(":")[1];
            final String[] imageColumns = {MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
            Uri tempUri = getUri();
            Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
                    MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
            if (imageCursor.moveToFirst()) {
                return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }
    }
</code>```

So I get my ExifInterface in onActivityResult method

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
        try {
            exif = new ExifInterface(getRealPathFromURI(data.getData()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        showImage(data.getData());
    } else if (requestCode == CAMERA_IMAGE_REQUEST && resultCode == RESULT_OK) {
        try {
            exif = new ExifInterface(Uri.fromFile(getCameraFile()).getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        showImage(Uri.fromFile(getCameraFile()));
    }
}
</code>```

and my show image method look like this

```<code>public void showImage(Uri uri) {
    if (uri != null) {
        try {

            Bitmap bitmap = scaleBitmapDown(MediaStore.Images.Media.getBitmap(getContentResolver(), uri), IMAGE_SIZE);

            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

            bitmap = rotateBitmap(bitmap, orientation);

            if (whatPlayer.equals("Player1")) {
                mImagePlayer1.setImageBitmap(bitmap);

                bitmapPlayer1 = bitmap; //*save picture in static variable so other activity can use this
            }
            if (whatPlayer.equals("Player2")) {
                mImagePlayer2.setImageBitmap(bitmap);

                bitmapPlayer2 = bitmap;
            }

        } catch (IOException e) {
            Log.d(TAG, "Image picking failed because " + e.getMessage());
            Toast.makeText(this, R.string.image_picker_error, Toast.LENGTH_LONG).show();
        }
    } else {
        Log.d(TAG, "Image picker gave us a null image.");
        Toast.makeText(this, R.string.image_picker_error, Toast.LENGTH_LONG).show();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My solution for this. Tested on LG G2 mobile. I noticed that when I use camera and take new picture everything works fine. ExifInterface returns right orientation. So it must be something in the path because my path was null in this line of code:

exif = new ExifInterface(path);

but when i used absolute path my app crash. But the solution is in this method below, because it depends on your sdk version. One more note to mention I used absolute path only for selecting gallery picture because if i used it for Camera my app crashed. Im new in programing and just lost 2 days to solve this. Hope it will help someone.

   public String getRealPathFromURI(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = uri.getLastPathSegment().split(":")[1];
            final String[] imageColumns = {MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
            Uri tempUri = getUri();
            Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
                    MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
            if (imageCursor.moveToFirst()) {
                return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }
    }

So I get my ExifInterface in onActivityResult method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
        try {
            exif = new ExifInterface(getRealPathFromURI(data.getData()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        showImage(data.getData());
    } else if (requestCode == CAMERA_IMAGE_REQUEST && resultCode == RESULT_OK) {
        try {
            exif = new ExifInterface(Uri.fromFile(getCameraFile()).getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        showImage(Uri.fromFile(getCameraFile()));
    }
}

and my show image method look like this

public void showImage(Uri uri) {
    if (uri != null) {
        try {

            Bitmap bitmap = scaleBitmapDown(MediaStore.Images.Media.getBitmap(getContentResolver(), uri), IMAGE_SIZE);

            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

            bitmap = rotateBitmap(bitmap, orientation);

            if (whatPlayer.equals("Player1")) {
                mImagePlayer1.setImageBitmap(bitmap);

                bitmapPlayer1 = bitmap; //*save picture in static variable so other activity can use this
            }
            if (whatPlayer.equals("Player2")) {
                mImagePlayer2.setImageBitmap(bitmap);

                bitmapPlayer2 = bitmap;
            }

        } catch (IOException e) {
            Log.d(TAG, "Image picking failed because " + e.getMessage());
            Toast.makeText(this, R.string.image_picker_error, Toast.LENGTH_LONG).show();
        }
    } else {
        Log.d(TAG, "Image picker gave us a null image.");
        Toast.makeText(this, R.string.image_picker_error, Toast.LENGTH_LONG).show();
    }
}


问:
tying a UISearchBar into an action
To let you know from the beginning, I am a newbie at iPhone development, and I have taken an a monstrous task.

First of all, I am writing an application that allows to you to online shop. We have an affiliate account with a known online shopping website, are trying to tie our app into searching that site, and putting the results into a table, with hyperlinks to the site, etc.

But first problems first, one thing at a time:

In Interface Builder, I have a Search Bar, and an outlet connected to the search bar. I also have an IBAction made just to take the text that is entered into the search bar, storing it into a variable, and then searching this website (yes, that's a lot of stuff for an action).

Because I am so new at this process with IB, how do I connect the Search Bar with the IBAction? I know, stupid question.

答:
You can set your view controller as the search bar's delegate in IB (or programmatically), and implement the UISearchBarDelegate protocol to define actions for your search bar.

As a beginner, you should familiarize yourself with the delegate pattern, since a lot of the iOS SDK relies on it (the iOS Application Programming Guide is a good place to start).

Update

You need to implement the UISearchBarDelegate methods in your search bar's delegate. For example, if your search bar is a property of MyViewController, you probably want to have this line in MyViewController's implementation:

```<code>[self.searchBar setDelegate:self];
</code>```

It's as simple as that; now, as long as you have those methods implemented in MyViewController, they will automatically get called when the related action occurs.

Title: tying a UISearchBar into an action

Body:
You can set your view controller as the search bar's delegate in IB (or programmatically), and implement the UISearchBarDelegate protocol to define actions for your search bar.

As a beginner, you should familiarize yourself with the delegate pattern, since a lot of the iOS SDK relies on it (the iOS Application Programming Guide is a good place to start).

Update

You need to implement the UISearchBarDelegate methods in your search bar's delegate. For example, if your search bar is a property of MyViewController, you probably want to have this line in MyViewController's implementation:

[self.searchBar setDelegate:self];

It's as simple as that; now, as long as you have those methods implemented in MyViewController, they will automatically get called when the related action occurs.


问:
Reset Bootstrap modal when clicking outside modal window
I'm having some problems with reseting my bootstrap modal whenever the user clicks outside the modal window to dismiss instead of pressing the dismiss button. My datetimepicker stops working whenever the modal window doesnt reset properly.

This is what my modal should do whenever it opens:

But this is what happens if I open the window just after dismissing my window by hitting the gray area outside the modal window:

Whenever I dismiss using the Avbryt (dismiss) button it works just fine.
I get no errors and this is the code I use for my modal

```<code>$scope.show = function() {
    ModalService.showModal({
            templateUrl: 'newProject.html',
            controller: "NewProjectModalController"
        }).then(function(modal) {
            modal.element.modal();
            modal.close.then(function(result) {
                $('#newProjectModal').modal('hide');
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            }
        });
    });
}
$scope.dismiss = function () {
    close(false, 500)
}
</code>```

The modal service can be found on JSfiddle.

I discovered that its not really the backdrop that is triggering the dismiss but the edges of the modal window. If I hit the outside of the modal within the small square, its dismisses, but not if I hit the backdrop outside.

答:
According to the image in question, you are using angular-modal-service along with bootstrap.js  in your project. So I searched its github repo and found this issue: https://github.com/dwmkerr/angular-modal-service/issues/107

According to the comments there, you should change your code as below:

```<code>ModalService.showModal({
        templateUrl: 'newProject.html',
        controller: "NewProjectModalController"
    }).then(function(modal) {
        modal.element.modal();
        modal.close.then(function(result) {
            $('#newProjectModal').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
        }
        // added by me
        modal.element.on('hidden.bs.modal', function () {// bootstrap event
            modal.scope.close(false,500);
        });
    });
});
</code>```

Body:
I'm having some problems with reseting my bootstrap modal whenever the user clicks outside the modal window to dismiss instead of pressing the dismiss button. My datetimepicker stops working whenever the modal window doesnt reset properly.

This is what my modal should do whenever it opens:

But this is what happens if I open the window just after dismissing my window by hitting the gray area outside the modal window:

Whenever I dismiss using the Avbryt (dismiss) button it works just fine.
I get no errors and this is the code I use for my modal

$scope.show = function() {
    ModalService.showModal({
            templateUrl: 'newProject.html',
            controller: "NewProjectModalController"
        }).then(function(modal) {
            modal.element.modal();
            modal.close.then(function(result) {
                $('#newProjectModal').modal('hide');
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            }
        });
    });
}
$scope.dismiss = function () {
    close(false, 500)
}

The modal service can be found on JSfiddle.

I discovered that its not really the backdrop that is triggering the dismiss but the edges of the modal window. If I hit the outside of the modal within the small square, its dismisses, but not if I hit the backdrop outside.

Body:
According to the image in question, you are using angular-modal-service along with bootstrap.js  in your project. So I searched its github repo and found this issue: https://github.com/dwmkerr/angular-modal-service/issues/107

According to the comments there, you should change your code as below:

ModalService.showModal({
        templateUrl: 'newProject.html',
        controller: "NewProjectModalController"
    }).then(function(modal) {
        modal.element.modal();
        modal.close.then(function(result) {
            $('#newProjectModal').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
        }
        // added by me
        modal.element.on('hidden.bs.modal', function () {// bootstrap event
            modal.scope.close(false,500);
        });
    });
});


问:
iOS - Crashlytics missing dSYMs to process crashes
I know this is a frequently asked question.

I just spent the entire day looking for answers, without success.

Here are the different posts that helped me, but didn't fix my issue.

Posts, Documentation, Twitt :

Missing dSYM, No matching UUID, Official Documentation but also It looks like we are missing dSYMs.

Here is my configuration and what I have tried so far :

I have bitcode enabled (watchOS support)

I have downloaded dSYM from iTunesConnect -> Without Success

I searched in the archive from the Organizer (Show Package) -> Without Success

I have set DWARF with dSYM file in the Build Settings.

I don't have matching UUID, like I read in some posts, it's because Apple compile the App again when you have bitcode enabled.

What should I do now ? We released a new version and now Crashlytics Dashboard is getting messy with all those missing dSYMs, for 2 different versions now.

If someone has additional information that I didn't read or know about, I am open-minded for suggestions.

NB: I have bitcode enabled for my Watch and Watch extension target, and the whole project, but not for my main target nor the widget.

答:
Thanks for reaching out on this, Todd from Fabric.

We do not currently support WatchOS crashes. We tested heavily when watchOS 2 came out, but unfortunately there were many changes to the APIs in that version. One of the changes heavily restricted our ability to capture information reliably and also get that information out. Since we couldn't do this reliability without using private APIs, we don't have support for it.

Thanks!


问:
Camel jetty component logging
how can I enable http logs in camel? I'm using rest-dsl. I would like to see http headers and bodies for every request and response My code:

```<code>restConfiguration()
                .component("jetty")
                .host("0.0.0.0")
                .port(port)
                .scheme("https")
                .bindingMode(RestBindingMode.json)
                .dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES")
                .dataFormatProperty("json.in.enableFeatures", "FAIL_ON_NULL_FOR_PRIMITIVES")
                .componentProperty("sslKeyPassword", KEYSTORE_PASSWORD)
                .componentProperty("sslKeystore", KEYSTORE)
                .componentProperty("sslPassword", KEYSTORE_PASSWORD)
                .enableCORS(true)
                .componentProperty("traceEnabled", "true")
                // swagger
                .apiContextPath("api-doc")
            .apiProperty("api.title", "Mobile Api").apiProperty("api.version", "v1.0")
            .apiProperty("schemes", "https")
           ;
</code>```

and

```<code>rest(MOBILE_API_PATH).produces("application/json").consumes("application/json")

            .post("/transaction").type(MobileTransactionRequest.class).outType(MobileTransactionResponse.class)
            .to("direct:mobileTransaction")
</code>```

答:
To enable component logging you'll need to create this beans :

```<code><bean id="log" class="org.eclipse.jetty.server.handler.RequestLogHandler">
    <property name="requestLog" ref="jettyLog"/>
</bean>
<bean id="jettyLog" class="org.eclipse.jetty.server.Slf4jRequestLog"/>
</code>```

And configure enpoint like this:

```<code>jetty:http://0.0.0.0:8040/test?handlers=#log
</code>```

But by default logger will not write body and all headers. You should create your class extending AbstractLifeCycle and implementing RequestLog, with own log logic.

Title: Camel jetty component logging

Body:
how can I enable http logs in camel? I'm using rest-dsl. I would like to see http headers and bodies for every request and response My code:

restConfiguration()
                .component("jetty")
                .host("0.0.0.0")
                .port(port)
                .scheme("https")
                .bindingMode(RestBindingMode.json)
                .dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES")
                .dataFormatProperty("json.in.enableFeatures", "FAIL_ON_NULL_FOR_PRIMITIVES")
                .componentProperty("sslKeyPassword", KEYSTORE_PASSWORD)
                .componentProperty("sslKeystore", KEYSTORE)
                .componentProperty("sslPassword", KEYSTORE_PASSWORD)
                .enableCORS(true)
                .componentProperty("traceEnabled", "true")
                // swagger
                .apiContextPath("api-doc")
            .apiProperty("api.title", "Mobile Api").apiProperty("api.version", "v1.0")
            .apiProperty("schemes", "https")
           ;

and

rest(MOBILE_API_PATH).produces("application/json").consumes("application/json")

            .post("/transaction").type(MobileTransactionRequest.class).outType(MobileTransactionResponse.class)
            .to("direct:mobileTransaction")

Body:
To enable component logging you'll need to create this beans :

<bean id="log" class="org.eclipse.jetty.server.handler.RequestLogHandler">
    <property name="requestLog" ref="jettyLog"/>
</bean>
<bean id="jettyLog" class="org.eclipse.jetty.server.Slf4jRequestLog"/>

And configure enpoint like this:

jetty:http://0.0.0.0:8040/test?handlers=#log

But by default logger will not write body and all headers. You should create your class extending AbstractLifeCycle and implementing RequestLog, with own log logic.


问:
Number of Duplicate Rows in multiple columns (more than 10) in SQL Server
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

```<code>Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3
</code>```

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

```<code>Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2
</code>```

答:
You can try this long way

```<code>SELECT * FROM CUST WHERE CUSTOMER in (SELECT CUSTOMER FROM CUST
GROUP BY CUSTOMER, X, Y, Z
HAVING COUNT(X)=1 AND COUNT(Y)=1 AND COUNT(Z)=1)
</code>```

If any person with good sql knowledge can short it will be good for you.

Body:
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2

Body:
You can try this long way

SELECT * FROM CUST WHERE CUSTOMER in (SELECT CUSTOMER FROM CUST
GROUP BY CUSTOMER, X, Y, Z
HAVING COUNT(X)=1 AND COUNT(Y)=1 AND COUNT(Z)=1)

If any person with good sql knowledge can short it will be good for you.


问:
correct OJDBC jar file version
I'm trying to use latest hibernate 5.2.9 to check the new functionality and performance for upgrading my project from 4.2.1.

How to choose the respective ojdbc jar file to import? Currently we are using   Oracle 11g.

答:
You can use ojdbc6 works fine with Oracle 11g for me.

If you are using Maven you can use this dependency:

```<code><dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>
</code>```

Title: correct OJDBC jar file version

Body:
You can use ojdbc6 works fine with Oracle 11g for me.

If you are using Maven you can use this dependency:

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>


问:
whats is the best way of getting the name of the controller action that i am currently in
i have a number of asp.net-mvc controller actions that look like this:

```<code> public ActionResult Home()
 {
      return View(new MyViewModel("Home"));
 }

 public ActionResult Architecture()
 {
      return View(new MyViewModel("Architecture"));
 }
</code>```

is there anyway to get the name of the method that i am in to avoid having to hard code the string "Home" or "Architecture" ??

答: Have a look at T4MVC. http://mvccontrib.codeplex.com/wikipage?title=T4MVC</p>

Body:
i have a number of asp.net-mvc controller actions that look like this:

 public ActionResult Home()
 {
      return View(new MyViewModel("Home"));
 }

 public ActionResult Architecture()
 {
      return View(new MyViewModel("Architecture"));
 }

is there anyway to get the name of the method that i am in to avoid having to hard code the string "Home" or "Architecture" ??


问:
Entity Framework 7 / Core code-first mapping to stored procedure
I am new to Entity Framework 7 code-first and came across a mapping issue with stored procedure.

Below are two classes where cityid is the relational property:

```<code>public class CityList
{
        [Key]
        public int CityId { get; set; }
        [Required]
        [MaxLength(50)]
        public string CityName { get; set; }
        [MaxLength(200)]
        public string CityDescription { get; set; }
        public ICollection<PointOfInterestList> PointOfInterestList { get; set; } = new List<PointOfInterestList>();
}

public class PointOfInterestList
{
        [Key]
        public int PointsofInterestId { get; set; }
        [Required]
        [MaxLength(50)]
        public string PointsofInterestName { get; set; }
        [MaxLength(200)]
        public string PointsofInterestDescription { get; set; }
        [ForeignKey("CityId")]
        public CityList CityList { get; set; }
        public int CityId { get; set; }
}
</code>```

Using DbContext to populate the CityList object from a stored procedure GetCity:

```<code>var returnlist = _context.CitiesList.FromSql("GetCity @p0", CityId).ToList();
</code>```

Stored procedure code:

```<code>CREATE PROCEDURE [GetCity]
    (@CityId INT = 0)
AS
BEGIN
    IF @CityId = 0
        SET @CityId = NULL

    SELECT
        c.Id CityId, C.Description CityDescription, C.Name CityName--,c.Country
        ,p.Id PointsofInterestId, p.Name PointsofInterestName, p.Description PointsofInterestDescription
    FROM
        dbo.Cities c
    INNER JOIN
        dbo.PointOfInterest p ON p.CityId = c.Id
    WHERE
        c.Id = ISNULL(@CityId, c.Id)
END
</code>```

The stored procedure gets executed and populates the CityList collection, but the PointOfInterestList collection within each CityList object does not get mapped with the stored procedure result.

Let me know if I have missed any step.

答:
When you map via a stored procedure, it isn't smart enough to know about any Includes are doing (since you can't do .Include(...)).  It only knows the direct fields on the entity you are directly mapping to.  Thus, the only way you'd be able to fix this is to create your own DTO that has both the header and lines in it and then have a custom map to push that data into the appropriate entities, along with having to deal with the duplicate header data yourself. (i.e. If you have 2 lines, you'd need 1 header and then add both lines to that header. Uniqueness based on PK would work.)

Edit - Example:

```<code>public class MyCustomRowDto
{
        public int CityId { get; set; }
        public string CityName { get; set; }
        public string CityDescription { get; set; }

        public int PointsofInterestId { get; set; }
        public string PointsofInterestName { get; set; }
        public string PointsofInterestDescription { get; set; }
}
</code>```

Then when you call the stored procedure:

```<code>var list = context.Database.SqlQuery<MyCustomRowDto>("...").ToList();
</code>```

Then you'll need some sort of mapping layer with a dictionary for the primary key. Something like this:

```<code>var data = new Dictionary<int, CityList>();

foreach (var item in list) {
   CityList entity;
   if (!data.TryGet(item.CityId, out entity)) {
      entity = new CityList() { CityId = item.CityId, CityName = item.CityName ..., PointOfInterestList = new List<PointOfInterestList>() };
      data.Add(item.CityId, entity);
   }
   entity.PointOfInterest.Add(new PointOfInterestList() { PointOfInterestId = item.PointofInterestId, ..., CityId = item.CityId, CityList = entity
}

return data.Select(a => a.Value).ToList();
</code>```

Body:
I am new to Entity Framework 7 code-first and came across a mapping issue with stored procedure.

Below are two classes where cityid is the relational property:

public class CityList
{
        [Key]
        public int CityId { get; set; }
        [Required]
        [MaxLength(50)]
        public string CityName { get; set; }
        [MaxLength(200)]
        public string CityDescription { get; set; }
        public ICollection<PointOfInterestList> PointOfInterestList { get; set; } = new List<PointOfInterestList>();
}

public class PointOfInterestList
{
        [Key]
        public int PointsofInterestId { get; set; }
        [Required]
        [MaxLength(50)]
        public string PointsofInterestName { get; set; }
        [MaxLength(200)]
        public string PointsofInterestDescription { get; set; }
        [ForeignKey("CityId")]
        public CityList CityList { get; set; }
        public int CityId { get; set; }
}

Using DbContext to populate the CityList object from a stored procedure GetCity:

var returnlist = _context.CitiesList.FromSql("GetCity @p0", CityId).ToList();

Stored procedure code:

CREATE PROCEDURE [GetCity]
    (@CityId INT = 0)
AS
BEGIN
    IF @CityId = 0
        SET @CityId = NULL

    SELECT
        c.Id CityId, C.Description CityDescription, C.Name CityName--,c.Country
        ,p.Id PointsofInterestId, p.Name PointsofInterestName, p.Description PointsofInterestDescription
    FROM
        dbo.Cities c
    INNER JOIN
        dbo.PointOfInterest p ON p.CityId = c.Id
    WHERE
        c.Id = ISNULL(@CityId, c.Id)
END

The stored procedure gets executed and populates the CityList collection, but the PointOfInterestList collection within each CityList object does not get mapped with the stored procedure result.

Let me know if I have missed any step.

Body:
When you map via a stored procedure, it isn't smart enough to know about any Includes are doing (since you can't do .Include(...)).  It only knows the direct fields on the entity you are directly mapping to.  Thus, the only way you'd be able to fix this is to create your own DTO that has both the header and lines in it and then have a custom map to push that data into the appropriate entities, along with having to deal with the duplicate header data yourself. (i.e. If you have 2 lines, you'd need 1 header and then add both lines to that header. Uniqueness based on PK would work.)

Edit - Example:

public class MyCustomRowDto
{
        public int CityId { get; set; }
        public string CityName { get; set; }
        public string CityDescription { get; set; }

        public int PointsofInterestId { get; set; }
        public string PointsofInterestName { get; set; }
        public string PointsofInterestDescription { get; set; }
}

Then when you call the stored procedure:

var list = context.Database.SqlQuery<MyCustomRowDto>("...").ToList();

Then you'll need some sort of mapping layer with a dictionary for the primary key. Something like this:

var data = new Dictionary<int, CityList>();

foreach (var item in list) {
   CityList entity;
   if (!data.TryGet(item.CityId, out entity)) {
      entity = new CityList() { CityId = item.CityId, CityName = item.CityName ..., PointOfInterestList = new List<PointOfInterestList>() };
      data.Add(item.CityId, entity);
   }
   entity.PointOfInterest.Add(new PointOfInterestList() { PointOfInterestId = item.PointofInterestId, ..., CityId = item.CityId, CityList = entity
}

return data.Select(a => a.Value).ToList();


问:
Artifact Dependencies not resolving
I have a teamcity job that publishes a single file as an artifact (this is the simplest configuration i could find that reproduces this issue)

I have another job that has this job as a snapshot dependency and an artifact dependency

The second job fails to start with the following in the logs:

```<code>[13:42:27]Collecting changes in 1 VCS root (2s)
[13:42:27][Collecting changes in 1 VCS root] VCS Root details
[13:42:27][VCS Root details] "xxx" {instance id=842, parent internal id=191, parent id=XXXXX, description: "GITURL.git#refs/heads/master"}
[13:42:32]Skip checking for changes - changes are already collected
[13:42:32]Clearing temporary directory: /home/centos/buildAgent/work/buildTmp
[13:42:32]Publishing internal artifacts
[13:42:32][Publishing internal artifacts] Publishing 1 file using [WebPublisher]
[13:42:32][Publishing internal artifacts] Publishing 1 file using [ArtifactsCachePublisher]
[13:42:32]Checkout directory: /home/centos/buildAgent/work/56c889e980287ca6
[13:42:32]Resolving artifact dependencies
[13:42:32][Resolving artifact dependencies] Started downloading files from <XXXX :: Build and push images, build #0.0.34 [id 256119]>
[13:42:32][Resolving artifact dependencies] Failed to resolve artifact dependency <XXXX :: Build and push images, build #0.0.34 [id 256119]>: IO exception while creating or opening temp file: No such file or directory (jetbrains.buildServer.artifacts.ResolvingFailedException)
[13:42:32]Publishing internal artifacts
[13:42:32][Publishing internal artifacts] Publishing 1 file using [WebPublisher]
[13:42:32][Publishing internal artifacts] Publishing 1 file using [ArtifactsCachePublisher]
[13:42:32]Build failed to start. Artifacts will not be published for this build
[13:42:33]Build finished
</code>```

We have verified that the teamcity server does indeed have the necessary artifact.

When i click on "Check artifact dependencies" when configuring dependencies they resolve without issue...

```<code>[13:46:45]: Dependency resolving started...
[13:46:45]: Downloading artifacts from: http://tcurl:8888
[13:46:45]: Downloading teamcity-deploy.sh from <XXXX :: Build and push images, build from the same chain> to teamcity-deploy.sh;
[13:46:45]: <XXXX :: Build and push images, build from the same chain> teamcity-deploy.sh => teamcity-deploy.sh
[13:46:45]: Dependency resolving finished successfully
</code>```

Does anyone have any suggestions as to what could be causing this issue?

答:
This is a known bug in Teamcity where by the temp sub folder fails to be auto created: https://youtrack.jetbrains.com/issue/TW-42473#tab=Comments

You can upgrade TC to v10 RC1 or move the temp folder used to one outside of the working dir and this has been proven to work fine.

Title: Artifact Dependencies not resolving

Body:
I have a teamcity job that publishes a single file as an artifact (this is the simplest configuration i could find that reproduces this issue)

I have another job that has this job as a snapshot dependency and an artifact dependency

The second job fails to start with the following in the logs:

[13:42:27]Collecting changes in 1 VCS root (2s)
[13:42:27][Collecting changes in 1 VCS root] VCS Root details
[13:42:27][VCS Root details] "xxx" {instance id=842, parent internal id=191, parent id=XXXXX, description: "GITURL.git#refs/heads/master"}
[13:42:32]Skip checking for changes - changes are already collected
[13:42:32]Clearing temporary directory: /home/centos/buildAgent/work/buildTmp
[13:42:32]Publishing internal artifacts
[13:42:32][Publishing internal artifacts] Publishing 1 file using [WebPublisher]
[13:42:32][Publishing internal artifacts] Publishing 1 file using [ArtifactsCachePublisher]
[13:42:32]Checkout directory: /home/centos/buildAgent/work/56c889e980287ca6
[13:42:32]Resolving artifact dependencies
[13:42:32][Resolving artifact dependencies] Started downloading files from <XXXX :: Build and push images, build #0.0.34 [id 256119]>
[13:42:32][Resolving artifact dependencies] Failed to resolve artifact dependency <XXXX :: Build and push images, build #0.0.34 [id 256119]>: IO exception while creating or opening temp file: No such file or directory (jetbrains.buildServer.artifacts.ResolvingFailedException)
[13:42:32]Publishing internal artifacts
[13:42:32][Publishing internal artifacts] Publishing 1 file using [WebPublisher]
[13:42:32][Publishing internal artifacts] Publishing 1 file using [ArtifactsCachePublisher]
[13:42:32]Build failed to start. Artifacts will not be published for this build
[13:42:33]Build finished

We have verified that the teamcity server does indeed have the necessary artifact.

When i click on "Check artifact dependencies" when configuring dependencies they resolve without issue...

[13:46:45]: Dependency resolving started...
[13:46:45]: Downloading artifacts from: http://tcurl:8888
[13:46:45]: Downloading teamcity-deploy.sh from <XXXX :: Build and push images, build from the same chain> to teamcity-deploy.sh;
[13:46:45]: <XXXX :: Build and push images, build from the same chain> teamcity-deploy.sh => teamcity-deploy.sh
[13:46:45]: Dependency resolving finished successfully

Does anyone have any suggestions as to what could be causing this issue?


问:
Jsoup casting Element as TextNode causes exception
what am trying to parse using jsoup is the following Numéro d'arrêt : 5216 and Numéro NOR : 63066, but nothing seems to works any advice and suggestions will be greatly appreciated:

`

```<code><div class="1st">
<p>
<h3>Numérotation : </h3>
Numéro d'arrêt : 5216
<br />
Numéro NOR : 63066
</div>
</code>```

`

UPDATE :

i got this code to work but it keep giving me this exception org.jsoup.nodes.Element cannot be cast to org.jsoup.nodes.TextNode :

```<code>Document tunisie = Jsoup.connect("http://www.juricaf.org/arret/TUNISIE-COURDECASSATION-20060126-5216").get();

for (Element titres : tunisie.select("div.arret")){

                    String titre = titres.select("h1#titre").first().text();
                    System.out.println(titre);
                    System.out.println("\n");
                }

                for (Element node : tunisie.select("h3")) {
                    TextNode numérodarrêt = (TextNode) node.nextSibling();
                    System.out.println(" " + numérodarrêt.text());
                    System.out.println("\n");

                }

                //NuméroNOR et Identifiant URN LEX
                for (Element element2 : tunisie.select("br")) {
                    TextNode NuméroNOR_IdentifiantURNLEX = (TextNode) element2.nextSibling();
                    System.out.println(" " + NuméroNOR_IdentifiantURNLEX.text());
                    System.out.println("\n");
                }
</code>```

UPDATE :

here is what am trying to parse image link is below.

Parsing text outside html tags

答:
```<code>String html = "<div class=\"1st\">\n" +
                        "<p>\n" +
                        "<h3>Numérotation : </h3>\n" +
                        "Numéro d'arrêt : 5216\n" +
                        "<br />\n" +
                        "Numéro NOR : 63066\n" +
                    "</div>";

 Document doc = Jsoup.parse(html);
 Elements divs = doc.select("div.1st");
 for(Element e : divs){
      System.out.println(e.ownText());
 }
</code>```

Body:
what am trying to parse using jsoup is the following Numéro d'arrêt : 5216 and Numéro NOR : 63066, but nothing seems to works any advice and suggestions will be greatly appreciated:

`

Numérotation :

Numéro d'arrêt : 5216

Numéro NOR : 63066

`

UPDATE :

i got this code to work but it keep giving me this exception org.jsoup.nodes.Element cannot be cast to org.jsoup.nodes.TextNode :

Document tunisie = Jsoup.connect("http://www.juricaf.org/arret/TUNISIE-COURDECASSATION-20060126-5216").get();

for (Element titres : tunisie.select("div.arret")){

                    String titre = titres.select("h1#titre").first().text();
                    System.out.println(titre);
                    System.out.println("\n");
                }

                for (Element node : tunisie.select("h3")) {
                    TextNode numérodarrêt = (TextNode) node.nextSibling();
                    System.out.println(" " + numérodarrêt.text());
                    System.out.println("\n");

                }

                //NuméroNOR et Identifiant URN LEX
                for (Element element2 : tunisie.select("br")) {
                    TextNode NuméroNOR_IdentifiantURNLEX = (TextNode) element2.nextSibling();
                    System.out.println(" " + NuméroNOR_IdentifiantURNLEX.text());
                    System.out.println("\n");
                }

UPDATE :

here is what am trying to parse image link is below.

Parsing text outside html tags


问:
FloathMath error in my project
I'm new to Android development, this is my error

Can you help me?

答:
you can use Math.sin instead of FlatMath.sin. From the doc

Math routines similar to those found in Math.

All methods were removed from the public API in version 23.

you can read more here

Title: FloathMath error in my project


问:
Where can I find the python Zeitgeist Programming modules?
On the Zeitgeist launchpad page, a link to a python API tutorial has been given for beginners.

I've fully configured and installed the zeitgeist-1.0 tarball from the launchpad site, but I still can't find or use the zeitgeist modules while python programming.

 Please Help.
edit:

I haven't tried anything yet, i've just installed the whole package. I've also got the following packages installed. libzeitgeist-1.0-1:amd64 libzeitgeist-2.0-0:amd64 python-zeitgeist rhythmbox-plugin-zeitgeist zeitgeist zeitgeist-core zeitgeist-datahub zeitgeist-explorer.

Also I am working in python 3.5 on ipython3.

答:
You have to install python-zeitgeist module:

```<code>pip install --user python-zeitgeist
</code>```

or

```<code>sudo apt-get install python-zeitgeist
</code>```

Looking for example code, take a look here

```<code>from zeitgeist.client import ZeitgeistClient
from zeitgeist.datamodel import *

zeitgeist = ZeitgeistClient()

def on_events_received(events):
    if events:
        song = events[0]
        print "Last song: %s" % song.subjects[0].uri
    else:
        print "You haven't listened to any songs."

template = Event.new_for_values(subject_interpretation=Interpretation.AUDIO)
zeitgeist.find_events_for_template(template, on_events_received, num_events=1)

# Start a mainloop - note: the Qt mainloop also works
from gi.repository import GLib
GLib.MainLoop().run()
</code>```

Body:
You have to install python-zeitgeist module:

pip install --user python-zeitgeist

or

sudo apt-get install python-zeitgeist

Looking for example code, take a look here

from zeitgeist.client import ZeitgeistClient
from zeitgeist.datamodel import *

zeitgeist = ZeitgeistClient()

def on_events_received(events):
    if events:
        song = events[0]
        print "Last song: %s" % song.subjects[0].uri
    else:
        print "You haven't listened to any songs."

template = Event.new_for_values(subject_interpretation=Interpretation.AUDIO)
zeitgeist.find_events_for_template(template, on_events_received, num_events=1)

# Start a mainloop - note: the Qt mainloop also works
from gi.repository import GLib
GLib.MainLoop().run()


问:
Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/AuctionWebsite]]
Ive got myself into a bit of a mess when trying to run my project, receiving a list of errors as shown below.

First error shown below-

```<code>29-Mar-2017 12:59:55.098 SEVERE [http-nio-8080-exec-65] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/AuctionWebsite]]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at com.mkyong.AuctionWebApplication$$EnhancerBySpringCGLIB$$b523f52f.entityManagerFactory(<generated>) ~[classes/:na]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:441)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_11]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_11]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_11]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_11]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
... 66 common frames omitted
</code>```

Caused by

```<code>Caused by: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernateEntityManagerFactory
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275) ~[catalina.jar:9.0.0.M17]
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1109) ~[catalina.jar:9.0.0.M17]
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:596)
at org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter.<init>(HibernateJpaVendorAdapter.java:89) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
... 77 common frames omitted

at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:467)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1617)
at sun.reflect.GeneratedMethodAccessor102.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1483)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:904)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:336)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:591)
at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:319)
at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:88)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
</code>```

The main error point to my AuctionWebApplication.java class which is my configuration -

```<code>@SpringBootApplication
@ComponentScan
@EnableJpaRepositories("All")
@EntityScan("All")
public class AuctionWebApplication extends SpringBootServletInitializer  {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(AuctionWebApplication.class);
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(AuctionWebApplication.class, args);
}

    @Bean
    DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/auctiondb?zeroDateTimeBehavior=convertToNull");
        dataSource.setUsername("root");
        dataSource.setPassword("toor");

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource);
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setPackagesToScan("All");

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        jpaProperties.setProperty("hibernate.id.new_generator_mappings", "false");
        entityManager.setJpaProperties(jpaProperties);

        return entityManager;
    }

}
</code>```

Specifically this line -

```<code>entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
</code>```

My thinkinking is that its a dependency error but i cant find any problems in POM-

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>AuctionWebsiteM</artifactId>
<packaging>war</packaging>
<name>AuctionWebsiteM</name>
<description>An auction website</description>
<version>1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <!-- Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Web with Tomcat + Embed -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- JSTL -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

    <!-- Need this to compile JSP -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- Need this to compile JSP -->
    <dependency>
        <groupId>org.eclipse.jdt.core.compiler</groupId>
        <artifactId>ecj</artifactId>
        <version>4.6.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- Optional, for bootstrap -->
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.7</version>
    </dependency>

            <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.41</version>
    </dependency>
             <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-commons</artifactId>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
            </dependency>
            <dependency>
               <groupId>org.springframework.data</groupId>
               <artifactId>spring-data-jpa</artifactId>
               <type>jar</type>
            </dependency>
            <dependency>
                <groupId>org.hibernate.javax.persistence</groupId>
                <artifactId>hibernate-jpa-2.1-api</artifactId>
                <version>1.0.0.Final</version>
                <type>jar</type>
            </dependency>
</dependencies>
<build>
    <plugins>
        <!-- Package as an executable jar/war -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
    <repositories>
            <repository>
                    <id>unknown-jars-temp-repo</id>
                    <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
                    <url>file:${project.basedir}/lib</url>
            </repository>
    </repositories>
</code>```

Any help would be much appreciated.

答: As discussed in the chat https://chat.stackoverflow.com/rooms/139379/discussion-between-amitk-and-hazardaguess , mvn clean package command resolved the issue, it looks like the dependency of  HibernateEntityManagerFactory class was missing initially, As OP was not using the auto-refresh feature of maven. and when OP ran mvn clean package command,it had downloaded the required jar, which resolved the issue.

Body:
Ive got myself into a bit of a mess when trying to run my project, receiving a list of errors as shown below.

First error shown below-

29-Mar-2017 12:59:55.098 SEVERE [http-nio-8080-exec-65] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/AuctionWebsite]]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at com.mkyong.AuctionWebApplication$$EnhancerBySpringCGLIB$$b523f52f.entityManagerFactory(<generated>) ~[classes/:na]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:441)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_11]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_11]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_11]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_11]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
... 66 common frames omitted

Caused by

Caused by: java.lang.ClassNotFoundException: org.hibernate.ejb.HibernateEntityManagerFactory
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275) ~[catalina.jar:9.0.0.M17]
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1109) ~[catalina.jar:9.0.0.M17]
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:596)
at org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter.<init>(HibernateJpaVendorAdapter.java:89) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
... 77 common frames omitted

at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:467)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1617)
at sun.reflect.GeneratedMethodAccessor102.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1483)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:904)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:336)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:591)
at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:319)
at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:88)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

The main error point to my AuctionWebApplication.java class which is my configuration -

@SpringBootApplication
@ComponentScan
@EnableJpaRepositories("All")
@EntityScan("All")
public class AuctionWebApplication extends SpringBootServletInitializer  {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(AuctionWebApplication.class);
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(AuctionWebApplication.class, args);
}

    @Bean
    DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/auctiondb?zeroDateTimeBehavior=convertToNull");
        dataSource.setUsername("root");
        dataSource.setPassword("toor");

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource);
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setPackagesToScan("All");

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        jpaProperties.setProperty("hibernate.id.new_generator_mappings", "false");
        entityManager.setJpaProperties(jpaProperties);

        return entityManager;
    }

}

Specifically this line -

entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

My thinkinking is that its a dependency error but i cant find any problems in POM-

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>AuctionWebsiteM</artifactId>
<packaging>war</packaging>
<name>AuctionWebsiteM</name>
<description>An auction website</description>
<version>1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jdt.core.compiler</groupId>
        <artifactId>ecj</artifactId>
        <version>4.6.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.7</version>
    </dependency>

            <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.41</version>
    </dependency>
             <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-commons</artifactId>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
            </dependency>
            <dependency>
               <groupId>org.springframework.data</groupId>
               <artifactId>spring-data-jpa</artifactId>
               <type>jar</type>
            </dependency>
            <dependency>
                <groupId>org.hibernate.javax.persistence</groupId>
                <artifactId>hibernate-jpa-2.1-api</artifactId>
                <version>1.0.0.Final</version>
                <type>jar</type>
            </dependency>
</dependencies>
<build>
    <plugins>

        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
    <repositories>
            <repository>
                    <id>unknown-jars-temp-repo</id>
                    <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
                    <url>file:${project.basedir}/lib</url>
            </repository>
    </repositories>

Any help would be much appreciated.