问:
CXF client works correctly in MyEclipse but gives errors in Tomcat
My CXF version is 2.6.16 and JDK's is 1.5 and Tomcat's is 5.0.

As the title says, the client can successfully invoke the service in the IDE but not in the web container. I think there could be some difference between the MyEclipse runtime environment and Tomcat's, but I don't know what it is.

I am using the JaxWsProxyFactoryBean prototype's create method to create a port prototype, however it throws an exception in Tomcat.

Here is the error stack info.

```<code>Caused by: java.lang.NullPointerException

    at org.apache.cxf.jaxb.Utils.getFieldXJTA(Utils.java:269)
    at org.apache.cxf.jaxb.JAXBContextInitializer.walkReferences(JAXBContextInitializer.java:357)
    at org.apache.cxf.jaxb.JAXBContextInitializer.addClass(JAXBContextInitializer.java:329)
    at org.apache.cxf.jaxb.JAXBContextInitializer.addType(JAXBContextInitializer.java:232)
    at org.apache.cxf.jaxb.JAXBContextInitializer.begin(JAXBContextInitializer.java:139)
    at org.apache.cxf.service.ServiceModelVisitor.visitOperation(ServiceModelVisitor.java:97)
    at org.apache.cxf.service.ServiceModelVisitor.walk(ServiceModelVisitor.java:74)
    at org.apache.cxf.jaxb.JAXBDataBinding.initialize(JAXBDataBinding.java:325)
    at org.apache.cxf.service.factory.AbstractServiceFactoryBean.initializeDataBindings(AbstractServiceFactoryBean.java:86)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.buildServiceFromClass(ReflectionServiceFactoryBean.java:490)
    at org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean.buildServiceFromClass(JaxWsServiceFactoryBean.java:697)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.initializeServiceModel(ReflectionServiceFactoryBean.java:550)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.create(ReflectionServiceFactoryBean.java:265)
    at org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean.create(JaxWsServiceFactoryBean.java:214)
    at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createEndpoint(AbstractWSDLBasedEndpointFactory.java:101)
    at org.apache.cxf.frontend.ClientFactoryBean.create(ClientFactoryBean.java:90)
    at org.apache.cxf.frontend.ClientProxyFactoryBean.create(ClientProxyFactoryBean.java:155)
    at org.apache.cxf.jaxws.JaxWsProxyFactoryBean.create(JaxWsProxyFactoryBean.java:156)
</code>```

答:
Finally,I resolved this problem by myself. Hoping this experience could help someone.

I read the source code of org.apache.cxf.jaxb.Utils.getFieldXJTA(Utils.java:269) where the error stack info writen on the first line.

```<code>XmlJavaTypeAdapters adapters = f.getDeclaringClass().getPackage().getAnnotation(XmlJavaTypeAdapters.class);
</code>```

As you can see, one of getDeclaringClass method or getPackage method must return null , so the exception could happen. But I don't know which one is the right one.So I edit the source code like this:

```<code>Class<?> clazz = f.getDeclaringClass();
Package pkg = clazz.getPackage();
XmlJavaTypeAdapters adapters = pkg.getAnnotation(XmlJavaTypeAdapters.class);
</code>```

And replace the class file in the jar file. Finally,I found that the getPackage method returned null.Then I continued to read the java source code about the getPackage method.

I found that it's hard to let the method return null, the only reason (only my thought) could be in the classloader.

In the IDE , my code was using Java defalut classloader,but in my Tomcat was using a classloader written by someone other. And the classloader's findClass method haven't invoken a definePackage method, so the getPackage method return null.Then I edit the classloader, the problem resolved.

Thanks for the people who helped me with the grammer issues and the people who answered me.

Body:
My CXF version is 2.6.16 and JDK's is 1.5 and Tomcat's is 5.0.

As the title says, the client can successfully invoke the service in the IDE but not in the web container. I think there could be some difference between the MyEclipse runtime environment and Tomcat's, but I don't know what it is.

I am using the JaxWsProxyFactoryBean prototype's create method to create a port prototype, however it throws an exception in Tomcat.

Here is the error stack info.

Caused by: java.lang.NullPointerException

    at org.apache.cxf.jaxb.Utils.getFieldXJTA(Utils.java:269)
    at org.apache.cxf.jaxb.JAXBContextInitializer.walkReferences(JAXBContextInitializer.java:357)
    at org.apache.cxf.jaxb.JAXBContextInitializer.addClass(JAXBContextInitializer.java:329)
    at org.apache.cxf.jaxb.JAXBContextInitializer.addType(JAXBContextInitializer.java:232)
    at org.apache.cxf.jaxb.JAXBContextInitializer.begin(JAXBContextInitializer.java:139)
    at org.apache.cxf.service.ServiceModelVisitor.visitOperation(ServiceModelVisitor.java:97)
    at org.apache.cxf.service.ServiceModelVisitor.walk(ServiceModelVisitor.java:74)
    at org.apache.cxf.jaxb.JAXBDataBinding.initialize(JAXBDataBinding.java:325)
    at org.apache.cxf.service.factory.AbstractServiceFactoryBean.initializeDataBindings(AbstractServiceFactoryBean.java:86)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.buildServiceFromClass(ReflectionServiceFactoryBean.java:490)
    at org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean.buildServiceFromClass(JaxWsServiceFactoryBean.java:697)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.initializeServiceModel(ReflectionServiceFactoryBean.java:550)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.create(ReflectionServiceFactoryBean.java:265)
    at org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean.create(JaxWsServiceFactoryBean.java:214)
    at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createEndpoint(AbstractWSDLBasedEndpointFactory.java:101)
    at org.apache.cxf.frontend.ClientFactoryBean.create(ClientFactoryBean.java:90)
    at org.apache.cxf.frontend.ClientProxyFactoryBean.create(ClientProxyFactoryBean.java:155)
    at org.apache.cxf.jaxws.JaxWsProxyFactoryBean.create(JaxWsProxyFactoryBean.java:156)

Body:
Finally,I resolved this problem by myself. Hoping this experience could help someone.

I read the source code of org.apache.cxf.jaxb.Utils.getFieldXJTA(Utils.java:269) where the error stack info writen on the first line.

XmlJavaTypeAdapters adapters = f.getDeclaringClass().getPackage().getAnnotation(XmlJavaTypeAdapters.class);

As you can see, one of getDeclaringClass method or getPackage method must return null , so the exception could happen. But I don't know which one is the right one.So I edit the source code like this:

Class<?> clazz = f.getDeclaringClass();
Package pkg = clazz.getPackage();
XmlJavaTypeAdapters adapters = pkg.getAnnotation(XmlJavaTypeAdapters.class);

And replace the class file in the jar file. Finally,I found that the getPackage method returned null.Then I continued to read the java source code about the getPackage method.

I found that it's hard to let the method return null, the only reason (only my thought) could be in the classloader.

In the IDE , my code was using Java defalut classloader,but in my Tomcat was using a classloader written by someone other. And the classloader's findClass method haven't invoken a definePackage method, so the getPackage method return null.Then I edit the classloader, the problem resolved.

Thanks for the people who helped me with the grammer issues and the people who answered me.


来源: stackexchange

问:
setting express js static files and including them in template files
I have set my static folder to public (in the root of my app folder) within the app.js.
But still the handlebars layout files when linking the css files, could not find the files within the public folder.</p>

```<code>// app.js code:
// init app
var app = express();

// view engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine','handlebars');
app.engine('handlebars',expressHandlebars({defaultLayout:'layout'}));

// middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());

// set static folder
app.set(express.static(path.join(__dirname,'public')));

handlebars layout file:
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
</code>```

答:
First of all you must use absolute path as mentioned by robertklep in comments.

Now the problem, you are using app.set thats the problem, you have to use .use method not .set.

Now about how you should structure your directory, I recommend assigning a directory path like '/public' for accessing public files. It can be done like this :

```<code>//app.use not .set
app.use('/public', express.static(path.join(__dirname,'public')));
//see the first argument in above line it assigns which directory path is used to access the public file through URL
</code>```

After this is done you can access the files you need like this :

