问:
DropDownListFor() does not select required item on get request (on post request works)
I've dusted off an older project (MVC 5.2.2) and discovered that one of my DropDownListFor() usages does not work correctly if the page is rendered first time as response on HttpGet request: generated HTML code does not contain selected attribute at all.

If I inspect view model i.e. SelectList items (in the controller and int the rendered view), the required item has member Selected set to true. Item's Id is enum value.

When the same page is rendered as response to HttpPost request, everything works OK. The worst is, when inspecting model, the values are the same as on HttpGet request and SelectLists are in both cases created the same routine...

Instead using enum as selected item Id I tried an instance of complete item for selected one as in the answer here with the same result: does not work on HttpGet.

The list is constructed this way:

```<code>  List<CashType> types;
  if (AIncludeAll)
    types = ADbContext.CashTypes.OrderBy(c => c.Ident).ToList();
  else
    types = ADbContext.CashTypes.Where(c => c.Id != CashTypeValues.All).OrderBy(c => c.Ident).ToList();
  //
  foreach (var type in types)
    type.Translation = CashTypeValueToDescription(type.Id);
  return new SelectList(types, "Id", "Translation", ACashType);
</code>```

CashType comes from DB model:

```<code>[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public CashTypeValues Id { get; set; }

[Required]
[StringLength(DBDomains.D_IDENTCODE)]
[Index(IsUnique = true)]
public string Ident { get; set; }

[NotMapped]
public string Translation { get; set; }
</code>```

view model is

```<code>[Display(Name = "View_Unit_CashType", ResourceType = typeof(WebGui))]
public CashTypeValues CashType { get; set; }
public SelectList CashTypes { get; set; }
</code>```

finally, usage in Razor looks like this:

```<code><div class="Theme-Bottom-Filter-Field">
  @Html.LabelFor(m => m.CashType)
  @Html.DropDownListFor(m => m.CashType, Model.CashTypes, new { Id = "CashTypeSelector" })
</div>
</code>```

Does anybody has an idea what I'm missing?

Thanx, pf

答:
The fact that Selected is true on the SelectListItem is inconsequential. When Razor renders the drop down list, it sets the selected value based on ModelState, so if the proper value is not being selected that means the proper value does not exist in ModelState.

ModelState is composed of values from Request, ViewData/ViewBag and finally Model. Generally, you'll just want to ensure that the model you're passing to the view has the appropriate value set. If you want the property on your view model to have a default value, for example, you can do:

```<code>private CashTypeValues? cashType;
public CashTypeValues CashType
{
    get { return cashType ?? CashTypeValues.Default; }
    set { cashType = value; }
}
</code>```

Or, in C# 6+:

```<code>public CashTypeValues CashType { get; set; } = CashTypeValues.Default;
</code>```

However, since values in Request and ViewData/ViewBag actually take precedence, you need to ensure that you're not passing an incorrect value that way. For example, if you had a query string like ?cashType=foo, then the selected value would be "foo", rather than whatever you had on your model originally. You also should avoid setting something like ViewBag.CashType. It's also important to note that in all of these cases, naming is case-insensitive. When it comes to ModelState, foo == FOO == Foo == fOO.

Body:
I've dusted off an older project (MVC 5.2.2) and discovered that one of my DropDownListFor() usages does not work correctly if the page is rendered first time as response on HttpGet request: generated HTML code does not contain selected attribute at all.

If I inspect view model i.e. SelectList items (in the controller and int the rendered view), the required item has member Selected set to true. Item's Id is enum value.

When the same page is rendered as response to HttpPost request, everything works OK. The worst is, when inspecting model, the values are the same as on HttpGet request and SelectLists are in both cases created the same routine...

Instead using enum as selected item Id I tried an instance of complete item for selected one as in the answer here with the same result: does not work on HttpGet.

The list is constructed this way:

  List<CashType> types;
  if (AIncludeAll)
    types = ADbContext.CashTypes.OrderBy(c => c.Ident).ToList();
  else
    types = ADbContext.CashTypes.Where(c => c.Id != CashTypeValues.All).OrderBy(c => c.Ident).ToList();
  //
  foreach (var type in types)
    type.Translation = CashTypeValueToDescription(type.Id);
  return new SelectList(types, "Id", "Translation", ACashType);

CashType comes from DB model:

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public CashTypeValues Id { get; set; }

[Required]
[StringLength(DBDomains.D_IDENTCODE)]
[Index(IsUnique = true)]
public string Ident { get; set; }

[NotMapped]
public string Translation { get; set; }

view model is

[Display(Name = "View_Unit_CashType", ResourceType = typeof(WebGui))]
public CashTypeValues CashType { get; set; }
public SelectList CashTypes { get; set; }

finally, usage in Razor looks like this:

  @Html.LabelFor(m => m.CashType)
  @Html.DropDownListFor(m => m.CashType, Model.CashTypes, new { Id = "CashTypeSelector" })

Does anybody has an idea what I'm missing?

Thanx, pf

Body:
The fact that Selected is true on the SelectListItem is inconsequential. When Razor renders the drop down list, it sets the selected value based on ModelState, so if the proper value is not being selected that means the proper value does not exist in ModelState.

ModelState is composed of values from Request, ViewData/ViewBag and finally Model. Generally, you'll just want to ensure that the model you're passing to the view has the appropriate value set. If you want the property on your view model to have a default value, for example, you can do:

private CashTypeValues? cashType;
public CashTypeValues CashType
{
    get { return cashType ?? CashTypeValues.Default; }
    set { cashType = value; }
}

Or, in C# 6+:

public CashTypeValues CashType { get; set; } = CashTypeValues.Default;

However, since values in Request and ViewData/ViewBag actually take precedence, you need to ensure that you're not passing an incorrect value that way. For example, if you had a query string like ?cashType=foo, then the selected value would be "foo", rather than whatever you had on your model originally. You also should avoid setting something like ViewBag.CashType. It's also important to note that in all of these cases, naming is case-insensitive. When it comes to ModelState, foo == FOO == Foo == fOO.


来源: stackexchange

问:
C# Memorystream is not fully saved to the file
I am exporting an object to csv using MemoryStream and StreamWriter. But after saving the file, I see that the end of the file is missing. Its cut of in the middle of a line.

Below is my code:

```<code>public void Export(ProductExport productExport)
{
    var country = (Country)(int.Parse(productExport.Firma.Code));

    using(var stream = new MemoryStream())
    {
        var sw = new StreamWriter(stream);

        // Write header row
        sw.WriteLine(
            "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
            "Groep",
            "TecDoc Leverancier",
            "TecDoc Ref",
            "SA",
            "EAN",
            "Omschrijving NL",
            "V/E",
            "VPE",
            "Prijs per",
            "Bruto prijs"
        );

        foreach(var product in productExport.Products)
        {
            // Write header row
            sw.WriteLine(
                "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
                product.Artgrp,
                product.TecDoc != null ? product.TecDoc.Supplier : "",
                product.TecDoc != null ? product.TecDoc.Value : "",
                product.Ids.Where<Id>(i => i.Type == "SA").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Ids.Where<Id>(i => i.Type == "EN").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Descriptions.Where<Description>(d => d.Lang == "NL").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.SalesUnit,
                product.PackingUnit.Value,
                product.PriceUnit.Value,
                product.Prices.First<Price>(p => p.Type == "BR" && p.Country == country.ToString()).Value
            );
        }

        FileSystem.AddFile(country + "-" + String.Format("{0:yyyyMMdd}", DateTime.Now) + ".csv", stream);

        sw.Flush();
    }
}
</code>```

And this is the code of the FileSystem.AddFile() function:

```<code>public void AddFile(string path, System.IO.Stream stream)
{
    var fullPath = GetFullPath(path);

    var directory = Path.GetDirectoryName(fullPath);
    if (directory == null) throw new InvalidOperationException("Can't get the directory.");
    Directory.CreateDirectory(directory); // Make sure the directory is created!

    if (stream.CanSeek)
        stream.Seek(0, SeekOrigin.Begin);

    using (var destination = (Stream)File.Create(fullPath))
        stream.CopyTo(destination);
}
</code>```

答: First sw.Flush(), then do the FileSystem.AddFile(). The StreamWriter is probably buffering the output before passing it to the MemoryStream.

ContentLicense: CC BY-SA 3.0

Body:
I am exporting an object to csv using MemoryStream and StreamWriter. But after saving the file, I see that the end of the file is missing. Its cut of in the middle of a line.

Below is my code:

public void Export(ProductExport productExport)
{
    var country = (Country)(int.Parse(productExport.Firma.Code));

    using(var stream = new MemoryStream())
    {
        var sw = new StreamWriter(stream);

        // Write header row
        sw.WriteLine(
            "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
            "Groep",
            "TecDoc Leverancier",
            "TecDoc Ref",
            "SA",
            "EAN",
            "Omschrijving NL",
            "V/E",
            "VPE",
            "Prijs per",
            "Bruto prijs"
        );

        foreach(var product in productExport.Products)
        {
            // Write header row
            sw.WriteLine(
                "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
                product.Artgrp,
                product.TecDoc != null ? product.TecDoc.Supplier : "",
                product.TecDoc != null ? product.TecDoc.Value : "",
                product.Ids.Where<Id>(i => i.Type == "SA").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Ids.Where<Id>(i => i.Type == "EN").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Descriptions.Where<Description>(d => d.Lang == "NL").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.SalesUnit,
                product.PackingUnit.Value,
                product.PriceUnit.Value,
                product.Prices.First<Price>(p => p.Type == "BR" && p.Country == country.ToString()).Value
            );
        }

        FileSystem.AddFile(country + "-" + String.Format("{0:yyyyMMdd}", DateTime.Now) + ".csv", stream);

        sw.Flush();
    }
}

