问:
Linq where-filter causes cast to base class
I have a generic IQueryable of a concrete class:

```<code>IQueryable<Person> result = GetAllEmployees(); //returns IQueryable<Employee>
</code>```

If I return result in a service-call for a Breeze-Entitytype, everything works fine:

```<code>breeze.EntityQuery.from("Employees").orderBy("EmployeeID");
</code>```

As soon as I add a where-filter to the result in the service-call, the whole IQueryable-Object seems to be casted to the base class Person and not have a property EmployeeID anymore:

```<code>IQueryable<Person> result = GetAllEmployees(); //returns IQueryable<Employee>
result = result.Where(o => myHashSet.Contains(o.Id));
</code>```

This causes the following Error:

```<code>Microsoft.Data.OData.ODataException: The query specified in the URI is not valid. Could not find a property named 'EmployeeID' on type 'Person'.
</code>```

答:
Apparently the where wrapps the IQueryable into a new IQueryable of the type of the variable it is stored in. The ElementType of the original IQueryable is lost.

You can see this when you break at the where and inspect result.ElementType. As soon as you step over the where it changes from Employee to Person.

With the following Code we restore the ElementType (feed it with result.ElementType from before the where):

```<code>public static IQueryable<T> ToTypedQueryable<T>(this IEnumerable<T> source, Type theType, bool exact = false) {
    if (source == null) throw new ArgumentNullException("source");

    System.Collections.IList result = (System.Collections.IList)typeof(List<>)
        .MakeGenericType(theType)
        .GetConstructor(Type.EmptyTypes)
        .Invoke(null);

    foreach (var s in source) {
        Type t = s.GetType();
        if (t == theType) {
            result.Add(s);
        } else if (!exact && t.IsSubclassOf(theType)) {
            result.Add(s);
        }
    }

    return (IQueryable<T>)(result.AsQueryable());
}
</code>```

Body:
I have a generic IQueryable of a concrete class:

IQueryable<Person> result = GetAllEmployees(); //returns IQueryable<Employee>

If I return result in a service-call for a Breeze-Entitytype, everything works fine:

breeze.EntityQuery.from("Employees").orderBy("EmployeeID");

As soon as I add a where-filter to the result in the service-call, the whole IQueryable-Object seems to be casted to the base class Person and not have a property EmployeeID anymore:

IQueryable<Person> result = GetAllEmployees(); //returns IQueryable<Employee>
result = result.Where(o => myHashSet.Contains(o.Id));

This causes the following Error:

Microsoft.Data.OData.ODataException: The query specified in the URI is not valid. Could not find a property named 'EmployeeID' on type 'Person'.

Body:
Apparently the where wrapps the IQueryable into a new IQueryable of the type of the variable it is stored in. The ElementType of the original IQueryable is lost.

You can see this when you break at the where and inspect result.ElementType. As soon as you step over the where it changes from Employee to Person.

With the following Code we restore the ElementType (feed it with result.ElementType from before the where):

public static IQueryable<T> ToTypedQueryable<T>(this IEnumerable<T> source, Type theType, bool exact = false) {
    if (source == null) throw new ArgumentNullException("source");

    System.Collections.IList result = (System.Collections.IList)typeof(List<>)
        .MakeGenericType(theType)
        .GetConstructor(Type.EmptyTypes)
        .Invoke(null);

    foreach (var s in source) {
        Type t = s.GetType();
        if (t == theType) {
            result.Add(s);
        } else if (!exact && t.IsSubclassOf(theType)) {
            result.Add(s);
        }
    }

    return (IQueryable<T>)(result.AsQueryable());
}


来源: stackexchange

问:
HTML5 type=range - showing label
Is there a way I can also set some label text for each steps in the HTML5 type=range control. Basically I have a range control <input type="range" step=1 min=0 max=4> and for each steps I want some label to be shown in the control. Is there a way to do this?

答:
FWIW the standard (HTML 5.1, HTML Living Standard),  specifies a label attribute for options when using a datalist. Sample code here.

This isn't implemented by any browser yet.

ContentLicense: CC BY-SA 3.0

Title: HTML5 type=range - showing label


问:
How to make overflow-y scroll without changing overflow-x to auto?
I know this is a duplicated question.

And below link is the answer the most nearest with my question that I've found.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

In this link, the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as
  their specified values, except that some combinations with ‘visible’
  are not possible: if one is specified as ‘visible’ and the other is
  ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed
  value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if
  ‘overflow-y’ is the same; otherwise it is the pair of computed values
  of ‘overflow-x’ and ‘overflow-y’.

What I want to know is, are there any new solution of this.

The problem of mine is in this fiddle.

I made 'sidebar' class of 'BootStrap' simple in a fiddle of mine.

```<code>overflow-x: visible;
//overflow-y: scroll;
</code>```

You can see that I commented out 'overflow-y: scroll' of class '.panel' in css part.

In this case, 'hover' will work but 'scroll' won't.

When if I clear that comment out, 'hover' won't work but 'scroll' will.

What I wanna see is, 'hover' and 'scroll' working together.

Does anyone have any ways or ideas to fix this?

Or are there still no way to solve this problem?

答: Your code is working you just can't see hover because of the width you set to that block is 50px also if you set position:absolute in hover you can see that hover effect but it overlap the child item. so one thing i want to know you want same width or you just set for a demo purpose.</p>

Body:
I know this is a duplicated question.

And below link is the answer the most nearest with my question that I've found.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

In this link, the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as
  their specified values, except that some combinations with ‘visible’
  are not possible: if one is specified as ‘visible’ and the other is
  ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed
  value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if
  ‘overflow-y’ is the same; otherwise it is the pair of computed values
  of ‘overflow-x’ and ‘overflow-y’.

What I want to know is, are there any new solution of this.

The problem of mine is in this fiddle.

I made 'sidebar' class of 'BootStrap' simple in a fiddle of mine.

overflow-x: visible;
//overflow-y: scroll;

You can see that I commented out 'overflow-y: scroll' of class '.panel' in css part.

In this case, 'hover' will work but 'scroll' won't.

When if I clear that comment out, 'hover' won't work but 'scroll' will.

What I wanna see is, 'hover' and 'scroll' working together.

Does anyone have any ways or ideas to fix this?

Or are there still no way to solve this problem?


问:
Webots robot doesn't speak while trying to use it with an external Kinect
I'm trying to create a Webots simulation where I want my robot to speak when the Kinect camera detects a person.

I have a Kinect V2 hooked up to the USB port and it can detect a person on its own by running my Python code using PyKinect2 and pygame.

As the next step, I put that code into the Webots environment and I've added a robot to speak to the user when Kinect detects them. However, when the Kinect starts running and the window pops up, Webots clock stops ticking and the robot doesn't do anything. After I close the Kinect window, the robot speaks the message but that code should have been executed inside the Kinect code, as listed below.

I believe this might be a synchronization issue due to Kinect and Webots having their own clocks, but I'm not sure. Even if that's the case, I don't know how to proceed. Any advice is welcome.

Here are the relevant parts of my code, I can provide the full code if needed. The Kinect body detection is a slightly modified version of this example:

```<code>class BodyGameRuntime(object):

    # ----- other functions here -----

    def run(self):
        # -------- Main Program Loop -----------
        while not self._done:

            # --- frame and window resize logic here

            # --- Draw skeletons to _frame_surface
            if self._bodies is not None:

                # ---------- Body Found ----------
                speaker.speak("User detected!", volume=1.0) # Speak to the user

                for i in range(0, self._kinect.max_body_count):
                    body = self._bodies.bodies[i]
                    if not body.is_tracked:
                        continue

                    joints = body.joints
                    # convert joint coordinates to color space
                    joint_points = self._kinect.body_joints_to_color_space(joints)
                    self.draw_body(joints, joint_points, SKELETON_COLORS[i])

            # --- copy back buffer logic here

            # --- Update the screen with what we've drawn.
            pygame.display.update()
            pygame.display.flip()

            # --- Limit to 30 frames per second
            self._clock.tick(30)

        # Close our Kinect sensor, close the window and quit.
        self._kinect.close()
        pygame.quit()

robot = Robot()
speaker = Speaker("Speaker")
#timestep = int(robot.getBasicTimeStep())

__main__ = "Kinect"
game = BodyGameRuntime()
game.run()
</code>```

答:
Webots needs that you call the robot.step(timeStep) function on a regular basis in order to progress on the simulation time, otherwise it will simply stop the simulation and wait until the next call to robot.step(timeStep). I would simply add a call to robot.step(timeStep) in your main loop, right before self._clock.tick(30) and uncomment the initialization of timeStep in your main program.

Note that if your Webots simulation is running in real time, calling robot.step(X) will last approximately X milliseconds. So you should probably set the WorldInfo.basicTimeStep to 30 milliseconds in your world file and get rid of the call to self._clock.tick(30).

Body:
I'm trying to create a Webots simulation where I want my robot to speak when the Kinect camera detects a person.