```<code><link rel="stylesheet" type="text/css" href="/public/css/bootstrap.min.css"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have set my static folder to public (in the root of my app folder) within the app.js.
But still the handlebars layout files when linking the css files, could not find the files within the public folder.

// app.js code:
// init app
var app = express();

// view engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine','handlebars');
app.engine('handlebars',expressHandlebars({defaultLayout:'layout'}));

// middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());

// set static folder
app.set(express.static(path.join(__dirname,'public')));

handlebars layout file:
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>

Body:
First of all you must use absolute path as mentioned by robertklep in comments.

Now the problem, you are using app.set thats the problem, you have to use .use method not .set.

Now about how you should structure your directory, I recommend assigning a directory path like '/public' for accessing public files. It can be done like this :

//app.use not .set
app.use('/public', express.static(path.join(__dirname,'public')));
//see the first argument in above line it assigns which directory path is used to access the public file through URL

After this is done you can access the files you need like this :

<link rel="stylesheet" type="text/css" href="/public/css/bootstrap.min.css"/>


问:
Disable StreetView navigation to non connected photospheres
Since StreetVew has no levels (floors), I am facing huge problems on multilevel tours because the navigation jumps from floor to floor (the panos are actually really close to each other but on different floors, and are not directly connected). I guess that by disabling one of the two navigation methods will do the trick, I just can't find it in the API.
I am embedding photospheres through MAPS API with the following code:

```<code>google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
  google.maps.streetViewViewer = 'photosphere';
  var panorama = new google.maps.StreetViewPanorama(
    document.getElementById('pano'), {
      pano: 'PANOID',
      pov: {heading: 348.27, pitch: -1.62, zoom: 0.26},
      linksControl: true,
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL,
        position: google.maps.ControlPosition.RIGHT_TOP
      },
      scaleControl: false,
      overviewMapControl: false,
      panControl: false,
      visible: true,
      motionTracking: false,
      motionTrackingControl: false
  });
}
</code>```

What is the option to disable the right arrow from the screenshot (the one with a circle around the arrow) if it exists at all?

screenshot

答:
The option is called "clickToGo" and should be set to false.

I searched for it and couldn't find, so I decided to go through all the options and experiment, and bumped into it...

Body:
Since StreetVew has no levels (floors), I am facing huge problems on multilevel tours because the navigation jumps from floor to floor (the panos are actually really close to each other but on different floors, and are not directly connected). I guess that by disabling one of the two navigation methods will do the trick, I just can't find it in the API.
I am embedding photospheres through MAPS API with the following code:

google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
  google.maps.streetViewViewer = 'photosphere';
  var panorama = new google.maps.StreetViewPanorama(
    document.getElementById('pano'), {
      pano: 'PANOID',
      pov: {heading: 348.27, pitch: -1.62, zoom: 0.26},
      linksControl: true,
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL,
        position: google.maps.ControlPosition.RIGHT_TOP
      },
      scaleControl: false,
      overviewMapControl: false,
      panControl: false,
      visible: true,
      motionTracking: false,
      motionTrackingControl: false
  });
}

What is the option to disable the right arrow from the screenshot (the one with a circle around the arrow) if it exists at all?

screenshot


问:
How do I delete a line from the table in index page when I press the delete button without deleting it from the database
How do I delete a line from the table in index page when I press the delete button without deleting it from the database.
i'm using asp.net mvc5 with visual studio 2017 and sql server 2016.

```<code>// GET: Information/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Information information = db.Informations.Find(id);
        if (information == null)
        {
            return HttpNotFound();
        }
        return View(information);
    }

    // POST: Information/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Information information = db.Informations.Find(id);
        db.Informations.Remove(information);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
</code>```

}

this code delete the selected row from database. i want to delete it just from index page.
Please could anyone give me any hint.

答:
```<code> <script type="text/javascript">
        $(document).ready(function () {
      function deleteRow() {
                var par = $(this).parent().parent();
                par.remove();
            };
            $("#Tableid").on("click", "#btnid", deleteRow);
    });
    </script>
</code>```

Write This Code in Index Page

"#Tableid"= id of Your Table,

"#btnid" = id of Your Delete Button(Which is unique for all Delete Buttons of Table)

This Code Only remove column on a page level not from database,

if you reload page you get back all the data

if you have any queries please ask

Body:
How do I delete a line from the table in index page when I press the delete button without deleting it from the database.
i'm using asp.net mvc5 with visual studio 2017 and sql server 2016.

// GET: Information/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Information information = db.Informations.Find(id);
        if (information == null)
        {
            return HttpNotFound();
        }
        return View(information);
    }

    // POST: Information/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Information information = db.Informations.Find(id);
        db.Informations.Remove(information);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

this code delete the selected row from database. i want to delete it just from index page.
Please could anyone give me any hint.

Body:
 <script type="text/javascript">
        $(document).ready(function () {
      function deleteRow() {
                var par = $(this).parent().parent();
                par.remove();
            };
            $("#Tableid").on("click", "#btnid", deleteRow);
    });
    </script>

Write This Code in Index Page

"#Tableid"= id of Your Table,

"#btnid" = id of Your Delete Button(Which is unique for all Delete Buttons of Table)

This Code Only remove column on a page level not from database,

if you reload page you get back all the data

if you have any queries please ask


问:
Select all categories with COUNT of sub-categories
I need to select all categories with count of its sub-categories.

Assume here are my tables:

categories

```<code>id | title
----------
1  | colors
2  | animals
3  | plants
</code>```

sub_categories

```<code>id | category_id | title | confirmed
------------------------------------
1        1          red       1
2        1          blue      1
3        1          pink      1
4        2          cat       1
5        2          tiger     0
6        2          lion      0
</code>```

What I want is :

```<code>id |  title  | count
------------------
1    colors     3
2    animals    1
3    plants     0
</code>```

What I have tried so far:

```<code>SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id
WHERE c.confirmed = 't' AND s.confirmed='t'
GROUP BY c.id, c.title
ORDER BY count DESC
</code>```

The only problem with this query is that this query does not show categories with 0 sub categories!

You also can check that on SqlFiddle

Any help would be great appreciated.

答:
I think you can try this too (it evidence what column(s) you are really grouping by):</p>

```<code>SELECT c.id, c.title, RC
from categories c
LEFT JOIN (SELECT category_id, COUNT(*) AS RC
           FROM sub_categories
           WHERE confirmed= 't'
           GROUP BY category_id) s on c.id = s.category_id
WHERE c.confirmed = 't'
ORDER BY RC DESC
</code>```

Body:
I need to select all categories with count of its sub-categories.

Assume here are my tables:

categories

id | title
----------
1  | colors
2  | animals
3  | plants

sub_categories

id | category_id | title | confirmed
------------------------------------
1        1          red       1
2        1          blue      1
3        1          pink      1
4        2          cat       1
5        2          tiger     0
6        2          lion      0

What I want is :

id |  title  | count
------------------
1    colors     3
2    animals    1
3    plants     0

What I have tried so far:

SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id
WHERE c.confirmed = 't' AND s.confirmed='t'
GROUP BY c.id, c.title
ORDER BY count DESC

The only problem with this query is that this query does not show categories with 0 sub categories!

You also can check that on SqlFiddle

Any help would be great appreciated.

Body:
I think you can try this too (it evidence what column(s) you are really grouping by):

SELECT c.id, c.title, RC
from categories c
LEFT JOIN (SELECT category_id, COUNT(*) AS RC
           FROM sub_categories
           WHERE confirmed= 't'
           GROUP BY category_id) s on c.id = s.category_id
WHERE c.confirmed = 't'
ORDER BY RC DESC


问:
When I start my app with PM2 + Docker, just run and exit
I try to follow this tutorial, but when I execute my app nothing happens

My Dockerfile (CHANGED)

```<code>FROM keymetrics/pm2-docker-alpine:7

WORKDIR /api

RUN npm install pm2 -g

ADD . .

CMD ["pm2-docker", "ecosystem.config.js"]
</code>```

And my ecosystem.config.js..

```<code>const maxMemory = process.env.WEB_MEMORY || 80;
const nodeEnv = process.env.NODE_ENV || 'development';

module.exports = {
  apps: [
    {
      name: 'api',
      script: 'api/index.js',
      node_args: [
        '--optimize_for_size', '--max_old_space_size=400', '--gc_interval=100',
      ],
      instances: process.env.WEB_CONCURRENCY || -1,
      exec_mode: 'cluster',
      max_memory_restart: `${maxMemory}M`,
      env: {
        PORT: process.env.PORT || 3000,
        NODE_ENV: nodeEnv,
      },
    },
  ],
};
</code>```

After run the docker ..

```<code>docker run -d -p 3000:3000 --name api api:latest
</code>```

Nothing happens.. follow the result of docker ps -a

```<code>CONTAINER ID        IMAGE                                                           COMMAND                  CREATED             STATUS                      PORTS                      NAMES
167cb2769438        api:latest   "pm2-docker start ..."   50 seconds ago      Exited (1) 47 seconds ago
</code>```

ADDED

If I run without -d option ..

```<code>> docker run -it -p 3000:3000 --name api api:latest
module.js:472
    throw err;
    ^