And this is the code of the FileSystem.AddFile() function:

public void AddFile(string path, System.IO.Stream stream)
{
    var fullPath = GetFullPath(path);

    var directory = Path.GetDirectoryName(fullPath);
    if (directory == null) throw new InvalidOperationException("Can't get the directory.");
    Directory.CreateDirectory(directory); // Make sure the directory is created!

    if (stream.CanSeek)
        stream.Seek(0, SeekOrigin.Begin);

    using (var destination = (Stream)File.Create(fullPath))
        stream.CopyTo(destination);
}


问:
React Native Android Run
I am just starting with react native. I created my first app using React Native CLI. It was created without any errors. When I am trying to react-native run-android It ends up with this error as shown.

答:
1) Run command " adb devices "
It will let you know if any device is connected or not

2) Try running by setting the Environment variable and proxy commands.
Follow this link: http://facebook.github.io/react-native/releases/0.38/docs/getting-started.html#content

Title: React Native Android Run


问:
Javascript querying SharePoint Date Column returning '/Date(1494460800000)/'
I've got some JavaScript which is querying a SharePoint Date Column. The format is: DD/MM/YYYY and the results come back fine except for the date which is coming back as pictured under Device Details.

I'm trying to use the Moment.js library to format it but I'm not having any luck.
I think it's either this line:

```<code>var LifeCycleStart = item.DeviceAvailableFrom;
</code>```

or this line I need to use the Moment formatting on:

```<code>$('#devicedetails').append($(txtTitle));
</code>```

Full code below:

```<code>function getDeviceDetails() {
  var txtTitle = "";
  var txtOverview = "";
  var txtAccessories = "";
  var txtDevicetype = "";
  var txtTypicalDeviceUsage ="";
  var txtKnownSystemIssues ="";
  var txtLifeCycles = "";
  var tempLCS2 = "";

  var query = "http://collaboration-dev.xxx.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=LifeCycleStatus&$filter=Id eq " + window.DeviceId + "";
  var call = $.ajax({
    url: query,
    type: "GET",
    dataType: "json",
    headers: {
      Accept: "application/json;odata=verbose"
    }
  });
  call.done(function (data,textStatus, jqXHR){
    $.each(data.d.results, function(index, item) {
      var tempID = item.Id;
      var tempTitle = item.Title;

      var LifeCycleStart = item.DeviceAvailableFrom;
      var LifeCycleStatus = item.LifeCycleStatusValue;
      var DeviceOverView = item.Description;
      var AccessDetails = item.Accessories;
      var DeviceKind = item.Devicetype;
      var Usage = item.TypicalUsage;
      //var KnownSystem = item.KnownSystemIssues

      txtTitle = "<p>" + LifeCycleStart + "</p>       <p>" +
        LifeCycleStatus + "</p>";
        txtOverview = "<p>" + DeviceOverView + "</p>";
        txtAccessories = "<p>" + AccessDetails + "</p>";
        txtDevicetype = "<p>" + DeviceKind  + "</p>";
        txtTypicalDeviceUsage = "<p>" + Usage + "</p>";
    });

    $('#devicedetails').append($(txtTitle));
    $('#deviceoverview').append($(txtOverview));
    $('#devicekind').append(txtDevicetype);
    $('#deviceacc').append(txtAccessories);
    $('#deviceuse').append(txtTypicalDeviceUsage);

  });

  call.fail(function (jqXHR,textStatus,errorThrown){
    alert("Error retrieving data: " + jqXHR.responseText);
  });
}
</code>```

答:
Momentjs can parse string like '/Date(1494460800000)/' as stated in the ASP.NET JSON Date section of the parsing doc.

In your case you can do something like:

```<code>var LifeCycleStart = moment(item.DeviceAvailableFrom).format('DD/MM/YYYY');
</code>```

using format to convert moment object to string.

Body:
I've got some JavaScript which is querying a SharePoint Date Column. The format is: DD/MM/YYYY and the results come back fine except for the date which is coming back as pictured under Device Details.

I'm trying to use the Moment.js library to format it but I'm not having any luck.
I think it's either this line:

var LifeCycleStart = item.DeviceAvailableFrom;

or this line I need to use the Moment formatting on:

$('#devicedetails').append($(txtTitle));

Full code below:

function getDeviceDetails() {
  var txtTitle = "";
  var txtOverview = "";
  var txtAccessories = "";
  var txtDevicetype = "";
  var txtTypicalDeviceUsage ="";
  var txtKnownSystemIssues ="";
  var txtLifeCycles = "";
  var tempLCS2 = "";

  var query = "http://collaboration-dev.xxx.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=LifeCycleStatus&$filter=Id eq " + window.DeviceId + "";
  var call = $.ajax({
    url: query,
    type: "GET",
    dataType: "json",
    headers: {
      Accept: "application/json;odata=verbose"
    }
  });
  call.done(function (data,textStatus, jqXHR){
    $.each(data.d.results, function(index, item) {
      var tempID = item.Id;
      var tempTitle = item.Title;

      var LifeCycleStart = item.DeviceAvailableFrom;
      var LifeCycleStatus = item.LifeCycleStatusValue;
      var DeviceOverView = item.Description;
      var AccessDetails = item.Accessories;
      var DeviceKind = item.Devicetype;
      var Usage = item.TypicalUsage;
      //var KnownSystem = item.KnownSystemIssues

      txtTitle = "
" + LifeCycleStart + "

" +
        LifeCycleStatus + "
";
        txtOverview = "
" + DeviceOverView + "
";
        txtAccessories = "
" + AccessDetails + "
";
        txtDevicetype = "
" + DeviceKind  + "
";
        txtTypicalDeviceUsage = "
" + Usage + "
";
    });

    $('#devicedetails').append($(txtTitle));
    $('#deviceoverview').append($(txtOverview));
    $('#devicekind').append(txtDevicetype);
    $('#deviceacc').append(txtAccessories);
    $('#deviceuse').append(txtTypicalDeviceUsage);

  });

  call.fail(function (jqXHR,textStatus,errorThrown){
    alert("Error retrieving data: " + jqXHR.responseText);
  });
}

Body:
Momentjs can parse string like '/Date(1494460800000)/' as stated in the ASP.NET JSON Date section of the parsing doc.

In your case you can do something like:

var LifeCycleStart = moment(item.DeviceAvailableFrom).format('DD/MM/YYYY');

using format to convert moment object to string.


问:
Angular : Uncaught ReferenceError: app is not defined
I am trying to create this very simple meanstack app and its almost running but with an uncaught reference error when it is redirecting to index page. Server is running ok. Browser is showing the text (Loading..) as in the index page. But as the custom tag  should have gone along with the selector to app.component.ts and printed "My First Angular App", it doesn't. Instead it is saying in console that "app is not defined".

Can anyone help? I am new to MEAN & Angular, so kindly elaborate. And please excuse my silly mistakes if there are any (or many).

This is my index.html

```<code><html>
<head>
<title>MyTaskList</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>System.import(app).catch(function(err){ console.error(err);});</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
</code>```

this is my app.component.ts

```<code>import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: 'My First Angular App'
})
export class AppComponent { }
</code>```

my index.js

```<code>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next){
res.render('index.html');
});

module.exports = router;
</code>```

and finally my server.js (starting point)

```<code>var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var tasks = require('./routes/tasks');

var port = 3000;

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/', index);
app.use('/api', tasks);

app.listen(port, function(){
console.log('Server started on port '+port);
});
</code>```

答: Put app in quotes because Javascript thinks app is a variable but it should actually be a string.

Body:
I am trying to create this very simple meanstack app and its almost running but with an uncaught reference error when it is redirecting to index page. Server is running ok. Browser is showing the text (Loading..) as in the index page. But as the custom tag  should have gone along with the selector to app.component.ts and printed "My First Angular App", it doesn't. Instead it is saying in console that "app is not defined".

Can anyone help? I am new to MEAN & Angular, so kindly elaborate. And please excuse my silly mistakes if there are any (or many).

This is my index.html

<title>MyTaskList</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">

<my-app>Loading...</my-app>

this is my app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: 'My First Angular App'
})
export class AppComponent { }

my index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next){
res.render('index.html');
});

module.exports = router;

and finally my server.js (starting point)

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var tasks = require('./routes/tasks');

var port = 3000;

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/', index);
app.use('/api', tasks);

app.listen(port, function(){
console.log('Server started on port '+port);
});


问:
Read Value from a merged Range (Excel)
I have a column whose header is a range of B1:C1. the data is more like

+----+----+

| Header  |

+----+----+