I have a Kinect V2 hooked up to the USB port and it can detect a person on its own by running my Python code using PyKinect2 and pygame.

As the next step, I put that code into the Webots environment and I've added a robot to speak to the user when Kinect detects them. However, when the Kinect starts running and the window pops up, Webots clock stops ticking and the robot doesn't do anything. After I close the Kinect window, the robot speaks the message but that code should have been executed inside the Kinect code, as listed below.

I believe this might be a synchronization issue due to Kinect and Webots having their own clocks, but I'm not sure. Even if that's the case, I don't know how to proceed. Any advice is welcome.

Here are the relevant parts of my code, I can provide the full code if needed. The Kinect body detection is a slightly modified version of this example:

class BodyGameRuntime(object):

    # ----- other functions here -----

    def run(self):
        # -------- Main Program Loop -----------
        while not self._done:

            # --- frame and window resize logic here

            # --- Draw skeletons to _frame_surface
            if self._bodies is not None:

                # ---------- Body Found ----------
                speaker.speak("User detected!", volume=1.0) # Speak to the user

                for i in range(0, self._kinect.max_body_count):
                    body = self._bodies.bodies[i]
                    if not body.is_tracked:
                        continue

                    joints = body.joints
                    # convert joint coordinates to color space
                    joint_points = self._kinect.body_joints_to_color_space(joints)
                    self.draw_body(joints, joint_points, SKELETON_COLORS[i])

            # --- copy back buffer logic here

            # --- Update the screen with what we've drawn.
            pygame.display.update()
            pygame.display.flip()

            # --- Limit to 30 frames per second
            self._clock.tick(30)

        # Close our Kinect sensor, close the window and quit.
        self._kinect.close()
        pygame.quit()

robot = Robot()
speaker = Speaker("Speaker")
#timestep = int(robot.getBasicTimeStep())

__main__ = "Kinect"
game = BodyGameRuntime()
game.run()


问:
How to continue code on next line (code too long)
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

```<code>CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"
</code>```

答:
You could also use DAO to make it a lot cleaner:

```<code>Dim rs As DAO.Recordset

Set rs = CurrentDb.OpenRecordset("Select Top 1 * From [AIP&BOP]")
rs.AddNew
    rs!PlanTitle.Value = RWPSheetvalues(10)
    rs!FileLocation.Value = RWPSheetvalues(11)
    ' etc.
rs.Update
rs.Close
</code>```

Body:
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"

Body:
You could also use DAO to make it a lot cleaner:

Dim rs As DAO.Recordset

Set rs = CurrentDb.OpenRecordset("Select Top 1 * From [AIP&BOP]")
rs.AddNew
    rs!PlanTitle.Value = RWPSheetvalues(10)
    rs!FileLocation.Value = RWPSheetvalues(11)
    ' etc.
rs.Update
rs.Close


问:
Session not restoring over page refresh - endlessly nested object
I am trying to use the redux-session library to store my apps state through page refreshes, however this is not working.

I have looked at the session object and it is getting the data, but populating quite slowly and endlessly nesting itself ie:

session: { myobject: {}, session: { myobject: {data:2}, session: { myobject: {data:2}, session: {...

By adding

```<code>   selectState (state) {
        return {
           user: state.toJS().session.myobject
       };
    }
</code>```

The session seems correct (session in local storage is {myobject: {data:2}}), however if the page is reloaded then the session does not seem to be recovered before it is overwritten. There does not seem to be a working example of the library or any questions online about it.

```<code>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import createHistory from 'history/createBrowserHistory';
import { createSession } from 'redux-session';
import 'sanitize.css/sanitize.css';

// Import root app
import App from 'containers/App';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-webpack-loader-syntax */
import '!file-loader?name=[name].[ext]!./images/favicon.ico';
import '!file-loader?name=[name].[ext]!./images/icon-72x72.png';
import '!file-loader?name=[name].[ext]!./images/icon-96x96.png';
import '!file-loader?name=[name].[ext]!./images/icon-120x120.png';
import '!file-loader?name=[name].[ext]!./images/icon-128x128.png';
import '!file-loader?name=[name].[ext]!./images/icon-144x144.png';
import '!file-loader?name=[name].[ext]!./images/icon-152x152.png';
import '!file-loader?name=[name].[ext]!./images/icon-167x167.png';
import '!file-loader?name=[name].[ext]!./images/icon-180x180.png';
import '!file-loader?name=[name].[ext]!./images/icon-192x192.png';
import '!file-loader?name=[name].[ext]!./images/icon-384x384.png';
import '!file-loader?name=[name].[ext]!./images/icon-512x512.png';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions
/* eslint-enable import/no-webpack-loader-syntax */

import configureStore from './configureStore';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});

// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
}, () => {
  document.body.classList.remove('fontLoaded');
});

// Create redux store with history
const initialState = {};
const history = createHistory();
const session = createSession({
    ns: 'dbwy1642b7c9e02q',
});

const store = configureStore(initialState, history, session);
const MOUNT_NODE = document.getElementById('app');

const render = (messages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
      </LanguageProvider>
    </Provider>,
    MOUNT_NODE
  );
};

if (module.hot) {
  // Hot reloadable React components and translation json files
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept(['./i18n', 'containers/App'], () => {
    ReactDOM.unmountComponentAtNode(MOUNT_NODE);
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
      import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
</code>```

configureStore.js:

```<code>/**
 * Create the store with dynamic reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import thunkMiddleware from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history, session) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
      session,
    sagaMiddleware,
    routerMiddleware(history),
      thunkMiddleware
  ];

  const enhancers = [
    applyMiddleware(...middlewares),
  ];

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        // TODO Try to remove when `react-router-redux` is out of beta, LOCATION_CHANGE should not be fired more than once after hot reloading
        // Prevent recomputing reducers for `replaceReducer`
        shouldHotReload: false,
      })
      : compose;
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.injectedReducers = {}; // Reducer registry
  store.injectedSagas = {}; // Saga registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      store.replaceReducer(createReducer(store.injectedReducers));
    });
  }

  return store;
}
</code>```

reducers.js

```<code>/**
 * Combine all reducers in this file and export the combined reducers.
 */

import { fromJS } from 'immutable';
import { combineReducers } from 'redux-immutable';
import { LOCATION_CHANGE } from 'react-router-redux';

import languageProviderReducer from 'containers/LanguageProvider/reducer';
import userReducer from 'containers/App/reducer';

/*
 * routeReducer
 *
 * The reducer merges route location changes into our immutable state.
 * The change is necessitated by moving to react-router-redux@5
 *
 */

// Initial routing state
const routeInitialState = fromJS({
  location: null,
});

/**
 * Merge route into the global application state
 */
function routeReducer(state = routeInitialState, action) {
  switch (action.type) {
    /* istanbul ignore next */
    case LOCATION_CHANGE:
      return state.merge({
        location: action.payload,
      });
    default:
      return state;
  }
}

/*Session reducer*/

function sessionReducer (state = {}, action) {
    switch (action.type) {
        case 'LOAD_STORED_STATE':
            return action.storedState;
        default:
            return state;
    }
}

/**
 * Creates the main reducer with the dynamically injected ones
 */
export default function createReducer(injectedReducers) {
  return combineReducers({
      route: routeReducer,
      session: sessionReducer,
      language: languageProviderReducer,
      user: userReducer,

    ...injectedReducers,
  });
}
</code>```

答:
no idea why state.toJS().myobject is {}

Fast code analysis shows that nothing had been restored from localStorage when redux store is created. At every code points initialState is always {}, so it's expected that store will have empty object.

Maybe following code should be refactored to check localStorage state and maybe load or merge with it. Also, there is no preloaded state from server side.

```<code>export default function configureStore(initialState = {}, history, session) {
  // [cut]
  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );
  // [cut]
  return store;
}
</code>```

Body:
I am trying to use the redux-session library to store my apps state through page refreshes, however this is not working.

I have looked at the session object and it is getting the data, but populating quite slowly and endlessly nesting itself ie:

session: { myobject: {}, session: { myobject: {data:2}, session: { myobject: {data:2}, session: {...

By adding

   selectState (state) {
        return {
           user: state.toJS().session.myobject
       };
    }

The session seems correct (session in local storage is {myobject: {data:2}}), however if the page is reloaded then the session does not seem to be recovered before it is overwritten. There does not seem to be a working example of the library or any questions online about it.

/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import createHistory from 'history/createBrowserHistory';
import { createSession } from 'redux-session';
import 'sanitize.css/sanitize.css';

// Import root app
import App from 'containers/App';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-webpack-loader-syntax */
import '!file-loader?name=[name].[ext]!./images/favicon.ico';
import '!file-loader?name=[name].[ext]!./images/icon-72x72.png';
import '!file-loader?name=[name].[ext]!./images/icon-96x96.png';
import '!file-loader?name=[name].[ext]!./images/icon-120x120.png';
import '!file-loader?name=[name].[ext]!./images/icon-128x128.png';
import '!file-loader?name=[name].[ext]!./images/icon-144x144.png';
import '!file-loader?name=[name].[ext]!./images/icon-152x152.png';
import '!file-loader?name=[name].[ext]!./images/icon-167x167.png';
import '!file-loader?name=[name].[ext]!./images/icon-180x180.png';
import '!file-loader?name=[name].[ext]!./images/icon-192x192.png';
import '!file-loader?name=[name].[ext]!./images/icon-384x384.png';
import '!file-loader?name=[name].[ext]!./images/icon-512x512.png';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions
/* eslint-enable import/no-webpack-loader-syntax */

import configureStore from './configureStore';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});

// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
}, () => {
  document.body.classList.remove('fontLoaded');
});

// Create redux store with history
const initialState = {};
const history = createHistory();
const session = createSession({
    ns: 'dbwy1642b7c9e02q',
});

const store = configureStore(initialState, history, session);
const MOUNT_NODE = document.getElementById('app');

const render = (messages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
      </LanguageProvider>
    </Provider>,
    MOUNT_NODE
  );
};

if (module.hot) {
  // Hot reloadable React components and translation json files
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept(['./i18n', 'containers/App'], () => {
    ReactDOM.unmountComponentAtNode(MOUNT_NODE);
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
      import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}

configureStore.js:

/**
 * Create the store with dynamic reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import thunkMiddleware from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history, session) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
      session,
    sagaMiddleware,
    routerMiddleware(history),
      thunkMiddleware
  ];

  const enhancers = [
    applyMiddleware(...middlewares),
  ];

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        // TODO Try to remove when `react-router-redux` is out of beta, LOCATION_CHANGE should not be fired more than once after hot reloading
        // Prevent recomputing reducers for `replaceReducer`
        shouldHotReload: false,
      })
      : compose;
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.injectedReducers = {}; // Reducer registry
  store.injectedSagas = {}; // Saga registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      store.replaceReducer(createReducer(store.injectedReducers));
    });
  }

  return store;
}

reducers.js

/**
 * Combine all reducers in this file and export the combined reducers.
 */

import { fromJS } from 'immutable';
import { combineReducers } from 'redux-immutable';
import { LOCATION_CHANGE } from 'react-router-redux';

import languageProviderReducer from 'containers/LanguageProvider/reducer';
import userReducer from 'containers/App/reducer';

/*
 * routeReducer
 *
 * The reducer merges route location changes into our immutable state.
 * The change is necessitated by moving to react-router-redux@5
 *
 */

// Initial routing state
const routeInitialState = fromJS({
  location: null,
});

/**
 * Merge route into the global application state
 */
function routeReducer(state = routeInitialState, action) {
  switch (action.type) {
    /* istanbul ignore next */
    case LOCATION_CHANGE:
      return state.merge({
        location: action.payload,
      });
    default:
      return state;
  }
}

/*Session reducer*/

function sessionReducer (state = {}, action) {
    switch (action.type) {
        case 'LOAD_STORED_STATE':
            return action.storedState;
        default:
            return state;
    }
}

/**
 * Creates the main reducer with the dynamically injected ones
 */
export default function createReducer(injectedReducers) {
  return combineReducers({
      route: routeReducer,
      session: sessionReducer,
      language: languageProviderReducer,
      user: userReducer,

    ...injectedReducers,
  });
}

Body:
no idea why state.toJS().myobject is {}

Fast code analysis shows that nothing had been restored from localStorage when redux store is created. At every code points initialState is always {}, so it's expected that store will have empty object.

Maybe following code should be refactored to check localStorage state and maybe load or merge with it. Also, there is no preloaded state from server side.

export default function configureStore(initialState = {}, history, session) {
  // [cut]
  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );
  // [cut]
  return store;
}


问:
How to set windowsoftinputmode programmatically from Fragments?
I have a requirement in which I have one MainActivity. From this activity I instantiate 4 fragments(Let us say FragmentA, FragmentB, FragmentC, FragmentD.

Out of these four Fragments; on 3 Fragments(Let us say FragmentA, FragmentB, FragmentC), I want to set MainActivity's windowsoftinputmode() to SOFT_INPUT_ADJUST_PAN so that window can resize.

And on one Fragment()let us say FragmentD), I want to set MainActivity's windowsoftinputmode() to SOFT_INPUT_ADJUST_NOTHING.

So what I do is, on each Fragment's onViewCreated() method I execute the following line of code with changing LayoutParams flag:

```<code>((MainActivity)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
</code>```

or

```<code>((MainActivity)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
</code>```

Problem is that it not working and I am not able to setSoftInputMode correctly and I can not prevent window getting resized.

Same lines of code works perfectly when I execute them in onCreate() of MainActivity as shown :

```<code>getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
</code>```

But than the value is set for all four fragments. My MainActivity declaration in manifest is :

```<code><activity
    android:name="com.test.MainActivity"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"/>
</code>```

Can somebody help what I am doing wrong in this. I want to have behaviour different for different Fragments.

答:
Adding implementation for iBEK's comment.
Two things are required to be done for windowsSoftInputMode to work properly :

First is add following flag :

```<code>windowSoftInputMode="adjustResize"
</code>```

in AndroidManifest.xml file as shown below :

```<code>    <activity
        android:name="com.test.TestActivity"
        android:windowSoftInputMode="adjustResize"/>
</code>```

Specifying this flag is madatory for windowsSoftInputMode to work.

Secondly add following in onCreate of your Activity, TestActivity in this case :

```<code>getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams. SOFT_INPUT_ADJUST_RESIZE);
</code>```

Now it should work for all fragments that activity is hosting.. I hope this answers your question @iBEK.

Body:
I have a requirement in which I have one MainActivity. From this activity I instantiate 4 fragments(Let us say FragmentA, FragmentB, FragmentC, FragmentD.

Out of these four Fragments; on 3 Fragments(Let us say FragmentA, FragmentB, FragmentC), I want to set MainActivity's windowsoftinputmode() to SOFT_INPUT_ADJUST_PAN so that window can resize.

And on one Fragment()let us say FragmentD), I want to set MainActivity's windowsoftinputmode() to SOFT_INPUT_ADJUST_NOTHING.

So what I do is, on each Fragment's onViewCreated() method I execute the following line of code with changing LayoutParams flag:

((MainActivity)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

or

((MainActivity)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

Problem is that it not working and I am not able to setSoftInputMode correctly and I can not prevent window getting resized.

Same lines of code works perfectly when I execute them in onCreate() of MainActivity as shown :

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

But than the value is set for all four fragments. My MainActivity declaration in manifest is :

<activity
    android:name="com.test.MainActivity"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"/>

Can somebody help what I am doing wrong in this. I want to have behaviour different for different Fragments.

Body:
Adding implementation for iBEK's comment.
Two things are required to be done for windowsSoftInputMode to work properly :

First is add following flag :

windowSoftInputMode="adjustResize"

in AndroidManifest.xml file as shown below :

    <activity
        android:name="com.test.TestActivity"
        android:windowSoftInputMode="adjustResize"/>

Specifying this flag is madatory for windowsSoftInputMode to work.

Secondly add following in onCreate of your Activity, TestActivity in this case :

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams. SOFT_INPUT_ADJUST_RESIZE);

Now it should work for all fragments that activity is hosting.. I hope this answers your question @iBEK.


问:
How to activate Windows 2012 R2 Terminal License with command line
I have Installed Remote Desktop Session Host and Remote Desktop Licensing  services on Windows 2012 R2 Server which is working in WORKGROUP.

I have Enterprise Agreement Number for "Per user Cal Licensing". Normally I can make this activation using Remote Desktop Licensing Manager. But, I want to make this  activation via command line such as powershell or cmd..

I need to fill some fields such as company name, email, name surname, Enterprise Agreement Number etc..

Is there any way to make this or it is impossible via command line ??

I found this command ;

```<code>gwmi -namespace "Root/CIMV2/TerminalServices" Win32_TerminalServiceSetting
</code>```

But, I could not found usage scenario for my case.

答:
First of all, you need to import the module </p>

```<code>Import-Module RemoteDesktopServices
</code>```

<p>Then you can use: </p>

```<code>Set-RDLicenseConfiguration -LicenseServer license_server_name -Mode PerUser -ConnectionBroker connection_broker_name
</code>```

Body:
I have Installed Remote Desktop Session Host and Remote Desktop Licensing  services on Windows 2012 R2 Server which is working in WORKGROUP.

I have Enterprise Agreement Number for "Per user Cal Licensing". Normally I can make this activation using Remote Desktop Licensing Manager. But, I want to make this  activation via command line such as powershell or cmd..

I need to fill some fields such as company name, email, name surname, Enterprise Agreement Number etc..

Is there any way to make this or it is impossible via command line ??

I found this command ;

gwmi -namespace "Root/CIMV2/TerminalServices" Win32_TerminalServiceSetting

But, I could not found usage scenario for my case.

Body:
First of all, you need to import the module

Import-Module RemoteDesktopServices

Then you can use:

Set-RDLicenseConfiguration -LicenseServer license_server_name -Mode PerUser -ConnectionBroker connection_broker_name


问:
Overlay video with custom graphics using Phonon & PyQt
I am building a eye-tracking data visualization tool using PyQt4 and Phonon module. Essentially, I have a video that a subject was watching while the subject's eye movements were tracked. The eye tracking data is in the form of x,y coordinates. I want to be able to play the video of interest and overlay that video with circles indicating where the subject was looking at.

Does anyone have any idea? According to this link: Play a video with custom overlay graphics
there seems to be a way by placing Phonon.VideoWidget inside a QGraphicsProxyWidget but I am unsure of a method to implement the suggestion.

Any help would be greatly appreciated!

I am also interested to know if there are ways to achieve my desired functionaility using pyqtgraph.

答:
As you comment an option is to use QGraphicsProxyWidget, you can create an object of that type or you can use addWidget:

```<code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.phonon import Phonon

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        lay = QVBoxLayout(self)
        vp = Phonon.VideoPlayer()
        media = Phonon.MediaSource('/path/of/video')
        vp.load(media)
        vp.play()
        scene = QGraphicsScene()
        self.view = QGraphicsView(scene, self)
        lay.addWidget(self.view)
        proxy = scene.addWidget(vp)
        # or
        # proxy = QGraphicsProxyWidget()
        # scene.addItem(proxy)
        self.item = scene.addEllipse(QRectF(0, 0, 20, 20), QPen(Qt.red), QBrush(Qt.green))
        self.item.setParentItem(proxy)

    def mousePressEvent(self, event):
        p = self.view.mapToScene(event.pos())
        # move item
        self.item.setPos(p-QPoint(20, 20))
        QWidget.mousePressEvent(self, event)

    def resizeEvent(self, event):
        if event.oldSize().isValid():
            print(self.view.scene().sceneRect())
            self.view.fitInView(self.view.scene().sceneRect(), Qt.KeepAspectRatio)
        QWidget.resizeEvent(self, event)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
</code>```

Output:

Body:
As you comment an option is to use QGraphicsProxyWidget, you can create an object of that type or you can use addWidget:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.phonon import Phonon

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        lay = QVBoxLayout(self)
        vp = Phonon.VideoPlayer()
        media = Phonon.MediaSource('/path/of/video')
        vp.load(media)
        vp.play()
        scene = QGraphicsScene()
        self.view = QGraphicsView(scene, self)
        lay.addWidget(self.view)
        proxy = scene.addWidget(vp)
        # or
        # proxy = QGraphicsProxyWidget()
        # scene.addItem(proxy)
        self.item = scene.addEllipse(QRectF(0, 0, 20, 20), QPen(Qt.red), QBrush(Qt.green))
        self.item.setParentItem(proxy)

    def mousePressEvent(self, event):
        p = self.view.mapToScene(event.pos())
        # move item
        self.item.setPos(p-QPoint(20, 20))
        QWidget.mousePressEvent(self, event)

    def resizeEvent(self, event):
        if event.oldSize().isValid():
            print(self.view.scene().sceneRect())
            self.view.fitInView(self.view.scene().sceneRect(), Qt.KeepAspectRatio)
        QWidget.resizeEvent(self, event)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Output:


问:
Do browsers have to "render" (for lack of a better term) divs that have the display:none property?
If I have, for instance:

```<code><div style="display:none">
    (The content of this div is a huge QuickTime movie.)
</div>
<div>
    (The content of this div is just lines of text.)
</div>
</code>```

Will the browser try to start downloading the QT movie in the first div?

I tried searching this site and Google before asking, so if it's been answered before and my Google-Fu is just off today, I sincerely apologize. It seems like a question that would have been asked, but I couldn't find it.

答:
Anything with a
 that is set to display:none is still technically and semantically there. Any content contained within the hidden
 will be loaded as if it were visible.

ContentLicense: CC BY-SA 2.5

Body:
If I have, for instance:

    (The content of this div is a huge QuickTime movie.)

    (The content of this div is just lines of text.)

Will the browser try to start downloading the QT movie in the first div?

I tried searching this site and Google before asking, so if it's been answered before and my Google-Fu is just off today, I sincerely apologize. It seems like a question that would have been asked, but I couldn't find it.

Body: Anything with a <div> that is set to display:none is still technically and semantically there. Any content contained within the hidden <div> will be loaded as if it were visible.


问:
Images not displaying properly from mysql database
i am trying to use mysql database and php to display a image in a table.  Every other information in my table is displaying fine except for image, i am receiving this.

����JFIF���    ( %!1!1)....383,7*-.7  +%&-----5---+--------5-----+-------------------5-/---����"����B!1A"Qa2

In my table and this goes on for awhile.  in my database i have images set to a blob and no null.  I am using this code to display it.

```<code> <?php
          include 'connect.php';
          $results = mysqli_query($con, 'select * from products');
          ?>
            <table cellpadding="3" cellspacing ="3" border="0">
                <tr>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Description</th>
                    <th>Price</th>
                    <th>Buy Product</th>
                </tr>
                <?php

                 while($products= mysqli_fetch_object($results)){
                     if($products->id<=10){?>
                <tr>
                    <td><?php echo $products->images;?></td>
                    <td><?php echo $products->name;?></td>
                    <td><?php echo $products->description;?></td>
                    <td><?php echo $products->price;?></td>
                    <td><a href="cart.php?id=<?php echo $products->id; ?
 >">Add to Cart</a></td>
                </tr>
                 <?php }} ?>
            </table>
</code>```

Any help would be appreciated.  Thank you.

答:
First I have to say that storing image data in the database can be a bad idea especially when you have a lot of images. A slightly better approach might be to store just the path to the file and link to it in your html code.

Anyway, you have a problem and there is a solution. At the moment you are just displaying the BLOB contents, which is the raw binary data of the image. To display an image, you need an  tag with the right source.

Something like this:

```<code><img src="data:image/jpeg;base64,<?= base64_encode($blob) ?>"/>;
</code>```

In your exact case it will look more like this:

```<code>...
<td>
   <!-- JPG image -->
   <img src="data:image/jpeg;base64,<?= base64_encode($products->images) ?>"/>;
</td>
...
</code>```

Body:
i am trying to use mysql database and php to display a image in a table.  Every other information in my table is displaying fine except for image, i am receiving this.

����JFIF���    ( %!1!1)....383,7*-.7  +%&-----5---+--------5-----+-------------------5-/---����"����B!1A"Qa2

In my table and this goes on for awhile.  in my database i have images set to a blob and no null.  I am using this code to display it.

 <?php
          include 'connect.php';
          $results = mysqli_query($con, 'select * from products');
          ?>

                    Image
                    Name
                    Description
                    Price
                    Buy Product

                <?php

                 while($products= mysqli_fetch_object($results)){
                     if($products->id<=10){?>

                    <?php echo $products->images;?>
                    <?php echo $products->name;?>
                    <?php echo $products->description;?>
                    <?php echo $products->price;?>
                    <a href="cart.php?id=<?php echo $products->id; ?
 >">Add to Cart

                 <?php }} ?>

Any help would be appreciated.  Thank you.

Body:
First I have to say that storing image data in the database can be a bad idea especially when you have a lot of images. A slightly better approach might be to store just the path to the file and link to it in your html code.

Anyway, you have a problem and there is a solution. At the moment you are just displaying the BLOB contents, which is the raw binary data of the image. To display an image, you need an <img> tag with the right source.

Something like this:

<img src="data:image/jpeg;base64,<?= base64_encode($blob) ?>"/>;

In your exact case it will look more like this:

...
<td>
   <!-- JPG image -->
   <img src="data:image/jpeg;base64,<?= base64_encode($products->images) ?>"/>;
</td>
...


问:
How to access files in VSTS Source Repo at the time of release definition?
I have some 10 files in the VSTS source code repo (Git) I want to access those files at the time of release definition. I have kept my PowerShell scripts in the VSTS source Repo and after the deployment, I need to run those script files.

So I have added power shell task after the deploy in the release definition but not sure how to access those script files and how can I run those? I can publish those script files from VSTS build definition and can use at the release definition time but I don't want to use in that way.

I want my release definition to run independently.

答:
You just need to add a Command Line task to get files from git repo. Detail steps as below:

Create alternate authentication credentials

In alternate authentication credentials page (https://account.visualstudio.com/_details/security/altcreds) ->  Enable alternate authentication credentials -> specify secondary username and password -> Save.

Add a Command Line task in release definition

Tool: git

Arguments: clone https://second:password@account.visualstudio.com/project/_git/reponame foldername (use secondary username and password for credential)

Now all the files of the git repo are located in $(System.DefaultWorkingDirectory)\foldername, and you can use the files from the directory.


问:
Radix sort not sorting "some" numbers?
I'm trying to implement Radix sort, from all i learnt is that it first compares the one's digit , places in the right order, the it goes for ten's so on and so fourth.

i tried to implement it but didn't got satisfactory results, what i'm doing wrong here?
Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>

struct heap {
    int data;
};

int main()
{
    int arr[18] = {545, 934, 829, 883, 842, 957, 241, 856, 878, 101, 555, 20, 964, 529, 156, 161, 566, 820};
    int i;

    struct heap *heaparr = malloc(sizeof(struct heap) * 18);

    for(i=0; i<18; i++) {
        heaparr[i].data = arr[i];
    }

    int k = 0, temp, div = 1;
    int ind = 0;

    while(div<=100 ){
        k=0;
        ind = 0;
        while(k<10) {
            for(i=0; i<18; i++) {
                if ((heaparr[i].data/div)% 10 == k) {
                    temp = heaparr[ind].data;
                    heaparr[ind].data = heaparr[i].data;
                    heaparr[i].data = temp;
                    ind++;
                }
            }
            k = k+1;
        }
        div = div*10;
    }

    printf("\n");
    free(heaparr);
    return 0;
}
</code>```

it is giving me result

```<code>20 101 156 161 241 545 555 566 529 842 856 820 829 878 883 957 934 964
</code>```

ans it should be.

```<code>20 101 156 161 241 529 545 555 566 820 829 842 856 878 883 934 964 957
</code>```

答:
@gsamaras beat me to it, but here's a much smaller minimal example.

```<code>Start with:
  52, 93, 84, 54, 24
</code>```

The entire pass in the 1s place leaves the values in the same places.
Now look at the swap operations when processing the 10s place:

```<code>10s, k=0
10s, k=1
10s, k=2
  24, 93, 84, 54, 52 //The first swap mis-orders the "50s"
   ^---------------^
10s, k=3
10s, k=4
10s, k=5
  24, 54, 84, 93, 52
       ^-------^
  24, 54, 52, 93, 84 //Hence they stay out-of-order when they're moved up
           ^-------^
10s, k=6
10s, k=7
10s, k=8
  24, 54, 52, 84, 93
               ^---^
10s, k=9
</code>```

Consider shifting the elements right to make space, rather than swapping, or do the processing of each decimal place out-of-place (i.e., alternating between two buffers).

Title: Radix sort not sorting "some" numbers?

Body:
I'm trying to implement Radix sort, from all i learnt is that it first compares the one's digit , places in the right order, the it goes for ten's so on and so fourth.

i tried to implement it but didn't got satisfactory results, what i'm doing wrong here?
Here is my code:

#include <stdio.h>
#include <stdlib.h>

struct heap {
    int data;
};

int main()
{
    int arr[18] = {545, 934, 829, 883, 842, 957, 241, 856, 878, 101, 555, 20, 964, 529, 156, 161, 566, 820};
    int i;

    struct heap *heaparr = malloc(sizeof(struct heap) * 18);

    for(i=0; i<18; i++) {
        heaparr[i].data = arr[i];
    }

    int k = 0, temp, div = 1;
    int ind = 0;

    while(div<=100 ){
        k=0;
        ind = 0;
        while(k<10) {
            for(i=0; i<18; i++) {
                if ((heaparr[i].data/div)% 10 == k) {
                    temp = heaparr[ind].data;
                    heaparr[ind].data = heaparr[i].data;
                    heaparr[i].data = temp;
                    ind++;
                }
            }
            k = k+1;
        }
        div = div*10;
    }

    printf("\n");
    free(heaparr);
    return 0;
}

it is giving me result

20 101 156 161 241 545 555 566 529 842 856 820 829 878 883 957 934 964

ans it should be.

20 101 156 161 241 529 545 555 566 820 829 842 856 878 883 934 964 957

Body:
@gsamaras beat me to it, but here's a much smaller minimal example.

Start with:
  52, 93, 84, 54, 24

The entire pass in the 1s place leaves the values in the same places.
Now look at the swap operations when processing the 10s place:

10s, k=0
10s, k=1
10s, k=2
  24, 93, 84, 54, 52 //The first swap mis-orders the "50s"
   ^---------------^
10s, k=3
10s, k=4
10s, k=5
  24, 54, 84, 93, 52
       ^-------^
  24, 54, 52, 93, 84 //Hence they stay out-of-order when they're moved up
           ^-------^
10s, k=6
10s, k=7
10s, k=8
  24, 54, 52, 84, 93
               ^---^
10s, k=9

Consider shifting the elements right to make space, rather than swapping, or do the processing of each decimal place out-of-place (i.e., alternating between two buffers).


问:
Animations not starting once in Phaser.js
I use phaser 2.6.1.

I have created an animation. This works fine but sometimes the animation is not starting. I don't know why.

In create() function, I add animations for my spritesheet:

```<code>this.car = game.add.sprite(game.world.centerX,500, 'car');
this.car.animations.add('mover',[0,1,2,3],1000, true);
this.car.fixedToCamera = true;
</code>```

When overlap, I start the function to animate this:

```<code>game.physics.arcade.overlap(this.car, this.borders, this.canMove, null, this);
</code>```

This is my function:

```<code>},canMove: function(car, objet){
    if(crash == 0){
        crash = 1;
        _this.car.animations.play("mover");
                console.log("fire")
        setTimeout(function(){
            _this.car.animations.stop();
            _this.car.frame = 0;
            crash = 0;
        },1000)
    }
}
</code>```

When the car overlaps a border, this function is triggered.

The console.log() is triggered but the animation suddenly is not starting. I can restart a lot of time my page and suddenly the animation is not starting even though the console.log() is triggered.

答:
The issue is because i have first initialized my car with :

```<code>this.car = game.add.sprite(game.world.centerX,500, 'car');
this.car.animations.add('mover',[0,1,2,3],1000, true);
this.car.fixedToCamera = true;
_this = this
</code>```

After in my function i call directly my car with _this

I used _this because inside setTimeout(), this property is no equal of this of document

I dont know why but if i initialize first with this and after i call with _this this is not working fine. Also for resolve my issue i have starting with _this directly.

```<code>_this = this;
_this.car = game.add.sprite(game.world.centerX,500, 'car');
_this.car.animations.add('mover',[0,1,2,3],1000, true);
_this.car.fixedToCamera = true;
</code>```

Body:
I use phaser 2.6.1.

I have created an animation. This works fine but sometimes the animation is not starting. I don't know why.

In create() function, I add animations for my spritesheet:

this.car = game.add.sprite(game.world.centerX,500, 'car');
this.car.animations.add('mover',[0,1,2,3],1000, true);
this.car.fixedToCamera = true;

When overlap, I start the function to animate this:

game.physics.arcade.overlap(this.car, this.borders, this.canMove, null, this);

This is my function:

},canMove: function(car, objet){
    if(crash == 0){
        crash = 1;
        _this.car.animations.play("mover");
                console.log("fire")
        setTimeout(function(){
            _this.car.animations.stop();
            _this.car.frame = 0;
            crash = 0;
        },1000)
    }
}

When the car overlaps a border, this function is triggered.

The console.log() is triggered but the animation suddenly is not starting. I can restart a lot of time my page and suddenly the animation is not starting even though the console.log() is triggered.

Body:
The issue is because i have first initialized my car with :

this.car = game.add.sprite(game.world.centerX,500, 'car');
this.car.animations.add('mover',[0,1,2,3],1000, true);
this.car.fixedToCamera = true;
_this = this

After in my function i call directly my car with _this

I used _this because inside setTimeout(), this property is no equal of this of document

I dont know why but if i initialize first with this and after i call with _this this is not working fine. Also for resolve my issue i have starting with _this directly.

_this = this;
_this.car = game.add.sprite(game.world.centerX,500, 'car');
_this.car.animations.add('mover',[0,1,2,3],1000, true);
_this.car.fixedToCamera = true;


问:
How to automatically authenticate windows integrate without login popup?
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

```<code><authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>
</code>```

答:
You can't do much from the server-side. However, your clients (if they are members of your orgnaization for instance) can add your site to their Local Intranet security zone in IE.

```<code>Tools - Internet Options - Security - Local Intranet - Sites
</code>```

Note this will probably only work for IE clients.

By default, IE automatically send current windows credentials to sites in the Local Intranet zone requesting for an authorization.

This way, they will not be prompted for their credentials each time they are accessing your site.

Body:
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

<authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>

Body:
You can't do much from the server-side. However, your clients (if they are members of your orgnaization for instance) can add your site to their Local Intranet security zone in IE.

Tools - Internet Options - Security - Local Intranet - Sites

Note this will probably only work for IE clients.

By default, IE automatically send current windows credentials to sites in the Local Intranet zone requesting for an authorization.

This way, they will not be prompted for their credentials each time they are accessing your site.


问:
Access iframe after it just was appended
My version that does not work:

```<code> $(window).on('load', function() {
      var $iframe = $("<iframe>",
                 {id:"up2europe",
                 marginheight:"5",
                 marginwidth:"5",
                 src:"https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
                 });

       $(".sidebar__right:first").append($iframe).on('load', function()
             alert(document.getElementbyId("#up2europe").documentElement.title);
       });
});
</code>```

So... I'm trying to access the title of the iframe...to check if it was loaded properly.

答:
There are more a couple of things wrong with your code:

You use $("...").append($iframe) which returns $("...") after the iframe is appended. That means that your load event is attached to $("...") rather than the iframe which is the logical thing to do in this case. To achieve that use $iframe.appendTo("..."), so that the return value of the method is $iframe.

You use getElementbyId inside the aforementioned load event listener which is basically the wrong way to write getElementById.

The argument you pass to alert inside the event listener isn't an effective way to get the title of the document of the iframe.

So, by correcting the above errors the code becomes:

```<code>$(window).on('load', function() {
  /* Create the iframe. */
  var $iframe = $("<iframe>", {
    id: "up2europe",
    marginheight: "5",
    marginwidth: "5",
    src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
  });

  /* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
  $iframe.appendTo(".sidebar__right:first").on('load', function() {
    /* 'this' refers to the iframe. */
    alert(this.contentDocument.title);
  });
</code>```

Note: In order to actually get the title of the document of the iframe both the content of the iframe and the parent window must be served by the same domain, otherwise your code will fail due to the Same-Origin Policy.

Snippet:

(Getting the document title fails due to the same-origin policy; read the error thrown.)

$(window).on('load', function() {
  /* Create the iframe. */
  var $iframe = $("", {
    id: "up2europe",
    marginheight: "5",
    marginwidth: "5",
    src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
  });

  /* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
  $iframe.appendTo(".sidebar__right:first").on('load', function() {
    /* 'this' refers to the iframe. */
    alert(this.contentDocument.title);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "sidebar__right"></div></code>```

Resource: You can read more about the Same-Origin Policy here.

If you only want to check whether the content of an iframe has loaded, you don't need to check its document's title, but rather simply attach a load event`:

```<code>$iframe.on("load", function () {
   // code to execute after it's loaded.
});
</code>```

Body:
My version that does not work:

 $(window).on('load', function() {
      var $iframe = $("",
                 {id:"up2europe",
                 marginheight:"5",
                 marginwidth:"5",
                 src:"https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
                 });

       $(".sidebar__right:first").append($iframe).on('load', function()
             alert(document.getElementbyId("#up2europe").documentElement.title);
       });
});

So... I'm trying to access the title of the iframe...to check if it was loaded properly.

Body:
There are more a couple of things wrong with your code:

You use $("...").append($iframe) which returns $("...") after the iframe is appended. That means that your load event is attached to $("...") rather than the iframe which is the logical thing to do in this case. To achieve that use $iframe.appendTo("..."), so that the return value of the method is $iframe.

You use getElementbyId inside the aforementioned load event listener which is basically the wrong way to write getElementById.

The argument you pass to alert inside the event listener isn't an effective way to get the title of the document of the iframe.

So, by correcting the above errors the code becomes:

$(window).on('load', function() {
  /* Create the iframe. */
  var $iframe = $("<iframe>", {
    id: "up2europe",
    marginheight: "5",
    marginwidth: "5",
    src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
  });

  /* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
  $iframe.appendTo(".sidebar__right:first").on('load', function() {
    /* 'this' refers to the iframe. */
    alert(this.contentDocument.title);
  });

Note: In order to actually get the title of the document of the iframe both the content of the iframe and the parent window must be served by the same domain, otherwise your code will fail due to the Same-Origin Policy.

Snippet:

(Getting the document title fails due to the same-origin policy; read the error thrown.)

$(window).on('load', function() {
  /* Create the iframe. */
  var $iframe = $("<iframe>", {
    id: "up2europe",
    marginheight: "5",
    marginwidth: "5",
    src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
  });

  /* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
  $iframe.appendTo(".sidebar__right:first").on('load', function() {
    /* 'this' refers to the iframe. */
    alert(this.contentDocument.title);
  });
});

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "sidebar__right"></div>

Resource: You can read more about the Same-Origin Policy here.

If you only want to check whether the content of an iframe has loaded, you don't need to check its document's title, but rather simply attach a load event`:

$iframe.on("load", function () {
   // code to execute after it's loaded.
});


问:
How to bind async method to a keystroke in Tkinter?
Consider the following example:

```<code>import asyncio
import tkinter as tk

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.create_widgets()
        self._configure_bindings() # I believe it is not possible
                                   # to do this if the method needs
                                   # to be async as well

    def create_widgets(self):
        pass

    def _configure_bindings(self):
        self.bind('<F5>', self.spam) # what's the proper way?
                                     # does this method need to be async as well?

    async def spam(self, event):
        await self.do_something()

    async def do_something():
        pass

async def run_tk(root):
    try:
        while True:
            root.update()
            await asyncio.sleep(.01)
    except tk.TclError as e:
        if "application has been destroyed" not in e.args[0]:
            raise

if __name__ == '__main__':
    app = App()
    asyncio.get_event_loop().run_until_complete(run_tk(app))
</code>```

What is the proper way to bind async method to a keystroke in tkinter?
I've tried something like:

```<code> self.bind('<F5>', self.spam)
 self.bind('<F5>', await self.spam)
 self.bind('<F5>', await self.spam())
 self.bind('<F5>', lambda event: await self.spam(event))
</code>```

...and a bunch of other combinations, but to no avail.

答:
tkinter itself is asynchronous thanks to event loop, the after method and the bindings.

However, if you trying to stick with asyncio it's also possible, but first let's consider what you tried.

Your first try is obviously a fail, because you trying to call spam as a generic function, when it's a coroutine. Your other tries are more correct than a first, but await coroutine or yield from coroutine can be used to start a coroutine from another coroutine only, so it fails again.

So the proper way of start that beast is a scheduling of its execution with a self-explanatory method ensure_future (or old async, which is just a deprecated alias).

Try this example:

```<code>import asyncio
import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self._configure_bindings()

    def _configure_bindings(self):
        self.bind('<F5>', lambda event: asyncio.ensure_future(self.spam(event)))

    async def spam(self, event):
        await self.do_something()
        await asyncio.sleep(2)
        print('%s executed!' % self.spam.__name__)

    async def do_something(self):
        print('%s executed!' % self.do_something.__name__)

async def run_tk(root):
    try:
        while True:
            root.update()
            await asyncio.sleep(.01)
    except tk.TclError as e:
        if "application has been destroyed" not in e.args[0]:
            raise

if __name__ == '__main__':
    app = App()
    asyncio.get_event_loop().run_until_complete(run_tk(app))
</code>```

Also, I think that it's worth to mention this question, since you use an update method.

Body:
Consider the following example:

import asyncio
import tkinter as tk

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.create_widgets()
        self._configure_bindings() # I believe it is not possible
                                   # to do this if the method needs
                                   # to be async as well

    def create_widgets(self):
        pass

    def _configure_bindings(self):
        self.bind('<F5>', self.spam) # what's the proper way?
                                     # does this method need to be async as well?

    async def spam(self, event):
        await self.do_something()

    async def do_something():
        pass

async def run_tk(root):
    try:
        while True:
            root.update()
            await asyncio.sleep(.01)
    except tk.TclError as e:
        if "application has been destroyed" not in e.args[0]:
            raise

if __name__ == '__main__':
    app = App()
    asyncio.get_event_loop().run_until_complete(run_tk(app))

What is the proper way to bind async method to a keystroke in tkinter?
I've tried something like:

 self.bind('<F5>', self.spam)
 self.bind('<F5>', await self.spam)
 self.bind('<F5>', await self.spam())
 self.bind('<F5>', lambda event: await self.spam(event))

...and a bunch of other combinations, but to no avail.

Body:
tkinter itself is asynchronous thanks to event loop, the after method and the bindings.

However, if you trying to stick with asyncio it's also possible, but first let's consider what you tried.

Your first try is obviously a fail, because you trying to call spam as a generic function, when it's a coroutine. Your other tries are more correct than a first, but await coroutine or yield from coroutine can be used to start a coroutine from another coroutine only, so it fails again.

So the proper way of start that beast is a scheduling of its execution with a self-explanatory method ensure_future (or old async, which is just a deprecated alias).

Try this example:

import asyncio
import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self._configure_bindings()

    def _configure_bindings(self):
        self.bind('<F5>', lambda event: asyncio.ensure_future(self.spam(event)))

    async def spam(self, event):
        await self.do_something()
        await asyncio.sleep(2)
        print('%s executed!' % self.spam.__name__)

    async def do_something(self):
        print('%s executed!' % self.do_something.__name__)

async def run_tk(root):
    try:
        while True:
            root.update()
            await asyncio.sleep(.01)
    except tk.TclError as e:
        if "application has been destroyed" not in e.args[0]:
            raise

if __name__ == '__main__':
    app = App()
    asyncio.get_event_loop().run_until_complete(run_tk(app))

Also, I think that it's worth to mention this question, since you use an update method.


问:
Best way to close the socket and streams
In eclipse in one of the classes SonarLint and sonarqube server saying socket is not closed, even I closed it.

FYR:

What is the best way to close the socket? Could anyone please guide me.

Note: I don't get this error if I don't have out = new ObjectOutputStream(...)  code in the same try block.

答:
Here is working code:</p>

```<code>    try (Socket socket=new Socket(ipAddress, port);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
           //this is how you can use socket & out
        out.write(null);
        socket.getInetAddress();
    }
</code>```

Body:
Here is working code:

    try (Socket socket=new Socket(ipAddress, port);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
           //this is how you can use socket & out
        out.write(null);
        socket.getInetAddress();
    }


答:
Storing images in database is generally considered a bad idea, you should try to store the image path instead.

If you really need to do it that way, you need to use the correct tags to display them :

```<code><td><img alt="" src="data:<?php echo $products->images;?>"></td>
</code>```

For example, but please reconsider.

Title: Images not displaying properly from mysql database

Body:
Storing images in database is generally considered a bad idea, you should try to store the image path instead.

If you really need to do it that way, you need to use the correct tags to display them :

<td><img alt="" src="data:<?php echo $products->images;?>"></td>

For example, but please reconsider.


问:
generating so files for ICU on AIX 7.1
I am trying to compile ICU 49.1.2 on AIX 7.1 with vaC++ 11.1.

By default ICU make files are configured to generate .a files instead of .so files.

There is an option to change the type of shared library extension inside /source/config/mh-aix-va file.

SO = a -> this can be changed to so to generate so files.

But when I change it to so, I get error as below. Any idea what else has to be done to generate .so files?

```<code>gmake[1]: Leaving directory `/export/home/cmbabu/xml/icu/source/common'
gmake[1]: Entering directory `/export/home/cmbabu/xml/icu/source/common'
gmake[1]: * No rule to make target `../lib/libicuuc.so', needed by `all-local'.  Stop.
gmake[1]: Leaving directory `/export/home/cmbabu/xml/icu/source/common'
gmake: *** [all-recursive] Error 2
</code>```

Thanks in advance.

答:
To get rid of the error and successfully generate so files, I did lot of trial and errors and finally came up with a solution to as described below.

I had to modify few existing rules and add few more rules in config/mh-aix-va file.

Changes are...

line# 17 and 18: uncomment line #18

```<code># If you readd this line, you must change the SO value
LDFLAGS += -brtl
</code>```

line # 80 and 81: change the line # 81

```<code># without the -brtl option, the library names use .a. AIX is funny that way.
SO= so
</code>```

line # 92 to 99:
comment all these lines

```<code>#%.a : %.so
#   ln -f $< $(SHARED_OBJECT_NO_VERSION)
#   $(AIX_PREDELETE) $(AR) $(ARFLAGS) $@ $(SHARED_OBJECT_NO_VERSION)
#   rm -f $(SHARED_OBJECT_NO_VERSION)
#$(LIBDIR)/%.a : %.so
#   ln -f $< $(SHARED_OBJECT_NO_VERSION)
#   $(AIX_PREDELETE) $(AR) $(ARFLAGS) $@ $(SHARED_OBJECT_NO_VERSION)
#   rm -f $(SHARED_OBJECT_NO_VERSION)
</code>```

Add below lines at line # 100:

```<code>$(LIBDIR)/%.so : %.so
    ln -f $< $@
$(LIBDIR)/%$(SO_TARGET_VERSION).so : %.so
    ln -s $< $@
$(LIBDIR)/%$(SO_TARGET_VERSION_MAJOR).so : %.so
    ln -s $< $@
</code>```

Title: generating so files for ICU on AIX 7.1

Body:
I am trying to compile ICU 49.1.2 on AIX 7.1 with vaC++ 11.1.

By default ICU make files are configured to generate .a files instead of .so files.

There is an option to change the type of shared library extension inside /source/config/mh-aix-va file.

SO = a -> this can be changed to so to generate so files.

But when I change it to so, I get error as below. Any idea what else has to be done to generate .so files?

gmake[1]: Leaving directory `/export/home/cmbabu/xml/icu/source/common'
gmake[1]: Entering directory `/export/home/cmbabu/xml/icu/source/common'
gmake[1]: * No rule to make target `../lib/libicuuc.so', needed by `all-local'.  Stop.
gmake[1]: Leaving directory `/export/home/cmbabu/xml/icu/source/common'
gmake: *** [all-recursive] Error 2

Thanks in advance.

Body:
To get rid of the error and successfully generate so files, I did lot of trial and errors and finally came up with a solution to as described below.

I had to modify few existing rules and add few more rules in config/mh-aix-va file.

Changes are...

line# 17 and 18: uncomment line #18

# If you readd this line, you must change the SO value
LDFLAGS += -brtl

line # 80 and 81: change the line # 81

# without the -brtl option, the library names use .a. AIX is funny that way.
SO= so

line # 92 to 99:
comment all these lines

#%.a : %.so
#   ln -f $< $(SHARED_OBJECT_NO_VERSION)
#   $(AIX_PREDELETE) $(AR) $(ARFLAGS) $@ $(SHARED_OBJECT_NO_VERSION)
#   rm -f $(SHARED_OBJECT_NO_VERSION)
#$(LIBDIR)/%.a : %.so
#   ln -f $< $(SHARED_OBJECT_NO_VERSION)
#   $(AIX_PREDELETE) $(AR) $(ARFLAGS) $@ $(SHARED_OBJECT_NO_VERSION)
#   rm -f $(SHARED_OBJECT_NO_VERSION)

Add below lines at line # 100:

$(LIBDIR)/%.so : %.so
    ln -f $< $@
$(LIBDIR)/%$(SO_TARGET_VERSION).so : %.so
    ln -s $< $@
$(LIBDIR)/%$(SO_TARGET_VERSION_MAJOR).so : %.so
    ln -s $< $@


问:
NopCommerce custom api methods are not showing in swaggerUi
I am working on nopCommerce webApi plugin, when I add new methods to api plugin.
For example I add GetTest() method to product api controller. It does not show in the list of methods which are shown in swaggerUI.

As you can see GetTest() method is not available in SwaggerUi List.

I have also added the web api route in the startup.cs.

Here is my api GetTest() method.

here is my SwaggerUi configuration in Startup.cs.

```<code>config.Filters.Add(new ServerErrorHandlerAttribute());

        config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        };

        config.Routes.MapHttpRoute(
            name: "GetTest",
            routeTemplate: "api/products/GetTest",
            defaults: new { controller = "Products", action = "GetTest" });

        // The default route templates for the Swagger docs and swagger-ui are "swagger/docs/{apiVersion}" and "swagger/ui/index#/{assetPath}" respectively.
        config
            .EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "RESTful API documentation");
                c.IncludeXmlComments(string.Format(@"{0}\Plugins\Nop.Plugin.Api\Nop.Plugin.Api.XML", AppDomain.CurrentDomain.BaseDirectory));
                // We need this filter to exclude some of the API endpoints from the documentation i.e /OAuth/Authorize endpoint
                c.DocumentFilter<ExcludeEnpointsDocumentFilter>();
                c.OperationFilter<RemovePrefixesOperationFilter>();
                c.OperationFilter<ChangeParameterTypeOperationFilter>();
            })
            .EnableSwaggerUi(c =>
            {
                var currentAssembly = Assembly.GetAssembly(this.GetType());
                var currentAssemblyName = currentAssembly.GetName().Name;

                c.InjectJavaScript(currentAssembly, string.Format("{0}.Scripts.swaggerPostPutTryItOutButtonsRemoval.js", currentAssemblyName));
            });

        app.UseWebApi(config);

        config.DependencyResolver = new AutofacWebApiDependencyResolver(EngineContext.Current.ContainerManager.Container);

        // Configure the asp.net webhooks.
        ConfigureWebhooks(config);