Error: Cannot find module 'commander'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/local/lib/node_modules/pm2/lib/CLI/RuntimeCLI.js:4:17)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
[vagrant@localhost]$
</code>```

答: Remove the RUN npm install pm2 -g, because PM2 is already bundled into pm2-docker-alpine

Body:
I try to follow this tutorial, but when I execute my app nothing happens

My Dockerfile (CHANGED)

FROM keymetrics/pm2-docker-alpine:7

WORKDIR /api

RUN npm install pm2 -g

ADD . .

CMD ["pm2-docker", "ecosystem.config.js"]

And my ecosystem.config.js..

const maxMemory = process.env.WEB_MEMORY || 80;
const nodeEnv = process.env.NODE_ENV || 'development';

module.exports = {
  apps: [
    {
      name: 'api',
      script: 'api/index.js',
      node_args: [
        '--optimize_for_size', '--max_old_space_size=400', '--gc_interval=100',
      ],
      instances: process.env.WEB_CONCURRENCY || -1,
      exec_mode: 'cluster',
      max_memory_restart: `${maxMemory}M`,
      env: {
        PORT: process.env.PORT || 3000,
        NODE_ENV: nodeEnv,
      },
    },
  ],
};

After run the docker ..

docker run -d -p 3000:3000 --name api api:latest

Nothing happens.. follow the result of docker ps -a

CONTAINER ID        IMAGE                                                           COMMAND                  CREATED             STATUS                      PORTS                      NAMES
167cb2769438        api:latest   "pm2-docker start ..."   50 seconds ago      Exited (1) 47 seconds ago

ADDED

If I run without -d option ..

> docker run -it -p 3000:3000 --name api api:latest
module.js:472
    throw err;
    ^

Error: Cannot find module 'commander'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/local/lib/node_modules/pm2/lib/CLI/RuntimeCLI.js:4:17)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
[vagrant@localhost]$


问:
Ask Users to Input the Date using the YYYY-MM-DD format
Good day!

I am new to programming and I am a little confused how to ask users to input the date in a web page

I have the form below to ask for dates:

My code is as follows:

```<code>   <form action="<?php print $_SERVER['PHP_SELF']; ?>" method="POST">
        <input name="event_startDate" type="text" id="event_startDate" size="17">
        <input name="event_endDate" type="text" id="event_endDate" size="17">
        <input name="SUBMIT" type="submit" id="submit" value="ADD EVENT">
    </form>
</code>```

The format of Mysql is YYYY-MM-DD so I've decided to use it. Now I need to ask the users to input using the YYYY-MM-DD format.

I can just insert the YYYY-MM-DD in the text box but I want the start date to be the date today so instead  I plan to this:

My problem is.... I don't know how. How can i insert the date in the textbox with that format using PHP? Can i add a value? But if i add the value, will it change also when the user decided to change the value and press the submit button? Also, how can I do it wherein the hypen (-) is not needed to be edited... I mean it will stay as is and the user just need to input the numbers       -  -  .

Your help would be highly appreciated. Thank you.

答:
You have to use input type as a date format:</p>

```<code><input type="date" name="event_startDate">
</code>```

Body:
Good day!

I am new to programming and I am a little confused how to ask users to input the date in a web page

I have the form below to ask for dates:

My code is as follows:

   <form action="<?php print $_SERVER['PHP_SELF']; ?>" method="POST">
        <input name="event_startDate" type="text" id="event_startDate" size="17">
        <input name="event_endDate" type="text" id="event_endDate" size="17">
        <input name="SUBMIT" type="submit" id="submit" value="ADD EVENT">
    </form>

The format of Mysql is YYYY-MM-DD so I've decided to use it. Now I need to ask the users to input using the YYYY-MM-DD format.

I can just insert the YYYY-MM-DD in the text box but I want the start date to be the date today so instead  I plan to this:

My problem is.... I don't know how. How can i insert the date in the textbox with that format using PHP? Can i add a value? But if i add the value, will it change also when the user decided to change the value and press the submit button? Also, how can I do it wherein the hypen (-) is not needed to be edited... I mean it will stay as is and the user just need to input the numbers       -  -  .

Your help would be highly appreciated. Thank you.

Body:
You have to use input type as a date format:

<input type="date" name="event_startDate">


问:
Most efficient way to check if any element in a JSON array contains a specific id?
I am using Node v8.1.3

I have a JSON array as following:

```<code>[
  {
    "id":99,
    "name": "ABC"
  },
  {
    "id": 187,
    "name": "AXZ"
  }
]
</code>```

This array has around 213000 e=objects in it.

Also, the ids in the objects are not in any order or pattern.

Now, I want to find if a particular id matches any ID in the array? what  is the fastest wait to do it?

I tried

```<code>isIdValid(id) {
    console.log(id)
    return this.list.filter((elem) => {
        return elem.id == id
    }).length > 0;
}
</code>```

But this is taking over 4 seconds.

答:
One option is to first sort the whole list (or insert it into a binary search tree) which takes some time but is only done once. and from there you can use binary search for the ID which is way faster.

here is a sample bst code for node:
js-bst

also here is a package that can be used to query json data list very faster: Defiant

Edit

actually creating a hash table is a faster solution than a bst; here is a sample code that does the job:

```<code>data = [
    {
        "id":99,
        "name": "ABC"
    },
    {
        "id": 187,
        "name": "AXZ"
    }
]

var hashCache = {};
data.forEach(function(item){
    hashCache[item.id] = item.name
});

// Usage:
var id = '99';
var record = hashCache[id];
if (record) {
    alert(record);
} else {
    console.log('no match found');
}
</code>```

you should also consider that this hash table only works if the IDs are unique. otherwise, you need to store a list of names in the hash table for each ID.

Body:
I am using Node v8.1.3

I have a JSON array as following:

[
  {
    "id":99,
    "name": "ABC"
  },
  {
    "id": 187,
    "name": "AXZ"
  }
]

This array has around 213000 e=objects in it.

Also, the ids in the objects are not in any order or pattern.

Now, I want to find if a particular id matches any ID in the array? what  is the fastest wait to do it?

I tried

isIdValid(id) {
    console.log(id)
    return this.list.filter((elem) => {
        return elem.id == id
    }).length > 0;
}

But this is taking over 4 seconds.

Body:
One option is to first sort the whole list (or insert it into a binary search tree) which takes some time but is only done once. and from there you can use binary search for the ID which is way faster.

here is a sample bst code for node:
js-bst

also here is a package that can be used to query json data list very faster: Defiant

Edit

actually creating a hash table is a faster solution than a bst; here is a sample code that does the job:

data = [
    {
        "id":99,
        "name": "ABC"
    },
    {
        "id": 187,
        "name": "AXZ"
    }
]

var hashCache = {};
data.forEach(function(item){
    hashCache[item.id] = item.name
});

// Usage:
var id = '99';
var record = hashCache[id];
if (record) {
    alert(record);
} else {
    console.log('no match found');
}

you should also consider that this hash table only works if the IDs are unique. otherwise, you need to store a list of names in the hash table for each ID.


问:
Rails 3 render problems
I am writing a script that allows for a user to pass a format via a URL parameter. I have JSON and XML working as needed, but I can't get YAML working.

```<code>case params[:format]
        when "xml" then respond_with(@labels)
        when "json" then respond_with(@labels_hash.to_json)
        when "yaml" then render :text => @labels_hash.to_yaml
      end
</code>```

For some reason when I pass the format=yaml in my URL then my script tries to force download a file. Any reason why this would happen?

Working Code:

```<code>case params[:format]
        when "xml" then respond_with(@labels)
        when "json" then respond_with(@labels_hash.to_json)
        when "yaml" then respond_with(@labels_hash) do |format|
          format.yaml { render :text => @labels_hash.to_s }
        end
      end
</code>```

答:
Try:

Adding :yaml to respond_to :yaml in the controller, and :

```<code>respond_to do |format|
  ....other formats....
  format.yaml { render :yaml => @labels_hash }
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Rails 3 render problems

Body:
I am writing a script that allows for a user to pass a format via a URL parameter. I have JSON and XML working as needed, but I can't get YAML working.

case params[:format]
        when "xml" then respond_with(@labels)
        when "json" then respond_with(@labels_hash.to_json)
        when "yaml" then render :text => @labels_hash.to_yaml
      end

For some reason when I pass the format=yaml in my URL then my script tries to force download a file. Any reason why this would happen?

Working Code:

case params[:format]
        when "xml" then respond_with(@labels)
        when "json" then respond_with(@labels_hash.to_json)
        when "yaml" then respond_with(@labels_hash) do |format|
          format.yaml { render :text => @labels_hash.to_s }
        end
      end

Body:
Try:

Adding :yaml to respond_to :yaml in the controller, and :

respond_to do |format|
  ....other formats....
  format.yaml { render :yaml => @labels_hash }
end