| H2 | H3 |

+----+----+

| 1  | 2  |

| 3  | 4  |

+----+----+

I have a variable named rng such as

```<code>Set rng = Range("B1:C1")
</code>```

now using rng variable, I want to select value "H3" or "2", or "4". I used the following syntax

```<code>rng.Offset(1,1).value
</code>```

and isntead of giving me "H3" it gave me value from next colum i.e d2.

答:
There is not a straight forward way to fix this unexpected behaviour. My understanding is that, regarding merged cells, the reference for the offset is based on the whole of the cell and that the merged cells are treated as one cell instead of many cells.

In your instance, if Range("B1:C1") is merged then the next column (i.e Offset(0,1)) is column D. Excel views the merged range as single cell and so from a visual standpoint the next column along is column D and not column C. This can be confusing in my view.

The best way to work around this is to avoid using merged cells as headers but instead use Centre Across Selection formatting:

1) De-merge Range("B1:C1")

2) Select Range("B1:C1") > Format > Cells

3) In Horizontal dialog box select 'Center Across Selection'

If you do that then the following code will work:

```<code>Sub GetOffsets()
    Dim rng As Range
    Set rng = Range("B1")

    Debug.Print rng.Offset(1, 0) // H2
    Debug.Print rng.Offset(2, 0) // 1
    Debug.Print rng.Offset(3, 0) // 3
    Debug.Print rng.Offset(1, 1) // H3
    Debug.Print rng.Offset(2, 1) // 2
    Debug.Print rng.Offset(3, 1) // 4
End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Title: Read Value from a merged Range (Excel)

Body:
I have a column whose header is a range of B1:C1. the data is more like

+----+----+

| Header  |

+----+----+

| H2 | H3 |

+----+----+

| 1  | 2  |

| 3  | 4  |

+----+----+

I have a variable named rng such as

Set rng = Range("B1:C1")

now using rng variable, I want to select value "H3" or "2", or "4". I used the following syntax

rng.Offset(1,1).value

and isntead of giving me "H3" it gave me value from next colum i.e d2.

Body:
There is not a straight forward way to fix this unexpected behaviour. My understanding is that, regarding merged cells, the reference for the offset is based on the whole of the cell and that the merged cells are treated as one cell instead of many cells.

In your instance, if Range("B1:C1") is merged then the next column (i.e Offset(0,1)) is column D. Excel views the merged range as single cell and so from a visual standpoint the next column along is column D and not column C. This can be confusing in my view.

The best way to work around this is to avoid using merged cells as headers but instead use Centre Across Selection formatting:

1) De-merge Range("B1:C1")

2) Select Range("B1:C1") > Format > Cells

3) In Horizontal dialog box select 'Center Across Selection'

If you do that then the following code will work:

Sub GetOffsets()
    Dim rng As Range
    Set rng = Range("B1")

    Debug.Print rng.Offset(1, 0) // H2
    Debug.Print rng.Offset(2, 0) // 1
    Debug.Print rng.Offset(3, 0) // 3
    Debug.Print rng.Offset(1, 1) // H3
    Debug.Print rng.Offset(2, 1) // 2
    Debug.Print rng.Offset(3, 1) // 4
End Sub


问:
Appended href Attribute not Working - Javascript
I'm setting up an alert that will slide in at the top of a page.  In the code the href attribute doesn't seem to be adding the web address. I'm not getting any errors in my console, but can't seem to find out what is causing this.  When you click on the 'Go to Google' button I've set up as a test, it should take you to Google, but it doesn't?  The code and Codepen are below, any help would be amazing.

Codepen is here: https://codepen.io/emilychews/pen/ZyGrrR

HTML

```<code><div id="header">Original Header</div>
</code>```

CSS

```<code>   * {font-family: arial;
 line-height: 100px;}

#header {width: 100%;
height: 100px;
background: red;
color: white;
text-align: center;}

div#newBar {
  width: 100%;
  height: 50px;
  background-color: blue;
  line-height: 50px;
  text-align: center;
  color: white;
}

div#topbar_button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 11%;
  height: 54%;
  background: white;
  position: relative;
  bottom: 41PX;
  margin-left: 75%;
  color: blue;
  border-radius: 2px;
}
</code>```

JAVASCRIPT

```<code>// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };
</code>```

答:
```<code>var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";
</code>```

Here you attached anchorTag to topBarButton and in next line making innerHTML to "Visit Google". Which is making anchorTag to be deleted. Change the code as below,

```<code>    var anchorTag = document.createElement('a');
            anchorTag.setAttribute('href', 'www.google.co.uk');
anchorTag.innerHTML = "Visit Google";
            topBarButton.appendChild(anchorTag);
</code>```

Body:
I'm setting up an alert that will slide in at the top of a page.  In the code the href attribute doesn't seem to be adding the web address. I'm not getting any errors in my console, but can't seem to find out what is causing this.  When you click on the 'Go to Google' button I've set up as a test, it should take you to Google, but it doesn't?  The code and Codepen are below, any help would be amazing.

Codepen is here: https://codepen.io/emilychews/pen/ZyGrrR

HTML

Original Header

CSS

   * {font-family: arial;
 line-height: 100px;}

#header {width: 100%;
height: 100px;
background: red;
color: white;
text-align: center;}

div#newBar {
  width: 100%;
  height: 50px;
  background-color: blue;
  line-height: 50px;
  text-align: center;
  color: white;
}

div#topbar_button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 11%;
  height: 54%;
  background: white;
  position: relative;
  bottom: 41PX;
  margin-left: 75%;
  color: blue;
  border-radius: 2px;
}

JAVASCRIPT

// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };

Body:
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";

Here you attached anchorTag to topBarButton and in next line making innerHTML to "Visit Google". Which is making anchorTag to be deleted. Change the code as below,

    var anchorTag = document.createElement('a');
            anchorTag.setAttribute('href', 'www.google.co.uk');
anchorTag.innerHTML = "Visit Google";
            topBarButton.appendChild(anchorTag);


问:
Retrieving Image From Firebase
The app run successfully , but the image did not show up in the table cell.</p>

```<code>let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            let pic = UIImage(data: data!)
            self.picArray.append(pic!)

        }
        self.tableViewHongKong.reloadData()
    })
</code>```

答:
You should move self.tableViewHongKong.reloadData() inside your completion handler. With your current code you reload the table before the asynchronous function would finish.

You shouldn't do force unwrapping unless you are 100% sure that data will actually return and that the UIImage initializer will succeed.

```<code>let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            guard let imageData = data, let pic = UIImage(data: imageData) else { return }
            self.picArray.append(pic)
            self.tableViewHongKong.reloadData()
        }
    })
</code>```

Title: Retrieving Image From Firebase

Body:
The app run successfully , but the image did not show up in the table cell.

let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            let pic = UIImage(data: data!)
            self.picArray.append(pic!)

        }
        self.tableViewHongKong.reloadData()
    })

Body:
You should move self.tableViewHongKong.reloadData() inside your completion handler. With your current code you reload the table before the asynchronous function would finish.

You shouldn't do force unwrapping unless you are 100% sure that data will actually return and that the UIImage initializer will succeed.

let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            guard let imageData = data, let pic = UIImage(data: imageData) else { return }
            self.picArray.append(pic)
            self.tableViewHongKong.reloadData()
        }
    })


答:
The images do not appear because you are reloading your table view before any pictures are appended to the array. The data(withMaxSize: starts an asynchronous request that gets a response after you have reloaded the table view.

If you move self.tableViewHongKong.reloadData() inside the data(withMaxSize: response block, you will reload the table view after you append each successfully loaded image.

Title: Retrieving Image From Firebase


问:
What is the difference between the Ping and WebClient classes in C#
I was looking for ways to check and report the status of a webservice, and came across both these classes. Is there any benefit in using one of these over the other?</p>

答:
Ping tells you whether a machine is accessible.

WebClient allows you to make HTTP (web) requests.

You almost certainly want the latter. Or consider HttpClient - https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx .

You may find https://stackoverflow.com/a/7523808/34092 useful as well.


问:
Remote shutdown command not working for Windows Embedded computer
Remote shutdown command not working for Windows Embedded computer. It is working fine for normal windows computers. Is there something special that we need to do for windows embedded?
I am trying to send following command from my C# program. Also tried over commandline.

```<code>shutdown /s /f /m \\192.168.100.2 /t 5 /d u:0:0 /c "The Computer is shutting down"
</code>```

Code looks like following

```<code> Process proc = new Process();
 proc.EnableRaisingEvents = false;
 proc.StartInfo.UseShellExecute = false;
 proc.StartInfo.CreateNoWindow = true;
 proc.StartInfo.FileName = "shutdown.exe";
 proc.StartInfo.UserName = adminName;
 proc.StartInfo.Password = adminPassword;
 proc.StartInfo.Domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

 proc.StartInfo.Arguments = string.Format(@" /s /f /m \\{0} /t 5 /d u:0:0 /c ""The computer is shutting down"" ", ipAddress);
 try
 {
     proc.Start();
 }
 catch( Exception ex )
 {
      // log
 }