</code>```

Please guide me a little I am new to SwaggerUI.

答:
Try to add a response type like all the other HttpGet methods have

eg.

```<code>[ResponseType(typeof(MyTestResult))]
</code>```

I could not test this, but this seems to be the only difference to the existing methods.

Body:
I am working on nopCommerce webApi plugin, when I add new methods to api plugin.
For example I add GetTest() method to product api controller. It does not show in the list of methods which are shown in swaggerUI.

As you can see GetTest() method is not available in SwaggerUi List.

I have also added the web api route in the startup.cs.

Here is my api GetTest() method.

here is my SwaggerUi configuration in Startup.cs.

config.Filters.Add(new ServerErrorHandlerAttribute());

        config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        };

        config.Routes.MapHttpRoute(
            name: "GetTest",
            routeTemplate: "api/products/GetTest",
            defaults: new { controller = "Products", action = "GetTest" });

        // The default route templates for the Swagger docs and swagger-ui are "swagger/docs/{apiVersion}" and "swagger/ui/index#/{assetPath}" respectively.
        config
            .EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "RESTful API documentation");
                c.IncludeXmlComments(string.Format(@"{0}\Plugins\Nop.Plugin.Api\Nop.Plugin.Api.XML", AppDomain.CurrentDomain.BaseDirectory));
                // We need this filter to exclude some of the API endpoints from the documentation i.e /OAuth/Authorize endpoint
                c.DocumentFilter<ExcludeEnpointsDocumentFilter>();
                c.OperationFilter<RemovePrefixesOperationFilter>();
                c.OperationFilter<ChangeParameterTypeOperationFilter>();
            })
            .EnableSwaggerUi(c =>
            {
                var currentAssembly = Assembly.GetAssembly(this.GetType());
                var currentAssemblyName = currentAssembly.GetName().Name;

                c.InjectJavaScript(currentAssembly, string.Format("{0}.Scripts.swaggerPostPutTryItOutButtonsRemoval.js", currentAssemblyName));
            });

        app.UseWebApi(config);

        config.DependencyResolver = new AutofacWebApiDependencyResolver(EngineContext.Current.ContainerManager.Container);

        // Configure the asp.net webhooks.
        ConfigureWebhooks(config);

Please guide me a little I am new to SwaggerUI.

Body:
Try to add a response type like all the other HttpGet methods have

eg.

[ResponseType(typeof(MyTestResult))]

I could not test this, but this seems to be the only difference to the existing methods.


问:
From word vector to document vector [text2vec]
I'd like to use the GloVe word embedding implemented in text2vec to perform supervised regression/classification. I read the helpful tutorial on the text2vec homepage on how to generate the word vectors. However, I'm having trouble grasping how to proceed further, namely apply or transform these word vectors and attach them to each document in such a way that each document is represented by a vector (derived from its component words' vectors I assume), to be used as input in a classifier. I've run into some quick fixes online for short documents, but my documents are rather lengthy (movie subtitles) and there doesn't seem to be any guidance on how to proceed with such documents - or at least guidance matching my comprehension level; I have experience working with n-grams, dictionaries, and topic models, but word embeddings puzzle me. </p>

<p>Thank you! </p>

答:
If your goal is to classify documents - I doubt any doc2vec approach will beat bag-of-words/ngrams. If you still want to try - common simple strategy short documents (< 20 words) is to represent document as weighted sum/average of word vectors.

You can obtain it by something like:

```<code>common_terms = intersect(colnames(dtm), rownames(word_vectors) )
dtm_averaged =  normalize(dtm[, common_terms], "l1")
# you can re-weight dtm above with tf-idf instead of "l1" norm
sentence_vectors = dtm_averaged %*% word_vectors[common_terms, ]
</code>```

I'm not aware of any universal established methods to obtain good document vectors for long documents.

Body:
I'd like to use the GloVe word embedding implemented in text2vec to perform supervised regression/classification. I read the helpful tutorial on the text2vec homepage on how to generate the word vectors. However, I'm having trouble grasping how to proceed further, namely apply or transform these word vectors and attach them to each document in such a way that each document is represented by a vector (derived from its component words' vectors I assume), to be used as input in a classifier. I've run into some quick fixes online for short documents, but my documents are rather lengthy (movie subtitles) and there doesn't seem to be any guidance on how to proceed with such documents - or at least guidance matching my comprehension level; I have experience working with n-grams, dictionaries, and topic models, but word embeddings puzzle me.

Thank you!

Body:
If your goal is to classify documents - I doubt any doc2vec approach will beat bag-of-words/ngrams. If you still want to try - common simple strategy short documents (< 20 words) is to represent document as weighted sum/average of word vectors.

You can obtain it by something like:

common_terms = intersect(colnames(dtm), rownames(word_vectors) )
dtm_averaged =  normalize(dtm[, common_terms], "l1")
# you can re-weight dtm above with tf-idf instead of "l1" norm
sentence_vectors = dtm_averaged %*% word_vectors[common_terms, ]

I'm not aware of any universal established methods to obtain good document vectors for long documents.


问:
TFS 2017 Builds
We have migrated to TFS 2017 from TFS 2010.

While executing the builds, the builds are taking too long to get completed successfully.

Previously, in 2010, we use to use community build manager to execute the builds, in TFS 2017 do we have any such tools to queued up the builds to execute them all at once. Not just manually executing them one by one.

答:
There are many reasons for this problem, eg hardware, software, bandwidth, size of the project... Please refer to below article to check that, it's still available for vNext build (Task based build process): Optimizing Team Foundation Server Build Time

In case if you installed earlier version of Visual Studio 2017 on your build agent machine, then you may have this problem. There are issues tracked in developer community site :

VS 2017 Build very slow

Slow compile times compared with VS 2013

In this case, you can try the solutions/workarounds mentioned in the issues, alternatively you can also try to install VS 2015 for the building.

ContentLicense: CC BY-SA 4.0

Title: TFS 2017 Builds


问:
Take Unknown number of Inputs as String
Input has an unknown amount of lines of Strings of length 20 each. I am using BufferedReader to take inputs from the console. After the last input it's just waiting for the input. How can I terminate the process?

Example Input:

```<code>10100101111011111111
00000000000000000000
01011101110110101111
</code>```

Above 3 lines are given as input. But its not given there are going to be 3 line of input. That is unknown and my programme is just waiting for the next input after the last line, when it should be terminating.

There is no terminator specified in the problem.

答:
This should work:

```<code>String line;
while ((line = br.readLine()) != null) {
   // do your stuff...
}
</code>```

And once the Buffered Reader fins a null (End of the input) it will stop reading.

EDIT:

In the code above, br is the name for my BufferedReader, so in your case you should use change br to the name for your BufferedReader.

Basically the code above, does whatever you want it to do (the code you put inside the while loop) while the BufferedReader doesn't find a null value.

EDIT 2:
You didn't specify that the input was taken from Console.

```<code>String line;
while ((line = br.readLine()).length < 20) {
// do your stuff...
}
</code>```

The code will keep asking for input until you input a line with a length below 20, (Since each line has a length of 20).
Essentially you can press RETURN once you are done writting the inputs.
But the first code I wrote should be the proper solution for your scenario.

Title: Take Unknown number of Inputs as String

Body:
Input has an unknown amount of lines of Strings of length 20 each. I am using BufferedReader to take inputs from the console. After the last input it's just waiting for the input. How can I terminate the process?

Example Input:

10100101111011111111
00000000000000000000
01011101110110101111

Above 3 lines are given as input. But its not given there are going to be 3 line of input. That is unknown and my programme is just waiting for the next input after the last line, when it should be terminating.

There is no terminator specified in the problem.

Body:
This should work:

String line;
while ((line = br.readLine()) != null) {
   // do your stuff...
}

And once the Buffered Reader fins a null (End of the input) it will stop reading.

EDIT:

In the code above, br is the name for my BufferedReader, so in your case you should use change br to the name for your BufferedReader.

Basically the code above, does whatever you want it to do (the code you put inside the while loop) while the BufferedReader doesn't find a null value.

EDIT 2:
You didn't specify that the input was taken from Console.

String line;
while ((line = br.readLine()).length < 20) {
// do your stuff...
}

The code will keep asking for input until you input a line with a length below 20, (Since each line has a length of 20).
Essentially you can press RETURN once you are done writting the inputs.
But the first code I wrote should be the proper solution for your scenario.


问:
Laravel Join 2 tables , one data from first table and multiple row from second table

FirstTable

id   |   name   |

1   | student1 |

2   | student2 |

3   | student3 |

4   | student4 |

==============================

SecondTable

Id | stud_id | subject | mark

1  |  1     | maths   | 50

2  |  1     | english   | 45

3  |  2     | maths   | 20

4  |  3     | maths   | 40

How would i query  in laravel with the above table structure..
i need outpus as

```<code>{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}
</code>```

答:
I'm doing it in laravel eloquent way. In your Student model create relationship method. It is a student can have many  subject relationship

```<code>public function subject(){
return $this->hasMany('App\"the second table model name",'stud_id');
</code>```

}

then you in controller you can access it like

```<code>public function index(){
$student = Student::find("Student_id")->subject;
dd($student);
}
</code>```

please read the documentation for better understanding
https://laravel.com/docs/5.5/eloquent-relationships

Body:
FirstTable

id   |   name   |

1   | student1 |

2   | student2 |

3   | student3 |

4   | student4 |

==============================

SecondTable

Id | stud_id | subject | mark

1  |  1     | maths   | 50

2  |  1     | english   | 45

3  |  2     | maths   | 20

4  |  3     | maths   | 40

How would i query  in laravel with the above table structure..
i need outpus as

{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}

Body:
I'm doing it in laravel eloquent way. In your Student model create relationship method. It is a student can have many  subject relationship

public function subject(){
return $this->hasMany('App\"the second table model name",'stud_id');

}

then you in controller you can access it like

public function index(){
$student = Student::find("Student_id")->subject;
dd($student);
}

please read the documentation for better understanding
https://laravel.com/docs/5.5/eloquent-relationships


问:
Ruby on Rails graphics
Would like to know what is the best framework/library for rich server side graphics on Ruby on Rails.</p>

答: http://ruby-toolbox.com/categories/graphing.html lists the most popular</p>

Title: Ruby on Rails graphics