问:
Pandas Columns Operations with List
I have a pandas dataframe with two columns, the first one with just a single date ('action_date') and the second one with a list of dates ('verification_date'). I am trying to calculate the time difference between the date in 'action_date' and each of the dates in the list in the corresponding 'verification_date' column, and then fill the df new columns with the number of dates in verification_date that have a difference of either over or under 360 days.

Here is my code:

```<code>df = pd.DataFrame()
df['action_date'] = ['2017-01-01', '2017-01-01', '2017-01-03']
df['action_date'] = pd.to_datetime(df['action_date'], format="%Y-%m-%d")
df['verification_date'] = ['2016-01-01', '2015-01-08', '2017-01-01']
df['verification_date'] = pd.to_datetime(df['verification_date'], format="%Y-%m-%d")
df['user_name'] = ['abc', 'wdt', 'sdf']
df.index = df.action_date
df = df.groupby(pd.TimeGrouper(freq='2D'))['verification_date'].apply(list).reset_index()

def make_columns(df):
    df = df
    for i in range(len(df)):
        over_360 = []
        under_360 = []
        for w in [(df['action_date'][i]-x).days for x in df['verification_date'][i]]:
            if w > 360:
                over_360.append(w)
            else:
                under_360.append(w)
        df['over_360'] = len(over_360)
        df['under_360'] = len(under_360)
return df

make_columns(df)
</code>```

This kinda works EXCEPT the df has the same values for each row, which is not true as the dates are different. For example, in the first row of the dataframe, there IS a difference of over 360 days between the action_date and both of the items in the list in the verification_date column, so the over_360 column should be populated with 2. However, it is empty and instead the under_360 column is populated with 1, which is accurate only for the second row in 'action_date'.

I have a feeling I'm just messing up the looping but am really stuck. Thanks for all help!

答:
Your problem was that you were always updating the whole column with the value of the last calculation with these lines:

```<code>df['over_360'] = len(over_360)
df['under_360'] = len(under_360)
</code>```

what you want to do instead is set the value for each line calculation accordingly, you can do this by replacing the above lines with these:

```<code>df.set_value(i,'over_360',len(over_360))
df.set_value(i,'under_360',len(under_360))
</code>```

what it does is, it sets a value in line i and column over_360 or under_360.

you can learn more about it here.

If you don't like using set_values you can also use this:

```<code>df.ix[i,'over_360'] = len(over_360)
df.ix[i,'under_360'] = len(under_360)
</code>```

you can check dataframe.ix here.

Title: Pandas Columns Operations with List

Body:
I have a pandas dataframe with two columns, the first one with just a single date ('action_date') and the second one with a list of dates ('verification_date'). I am trying to calculate the time difference between the date in 'action_date' and each of the dates in the list in the corresponding 'verification_date' column, and then fill the df new columns with the number of dates in verification_date that have a difference of either over or under 360 days.

Here is my code:

df = pd.DataFrame()
df['action_date'] = ['2017-01-01', '2017-01-01', '2017-01-03']
df['action_date'] = pd.to_datetime(df['action_date'], format="%Y-%m-%d")
df['verification_date'] = ['2016-01-01', '2015-01-08', '2017-01-01']
df['verification_date'] = pd.to_datetime(df['verification_date'], format="%Y-%m-%d")
df['user_name'] = ['abc', 'wdt', 'sdf']
df.index = df.action_date
df = df.groupby(pd.TimeGrouper(freq='2D'))['verification_date'].apply(list).reset_index()

def make_columns(df):
    df = df
    for i in range(len(df)):
        over_360 = []
        under_360 = []
        for w in [(df['action_date'][i]-x).days for x in df['verification_date'][i]]:
            if w > 360:
                over_360.append(w)
            else:
                under_360.append(w)
        df['over_360'] = len(over_360)
        df['under_360'] = len(under_360)
return df

make_columns(df)

This kinda works EXCEPT the df has the same values for each row, which is not true as the dates are different. For example, in the first row of the dataframe, there IS a difference of over 360 days between the action_date and both of the items in the list in the verification_date column, so the over_360 column should be populated with 2. However, it is empty and instead the under_360 column is populated with 1, which is accurate only for the second row in 'action_date'.

I have a feeling I'm just messing up the looping but am really stuck. Thanks for all help!

Body:
Your problem was that you were always updating the whole column with the value of the last calculation with these lines:

df['over_360'] = len(over_360)
df['under_360'] = len(under_360)

what you want to do instead is set the value for each line calculation accordingly, you can do this by replacing the above lines with these:

df.set_value(i,'over_360',len(over_360))
df.set_value(i,'under_360',len(under_360))

what it does is, it sets a value in line i and column over_360 or under_360.

you can learn more about it here.

If you don't like using set_values you can also use this:

df.ix[i,'over_360'] = len(over_360)
df.ix[i,'under_360'] = len(under_360)

you can check dataframe.ix here.


问:
Should multiple array/hash lookups be stored in a variable
I've been using Reek lately to refactor my code and one of the smells, DuplicateMethodCall, is being called on array and hash lookups, such as array[1] or hash[:key] when called multiple times.

So I was wondering if multiple array or hash lookups are so expensive, that we should be storing them in a variable rather than calling them directly, which is what everyone does from my experience.

I would not hesitate to store multiple object method calls (especially if it's a DB call) in a variable, but doing that for array and hash lookups feel like an overkill.

For example, I'll get a warning for this piece of code:

```<code>  def sort_params
    return [] if params[:reference_letter_section].nil?

    params[:reference_letter_section].map.with_index(1) do |id, index|
      { id: id, position: index }
    end
  end
</code>```

but I feel like storing params[:reference_letter_section] in its own variable is too much

答:
So I was wondering if multiple array or hash lookups are so expensive

Expensive calls are not the only reason for not doing the call multiple times. It also clutters the code without real need. Consider this not-so-contrived example:

```<code>Order.new(
  name:       params[:order][:name],
  total:      params[:order][:total],
  line_items: [
    {
      product_name: params[:order][:line_item][:product],
      price:        params[:order][:line_item][:price],
    }
  ]
)
</code>```

Even though those hash accesses are super-cheap, it still makes sense to extract them, for readability reasons.

```<code>order_params     = params[:order]
line_item_params = order_params[:line_item]

Order.new(
  name:       order_params[:name],
  total:      order_params[:total],
  line_items: [
    {
      product_name: line_item_params[:product],
      price:        line_item_params[:price],
    }
  ]
)
</code>```

Body:
I've been using Reek lately to refactor my code and one of the smells, DuplicateMethodCall, is being called on array and hash lookups, such as array[1] or hash[:key] when called multiple times.

So I was wondering if multiple array or hash lookups are so expensive, that we should be storing them in a variable rather than calling them directly, which is what everyone does from my experience.

I would not hesitate to store multiple object method calls (especially if it's a DB call) in a variable, but doing that for array and hash lookups feel like an overkill.

For example, I'll get a warning for this piece of code:

  def sort_params
    return [] if params[:reference_letter_section].nil?

    params[:reference_letter_section].map.with_index(1) do |id, index|
      { id: id, position: index }
    end
  end

but I feel like storing params[:reference_letter_section] in its own variable is too much

Body:
So I was wondering if multiple array or hash lookups are so expensive

Expensive calls are not the only reason for not doing the call multiple times. It also clutters the code without real need. Consider this not-so-contrived example:

Order.new(
  name:       params[:order][:name],
  total:      params[:order][:total],
  line_items: [
    {
      product_name: params[:order][:line_item][:product],
      price:        params[:order][:line_item][:price],
    }
  ]
)

Even though those hash accesses are super-cheap, it still makes sense to extract them, for readability reasons.

order_params     = params[:order]
line_item_params = order_params[:line_item]

Order.new(
  name:       order_params[:name],
  total:      order_params[:total],
  line_items: [
    {
      product_name: line_item_params[:product],
      price:        line_item_params[:price],
    }
  ]
)


问:
Download to computer from URL
I have a server for which I send a request (ID) in response from the server I get a json, inside json i have field ImagePath with url to image. How can I download this picture?

html

```<code><button md-raised-button (click)="DownloadImage(application.ApplicationId)">Download Image</button>
</code>```

Component

```<code> DownloadImage(applicationId:number)
    {
        var ID=applicationId;
        this.httpService.downloadImage(ID).subscribe((response)=>{
            console.log(response);
        })

    }
</code>```

Service

```<code>downloadImage(applicationId:number)
{
         return this.http.get('http://192.168.0.138/api/GetPhoto?applicationId='+applicationId,{headers:this.headers})
                         .map((res:Response)=> res.json() as DownloadImage
                        );

}
</code>```

JSON

```<code>Object {ImagePath: "http://192.168.0.138:80/Content/photos/29ef5a62-8a84-41cf-92d7-7b76da20357b.jpg"}
</code>```

答:
To chain requests, you can transform the Observable to a Promise, and then call .then() on it, which will get the mapped result of the previous call as a parameter. I'm not going to add the code for downloading a file in angular2 because it has been answered repeatedly in a dozen of posts.

Service

```<code>downloadImage(applicationId:number) {
    const _self = this;
    return this.http.get(`http://192.168.0.138/api/GetPhoto?applicationId=${applicationId}`, {headers:this.headers})
       .map((res:Response) => res.json() as DownloadImage)
       .toPromise()
       .then(function(dlImage: DownloadImage) {
          // Launch second call to dlImage.ImagePath
          const options = new RequestOptions({headers: myHeaderObj});
          return _self.http.get(dlImage.ImagePath, options);
        });
  }
</code>```

Component

```<code>DownloadImage(applicationId:number) {
    this.httpService.downloadImage(applicationId).subscribe(resp => {
          // ... See numerous other SO topics for examples
    });
}
</code>```

Just make sure the pictures are served from the same domain, otherwise you will run into CORS issues (but this also has been solved in a dozen of SO posts).

Title: Download to computer from URL

Body:
I have a server for which I send a request (ID) in response from the server I get a json, inside json i have field ImagePath with url to image. How can I download this picture?

html

<button md-raised-button (click)="DownloadImage(application.ApplicationId)">Download Image</button>

Component

 DownloadImage(applicationId:number)
    {
        var ID=applicationId;
        this.httpService.downloadImage(ID).subscribe((response)=>{
            console.log(response);
        })

    }

Service

downloadImage(applicationId:number)
{
         return this.http.get('http://192.168.0.138/api/GetPhoto?applicationId='+applicationId,{headers:this.headers})
                         .map((res:Response)=> res.json() as DownloadImage
                        );

}

JSON

Object {ImagePath: "http://192.168.0.138:80/Content/photos/29ef5a62-8a84-41cf-92d7-7b76da20357b.jpg"}

Body:
To chain requests, you can transform the Observable to a Promise, and then call .then() on it, which will get the mapped result of the previous call as a parameter. I'm not going to add the code for downloading a file in angular2 because it has been answered repeatedly in a dozen of posts.

Service

downloadImage(applicationId:number) {
    const _self = this;
    return this.http.get(`http://192.168.0.138/api/GetPhoto?applicationId=${applicationId}`, {headers:this.headers})
       .map((res:Response) => res.json() as DownloadImage)
       .toPromise()
       .then(function(dlImage: DownloadImage) {
          // Launch second call to dlImage.ImagePath
          const options = new RequestOptions({headers: myHeaderObj});
          return _self.http.get(dlImage.ImagePath, options);
        });
  }