</code>```

答:
Command line tools didn't work and I ended up writing following code to shutdown computer remotely. However the code will work also for the local computer.</p>

```<code>public void ShutdownRemotePC(string ipAddress, string adminName, string adminPassword)
        {
            try
            {
                var query = new SelectQuery("Win32_OperatingSystem");

                // create always a new management scope
                // create a default one and get immediate info if connection is be possible
                ConnectionOptions connectionOptions = new ConnectionOptions
                {
                    Impersonation = ImpersonationLevel.Impersonate,
                    EnablePrivileges = true,
                    //changed to packet privacy as some service requires it
                    Authentication = AuthenticationLevel.PacketPrivacy,
                    Username = ipAddress + @"\" + adminName,
                    Password = adminPassword,
                    Timeout = TimeSpan.FromMilliseconds(5000)
                };
                string name = @"\\" + ipAddress + @"\root\cimv2";
                ManagementScope managementScope = new ManagementScope(name, connectionOptions);

                // if already connected is checked inside connect
                managementScope.Connect();
                if( !managementScope.IsConnected )
                {
                    //Shutdown Failed. Managment Scope could not be connected.
                    return;
                }

                using( var searcher = new ManagementObjectSearcher(managementScope, query) )
                {
                    // impersonate the searcher if not allready done
                    searcher.Scope.Options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
                    searcher.Scope.Options.EnablePrivileges = true;

                    using( ManagementObjectCollection found = searcher.Get() )
                    {
                        foreach( ManagementObject os in found )
                        {
                            // Obtain in-parameters for the method
                            using( ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown") )
                            {

                                // Add the input parameters.
                                inParams["Flags"] = 12;

                                // Execute the method and obtain the return values.
                                using( ManagementBaseObject outParams = os.InvokeMethod("Win32Shutdown", inParams, null) )
                                {
                                    if( outParams != null )
                                    {
                                        var result = Convert.ToInt32(outParams["returnValue"]);
                                        if( result == 0 )
                                        {
                                            Logger.LogError("Shutdown successfully.");
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch( Exception ex )
            {
                // Shutdown PC=failed.
            }
        }
</code>```

Body:
Remote shutdown command not working for Windows Embedded computer. It is working fine for normal windows computers. Is there something special that we need to do for windows embedded?
I am trying to send following command from my C# program. Also tried over commandline.

shutdown /s /f /m \\192.168.100.2 /t 5 /d u:0:0 /c "The Computer is shutting down"

Code looks like following

 Process proc = new Process();
 proc.EnableRaisingEvents = false;
 proc.StartInfo.UseShellExecute = false;
 proc.StartInfo.CreateNoWindow = true;
 proc.StartInfo.FileName = "shutdown.exe";
 proc.StartInfo.UserName = adminName;
 proc.StartInfo.Password = adminPassword;
 proc.StartInfo.Domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

 proc.StartInfo.Arguments = string.Format(@" /s /f /m \\{0} /t 5 /d u:0:0 /c ""The computer is shutting down"" ", ipAddress);
 try
 {
     proc.Start();
 }
 catch( Exception ex )
 {
      // log
 }

Body:
Command line tools didn't work and I ended up writing following code to shutdown computer remotely. However the code will work also for the local computer.

public void ShutdownRemotePC(string ipAddress, string adminName, string adminPassword)
        {
            try
            {
                var query = new SelectQuery("Win32_OperatingSystem");

                // create always a new management scope
                // create a default one and get immediate info if connection is be possible
                ConnectionOptions connectionOptions = new ConnectionOptions
                {
                    Impersonation = ImpersonationLevel.Impersonate,
                    EnablePrivileges = true,
                    //changed to packet privacy as some service requires it
                    Authentication = AuthenticationLevel.PacketPrivacy,
                    Username = ipAddress + @"\" + adminName,
                    Password = adminPassword,
                    Timeout = TimeSpan.FromMilliseconds(5000)
                };
                string name = @"\\" + ipAddress + @"\root\cimv2";
                ManagementScope managementScope = new ManagementScope(name, connectionOptions);

                // if already connected is checked inside connect
                managementScope.Connect();
                if( !managementScope.IsConnected )
                {
                    //Shutdown Failed. Managment Scope could not be connected.
                    return;
                }

                using( var searcher = new ManagementObjectSearcher(managementScope, query) )
                {
                    // impersonate the searcher if not allready done
                    searcher.Scope.Options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
                    searcher.Scope.Options.EnablePrivileges = true;

                    using( ManagementObjectCollection found = searcher.Get() )
                    {
                        foreach( ManagementObject os in found )
                        {
                            // Obtain in-parameters for the method
                            using( ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown") )
                            {

                                // Add the input parameters.
                                inParams["Flags"] = 12;

                                // Execute the method and obtain the return values.
                                using( ManagementBaseObject outParams = os.InvokeMethod("Win32Shutdown", inParams, null) )
                                {
                                    if( outParams != null )
                                    {
                                        var result = Convert.ToInt32(outParams["returnValue"]);
                                        if( result == 0 )
                                        {
                                            Logger.LogError("Shutdown successfully.");
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch( Exception ex )
            {
                // Shutdown PC=failed.
            }
        }


问:
How to implement a Compound View/Presenter for a GWT DecoratedTabPanel?
I'm new to GWT, and I've been reviewing the MVP implementation which uses the rpcService and the eventBus.  I was wondering how a tab panel can be implemented such that each tab has its own sub-view.  I have been waffling between making a custom widget that derives from a panel, or to figuring out how to make a presenter use another presenter, or to make a compound presenter class which handles it all for me.

Does anyone have advice on how to separate the functionality for each tab as opposed to keeping the implementation within one view/presenter pair?

答:
I was in the same situation, but decided to change my implementation to simulate a TabPanel.  If your views and presenters don't need to interact with each other (e.g. dragging something from one tab to another) then I think it'll be easier to separate functionality by loading your View into a shared SimplePanel.  You can simulate the tabbed portion of the TabPanel with a widget that listens for PlaceChangeEvents (to change the highlighted tab) and sends goTo commands to the PlaceController your app is using (to handle clicks on the different headers).

It took a couple of hours to implement this, and the resulting code is much cleaner.  My initial attempt involved listening for PlaceChangeEvents and then calling the appropriate tabPanel.selectTab() function, but trying to figure out how to start and stop the presenters for the different tabs was too jumbled up - like you suggest, you'd have to implement your own compound view model.


问:
RxJava from list with async wait for callback
```<code>List<String> listExample = Arrays.asList("one", "two", "three");
</code>```

Think of i have list of string, and using RxJava (Observable.fromArray)

```<code>Observable.fromArray(ids.toArray(new String[ids.size()])).subscribe(new Consumer<String>() {
    @Override
    public void accept(@NonNull String s) throws Exception {

    }
});
</code>```

Here think each string has a Async callback here once i receive that callback it should move to next string. Is it possible using rxjava?

This is the code which i'am having currently, it doesn't wait for till the callback right!.

```<code>for (String id : ids) {
    getMessage(id, new urlGenCallback() {
        @Override
        public void urlAndToken(String url, String token, String idx) {

        }
    });
}
</code>```

Thank you @Geoffrey Marizy

Answer: Check Below
For More Info About ConcatMap Visit Here

答:
```<code>Observable.fromArray(ids.toArray(new String[ids.size()]))
        .concatMap(s -> {
            return Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                    getMessage(s, new urlGenCallback() {
                        @Override
                        public void urlAndToken(String url, String token, String id) {
                            e.onNext("......");
                            e.onComplete();
                        }
                    });
                }
            });
        }).subscribe(new Consumer<String>() {
    @Override
    public void accept(@NonNull String s) throws Exception {
       //All other code goes here
    }
});
</code>```

Body:
List<String> listExample = Arrays.asList("one", "two", "three");

Think of i have list of string, and using RxJava (Observable.fromArray)

Observable.fromArray(ids.toArray(new String[ids.size()])).subscribe(new Consumer<String>() {
    @Override
    public void accept(@NonNull String s) throws Exception {

    }
});

Here think each string has a Async callback here once i receive that callback it should move to next string. Is it possible using rxjava?

This is the code which i'am having currently, it doesn't wait for till the callback right!.

for (String id : ids) {
    getMessage(id, new urlGenCallback() {
        @Override
        public void urlAndToken(String url, String token, String idx) {

        }
    });
}

Thank you @Geoffrey Marizy

Answer: Check Below
For More Info About ConcatMap Visit Here


问:
Count number of shared observations between samples using dplyr
I have a list of observations grouped by samples. I want to find the samples that share the most identical observations. An identical observation is where the start and end number are both matching between two samples. I'd like to use R and preferably dplyr to do this if possible.
I've been getting used to using dplyr for simpler data handling but this task is beyond what I am currently able to do. I've been thinking the solution would involve grouping the start and end into a single variable: group_by(start,end) but I also need to keep the information about which sample each observation belongs to and compare between samples.

example:

```<code>sample  start   end
a   2   4
a   3   6
a   4   8
b   2   4
b   3   6
b   10  12
c   10  12
c   0   4
c   2   4
</code>```

Here samples a, b and c share 1 observation (2, 4)
sample a and b share 2 observations (2 4, 3 6)
sample b and c share 2 observations (2 4, 10 12)
sample a and c share 1 observation (2 4)

I'd like an output like:

```<code>abc 1
ab 2
bc 2
ac 1
</code>```

and also to see what the shared observations are if possible:

```<code>abc 2 4
ab 2 4
ab 3 6
</code>```

etc

Thanks in advance

答:
Here's something that should get you going:</p>

```<code>df %>%
  group_by(start, end) %>%
  summarise(
    samples = paste(unique(sample), collapse = ""),
    n = length(unique(sample)))

# Source: local data frame [5 x 4]
# Groups: start [?]
#
#   start   end samples     n
#   <int> <int>   <chr> <int>
# 1     0     4       c     1
# 2     2     4     abc     3
# 3     3     6      ab     2
# 4     4     8       a     1
# 5    10    12      bc     2
</code>```

Body:
I have a list of observations grouped by samples. I want to find the samples that share the most identical observations. An identical observation is where the start and end number are both matching between two samples. I'd like to use R and preferably dplyr to do this if possible.
I've been getting used to using dplyr for simpler data handling but this task is beyond what I am currently able to do. I've been thinking the solution would involve grouping the start and end into a single variable: group_by(start,end) but I also need to keep the information about which sample each observation belongs to and compare between samples.

example:

sample  start   end
a   2   4
a   3   6
a   4   8
b   2   4
b   3   6
b   10  12
c   10  12
c   0   4
c   2   4

Here samples a, b and c share 1 observation (2, 4)
sample a and b share 2 observations (2 4, 3 6)
sample b and c share 2 observations (2 4, 10 12)
sample a and c share 1 observation (2 4)

I'd like an output like:

abc 1
ab 2
bc 2
ac 1

and also to see what the shared observations are if possible:

abc 2 4
ab 2 4
ab 3 6

etc

Thanks in advance

Body:
Here's something that should get you going:

df %>%
  group_by(start, end) %>%
  summarise(
    samples = paste(unique(sample), collapse = ""),
    n = length(unique(sample)))

# Source: local data frame [5 x 4]
# Groups: start [?]
#
#   start   end samples     n
#   <int> <int>   <chr> <int>
# 1     0     4       c     1
# 2     2     4     abc     3
# 3     3     6      ab     2
# 4     4     8       a     1
# 5    10    12      bc     2


问:
UIViewController status bar top inset
I'm using SCPageViewController in my app:

```<code>class RootPageViewController: UIViewController {

    var pageViewController : SCPageViewController = SCPageViewController()

    var viewControllers = [UIViewController]()
    ......
</code>```

in viewDidLoad I'm configuring it:

```<code>self.pageViewController.setLayouter(SCPageLayouter(), animated: false, completion: nil)
self.pageViewController.easingFunction = SCEasingFunction(type: SCEasingFunctionType.linear)
self.pageViewController.dataSource = self;
self.pageViewController.delegate = self;
self.addChildViewController(self.pageViewController)
self.pageViewController.view.frame = self.view.bounds
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMove(toParentViewController: self)
</code>```

I'm setting size of content view controllers in SCPageViewController data source method to be size of RootPageViewController. When app launches, I have my "status bar" that is just plain UIView with background color behind system status bar. But when I'm scrolling to next/previous page, it is offset by few pixels. How I can unify that? Why I'm getting this small offset on top?

I'm using Storyboards to model view controllers:

This is how it looks after app launches (as expected):

And when I scroll to next page:

This white area shouldn't be there... Everything is fine after I rotate device.

答:
You could change the originY for the view to move it up a bit:

```<code>yourView.frame.origin.y = -5
</code>```

BUT you should take a look at your constraints and see what happens to them when you change view and see if you could solve it that way instead. Because the solution provided above will move up the view, so you will have - 5 pixels at the bottom.

Title: UIViewController status bar top inset

Body:
I'm using SCPageViewController in my app:

class RootPageViewController: UIViewController {

    var pageViewController : SCPageViewController = SCPageViewController()

    var viewControllers = [UIViewController]()
    ......

in viewDidLoad I'm configuring it:

self.pageViewController.setLayouter(SCPageLayouter(), animated: false, completion: nil)
self.pageViewController.easingFunction = SCEasingFunction(type: SCEasingFunctionType.linear)
self.pageViewController.dataSource = self;
self.pageViewController.delegate = self;
self.addChildViewController(self.pageViewController)
self.pageViewController.view.frame = self.view.bounds
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMove(toParentViewController: self)

I'm setting size of content view controllers in SCPageViewController data source method to be size of RootPageViewController. When app launches, I have my "status bar" that is just plain UIView with background color behind system status bar. But when I'm scrolling to next/previous page, it is offset by few pixels. How I can unify that? Why I'm getting this small offset on top?

I'm using Storyboards to model view controllers:

This is how it looks after app launches (as expected):

And when I scroll to next page:

This white area shouldn't be there... Everything is fine after I rotate device.

Body:
You could change the originY for the view to move it up a bit:

yourView.frame.origin.y = -5

BUT you should take a look at your constraints and see what happens to them when you change view and see if you could solve it that way instead. Because the solution provided above will move up the view, so you will have - 5 pixels at the bottom.


问:
Is it bad to have your test and production environments on the same machine?
Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test?  Both running off the same machine.  The site doesn't get a lot of traffic.

UPDATE

I am talking about an ASP.NET web application running on a Windows server.

答:
Yes, it is a bad idea.

Suppose your test code has a bug that consumes all memory/cpu/disk space? Then your production site goes down.

Have separate machines for production and test and use DNS to point the URLs to each.

Edit (more points):

If the sites share a machine, they share an IP address, so when using an IP address to access a site, you will not know whether you are on production or test.

When sharing the same machine, deployment can be tricky, you have to be extra careful not to deploy untested code to production (easier to do, since both live on the same machine).

The security considerations for production and test should be separate - this kind of setup makes it more difficult.


问:
Html code need to display image while using typerwriter javascript.Please
As title, i need codes for displaying image while typewriter javascript is typing a specify words. Please help. That code needs to both type words and display images.

var aText = new Array(
"Of cause it is about me",
"At the moment I am studying in S3D in St.Louis school and i am 15.",
"Hello.",
"I love messing around with electronics,that is my hobby since i was young.",
"So,I am quite active and brave.",
"My interst in electronic cause me to start digging into computer technology."
);
var iSpeed = 40;
var iIndex = 0;
var iArrLength = aText[0].length;
var iScrollAt = 10;

var iTextPos = 0;
var sContents = '';
var iRow;

function typewriter()
{
 sContents =  ' ';
 iRow = Math.max(0, iIndex-iScrollAt);
 var destination = document.getElementById("typedtext");

 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '
';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
 if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
 height: 100%;
 margin: 0;
 width: 100%;
 background-color: rgb(0,0,0);
}

#typedtext {
 padding-top: 20px;
 margin-left: auto;
 margin-right: auto;
 width: 80vw;
 position: relative;
 color: #CCCCCC;
 font-family: Inconsolata, monospace;
 font-size: 18px;
 font-style: normal;
 font-weight: 200;
}</code>```

c<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>My profile</title>

```

And I cannot figure a way to do it and I have searched on google.

答:
If I understood what you want... You have tried that?

*The delay it's because the image url is referenced to website.

var aText = new Array(
"That's me ",
"Of cause it is about me",
"At the moment I am studying in S3D in St.Louis school and i am 15.",
"Hello.",
"I love messing around with electronics,that is my hobby since i was young.",
"So,I am quite active and brave.",
"My interst in electronic cause me to start digging into computer technology."
);
var iSpeed = 40;
var iIndex = 0;
var iArrLength = aText[0].length;
var iScrollAt = 10;

var iTextPos = 0;
var sContents = '';
var iRow;

function typewriter()
{
 sContents =  ' ';
 iRow = Math.max(0, iIndex-iScrollAt);
 var destination = document.getElementById("typedtext");

 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '
';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
 if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
 height: 100%;
 margin: 0;
 width: 100%;
 background-color: rgb(0,0,0);
}

#typedtext {
 padding-top: 20px;
 margin-left: auto;
 margin-right: auto;
 width: 80vw;
 position: relative;
 color: #CCCCCC;
 font-family: Inconsolata, monospace;
 font-size: 18px;
 font-style: normal;
 font-weight: 200;
}</code>```

c<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>My profile</title>

```

Body:
As title, i need codes for displaying image while typewriter javascript is typing a specify words. Please help. That code needs to both type words and display images.

var aText = new Array(
"Of cause it is about me",
"At the moment I am studying in S3D in St.Louis school and i am 15.",
"Hello.",
"I love messing around with electronics,that is my hobby since i was young.",
"So,I am quite active and brave.",
"My interst in electronic cause me to start digging into computer technology."
);
var iSpeed = 40;
var iIndex = 0;
var iArrLength = aText[0].length;
var iScrollAt = 10;

var iTextPos = 0;
var sContents = '';
var iRow;

function typewriter()
{
 sContents =  ' ';
 iRow = Math.max(0, iIndex-iScrollAt);
 var destination = document.getElementById("typedtext");

 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '
';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
 if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}

html, body {
 height: 100%;
 margin: 0;
 width: 100%;
 background-color: rgb(0,0,0);
}

#typedtext {
 padding-top: 20px;
 margin-left: auto;
 margin-right: auto;
 width: 80vw;
 position: relative;
 color: #CCCCCC;
 font-family: Inconsolata, monospace;
 font-size: 18px;
 font-style: normal;
 font-weight: 200;
}

c<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>My profile</title>

And I cannot figure a way to do it and I have searched on google.

Body:
If I understood what you want... You have tried that?

*The delay it's because the image url is referenced to website.

var aText = new Array(
"That's me <img src='https://graph.facebook.com/1300943986689433/picture?type=large' alt='' width='32' height='32'>",
"Of cause it is about me",
"At the moment I am studying in S3D in St.Louis school and i am 15.",
"Hello.",
"I love messing around with electronics,that is my hobby since i was young.",
"So,I am quite active and brave.",
"My interst in electronic cause me to start digging into computer technology."
);
var iSpeed = 40;
var iIndex = 0;
var iArrLength = aText[0].length;
var iScrollAt = 10;

var iTextPos = 0;
var sContents = '';
var iRow;

function typewriter()
{
 sContents =  ' ';
 iRow = Math.max(0, iIndex-iScrollAt);
 var destination = document.getElementById("typedtext");

 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '<br />';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
 if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}

html, body {
 height: 100%;
 margin: 0;
 width: 100%;
 background-color: rgb(0,0,0);
}

#typedtext {
 padding-top: 20px;
 margin-left: auto;
 margin-right: auto;
 width: 80vw;
 position: relative;
 color: #CCCCCC;
 font-family: Inconsolata, monospace;
 font-size: 18px;
 font-style: normal;
 font-weight: 200;
}

c<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>My profile</title>
</head>
<body>
<body onload="typewriter();">
<div id="typedtext"></div>
</body>

</html>


问:
how to create httpprovider for another server
i tried to create httpprovider in eclipe and when run in wowza media server it does not load properly it returns only wowza server version.
code of eclipse is here

```<code>package com.domain.appname;

import java.io.IOException;
import java.io.OutputStream;

import com.wowza.wms.vhost.IVHost;
import com.wowza.wms.http.HTTProvider2Base;
import com.wowza.wms.http.IHTTPRequest;
import com.wowza.wms.http.IHTTPResponse;

public class CreateApp extends HTTProvider2Base {

    public void onHTTPRequest(IVHost inVhost, IHTTPRequest req, IHTTPResponse resp){

        String ret = req.getQueryString();

        resp.setHeader("Content-Type", "text/xml");

        OutputStream out = resp.getOutputStream();
        byte[] outBytes = ret.toString().getBytes();
        try {
            out.write(outBytes);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
</code>```

and also set vhost file as

```<code><HTTPProvider>
<BaseClass>com.domain.appname.CreateApp</BaseClass>
<RequestFilters>CreateProducerApp*</RequestFilters>
<AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
</code>```

Please help

答:
Please put your HTTPProvider entry in vHosts file before following block:

<HTTPProvider>
  <BaseClass>com.wowza.wms.http.HTTPServerVersion</BaseClass>
  <RequestFilters>*</RequestFilters>
  <AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
```

<p>Otherwise all of your request will give Wowza version details.</p>

<p>So, your final vhost file's end should look like:</p>

<pre class="lang-xml prettyprint-override"><code><HTTPProvider>
  <BaseClass>com.domain.appname.CreateApp</BaseClass>
  <RequestFilters>CreateProducerApp*</RequestFilters>
  <AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
<HTTPProvider>
  <BaseClass>com.wowza.wms.http.HTTPServerVersion</BaseClass>
  <RequestFilters>*</RequestFilters>
  <AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
</code>```

Body:
i tried to create httpprovider in eclipe and when run in wowza media server it does not load properly it returns only wowza server version.
code of eclipse is here

package com.domain.appname;

import java.io.IOException;
import java.io.OutputStream;

import com.wowza.wms.vhost.IVHost;
import com.wowza.wms.http.HTTProvider2Base;
import com.wowza.wms.http.IHTTPRequest;
import com.wowza.wms.http.IHTTPResponse;

public class CreateApp extends HTTProvider2Base {

    public void onHTTPRequest(IVHost inVhost, IHTTPRequest req, IHTTPResponse resp){

        String ret = req.getQueryString();

        resp.setHeader("Content-Type", "text/xml");

        OutputStream out = resp.getOutputStream();
        byte[] outBytes = ret.toString().getBytes();
        try {
            out.write(outBytes);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

and also set vhost file as

<HTTPProvider>
<BaseClass>com.domain.appname.CreateApp</BaseClass>
<RequestFilters>CreateProducerApp*</RequestFilters>
<AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>

Please help

Body:
Please put your HTTPProvider entry in vHosts file before following block:

<HTTPProvider>
  <BaseClass>com.wowza.wms.http.HTTPServerVersion</BaseClass>
  <RequestFilters>*</RequestFilters>
  <AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>

Otherwise all of your request will give Wowza version details.

So, your final vhost file's end should look like:

<HTTPProvider>
  <BaseClass>com.domain.appname.CreateApp</BaseClass>
  <RequestFilters>CreateProducerApp*</RequestFilters>
  <AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>
<HTTPProvider>
  <BaseClass>com.wowza.wms.http.HTTPServerVersion</BaseClass>
  <RequestFilters>*</RequestFilters>
  <AuthenticationMethod>none</AuthenticationMethod>
</HTTPProvider>


问:
Fire AJAX when value selected from dropdown
I'm making a simple dropdown menu that i'm showing only when a user is using a mobile device on our website. The goal is to have the user select a value and have this value post trough AJAX.

I've got this all working for non mobile devices using normal links (a href's), but on mobile devices I can't seem to get it to work. Here is what I've got so far.

My Simple dropdown menu

```<code><select id="dropdown-mobile" name="Select-item">
    <option>Select something ... </option>
    <option class="class-x" href="#" data-value="item-A" data-name="item-A" value="item-A">item-A</option>
    <option class="class-x" href="#" data-value="item-B" data-name="item-B" value="item-B">item-B</option>
    <option class="class-x" href="#" data-value="item-C" data-name="item-C" value="item-C">item-C</option>
</select>
</code>```

My AJAX script

```<code>$(document).ready(function()  {
    $('option.class-x').click(function(e){
        var datalist = $(this).data('value');
        var dataname = $(this).data('name');
        console.log(datalist,dataname);
        $.ajax({
            type: "POST",
            url: "/loop-change.php",
            data:{datalist:datalist,dataname:dataname},
            success: function(response) {

                        if ($("#content").html() != response) {
                            $('.loadscreen').delay(1000).fadeOut(500);
                        $("#content").fadeIn(3000, function() {
                            $('a').removeClass('clicked');
                        $("#content").html(response);
                            $('a[data-value = '+datalist+']').addClass('clicked');
                            $("#content").fadeIn(3000);
                            $('.loadscreen').delay(1000).fadeOut(500);
                    });
                }
            }
        });
        return false;

    });

});
</code>```

It seems like there is nothing selected. When I use this code on that normal links the console.log shows the correct information, but not the dropdown menu.

What I've tried so far:
Of course I've searched google and came across some examples, like:

```<code>$('option.class-x').change(function(e){
       // Your event handler
       alert('Selected');
    });
</code>```

Also I've tried this:

```<code>$(document).on('change', 'option.class-x', function(){
    console.log("list item selected");
    // do whatever here
});
</code>```

If I use the Bootstrap dropdown menu with my working code, it all works fine. But I think the mobile devices don't register the click function. I've read about the touch function or something. But that hasn't worked for me.

I would like to just use the normal dropdown and have the mobile device default dropdown option to show.

Like this iOS:

And this Android:

But noting works. What am I doing wrong? Here is the code from my working normal link and AJAX call (it doesn't work in Fiddle but it works on my site) https://jsfiddle.net/dk3mnk8w/. I hope someone here know what I'm doing wrong.

答:
$("#dropdown-mobile").on('change', function(){
    console.log("list item selected");
    var val = $(this).val();

    console.log(val);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<select id="dropdown-mobile" name="select">
  <option>abc</option>
   <option>abcd</option>
</select></code>```

You should change this

```<code>$(document).on('change', 'option.class-x', function(){
    console.log("list item selected");
    // do whatever here
});
</code>```

into

```<code>$("#dropdown-mobile").on('change', function(){
    console.log("list item selected");
    // do whatever here
});
</code>```

Body:
I'm making a simple dropdown menu that i'm showing only when a user is using a mobile device on our website. The goal is to have the user select a value and have this value post trough AJAX.

I've got this all working for non mobile devices using normal links (a href's), but on mobile devices I can't seem to get it to work. Here is what I've got so far.

My Simple dropdown menu

<select id="dropdown-mobile" name="Select-item">
    <option>Select something ... </option>
    <option class="class-x" href="#" data-value="item-A" data-name="item-A" value="item-A">item-A</option>
    <option class="class-x" href="#" data-value="item-B" data-name="item-B" value="item-B">item-B</option>
    <option class="class-x" href="#" data-value="item-C" data-name="item-C" value="item-C">item-C</option>
</select>

My AJAX script

$(document).ready(function()  {
    $('option.class-x').click(function(e){
        var datalist = $(this).data('value');
        var dataname = $(this).data('name');
        console.log(datalist,dataname);
        $.ajax({
            type: "POST",
            url: "/loop-change.php",
            data:{datalist:datalist,dataname:dataname},
            success: function(response) {

                        if ($("#content").html() != response) {
                            $('.loadscreen').delay(1000).fadeOut(500);
                        $("#content").fadeIn(3000, function() {
                            $('a').removeClass('clicked');
                        $("#content").html(response);
                            $('a[data-value = '+datalist+']').addClass('clicked');
                            $("#content").fadeIn(3000);
                            $('.loadscreen').delay(1000).fadeOut(500);
                    });
                }
            }
        });
        return false;

    });

});

It seems like there is nothing selected. When I use this code on that normal links the console.log shows the correct information, but not the dropdown menu.

What I've tried so far:
Of course I've searched google and came across some examples, like:

$('option.class-x').change(function(e){
       // Your event handler
       alert('Selected');
    });

Also I've tried this:

$(document).on('change', 'option.class-x', function(){
    console.log("list item selected");
    // do whatever here
});

If I use the Bootstrap dropdown menu with my working code, it all works fine. But I think the mobile devices don't register the click function. I've read about the touch function or something. But that hasn't worked for me.

I would like to just use the normal dropdown and have the mobile device default dropdown option to show.

Like this iOS:

And this Android:

But noting works. What am I doing wrong? Here is the code from my working normal link and AJAX call (it doesn't work in Fiddle but it works on my site) https://jsfiddle.net/dk3mnk8w/. I hope someone here know what I'm doing wrong.

Body:
$("#dropdown-mobile").on('change', function(){
    console.log("list item selected");
    var val = $(this).val();

    console.log(val);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<select id="dropdown-mobile" name="select">
  <option>abc</option>
   <option>abcd</option>
</select>

You should change this

$(document).on('change', 'option.class-x', function(){
    console.log("list item selected");
    // do whatever here
});

into

$("#dropdown-mobile").on('change', function(){
    console.log("list item selected");
    // do whatever here
});


问:
Firebase cloud messaging message id shows but not receiving notifications
I was able to get the message id in return but the notifications are not showing in the android device but it was working fine from the firebase console i can send to topic "nadakko" from firebase console

```<code>     <?php
 $data = array(
           "message" => "sfsdgdgdfg"
          );
  $final = array(
            "condition" => "'nadakko' in topics",
            "data" => $data
           );

  $url = 'https://fcm.googleapis.com/fcm/send';

  $headers = array(
              'Authorization: key=AIzaSyAkjY4wwambC7ryNxr-KEjsx4VgSZuh-UY',
              'Content-Type: application/json'
             );
  // Open connection
  $ch = curl_init();

  // Set the url, number of POST vars, POST data
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Disabling SSL Certificate support temporarly
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($final));
  // Execute post
  $result = curl_exec($ch);

  if ($result === FALSE) {
      // curl failed
      echo "Faild";
  }
echo $result;
  // Close connection
  curl_close($ch);
  ?>
</code>```

After sending the message i got this error from android monitor the message is received on to the mobile but there is some problem

```<code>06-07 18:06:16.139 8802-12118/info.***.*** E/MyFirebaseMessagingService: Data Payload: {message=sfsdgdgdfg}
06-07 18:06:16.139 8802-12118/info.**.**** E/MyFirebaseMessagingService: push json: {"message":"sfsdgdgdfg"}
06-07 18:06:16.139 8802-12118/info.**.*** E/MyFirebaseMessagingService: Json Exception: No value for data
</code>```

答:
```<code>06-07 18:06:16.139 8802-12118/info.**.*** E/MyFirebaseMessagingService: Json Exception: No value for data
</code>```

this is the problem, you need to read the message instead of data
use so it will be

String message = json.getString("message");

Body:
I was able to get the message id in return but the notifications are not showing in the android device but it was working fine from the firebase console i can send to topic "nadakko" from firebase console

     <?php
 $data = array(
           "message" => "sfsdgdgdfg"
          );
  $final = array(
            "condition" => "'nadakko' in topics",
            "data" => $data
           );

  $url = 'https://fcm.googleapis.com/fcm/send';

  $headers = array(
              'Authorization: key=AIzaSyAkjY4wwambC7ryNxr-KEjsx4VgSZuh-UY',
              'Content-Type: application/json'
             );
  // Open connection
  $ch = curl_init();

  // Set the url, number of POST vars, POST data
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Disabling SSL Certificate support temporarly
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($final));
  // Execute post
  $result = curl_exec($ch);

  if ($result === FALSE) {
      // curl failed
      echo "Faild";
  }
echo $result;
  // Close connection
  curl_close($ch);
  ?>

After sending the message i got this error from android monitor the message is received on to the mobile but there is some problem

06-07 18:06:16.139 8802-12118/info.***.*** E/MyFirebaseMessagingService: Data Payload: {message=sfsdgdgdfg}
06-07 18:06:16.139 8802-12118/info.**.**** E/MyFirebaseMessagingService: push json: {"message":"sfsdgdgdfg"}
06-07 18:06:16.139 8802-12118/info.**.*** E/MyFirebaseMessagingService: Json Exception: No value for data

Body:
06-07 18:06:16.139 8802-12118/info.**.*** E/MyFirebaseMessagingService: Json Exception: No value for data

this is the problem, you need to read the message instead of data
use so it will be

String message = json.getString("message");


问:
how not to fall into infinite loop with viewWillLayoutSubviews?
I have a tableView with cells and header. header consists of two views in a stack view. I set a specific height of the header every time the tableView width change.

The question: how to not fall into infinite loop? here is the code:

```<code>override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    guard let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else {
        return
    }

    UIView.animate(withDuration: 0.5, animations: { [weak self] (_) in
        self?.tableView.beginUpdates()
        if (self?.filtersView.isHidden)! {
            self?.filtersViewHeight.constant = .leastNormalMagnitude
            self?.stackView.bounds.size.height = 45
        } else {
            self?.filtersViewHeight.constant = 100
            self?.stackView.bounds.size.height = 45 + (self?.filtersViewHeight.constant)!
        }
        }, completion: { [weak self] (_) in
            flowLayout.invalidateLayout()

            self?.tableView.endUpdates() <---- this is wrong, as it forces the infinite loop.
    })
}
</code>```

答:
You should take this functionality out of viewWIllLayoutSubviews and put it into it's own function. Call that function for your animation, and call the setNeedsLayout in your animation block. viewWillLayoutSubviews can be called for many reasons.

The tableView beginUpdates and endUpdates notify the view that the tableView, or parts of it need to be redrawn, so it will call viewWillLayoutSubviews.

Body:
I have a tableView with cells and header. header consists of two views in a stack view. I set a specific height of the header every time the tableView width change.

The question: how to not fall into infinite loop? here is the code:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    guard let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else {
        return
    }

    UIView.animate(withDuration: 0.5, animations: { [weak self] (_) in
        self?.tableView.beginUpdates()
        if (self?.filtersView.isHidden)! {
            self?.filtersViewHeight.constant = .leastNormalMagnitude
            self?.stackView.bounds.size.height = 45
        } else {
            self?.filtersViewHeight.constant = 100
            self?.stackView.bounds.size.height = 45 + (self?.filtersViewHeight.constant)!
        }
        }, completion: { [weak self] (_) in
            flowLayout.invalidateLayout()

            self?.tableView.endUpdates() <---- this is wrong, as it forces the infinite loop.
    })
}


问:
Twitter Cards: "No card found (Card Error)"
On Twitter, I can't show an image card when tweeting my website https://startcrowd.club
But it works perfectly on Facebook.

I want to show this card: http://startcrowd.club/images/startcrowdimage.jpg

I tried https://cards-dev.twitter.com/validator and I got:

INFO:  Page fetched successfully

  INFO:  9 metatags were found

  ERROR: No card found (Card error)

The relevant metatags on my page https://startcrowd.club/index.html are:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta property="og:image" content="images/startcrowdimage.jpg">
```

The documentation I followed is:

https://dev.twitter.com/cards/getting-started

答:
Add:

```<code><meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://startcrowd.club/images/startcrowdimage.jpg">
</code>```

Doc: https://dev.twitter.com/cards/types/summary-large-image

Body:
On Twitter, I can't show an image card when tweeting my website https://startcrowd.club
But it works perfectly on Facebook.

I want to show this card: http://startcrowd.club/images/startcrowdimage.jpg

I tried https://cards-dev.twitter.com/validator and I got:

INFO:  Page fetched successfully

  INFO:  9 metatags were found

  ERROR: No card found (Card error)

The relevant metatags on my page https://startcrowd.club/index.html are:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta property="og:image" content="images/startcrowdimage.jpg">

The documentation I followed is:

https://dev.twitter.com/cards/getting-started

Body:
Add:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://startcrowd.club/images/startcrowdimage.jpg">

Doc: https://dev.twitter.com/cards/types/summary-large-image


问:
Spring Security Child Thread Context
So I'm working on this Spring MVC application using Spring Security. I've been hitting a performance problem in some instances where my controller is taking way too long to respond.
This is due to a processing method that can take a huge amount of data in to process, based on some user input.

Now I've been tweaking the code a bit in and around that processing method with my team and I don't think we can get much better performance out of that without slicing it and executing each slice asynchronously.

The problem is when I try to slice it and distribute the work to child threads, using a threadpool from java.util.concurrent, I get error messages about the security context when those execute.

Here is an extract of the stacktrace:

```<code>Exception in thread "pool-1-thread-3" org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
    at org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:63)
Exception in thread "pool-1-thread-4"   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy63.batchSaveCampaignpayment(Unknown Source)
    at com.fim.pnp.controller.PaymentForm$1.run(PaymentForm.java:224)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)
org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
    at org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:63)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy63.batchSaveCampaignPayment(Unknown Source)
    at com.fim.pnp.controller.PaymentForm$1.run(PaymentForm.java:224)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)
Exception in thread "pool-1-thread-5" org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
    at org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:63)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy63.batchSaveCampaignPayment(Unknown Source)
    at com.fim.pnp.controller.PaymentForm$1.run(PaymentForm.java:224)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)
</code>```

I know it's not good practice to spawn threads from a request... but we've ran out of ideas at this point and each worker thread shouldn't take more than a handful of seconds by our measurements. Also it is expected that this feature is going to be used by 1 or 2 dedicated users once a week only.

Is there a way to pass the securityContext to the child threads or anything similar that would allow those threads to execute?

Thanks

答:
I found two solutions when I had a similar problem:

Solution 1
Change strategy of SecurityContextHolder to MODE_INHERITABLETHREADLOCAL

You may do it in such way

```<code><beans:bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <beans:property name="targetClass"
              value="org.springframework.security.core.context.SecurityContextHolder"/>
    <beans:property name="targetMethod" value="setStrategyName"/>
    <beans:property name="arguments" value="MODE_INHERITABLETHREADLOCAL"/>
</beans:bean>
</code>```

Solution 2 Use DelegatingSecurityContextRunnable, DelegatingSecurityContextExecutor or DelegatingSecurityContextExecutor. This soulution is well described in Spring Concurrency Support Documentation

Title: Spring Security Child Thread Context

Body:
So I'm working on this Spring MVC application using Spring Security. I've been hitting a performance problem in some instances where my controller is taking way too long to respond.
This is due to a processing method that can take a huge amount of data in to process, based on some user input.

Now I've been tweaking the code a bit in and around that processing method with my team and I don't think we can get much better performance out of that without slicing it and executing each slice asynchronously.

The problem is when I try to slice it and distribute the work to child threads, using a threadpool from java.util.concurrent, I get error messages about the security context when those execute.

Here is an extract of the stacktrace:

Exception in thread "pool-1-thread-3" org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
    at org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:63)
Exception in thread "pool-1-thread-4"   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy63.batchSaveCampaignpayment(Unknown Source)
    at com.fim.pnp.controller.PaymentForm$1.run(PaymentForm.java:224)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)
org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
    at org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:63)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy63.batchSaveCampaignPayment(Unknown Source)
    at com.fim.pnp.controller.PaymentForm$1.run(PaymentForm.java:224)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)
Exception in thread "pool-1-thread-5" org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
    at org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:63)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy63.batchSaveCampaignPayment(Unknown Source)
    at com.fim.pnp.controller.PaymentForm$1.run(PaymentForm.java:224)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)

I know it's not good practice to spawn threads from a request... but we've ran out of ideas at this point and each worker thread shouldn't take more than a handful of seconds by our measurements. Also it is expected that this feature is going to be used by 1 or 2 dedicated users once a week only.

Is there a way to pass the securityContext to the child threads or anything similar that would allow those threads to execute?

Thanks

Body:
I found two solutions when I had a similar problem:

Solution 1
Change strategy of SecurityContextHolder to MODE_INHERITABLETHREADLOCAL

You may do it in such way

<beans:bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <beans:property name="targetClass"
              value="org.springframework.security.core.context.SecurityContextHolder"/>
    <beans:property name="targetMethod" value="setStrategyName"/>
    <beans:property name="arguments" value="MODE_INHERITABLETHREADLOCAL"/>
</beans:bean>

Solution 2 Use DelegatingSecurityContextRunnable, DelegatingSecurityContextExecutor or DelegatingSecurityContextExecutor. This soulution is well described in Spring Concurrency Support Documentation


问:
Convert binary number 5 into list of intergers (4,1)
I have a configuration value expressed as a binary number to allow several options within the same value.

E.g. the value of 5 would be "101" or both 4 and 1.

Does anyone know of the best/fastest way to "input" the value '5' and get a list of {1,4} back?

答:
To show binary representation use

```<code> int value = 7;
 var binary = Convert.ToString(value, 2);
</code>```

To see binary numbers:

```<code>    private int[] ToBinaryNumbers(int value)
    {
        var binary = Convert.ToString(value, 2).Reverse();
        int ix = 0;
        return binary.Select(x => { var res = x == '1' ? (int?)Math.Pow(2, ix) : (int?)null; ix++; return res; }).Where(x => x.HasValue).Select(x => x.Value).ToArray();
    }
</code>```

This will give you 1,2,4 for 7 or 1,8 for 9

Body:
To show binary representation use

 int value = 7;
 var binary = Convert.ToString(value, 2);

To see binary numbers:

    private int[] ToBinaryNumbers(int value)
    {
        var binary = Convert.ToString(value, 2).Reverse();
        int ix = 0;
        return binary.Select(x => { var res = x == '1' ? (int?)Math.Pow(2, ix) : (int?)null; ix++; return res; }).Where(x => x.HasValue).Select(x => x.Value).ToArray();
    }

This will give you 1,2,4 for 7 or 1,8 for 9


问:
enable CORS over AWS CLI
we got an Angular2 App which is hosted on an S3 Bucket and sends calls to an Backend behind an API Gateway.

This works perfectly if we enable CORS by ourself at the API Gateway, but if we change something in our Backend and we deploy it with our api_deploy.sh skript, it usally resets some of the CORS configs.

```<code>aws apigateway create-deployment --rest-api-id XXXXXX --stage-name $1 --description "$2"
</code>```

Is there a solution that we dont have to change it by ourself evrytime? I guess the Amazon CLI could help, but nothing seems to work so far.

答:
You could rather use CloudFormation / SAM to deploy your API Gateway.

After you enable CORS on your endpoints, try the following:

Export your API as a Swagger file with API Gateway Extensions (e.g. swagger-stage.yaml),

Create a template file that points to a swagger file on your local drive, e.g. template.yaml:

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: API deployment
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      DefinitionUri: ./swagger-stage.yaml
      StageName: Staging
Outputs:
  ApiUrl:
    Description: URL of the API endpoint
    Value: !Join
      - ''
      - - https://
        - !Ref ApiGatewayApi
        - '.execute-api.'
        - !Ref 'AWS::Region'
        - '.amazonaws.com/staging'
</code>```

Deploy your stack to AWS CloudFormation with a few simple commands, e.g., deploy.sh:

```<code>#!/bin/bash
aws s3 mb --region eu-west-1 s3://cloudformation-uploads # only needed if bucket does not exist yet
aws cloudformation package --template-file template.yaml --s3-bucket cloudformation-uploads --output-template-file template.pkg.yaml
aws cloudformation deploy --template-file template.pkg.yaml --stack-name api-deploy-stack
</code>```

Title: enable CORS over AWS CLI

Body:
we got an Angular2 App which is hosted on an S3 Bucket and sends calls to an Backend behind an API Gateway.

This works perfectly if we enable CORS by ourself at the API Gateway, but if we change something in our Backend and we deploy it with our api_deploy.sh skript, it usally resets some of the CORS configs.

aws apigateway create-deployment --rest-api-id XXXXXX --stage-name $1 --description "$2"

Is there a solution that we dont have to change it by ourself evrytime? I guess the Amazon CLI could help, but nothing seems to work so far.

Body:
You could rather use CloudFormation / SAM to deploy your API Gateway.

After you enable CORS on your endpoints, try the following:

Export your API as a Swagger file with API Gateway Extensions (e.g. swagger-stage.yaml),

Create a template file that points to a swagger file on your local drive, e.g. template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: API deployment
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      DefinitionUri: ./swagger-stage.yaml
      StageName: Staging
Outputs:
  ApiUrl:
    Description: URL of the API endpoint
    Value: !Join
      - ''
      - - https://
        - !Ref ApiGatewayApi
        - '.execute-api.'
        - !Ref 'AWS::Region'
        - '.amazonaws.com/staging'

Deploy your stack to AWS CloudFormation with a few simple commands, e.g., deploy.sh:

#!/bin/bash
aws s3 mb --region eu-west-1 s3://cloudformation-uploads # only needed if bucket does not exist yet
aws cloudformation package --template-file template.yaml --s3-bucket cloudformation-uploads --output-template-file template.pkg.yaml
aws cloudformation deploy --template-file template.pkg.yaml --stack-name api-deploy-stack