Component

DownloadImage(applicationId:number) {
    this.httpService.downloadImage(applicationId).subscribe(resp => {
          // ... See numerous other SO topics for examples
    });
}

Just make sure the pictures are served from the same domain, otherwise you will run into CORS issues (but this also has been solved in a dozen of SO posts).


问:
I am getting Connection TIME OUT Error When Users Access .net Application
Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.
This could be because the pre-login handshake failed or the server was unable to respond back in time.</p>

答:
It seems to be a firewall issue. Firewall seems to be blocking connection to sql server for port 1433. You will need to add a rule to allow connection on this port.

You can find more on this here: SQL Server Pre-Login Handshake Acknowledgement Error


问:
I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0"
I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0" respectively as I assigned condition in  setitmprch(int itmprch) and setitmprch(int itmprch) methods. Kindly tell where I did a mistake.

```<code>public class INVOICE {
private String pn;
private String pdscp;
private int itmprch;
private double prpitm;
private double amount;

public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
    this.pn=pn;
    this.pdscp=pdscp;
    this.itmprch=itmprch;
    this.prpitm=prpitm;

}

public void setpn(String pn){
    this.pn=pn;
}
public void setpdscp(String pdscp){
    this.pdscp=pdscp;
   }

public void setitmprch(int itmprch){
    if (itmprch < 0)
        itmprch=0;
}
public void setprpitm(double prpitm){
   if(prpitm > 0.0)
       this.prpitm=prpitm;
   else if(prpitm < 0.0)
       this.prpitm=0.0;
}

public String getpn(){
return pn;
}

public String getpdscp(){
return pdscp;
}
public int getitmprch(){
return itmprch;
}
public double getprpitm(){
return prpitm;
}
public double getInvoiceAmount(){
amount= getitmprch()*getprpitm();
return amount;
}
}

   public class INVOICETEST {

public static void main(String[] args) {
    // TODO code application logic here
INVOICE in= new INVOICE("Mercedez","Arw 777",-3,-2.0);

System.out.printf("Part number is: %s\n",in.getpn());
System.out.printf("Part decription is: %s\n", in.getpdscp());
System.out.printf("Item purchased: %s\n",in.getitmprch());
System.out.printf("Price per item is: %s\n",in.getprpitm());
System.out.printf("Total amount is: %s\n",in.getInvoiceAmount());

}

}
</code>```

答:
Don't use all caps for class names.

Use more descriptive variable names - my eyes are bleeding looking at this and it takes 10x longer to understand than it should.

Use automatic properties rather than having private backing fields and void methods to set/get.

Use property for simple calculations such as working out invoice amount.

Don't asssign to private variable then return said variable.

Use unit tests to test your logic rather than a main method. What happens when your code grows, how are you going to test it all using one entry point?

Don't use protected keywords like in for variable names (in your main function).

The following code is in C#, but it should be easily transcribable to Java. Do some research on unit testing frameworks for Java and try and incorporate that into your workflow.

```<code>public class Invoice
{
    public string ModelName { get; set; }
    public double Price { get; set; }
    public double Amount { get; set; }
    public double InvoiceAmount => Price * Amount;
}

[TestClass]
public class InvoiceTest
{
    [TestMethod]
    public void TestInvoiceAmount()
    {
        // Arrange
        var testInvoice = new Invoice()
        {
            ModelName = "Audi R8",
            Price = 5000.0,
            Amount = 1
        };

        // Act
        double invoiceAmount = testInvoice.InvoiceAmount;

        // Assert
        Assert.IsTrue(invoiceAmount == 5000.0);
    }
}
</code>```

Body:
I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0" respectively as I assigned condition in  setitmprch(int itmprch) and setitmprch(int itmprch) methods. Kindly tell where I did a mistake.

public class INVOICE {
private String pn;
private String pdscp;
private int itmprch;
private double prpitm;
private double amount;

public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
    this.pn=pn;
    this.pdscp=pdscp;
    this.itmprch=itmprch;
    this.prpitm=prpitm;

}

public void setpn(String pn){
    this.pn=pn;
}
public void setpdscp(String pdscp){
    this.pdscp=pdscp;
   }

public void setitmprch(int itmprch){
    if (itmprch < 0)
        itmprch=0;
}
public void setprpitm(double prpitm){
   if(prpitm > 0.0)
       this.prpitm=prpitm;
   else if(prpitm < 0.0)
       this.prpitm=0.0;
}

public String getpn(){
return pn;
}

public String getpdscp(){
return pdscp;
}
public int getitmprch(){
return itmprch;
}
public double getprpitm(){
return prpitm;
}
public double getInvoiceAmount(){
amount= getitmprch()*getprpitm();
return amount;
}
}

   public class INVOICETEST {

public static void main(String[] args) {
    // TODO code application logic here
INVOICE in= new INVOICE("Mercedez","Arw 777",-3,-2.0);

System.out.printf("Part number is: %s\n",in.getpn());
System.out.printf("Part decription is: %s\n", in.getpdscp());
System.out.printf("Item purchased: %s\n",in.getitmprch());
System.out.printf("Price per item is: %s\n",in.getprpitm());
System.out.printf("Total amount is: %s\n",in.getInvoiceAmount());

}

}

Body:
Don't use all caps for class names.

Use more descriptive variable names - my eyes are bleeding looking at this and it takes 10x longer to understand than it should.

Use automatic properties rather than having private backing fields and void methods to set/get.

Use property for simple calculations such as working out invoice amount.

Don't asssign to private variable then return said variable.

Use unit tests to test your logic rather than a main method. What happens when your code grows, how are you going to test it all using one entry point?

Don't use protected keywords like in for variable names (in your main function).

The following code is in C#, but it should be easily transcribable to Java. Do some research on unit testing frameworks for Java and try and incorporate that into your workflow.

public class Invoice
{
    public string ModelName { get; set; }
    public double Price { get; set; }
    public double Amount { get; set; }
    public double InvoiceAmount => Price * Amount;
}

[TestClass]
public class InvoiceTest
{
    [TestMethod]
    public void TestInvoiceAmount()
    {
        // Arrange
        var testInvoice = new Invoice()
        {
            ModelName = "Audi R8",
            Price = 5000.0,
            Amount = 1
        };

        // Act
        double invoiceAmount = testInvoice.InvoiceAmount;

        // Assert
        Assert.IsTrue(invoiceAmount == 5000.0);
    }
}


问:
Someone help me setting up a react-toolbox project with scss support, redux-devtools, hotmodule replacement?
I am trying to set up MERN project. I need below configuration

react-toolbox as UI library

scss and css for styling

hot module replacement

redux devtools for development

Is there any boilerplate which is having this setup?
If not please someone create or tweak these existing repo's and set it for me?

https://github.com/theajr/react-redux-webpack2-boilerplate.git or

https://github.com/react-toolbox/react-toolbox.git

Thanks in advance.

答:
Check out this boilerplate.

webpack configuration

Hot reloading and Redux devtools in dev mode

manifest, vendor and app code separation in production mode

react-toolbox

redux-saga (you can remove if you don't want this)


问:
Getting actual value of local variables in llvm
If I have this example:

```<code>int a=0, b=0;
</code>```

a and b are local variables and make any modifications in their values, such as:

```<code>a++;
b++;
</code>```

I need to get the value in this line code during running MCJIT.

I mean by value not Value class, but the actual integer or any type value.

答:
Put a break point after execution of the statement where you want to check the value. In the console (lldb) po <variable name>.

Although I guess watch point is more suitable for your requirement, add a watch point for the variable like, watchpoint set variable <variable key path>.

Body:
If I have this example:

int a=0, b=0;

a and b are local variables and make any modifications in their values, such as:

a++;
b++;

I need to get the value in this line code during running MCJIT.

I mean by value not Value class, but the actual integer or any type value.


问:
Image has extra space at the top
I have an image on my website and there is about 50px of extra white space at the top. I have tried padding none and margin none, display block but none of them work. Here is a working jsfiddle of it.
Here's my HTML

     h1 {
     font-size: 100px;
     color: white;
     text-align: center;
     opacity: none;
     font-family: 'Noto Sans', sans-serif;
      }

    p {
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 70px;
    color: black;
    text-align: center;
    }

      .rotate {
       float: left;
      -webkit-transform: rotate(180deg) 2s;
      transform: rotate(180deg) 2s;
      transition: all 2s ease;
      transition-delay: 0.4s;
        }

      .rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
         }

    .container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
    z-index: 150;
     margin-bottom: -80px;
      }

    .container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
       }

    .dropdown {
    float: right;
    overflow: hidden;
     }

    .dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
      }

       .container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
        }

     .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
     }

    .dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
      }

    .dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
     }

    .dropdown:hover .dropdown-content {
    display: block;
         }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>     <body>
      <div class="active">
      <div id="background">
     <div class="opacity">
     <div class="container">
     <div class="rotate">
     <img class="chiz" src="kkk.png" alt="Vortex Games">
    </div>
       Home
       About
      FAQ
       Games
       <div class="dropdown">
      <button class="dropbtn"
       onclick="window.location.href='store.html'">Store</button>
      <div class="dropdown-content">
        Powerups
        Coins
      </div>
      </div>
       </div>
      </div>
       <p class="title">
       We're a top-of-the-line high tech <br>game company
      <br>
      <span style="color:white;font-size:20px;padding:none;display:inline-
       block;">
      <span style="color:red;font-size:100px;padding-top:none;">
      –<br></span>Driven by passion. Always at our best.</span>
    </p>
     <!--the background div-->
      </div>

      <div class="creative">
     <img src="cree.jpg" align="abstop">
      </div>
CSS</code>```

Any help would be appreciated.

Thanks

答:
You need to add *{margin:0;padding: 0;} this in your css. Because its not only about your image property. You have more element which has some default css property, which is and can affect your html. * make a universal tag

*{
    margin:0;padding: 0;
}
.creative {
    padding-top: none;
}
img {
    display: block;
}

body {
    /*body:0;*/
}

#background {
  background: url('https://sellorelse.ogilvy.com/wp-content/uploads/2016/06/creativity_technology.png');
  background-position:center top;
}

h1 {
  font-size: 100px;
  color: white;
  text-align: center;
  opacity: none;
  font-family: 'Noto Sans', sans-serif;
}
p {
  font-family: 'Roboto Condensed', sans-serif;
  font-size: 70px;
  color: black;
  text-align: center;
}

.rotate {
  float: left;
 -webkit-transform: rotate(180deg) 2s;
  transform: rotate(180deg) 2s;
  transition: all 2s ease;
  transition-delay: 0.4s;
}

.rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
}

.container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
  z-index: 150;
  margin-bottom: -80px;
}

.container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
}

.dropdown {
    float: right;
    overflow: hidden;
}

.dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
}

.container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
}

.dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
}

.dropdown:hover .dropdown-content {
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="active">
  <div id="background">
  <div class="opacity">
  <div class="container">
  <div class="rotate">
  <img class="chiz" src="kkk.png" alt="Vortex Games">
</div>
    Home
    About
  FAQ
  Games
    <div class="dropdown">
      <button class="dropbtn" onclick="window.location.href='store.html'">Store</button>
      <div class="dropdown-content">
        Powerups
        Coins
      </div>
  </div>
</div>
</div>
<p class="title">
  We're a top-of-the-line high tech <br>game company
<br>
  <span style="color:white;font-size:20px;padding:none;display:inline-block;">
      <span style="color:red;font-size:100px;padding-top:none;">
      –<br></span>Driven by passion. Always at our best.</span>
    </p>
<!--the background div-->
</div>

<div class="creative">
<img src="http://drwillsparks.com/wp-content/uploads/2017/02/creativity.jpg" align="abstop">
</div></code>```

Title: Image has extra space at the top

Body:
I have an image on my website and there is about 50px of extra white space at the top. I have tried padding none and margin none, display block but none of them work. Here is a working jsfiddle of it.
Here's my HTML

     h1 {
     font-size: 100px;
     color: white;
     text-align: center;
     opacity: none;
     font-family: 'Noto Sans', sans-serif;
      }

    p {
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 70px;
    color: black;
    text-align: center;
    }

      .rotate {
       float: left;
      -webkit-transform: rotate(180deg) 2s;
      transform: rotate(180deg) 2s;
      transition: all 2s ease;
      transition-delay: 0.4s;
        }

      .rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
         }

    .container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
    z-index: 150;
     margin-bottom: -80px;
      }

    .container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
       }

    .dropdown {
    float: right;
    overflow: hidden;
     }

    .dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
      }

       .container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
        }

     .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
     }

    .dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
      }

    .dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
     }

    .dropdown:hover .dropdown-content {
    display: block;
         }

       Home
       About
      FAQ
       Games

      <button class="dropbtn"
       onclick="window.location.href='store.html'">Store</button>

        Powerups
        Coins

       We're a top-of-the-line high tech
game company

      –
Driven by passion. Always at our best.

CSS

Any help would be appreciated.

Thanks

Body:
You need to add *{margin:0;padding: 0;} this in your css. Because its not only about your image property. You have more element which has some default css property, which is and can affect your html. * make a universal tag

*{
    margin:0;padding: 0;
}
.creative {
    padding-top: none;
}
img {
    display: block;
}

body {
    /*body:0;*/
}

#background {
  background: url('https://sellorelse.ogilvy.com/wp-content/uploads/2016/06/creativity_technology.png');
  background-position:center top;
}

h1 {
  font-size: 100px;
  color: white;
  text-align: center;
  opacity: none;
  font-family: 'Noto Sans', sans-serif;
}
p {
  font-family: 'Roboto Condensed', sans-serif;
  font-size: 70px;
  color: black;
  text-align: center;
}

.rotate {
  float: left;
 -webkit-transform: rotate(180deg) 2s;
  transform: rotate(180deg) 2s;
  transition: all 2s ease;
  transition-delay: 0.4s;
}

.rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
}

.container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
  z-index: 150;
  margin-bottom: -80px;
}

.container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
}

.dropdown {
    float: right;
    overflow: hidden;
}

.dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
}

.container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
}

.dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
}

.dropdown:hover .dropdown-content {
    display: block;
}

<div class="active">
  <div id="background">
  <div class="opacity">
  <div class="container">
  <div class="rotate">
  <img class="chiz" src="kkk.png" alt="Vortex Games">
</div>
    <a href="index.html">Home</a>
    <a href="about.html">About</a>
  <a href="FAQ.html">FAQ</a>
  <a href="games.html">Games</a>
    <div class="dropdown">
      <button class="dropbtn" onclick="window.location.href='store.html'">Store</button>
      <div class="dropdown-content">
        <a href="wall.html">Powerups</a>
        <a href="store.html">Coins</a>
      </div>
  </div>
</div>
</div>
<p class="title">
  We're a top-of-the-line high tech <br>game company
<br>
  <span style="color:white;font-size:20px;padding:none;display:inline-block;">
      <span style="color:red;font-size:100px;padding-top:none;">
      &ndash;<br></span>Driven by passion. Always at our best.</span>
    </p>
<!--the background div-->
</div>

<div class="creative">
<img src="http://drwillsparks.com/wp-content/uploads/2017/02/creativity.jpg" align="abstop">
</div>


问:
Add key values dynamically to nested object in Javascript
This might be a duplicate of this but did not get proper solution over there. I have object as below,

```<code>var replyDataObj = {

                  "department": {
                    "name": getCache("departmentName")
                  },
                  "subject": replyEmailSubject,
                  "payload": {
                    "email": {
                      "contents": {
                        "content": [
                          {
                            "type": "html",
                            "value": replyEmailContent
                          }
                        ]
                      },
                      "emailAddresses": {
                        "from": fromEmailId,
                        "to": {
                          "address": [
                            toEmailId
                          ]
                        }
                      }
                    }
                  }
            }
</code>```

I want to add following key values to 'emailAddresses' key dynamically depending upon whether cc field is present or not,

```<code>"cc": {
         "address": [
           ccEmailId
          ]
      }
</code>```

So it will look like,

```<code>var replyDataObj = {

              "department": {
                "name": getCache("departmentName")
              },
              "subject": replyEmailSubject,
              "payload": {
                "email": {
                  "contents": {
                    "content": [
                      {
                        "type": "html",
                        "value": replyEmailContent
                      }
                    ]
                  },
                  "emailAddresses": {
                    "from": fromEmailId,
                    "to": {
                      "address": [
                        toEmailId
                      ],
                    "cc": {
                      "address": [
                         ccEmailId
                        ]
                      }
                    }
                  }
                }
              }
        }
</code>```

I tried to add this using object[key] as below, object.key but no luck

```<code>replyDataObj[payload][emailAddresses][cc]={
     "address": [
       ccEmailId
      ]
  }
</code>```

I tried multiple ways and searched a lot but did not get the solution. Any help in this regard will be greatly appreciated. Thank you.

答:
Put strings inside []:

```<code>replyDataObj['payload']['emailAddresses']['cc']={
     "address": [
       ccEmailId
      ]
  }
</code>```

Body:
This might be a duplicate of this but did not get proper solution over there. I have object as below,

var replyDataObj = {

                  "department": {
                    "name": getCache("departmentName")
                  },
                  "subject": replyEmailSubject,
                  "payload": {
                    "email": {
                      "contents": {
                        "content": [
                          {
                            "type": "html",
                            "value": replyEmailContent
                          }
                        ]
                      },
                      "emailAddresses": {
                        "from": fromEmailId,
                        "to": {
                          "address": [
                            toEmailId
                          ]
                        }
                      }
                    }
                  }
            }

I want to add following key values to 'emailAddresses' key dynamically depending upon whether cc field is present or not,

"cc": {
         "address": [
           ccEmailId
          ]
      }

So it will look like,

var replyDataObj = {

              "department": {
                "name": getCache("departmentName")
              },
              "subject": replyEmailSubject,
              "payload": {
                "email": {
                  "contents": {
                    "content": [
                      {
                        "type": "html",
                        "value": replyEmailContent
                      }
                    ]
                  },
                  "emailAddresses": {
                    "from": fromEmailId,
                    "to": {
                      "address": [
                        toEmailId
                      ],
                    "cc": {
                      "address": [
                         ccEmailId
                        ]
                      }
                    }
                  }
                }
              }
        }

I tried to add this using object[key] as below, object.key but no luck

replyDataObj[payload][emailAddresses][cc]={
     "address": [
       ccEmailId
      ]
  }

I tried multiple ways and searched a lot but did not get the solution. Any help in this regard will be greatly appreciated. Thank you.

Body:
Put strings inside []:

replyDataObj['payload']['emailAddresses']['cc']={
     "address": [
       ccEmailId
      ]
  }


答:
float:left and float:right

you can use inline css for this:
 and

heres a tutorial: http://css.maxdesign.com.au/floatutorial/

Title: What CSS would get two buttons to line up, respectively, on the left and right side of a 3-colspan table cell?

Body:
I have a table like this:

    short text
    long long long text
    short text

      <button id='leftbutton'/>
      <button id='rightbutton'/>

What CSS styles should I apply to get my buttons to lay out like this:

-----------------------------------------------------------------
|short text       |      long long long text     |  short text  |
-----------------------------------------------------------------
| button left     |                              | button right |
-----------------------------------------------------------------

instead of their current layout:

-----------------------------------------------------------------
|short text       |      long long long text     |  short text  |
-----------------------------------------------------------------
|button left|button right|
-----------------------------------------------------------------


问:
Li element added from javascript not able to hide
I need to create  list item  and child list on each parent, and when the parent clicked the child need to be hide/show. Below is the code which works fine in the case of li element added as html.

    function add() {
      var ul = document.getElementById("locations_id");
      var li = document.createElement("li");
      li.appendChild(document.createTextNode("Element 4"));
      ul.appendChild(li);

    }

    function addLoc() {
      var loc = ["loc1","loc2","loc3"];
      var cam = ["cam1","cam2","cam3"];

      for(var i=0;i<loc.length;i++){
       var ul = document.getElementById("locations_id");
       var li = document.createElement("li");
       var a = document.createElement('a');
       a.appendChild(document.createTextNode(loc[i]));
       a.onclick = test();
       li.appendChild(a);

       var ul1 = document.createElement("ul");
       for(var j=0;j<cam.length;j++){
         var check = document.createElement("input");
         check.setAttribute('type','checkbox');
         check.setAttribute('name','cam');
         check.setAttribute('value',cam[j]);
         ul1.appendChild(check);
         ul1.appendChild(document.createTextNode(cam[j]));
         ul1.appendChild(document.createElement("br"));
       }
        li.appendChild(ul1);

        ul.appendChild(li);
      }

    }
    function test() { alert('blah'); }

    $('.list > li a').click(function() {
            $(this).parent().find('ul').toggle();
        });

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Test</title>

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script type="text/javascript"></script>
    </head>

    <body>
     <button onclick="addLoc()">Add </button>

     <ul id="locations_id" class="list" style="list-style-type:none">
            <li>
                <a>Vehicle</a>
                <ul>
                  <input type="checkbox" name="vehicle" value="Bike"> Bike<br>
            <input type="checkbox" name="vehicle" value="Car" > Car<br>
                </ul>
            </li>
        </ul>
        </body>
    </html>
    </code>```

Where as the element I have added from javascript not seems show or hid when I click the parent item.

What could be the problem.

答: The issue is that the listener is not attaching to the new li elements because they do not exist at the time that code is being run. Include the addition of the .click listener in the body of the addLoc() function, after the element has been added to the DOM.</p>

Body:
I need to create  list item  and child list on each parent, and when the parent clicked the child need to be hide/show. Below is the code which works fine in the case of li element added as html.

    function add() {
      var ul = document.getElementById("locations_id");
      var li = document.createElement("li");
      li.appendChild(document.createTextNode("Element 4"));
      ul.appendChild(li);

    }

    function addLoc() {
      var loc = ["loc1","loc2","loc3"];
      var cam = ["cam1","cam2","cam3"];

      for(var i=0;i<loc.length;i++){
       var ul = document.getElementById("locations_id");
       var li = document.createElement("li");
       var a = document.createElement('a');
       a.appendChild(document.createTextNode(loc[i]));
       a.onclick = test();
       li.appendChild(a);

       var ul1 = document.createElement("ul");
       for(var j=0;j<cam.length;j++){
         var check = document.createElement("input");
         check.setAttribute('type','checkbox');
         check.setAttribute('name','cam');
         check.setAttribute('value',cam[j]);
         ul1.appendChild(check);
         ul1.appendChild(document.createTextNode(cam[j]));
         ul1.appendChild(document.createElement("br"));
       }
        li.appendChild(ul1);

        ul.appendChild(li);
      }

    }
    function test() { alert('blah'); }

    $('.list > li a').click(function() {
            $(this).parent().find('ul').toggle();
        });

    <!DOCTYPE html>

    <meta charset=utf-8 />
    <title>Test</title>

     <button onclick="addLoc()">Add </button>

                Vehicle

                  <input type="checkbox" name="vehicle" value="Bike"> Bike

            <input type="checkbox" name="vehicle" value="Car" > Car

Where as the element I have added from javascript not seems show or hid when I click the parent item.

What could be the problem.


问:
Best way of chaining reduce with Java 8
I have the following code that I'm trying to improve:

```<code>BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);
</code>```

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

答:
If all these properties are of the same type (it seems they are all BigDecimal), you can use flatMap to create a single Stream of them all and then reduce it to the total sum:

```<code>BigDecimal total =
    entity.getAssociate()
          .stream()
          .flatMap (a -> Stream.of(a.getPropertyA(),a.getPropertyB(),a.getPropertyC(),a.getPropertyD()))
          .reduce(BigDecimal.ZERO, BigDecimal::add);
</code>```

Title: Best way of chaining reduce with Java 8

Body:
I have the following code that I'm trying to improve:

BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

Body:
If all these properties are of the same type (it seems they are all BigDecimal), you can use flatMap to create a single Stream of them all and then reduce it to the total sum:

BigDecimal total =
    entity.getAssociate()
          .stream()
          .flatMap (a -> Stream.of(a.getPropertyA(),a.getPropertyB(),a.getPropertyC(),a.getPropertyD()))
          .reduce(BigDecimal.ZERO, BigDecimal::add);


问:
Undefinded $_GET[' ...'] index
After making a javascript variable accesable into a php file the $_GET['something'] keeps saying undefined index.

Although the proper result gets displayed and being written into the xml.

If i try to initialise it my score no longer shows up for some reason.

How can i initalise this without it showing anything at al on my screen?

Regards.

答:
If you do  this with javascript:

```<code>window.location.href="index.php?scoreresult="+score
</code>```

you have to access the variable in PHP using

```<code>$_GET['scoreresult']
</code>```

instead of

```<code>$_GET['score']
</code>```

If you make use of XSL to transform the XML, XSLT::setParameter may be interesting to you. It allows you to register (PHP)-variables for use inside a XSL-stylesheet.

Title: Undefinded $_GET[' ...'] index

Body:
If you do  this with javascript:

window.location.href="index.php?scoreresult="+score

you have to access the variable in PHP using

$_GET['scoreresult']

instead of

$_GET['score']

If you make use of XSL to transform the XML, XSLT::setParameter may be interesting to you. It allows you to register (PHP)-variables for use inside a XSL-stylesheet.


问:
Create csv based on a object property assigned dynamically
I need to build a csv string based on a specific property from an object stored in a list but I've got to do this for multiple properties:

The below works fine when "hardcoded":

```<code>var list = customers.Select(p => p.Email).ToArray();
csvString = string.Join(";", list1);
</code>```

but I obviously don't want to have to do this for every property I need. Is there a way for me to build a function and assign the property name I want to use to one of the parameters. Something similar to this:

```<code>var emails = ConvertCollectionToCsv(customers, "Email");
var names = ConvertCollectionToCsv(customers, "Name");
var mobile = ConvertCollectionToCsv(customers, "Mobile");
...
</code>```

I thought I'd try the following:

```<code>private string ConvertCollectionToCsv(List<Customer> customers, string propertyName)
{
   var prop = typeof(EmailAddress).GetProperties().FirstOrDefault
   (p => p.Name.ToLowerInvariant() == propertyName.ToLowerInvariant());

   var list = customers.Select(p => prop.Name).ToArray();
   return string.Join(";", list);
}
</code>```

but when called:

```<code>var emails = ConvertCollectionToCsv(customers, "Email");
</code>```

it returns Email;Email;Email instead of the email address which makes sense as the prop.Name is used. I'm trying to use the GetValue instead:

```<code>var list = customers.Select(p => prop.GetValue(p)).ToArray();
</code>```

but that's throwing the following error:

```<code>"Object does not match target type."
</code>```

Any suggestions?

Thanks

答:
You are passing a List of Customer-objects to the method but use a property of EmailAddress, these types don't match.

I'd suggest a generic method here:

```<code>private string ConvertCollectionToCsv<T>(IEnumerable<T> items, string propertyName)
{
   var prop = typeof(T).GetProperties().FirstOrDefault
   (p => p.Name.ToLowerInvariant() == propertyName.ToLowerInvariant());

   var list = items.Select(p => prop.GetValue(p)).ToArray();
   return string.Join(";", list);
}
</code>```

This way, you pass in any collection, e.g. a List<string> or an array like MyCustomType[]

Body:
I need to build a csv string based on a specific property from an object stored in a list but I've got to do this for multiple properties:

The below works fine when "hardcoded":

var list = customers.Select(p => p.Email).ToArray();
csvString = string.Join(";", list1);

but I obviously don't want to have to do this for every property I need. Is there a way for me to build a function and assign the property name I want to use to one of the parameters. Something similar to this:

var emails = ConvertCollectionToCsv(customers, "Email");
var names = ConvertCollectionToCsv(customers, "Name");
var mobile = ConvertCollectionToCsv(customers, "Mobile");
...

I thought I'd try the following:

private string ConvertCollectionToCsv(List<Customer> customers, string propertyName)
{
   var prop = typeof(EmailAddress).GetProperties().FirstOrDefault
   (p => p.Name.ToLowerInvariant() == propertyName.ToLowerInvariant());

   var list = customers.Select(p => prop.Name).ToArray();
   return string.Join(";", list);
}

but when called:

var emails = ConvertCollectionToCsv(customers, "Email");

it returns Email;Email;Email instead of the email address which makes sense as the prop.Name is used. I'm trying to use the GetValue instead:

var list = customers.Select(p => prop.GetValue(p)).ToArray();

but that's throwing the following error:

"Object does not match target type."

Any suggestions?

Thanks

Body:
You are passing a List of Customer-objects to the method but use a property of EmailAddress, these types don't match.

I'd suggest a generic method here:

private string ConvertCollectionToCsv<T>(IEnumerable<T> items, string propertyName)
{
   var prop = typeof(T).GetProperties().FirstOrDefault
   (p => p.Name.ToLowerInvariant() == propertyName.ToLowerInvariant());

   var list = items.Select(p => prop.GetValue(p)).ToArray();
   return string.Join(";", list);
}

This way, you pass in any collection, e.g. a List<string> or an array like MyCustomType[]


答:
Use event delegation. since you are creating li dynamically.

```<code>$(document).on('.list > li a','click',function() {
        $(this).parent().find('ul').toggle();
});
</code>```

Also

Add function name for onClick. It should not be

```<code> a.onclick = test();
</code>```

Use this

```<code> a.onclick = test;
</code>```

Title: Li element added from javascript not able to hide

Body:
Use event delegation. since you are creating li dynamically.

$(document).on('.list > li a','click',function() {
        $(this).parent().find('ul').toggle();
});

Also

Add function name for onClick. It should not be

 a.onclick = test();

Use this

 a.onclick = test;


问:
laravel can't retrieve session when redirect
in laravel 5.4

```<code>class AdminController extends Controller
{

   public function checkLogin(Request $request)
   {
      Session::put('admin','yes');
      return redirect('mobiles');
   }
}

class MobilesController extends Controller
{
      public function __construct()
      {
         if( ( Session::has('admin') ) )
           { dd('admin');}
        else
           { dd('not admin'); }
     }
}
</code>```

it prints 'not admin' so what happen to the session , if i prints the admin session in class checkLogin it prints normally

答:
you have to use laravel flashed-session-data

https://laravel.com/docs/5.4/redirects#redirecting-with-flashed-session-data

return redirect('mtest2')->with('admin','yes');

so modify your code like this

```<code>class AdminController extends Controller {

    public function checkLogin(Request $request){
        return redirect('mobiles')->with('admin',true);
     }
 }

 class MobilesController extends Controller {

     public function __construct() {

       if( session()->has('admin') ){
          dd('admin');
       }else{
          dd('not admin');
       }
     }
 }
</code>```

Here is updated code if you do not want to use Flashed data

```<code>class AdminController extends Controller {

    public function checkLogin(Request $request){

        $request->session()->put('admin',true);
        return redirect('mobiles');
     }
 }
</code>```

it should work.

Body:
in laravel 5.4

class AdminController extends Controller
{

   public function checkLogin(Request $request)
   {
      Session::put('admin','yes');
      return redirect('mobiles');
   }
}

class MobilesController extends Controller
{
      public function __construct()
      {
         if( ( Session::has('admin') ) )
           { dd('admin');}
        else
           { dd('not admin'); }
     }
}

it prints 'not admin' so what happen to the session , if i prints the admin session in class checkLogin it prints normally

Body:
you have to use laravel flashed-session-data

https://laravel.com/docs/5.4/redirects#redirecting-with-flashed-session-data

return redirect('mtest2')->with('admin','yes');

so modify your code like this

class AdminController extends Controller {

    public function checkLogin(Request $request){
        return redirect('mobiles')->with('admin',true);
     }
 }

 class MobilesController extends Controller {

     public function __construct() {

       if( session()->has('admin') ){
          dd('admin');
       }else{
          dd('not admin');
       }
     }
 }

Here is updated code if you do not want to use Flashed data

class AdminController extends Controller {

    public function checkLogin(Request $request){

        $request->session()->put('admin',true);
        return redirect('mobiles');
     }
 }

it should work.