问:
How do I size a font in CSS/JS to have a certain margin on the sides relative to its container?
I can make a font relative sized to the viewport (if I just put it in the body), with 200vh, etc. But how do I make it sized to perfectly fit within the container? That is, I want a certain margin such as 8% of the width to be on each side of the text, and for the text to fill the remaining 84%. How can I do this with HTML/JS/CSS?

body {
  font-size: 70vh;
  display: flex;
  text-align: center;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>hello</code>```

答:
This approach is not pixel perfect, but it will have an approximate result.

By wrapping the text, such as in a , you can get the initial text width and font size, which will be used to calculate the final font size using also the width of the container.

window.addEventListener('resize', calcFontSize);

var textEl = document.querySelector('span'),
textElParent = textEl.parentNode,
textFontSize = parseFloat(window.getComputedStyle(textEl, null).getPropertyValue('font-size')),
textWidth = textEl.clientWidth,
spaceToFill;

function calcFontSize() {
  spaceToFill = textElParent.clientWidth;
  textEl.style.fontSize = (spaceToFill * textFontSize)/textWidth + "px";
}

calcFontSize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  background-color: #fff;
}
body {
  background-color: #f3f3f3;
  display: flex;
  text-align: center;
  justify-content: center;
  margin: 0 8%;
}</code>```

  hello
```

Body:
I can make a font relative sized to the viewport (if I just put it in the body), with 200vh, etc. But how do I make it sized to perfectly fit within the container? That is, I want a certain margin such as 8% of the width to be on each side of the text, and for the text to fill the remaining 84%. How can I do this with HTML/JS/CSS?

body {
  font-size: 70vh;
  display: flex;
  text-align: center;
  justify-content: center;
}

hello

Body:
This approach is not pixel perfect, but it will have an approximate result.

By wrapping the text, such as in a <span>, you can get the initial text width and font size, which will be used to calculate the final font size using also the width of the container.

window.addEventListener('resize', calcFontSize);

var textEl = document.querySelector('span'),
textElParent = textEl.parentNode,
textFontSize = parseFloat(window.getComputedStyle(textEl, null).getPropertyValue('font-size')),
textWidth = textEl.clientWidth,
spaceToFill;

function calcFontSize() {
  spaceToFill = textElParent.clientWidth;
  textEl.style.fontSize = (spaceToFill * textFontSize)/textWidth + "px";
}

calcFontSize();

html {
  background-color: #fff;
}
body {
  background-color: #f3f3f3;
  display: flex;
  text-align: center;
  justify-content: center;
  margin: 0 8%;
}

<body>
  <span>hello</span>
</body>


来源: stackexchange

问:
Better way to convert a string field into timestamp in Spark
I have a CSV in which a field is datetime in a specific format. I cannot import it directly in my Dataframe because it needs to be a timestamp. So I import it as string and convert it into a Timestamp like this

```<code>import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.sql.Row

def getTimestamp(x:Any) : Timestamp = {
    val format = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss")
    if (x.toString() == "")
    return null
    else {
        val d = format.parse(x.toString());
        val t = new Timestamp(d.getTime());
        return t
    }
}

def convert(row : Row) : Row = {
    val d1 = getTimestamp(row(3))
    return Row(row(0),row(1),row(2),d1)
}
</code>```

Is there a better, more concise way to do this, with the Dataframe API or spark-sql? The above method requires the creation of an RDD and to give the schema for the Dataframe again.

答:
Spark Version: 2.4.4</p>

```<code>scala> import org.apache.spark.sql.types.TimestampType
import org.apache.spark.sql.types.TimestampType

scala> val df = Seq("2019-04-01 08:28:00").toDF("ts")
df: org.apache.spark.sql.DataFrame = [ts: string]

scala> val df_mod = df.select($"ts".cast(TimestampType))
df_mod: org.apache.spark.sql.DataFrame = [ts: timestamp]

scala> df_mod.printSchema()
root
 |-- ts: timestamp (nullable = true)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a CSV in which a field is datetime in a specific format. I cannot import it directly in my Dataframe because it needs to be a timestamp. So I import it as string and convert it into a Timestamp like this

import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.sql.Row

def getTimestamp(x:Any) : Timestamp = {
    val format = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss")
    if (x.toString() == "")
    return null
    else {
        val d = format.parse(x.toString());
        val t = new Timestamp(d.getTime());
        return t
    }
}

def convert(row : Row) : Row = {
    val d1 = getTimestamp(row(3))
    return Row(row(0),row(1),row(2),d1)
}

Is there a better, more concise way to do this, with the Dataframe API or spark-sql? The above method requires the creation of an RDD and to give the schema for the Dataframe again.

Body:
Spark Version: 2.4.4

scala> import org.apache.spark.sql.types.TimestampType
import org.apache.spark.sql.types.TimestampType

scala> val df = Seq("2019-04-01 08:28:00").toDF("ts")
df: org.apache.spark.sql.DataFrame = [ts: string]

scala> val df_mod = df.select($"ts".cast(TimestampType))
df_mod: org.apache.spark.sql.DataFrame = [ts: timestamp]

scala> df_mod.printSchema()
root
 |-- ts: timestamp (nullable = true)

ContentLicense: CC BY-SA 4.0


问:
Enforcing type checking in Python functions
I am trying to write Python functions that enforce type checking. The way I would attempt to do this is using assert and isinstance() in the first line of the function like so:

```<code>import numpy as np
import pandas as pd

array_like = Union[pd.core.series.Series, np.ndarray]
LOG_TRANSFORM_CONST = 1.01

def log_transform(feature: array_like) -> array_like:
    assert isinstance(feature, array_like)

    # First remove negative entries
    feature[feature < 0.0] = 0.0

    # Add a small constant to avoid NANs while applying logs
    feature = feature + LOG_TRANSFORM_CONST

    return np.log(feature)
</code>```

This code does not work as you cannot use Union along with isinstance(). However, the following piece of code does work:

```<code>def log_transform(feature: array_like) -> array_like:
    assert type(feature) in [pd.core.series.Series, np.ndarray]

    # First remove negative entries
    feature[feature < 0.0] = 0.0

    # Add a small constant to avoid NANs while applying logs
    feature = feature + LOG_TRANSFORM_CONST

    return np.log(feature)

if __name__ == '__main__':
    df = pd.DataFrame(columns=['A', 'B'])
    df['A'] = [1, 2, 3, 4]
    df['B'] = [10, 20, 30, 40]
    tr_arr = log_transform(df.A)
    print(tr_arr)
    y = log_transform(np.array([2, 4, 6, 8, 10]))
    print(y)
</code>```

My question is whether this practice is advisable. What are best practices regarding type checking in Python? I know that one can install third-party libraries specifically for type checking, but I'm trying to avoid that.

答:
The pythonic way is to use isinstance(), however isinstance takes a type or a tuple of types, rather than a union. It won't take a list or anything else, only a tuple. Personally I find this slightly annoying as I rarely find myself using python tuples, but that's besides the point.

If you change your array_like Union to:

```<code>array_like = (pd.core.series.Series, np.ndarray)
</code>```

then your code will work with assert isinstance(feature, array_like)

Full Code:

```<code>import numpy as np
import pandas as pd
from typing import Union

array_like = (pd.core.series.Series, np.ndarray)
LOG_TRANSFORM_CONST = 1.01

def log_transform(feature: array_like) -> array_like:
    assert isinstance(feature, array_like)

    # First remove negative entries
    feature[feature < 0.0] = 0.0

    # Add a small constant to avoid NANs while applying logs
    feature = feature + LOG_TRANSFORM_CONST

    return np.log(feature)

if __name__ == '__main__':
    df = pd.DataFrame(columns=['A', 'B'])
    df['A'] = [1, 2, 3, 4]
    df['B'] = [10, 20, 30, 40]
    tr_arr = log_transform(df.A)
    print(tr_arr)
    y = log_transform(np.array([2, 4, 6, 8, 10]))
    print(y)
</code>```

Hopefully this helps!

Body:
I am trying to write Python functions that enforce type checking. The way I would attempt to do this is using assert and isinstance() in the first line of the function like so:

import numpy as np
import pandas as pd

array_like = Union[pd.core.series.Series, np.ndarray]
LOG_TRANSFORM_CONST = 1.01

def log_transform(feature: array_like) -> array_like:
    assert isinstance(feature, array_like)

    # First remove negative entries
    feature[feature < 0.0] = 0.0

    # Add a small constant to avoid NANs while applying logs
    feature = feature + LOG_TRANSFORM_CONST

    return np.log(feature)

This code does not work as you cannot use Union along with isinstance(). However, the following piece of code does work:

def log_transform(feature: array_like) -> array_like:
    assert type(feature) in [pd.core.series.Series, np.ndarray]

    # First remove negative entries
    feature[feature < 0.0] = 0.0

    # Add a small constant to avoid NANs while applying logs
    feature = feature + LOG_TRANSFORM_CONST

    return np.log(feature)

if __name__ == '__main__':
    df = pd.DataFrame(columns=['A', 'B'])
    df['A'] = [1, 2, 3, 4]
    df['B'] = [10, 20, 30, 40]
    tr_arr = log_transform(df.A)
    print(tr_arr)
    y = log_transform(np.array([2, 4, 6, 8, 10]))
    print(y)

My question is whether this practice is advisable. What are best practices regarding type checking in Python? I know that one can install third-party libraries specifically for type checking, but I'm trying to avoid that.

Body:
The pythonic way is to use isinstance(), however isinstance takes a type or a tuple of types, rather than a union. It won't take a list or anything else, only a tuple. Personally I find this slightly annoying as I rarely find myself using python tuples, but that's besides the point.

If you change your array_like Union to:

array_like = (pd.core.series.Series, np.ndarray)

then your code will work with assert isinstance(feature, array_like)

Full Code:

import numpy as np
import pandas as pd
from typing import Union

array_like = (pd.core.series.Series, np.ndarray)
LOG_TRANSFORM_CONST = 1.01

def log_transform(feature: array_like) -> array_like:
    assert isinstance(feature, array_like)

    # First remove negative entries
    feature[feature < 0.0] = 0.0

    # Add a small constant to avoid NANs while applying logs
    feature = feature + LOG_TRANSFORM_CONST

    return np.log(feature)

if __name__ == '__main__':
    df = pd.DataFrame(columns=['A', 'B'])
    df['A'] = [1, 2, 3, 4]
    df['B'] = [10, 20, 30, 40]
    tr_arr = log_transform(df.A)
    print(tr_arr)
    y = log_transform(np.array([2, 4, 6, 8, 10]))
    print(y)

Hopefully this helps!


问:
Is there a better way to mimic do notation in JS?
Monadic computations quickly become confusing in JS:

const chain = fm => xs =>
  xs.reduce((acc, x) => acc.concat(fm(x)), []);

const of = x => [x];

const main = xs => ys => zs =>
  chain(x =>
    x === 0
      ? []
      : chain(y =>
          chain(z => [[x, y, z]]) (zs)) (ys)) (xs);

console.log("run to completion",
  main([1, 2]) (["a", "b"]) ([true, false]));

console.log("short circuiting",
  main([0, 2]) (["a", "b"]) ([true, false]));```
</div>
</div>
</p>

<p>In Haskell <code>do</code> notation can be used to hide the nested function calls. However, <code>do</code> is a compile time technique that Javascript lacks.</p>

<p>Generator functions seem to be a good fit, but they don't work with monads that supply a priorized choice. So I have been looking for an alternative for quite some time and recently came up with a sort of monadic applicator in order to untangle the nested computation a bit:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const chain = fm => xs =>
  xs.reduce((acc, x) => acc.concat(fm(x)), []);

const of = x => [x];

const id = x => x;

const infixM3 = (w, f, x, g, y, h, z) =>
  f(x_ =>
    w(x_, w_ => g(y_ =>
      w_(y_, w__ => h(z_ =>
        w__(z_, id)) (z))) (y))) (x);

const mainApp = xs => ys => zs => infixM3(
  (x, k) =>
    x === 0
      ? []
      : k((y, k) =>
          k((z, k) => [[x, y, z]])),
  chain, xs,
  chain, ys,
  chain, zs);

console.log("run to completion",
  mainApp([1, 2]) (["a", "b"]) ([true, false]));

console.log("short circuiting",
  mainApp([0, 2]) (["a", "b"]) ([true, false]));</code>```

The applicator mimics chain in infix position hence the name. It is based on local continuations, therefore the lifted function expects a pair of arguments constisting of the bound value and the continuation respectively. If the continuation isn't applied the computation short circuits. It looks complicated but is rather a mechanical process.

Comparing the explicit version with the abstracted one I think this is an improvement in terms of readability:

```<code>chain(x =>
  x === 0
    ? []
    : chain(y =>
        chain(z => [[x, y, z]]) (zs)) (ys)) (xs);

infixM3(
  (x, k) =>
    x === 0
      ? []
      : k((y, k) =>
          k((z, k) => [[x, y, z]])),
  chain, xs,
  chain, ys,
  chain, zs);
</code>```

The continuations in the lifted function bother though as well as the fact that the applicator is arity aware. Besides it doesn't look like do-notation at all. Can we get closer to a syntax that resembles do notation?

答:
You can use the immutagen library to write monadic code using generators.

const monad = bind => regen => (...args) => function loop({ value, next }) {
    return next ? bind(value, val => loop(next(val))) : value;
}(immutagen.default(regen)(...args));

const flatMap = (array, callback) => array.flatMap(callback);

const list = monad(flatMap);

const main = list(function* (xs, ys, zs) {
    const x = yield xs;
    if (x === 0) return [];
    const y = yield ys;
    const z = yield zs;
    return [[x, y, z]];
});

console.log("run to completion", main([1, 2], ["a", "b"], [true, false]));

console.log("short circuiting", main([0, 2], ["a", "b"], [true, false]));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```
</div>
</div>
</p>

<p>As you can see, this works with non-deterministic monads too. However, it has two disadvantages.</p>

<ol>
<li>It's inefficient because multiple generators need to be created and replayed, leading to quadratic growth in time complexity.</li>
<li>It only works for pure monads and pure computations because multiple generators need to be created and replayed. Hence, side effects would be incorrectly executed multiple times.</li>
</ol>

<p>Nevertheless, even if you don't use generators writing monadic code in JavaScript isn't so bad.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const flatMap = (array, callback) => array.flatMap(callback);

const main = (xs, ys, zs) =>
    flatMap(xs, x =>
    x === 0 ? [] :
    flatMap(ys, y =>
    flatMap(zs, z =>
    [[x, y, z]])));

console.log("run to completion", main([1, 2], ["a", "b"], [true, false]));

console.log("short circuiting", main([0, 2], ["a", "b"], [true, false]));</code>```

.as-console-wrapper { max-height: 100% !important; top: 0; }```

At the end of the day, if you want the best of both worlds then you'll either need to use a language that compiles to JavaScript or use a preprocessor like Babel or sweet.js.

Body:
Monadic computations quickly become confusing in JS:

const chain = fm => xs =>
  xs.reduce((acc, x) => acc.concat(fm(x)), []);

const of = x => [x];

const main = xs => ys => zs =>
  chain(x =>
    x === 0
      ? []
      : chain(y =>
          chain(z => [[x, y, z]]) (zs)) (ys)) (xs);

console.log("run to completion",
  main([1, 2]) (["a", "b"]) ([true, false]));

console.log("short circuiting",
  main([0, 2]) (["a", "b"]) ([true, false]));

In Haskell do notation can be used to hide the nested function calls. However, do is a compile time technique that Javascript lacks.

Generator functions seem to be a good fit, but they don't work with monads that supply a priorized choice. So I have been looking for an alternative for quite some time and recently came up with a sort of monadic applicator in order to untangle the nested computation a bit:

const chain = fm => xs =>
  xs.reduce((acc, x) => acc.concat(fm(x)), []);

const of = x => [x];

const id = x => x;

const infixM3 = (w, f, x, g, y, h, z) =>
  f(x_ =>
    w(x_, w_ => g(y_ =>
      w_(y_, w__ => h(z_ =>
        w__(z_, id)) (z))) (y))) (x);

const mainApp = xs => ys => zs => infixM3(
  (x, k) =>
    x === 0
      ? []
      : k((y, k) =>
          k((z, k) => [[x, y, z]])),
  chain, xs,
  chain, ys,
  chain, zs);

console.log("run to completion",
  mainApp([1, 2]) (["a", "b"]) ([true, false]));

console.log("short circuiting",
  mainApp([0, 2]) (["a", "b"]) ([true, false]));

The applicator mimics chain in infix position hence the name. It is based on local continuations, therefore the lifted function expects a pair of arguments constisting of the bound value and the continuation respectively. If the continuation isn't applied the computation short circuits. It looks complicated but is rather a mechanical process.

Comparing the explicit version with the abstracted one I think this is an improvement in terms of readability:

chain(x =>
  x === 0
    ? []
    : chain(y =>
        chain(z => [[x, y, z]]) (zs)) (ys)) (xs);

infixM3(
  (x, k) =>
    x === 0
      ? []
      : k((y, k) =>
          k((z, k) => [[x, y, z]])),
  chain, xs,
  chain, ys,
  chain, zs);

The continuations in the lifted function bother though as well as the fact that the applicator is arity aware. Besides it doesn't look like do-notation at all. Can we get closer to a syntax that resembles do notation?

Body:
You can use the immutagen library to write monadic code using generators.

const monad = bind => regen => (...args) => function loop({ value, next }) {
    return next ? bind(value, val => loop(next(val))) : value;
}(immutagen.default(regen)(...args));

const flatMap = (array, callback) => array.flatMap(callback);

const list = monad(flatMap);

const main = list(function* (xs, ys, zs) {
    const x = yield xs;
    if (x === 0) return [];
    const y = yield ys;
    const z = yield zs;
    return [[x, y, z]];
});

console.log("run to completion", main([1, 2], ["a", "b"], [true, false]));

console.log("short circuiting", main([0, 2], ["a", "b"], [true, false]));

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/immutagen@1.0.9/immutagen.js"></script>

As you can see, this works with non-deterministic monads too. However, it has two disadvantages.

It's inefficient because multiple generators need to be created and replayed, leading to quadratic growth in time complexity.

It only works for pure monads and pure computations because multiple generators need to be created and replayed. Hence, side effects would be incorrectly executed multiple times.

Nevertheless, even if you don't use generators writing monadic code in JavaScript isn't so bad.

const flatMap = (array, callback) => array.flatMap(callback);

const main = (xs, ys, zs) =>
    flatMap(xs, x =>
    x === 0 ? [] :
    flatMap(ys, y =>
    flatMap(zs, z =>
    [[x, y, z]])));

console.log("run to completion", main([1, 2], ["a", "b"], [true, false]));

console.log("short circuiting", main([0, 2], ["a", "b"], [true, false]));

.as-console-wrapper { max-height: 100% !important; top: 0; }

At the end of the day, if you want the best of both worlds then you'll either need to use a language that compiles to JavaScript or use a preprocessor like Babel or sweet.js.


问:
Deserialize json object from a combobox data (loaded from database) Winform
Good morning, I'm having a hard time finding solution to my problem. I have a combobox which is populated using datasource which is from DB and those data where JSON objects. How will I deserialize those data?
This is the JSON data from Database:

{"displayname":{"value":"Test","scope":"contacts","verified":"0"},"address":{"value":"","scope":"private","verified":"0"},"website":{"value":"","scope":"private","verified":"0"},"email":{"value":"","scope":"contacts","verified":"0"},"avatar":{"scope":"contacts","verified":"0"},"phone":{"value":"01234567890","scope":"private","verified":"0"},"twitter":{"value":"","scope":"private","verified":"0"}}

And below is what will be shown in the combobox. I don't want a JSON object in my combobox but instead a deserialized data. Ex: I want to only show the names in my combobox which is the value under displayname in JSON Object.

答:
Create a class as your Combo box Data Source like this,

```<code>public class Displayname
{
    public string scope;
    public string value; // as your display member in combobox
    public int verified;
}
public class MyData
{
    public string address;
    public Displayname displayname;
}
</code>```

then deserialize your JSON to an object of MyData like this

```<code>string json = @"{
                'displayname': {'value' : 'james@example.com',
  'scope': 'contacts'},
  'verified': '0' } ,  'address':'blabla' ";
    var t = JsonConvert.DeserializeObject<MyData>(json);
combobox.datasource = t.displayname; // not sure about syntax of this line,
</code>```

Then in combobox property set the display member as value (this is the name of the property you have in your json and also you have in Deserialized class which is Displayname). exactly write the the name of the property that you want.

by the way, value is not good name for display member and the json string you provided I believe is not right json. good luck

Body:
Create a class as your Combo box Data Source like this,

public class Displayname
{
    public string scope;
    public string value; // as your display member in combobox
    public int verified;
}
public class MyData
{
    public string address;
    public Displayname displayname;
}

then deserialize your JSON to an object of MyData like this

string json = @"{
                'displayname': {'value' : 'james@example.com',
  'scope': 'contacts'},
  'verified': '0' } ,  'address':'blabla' ";
    var t = JsonConvert.DeserializeObject<MyData>(json);
combobox.datasource = t.displayname; // not sure about syntax of this line,

Then in combobox property set the display member as value (this is the name of the property you have in your json and also you have in Deserialized class which is Displayname). exactly write the the name of the property that you want.

by the way, value is not good name for display member and the json string you provided I believe is not right json. good luck


问:
How can i display Sales made by customer in customers detail page
How can i display data from Multiple Model. I have customer and Sale Table, when View detail slected i want to see the sales made by the selected Customer.

Customer Model

```<code>namespace MasterDetailMVC.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Customer
    {
        public Customer()
        {
            this.Sales = new HashSet<Sale>();
        }

        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string MiddleInitial { get; set; }
        public string LastName { get; set; }

       public virtual ICollection<Sale> Sales { get; set; }
    }
  }
</code>```

Sale Model

```<code>namespace MasterDetailMVC.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Sale
    {
        public int SalesID { get; set; }
        public int SalesPersonID { get; set; }
        public int CustomerID { get; set; }
        public int ProductID { get; set; }
        public int Quantity { get; set; }

        public virtual Customer Customer { get; set; }
        public virtual Employee Employee { get; set; }
        public virtual Product Product { get; set; }
    }
}
</code>```

Customer Controller

```<code>namespace MasterDetailMVC.Controllers
{
public class CustomersController : Controller
{
private salesdbEntities db = new salesdbEntities();
// GET: Customers
public ActionResult Index()
{
 return View(db.Customers.ToList());
 }
 // GET: Customers/Details/5
 public ActionResult Details(int? id)
 {
 Customer customer = db.Customers.Find(id);
  if (customer == null)
  {
  return HttpNotFound();
 }
  return View(customer);
 }
 }
</code>```

Index View

```<code>@model IEnumerable<MasterDetailMVC.Models.Customer>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MiddleInitial)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MiddleInitial)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
            @Html.ActionLink("Details", "Details", new { id=item.CustomerID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID })
        </td>
    </tr>
}

</table>
</code>```

Detail View

```<code>@model MasterDetailMVC.Models.Customer

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Customer</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.MiddleInitial)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.MiddleInitial)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.CustomerID }) |
    @Html.ActionLink("Back to List", "Index")
</p>
</code>```

when i go this link Customers/Details/5 I want to display sales mad by this customer in a Table or grid.

sales Table looks like this

```<code>SELECT TOP (1000) [SalesID]
      ,[SalesPersonID]
      ,[CustomerID]
      ,[ProductID]
      ,[Quantity]
  FROM [salesdb].[dbo].[Sales]
</code>```

Product Table looks Like this

```<code>SELECT TOP (1000) [ProductID]
      ,[Name]
      ,[Price]
  FROM [salesdb].[dbo].[Products]
</code>```

Sales Person/Employee Table

```<code> SELECT TOP (1000) [EmployeeID]
      ,[FirstName]
      ,[MiddleInitial]
      ,[LastName]
  FROM [salesdb].[dbo].[Employees]
</code>```

答:
Model

You need to create CustomerViewModel

```<code>public class CustomerViewModel
{
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string MiddleInitial { get; set; }
    public string LastName { get; set; }

    public List<SaleViewModel> Sales { get; set; }
}
</code>```

and SaleViewModel like below

```<code>public class SaleViewModel
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
}
</code>```

Controller

You can get a list of view SaleViewModel by joining between Sales and Products table like below

```<code>var sales = (from s in db.Sales
                join p in db.Products on s.ProductId equals p.ProductID
                where s.CustomerID == id
                select new SaleViewModel
                {
                    ProductId = s.ProductId,
                    ProductName = p.ProductName,
                    Price = p.Price
                    Quantity = s.Quantity
                }).ToList();
var result = new CustomerViewModel
{
  CustomerID = customer.CustomerID,
  FirstName = customer.FirstName,
  MiddleInitial = customer.MiddleInitial,
  LastName = customer.LastName,
  Sales = sales
}
</code>```

View

```<code>@model MasterDetailMVC.Models.CustomerViewModel

@{
     ViewBag.Title = "List of item by Customer";
}
<table>
    <th>
      <td>Product Name </td>
      // The rest of items....
    </th>
    @foreach(var item in Model.Sales)
        <tr>
            <td>@item.ProductName</td>
            // The rest of items....
        </tr>
    }
</table>
</code>```

Body:
How can i display data from Multiple Model. I have customer and Sale Table, when View detail slected i want to see the sales made by the selected Customer.

Customer Model

namespace MasterDetailMVC.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Customer
    {
        public Customer()
        {
            this.Sales = new HashSet<Sale>();
        }

        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string MiddleInitial { get; set; }
        public string LastName { get; set; }

       public virtual ICollection<Sale> Sales { get; set; }
    }
  }

Sale Model

namespace MasterDetailMVC.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Sale
    {
        public int SalesID { get; set; }
        public int SalesPersonID { get; set; }
        public int CustomerID { get; set; }
        public int ProductID { get; set; }
        public int Quantity { get; set; }

        public virtual Customer Customer { get; set; }
        public virtual Employee Employee { get; set; }
        public virtual Product Product { get; set; }
    }
}

Customer Controller

namespace MasterDetailMVC.Controllers
{
public class CustomersController : Controller
{
private salesdbEntities db = new salesdbEntities();
// GET: Customers
public ActionResult Index()
{
 return View(db.Customers.ToList());
 }
 // GET: Customers/Details/5
 public ActionResult Details(int? id)
 {
 Customer customer = db.Customers.Find(id);
  if (customer == null)
  {
  return HttpNotFound();
 }
  return View(customer);
 }
 }

Index View

@model IEnumerable<MasterDetailMVC.Models.Customer>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            @Html.DisplayNameFor(model => model.FirstName)

            @Html.DisplayNameFor(model => model.MiddleInitial)

            @Html.DisplayNameFor(model => model.LastName)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.FirstName)

            @Html.DisplayFor(modelItem => item.MiddleInitial)

            @Html.DisplayFor(modelItem => item.LastName)

            @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
            @Html.ActionLink("Details", "Details", new { id=item.CustomerID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID })

}

Detail View

@model MasterDetailMVC.Models.Customer

@{
    ViewBag.Title = "Details";
}

Details

Customer

            @Html.DisplayNameFor(model => model.FirstName)

            @Html.DisplayFor(model => model.FirstName)

            @Html.DisplayNameFor(model => model.MiddleInitial)

            @Html.DisplayFor(model => model.MiddleInitial)

            @Html.DisplayNameFor(model => model.LastName)

            @Html.DisplayFor(model => model.LastName)

    @Html.ActionLink("Edit", "Edit", new { id = Model.CustomerID }) |
    @Html.ActionLink("Back to List", "Index")

when i go this link Customers/Details/5 I want to display sales mad by this customer in a Table or grid.

sales Table looks like this

SELECT TOP (1000) [SalesID]
      ,[SalesPersonID]
      ,[CustomerID]
      ,[ProductID]
      ,[Quantity]
  FROM [salesdb].[dbo].[Sales]

Product Table looks Like this

SELECT TOP (1000) [ProductID]
      ,[Name]
      ,[Price]
  FROM [salesdb].[dbo].[Products]

Sales Person/Employee Table

 SELECT TOP (1000) [EmployeeID]
      ,[FirstName]
      ,[MiddleInitial]
      ,[LastName]
  FROM [salesdb].[dbo].[Employees]

Body:
Model

You need to create CustomerViewModel

public class CustomerViewModel
{
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string MiddleInitial { get; set; }
    public string LastName { get; set; }

    public List<SaleViewModel> Sales { get; set; }
}

and SaleViewModel like below

public class SaleViewModel
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
}

Controller

You can get a list of view SaleViewModel by joining between Sales and Products table like below

var sales = (from s in db.Sales
                join p in db.Products on s.ProductId equals p.ProductID
                where s.CustomerID == id
                select new SaleViewModel
                {
                    ProductId = s.ProductId,
                    ProductName = p.ProductName,
                    Price = p.Price
                    Quantity = s.Quantity
                }).ToList();
var result = new CustomerViewModel
{
  CustomerID = customer.CustomerID,
  FirstName = customer.FirstName,
  MiddleInitial = customer.MiddleInitial,
  LastName = customer.LastName,
  Sales = sales
}

View

@model MasterDetailMVC.Models.CustomerViewModel

@{
     ViewBag.Title = "List of item by Customer";
}
<table>
    <th>
      <td>Product Name </td>
      // The rest of items....
    </th>
    @foreach(var item in Model.Sales)
        <tr>
            <td>@item.ProductName</td>
            // The rest of items....
        </tr>
    }
</table>


问:
How to Connect to a Sign In User Flow
I'm authenticating a Java Web App using MSAL4J with success using the /authorize endpoint to obtain both the ID and Access tokens.

But I did not found any Java example for connecting to a given User's Flow defined in Azure AD B2C.

答:
Have you seen this MSAL4J B2C sample?

Here are where the user flows/policies are defined for the sample. In the AAD B2C portal, you will define the user flows and applications. In MSAL4J, you will construct the authority using the user flow/policy, as each user flow/policy is a separate token issuer in B2C.

B2C MSAL4J authority example

Title: How to Connect to a Sign In User Flow


问:
stacked barplot returning individual bars
I am attempting to make a stacked bar plot and it is simply not working. I have attached my data and the script I have tried. My data is tab delimited and only has 4 rows of data. Color is suppose to be a method by which I can color my bar graph.

```<code>Person   Count   Color
Jim   35   Y
Jim   10   N
Jenny   12   Y
Jenny   25   N
</code>```

So what I am expecting is Jim's bars to stack on top of each other and have Jenny's next his stacked as well. But that is not what is occuring, the bars are present but they are besides each other despite belonging to the same person.

Code I have tried

```<code>barplot(count, col = color) ##this will get me the unstacked bars

###what I have seen as examples but I already have a table...
count = table (person, count)
count
barplot(count, col = color)
</code>```

答:
The barplot function (from the graphics package) requires either a vector or matrix of values describing the bars which make up the plot. Not a data frame. So, if your data is structure like this:

```<code>> X <- matrix(c(12,25,35,10), nr=2)
> dimnames(X) <- list(Color=c("Y","N"), Person=c("Jenny","Jim"))
> X
     Person
Color Jenny Jim
    Y    12  35
    N    25  10
</code>```

Which is a 2x2 table of counts, then you can plot that easily:

```<code>> barplot(X)
</code>```

Of course R usually gives minimal output, including graphs, so to make it look more presentable, you'll need to add some arguments.

```<code>op <- par(mar=par("mar") + c(0,0,0,1)) # add some space for the legend on the right, saving the original pars
barplot(X, xlab="Person", ylab="Count", # add axis labels
        las=1, # make tick labels horizontal
        col=c("turquoise2","tomato"), border="white", # change colors
        legend=TRUE, # add a legend with some parameters...
        args.legend=list(x="right", title="Color", bt="n", border="white", inset=-0.2)
        )
par(op) # restore original graphical parameters
</code>```

The result is similar to the default graph produced by ggplot, which requires a data frame, not a matrix.

Body:
I am attempting to make a stacked bar plot and it is simply not working. I have attached my data and the script I have tried. My data is tab delimited and only has 4 rows of data. Color is suppose to be a method by which I can color my bar graph.

Person   Count   Color
Jim   35   Y
Jim   10   N
Jenny   12   Y
Jenny   25   N

So what I am expecting is Jim's bars to stack on top of each other and have Jenny's next his stacked as well. But that is not what is occuring, the bars are present but they are besides each other despite belonging to the same person.

Code I have tried

barplot(count, col = color) ##this will get me the unstacked bars

###what I have seen as examples but I already have a table...
count = table (person, count)
count
barplot(count, col = color)

Body:
The barplot function (from the graphics package) requires either a vector or matrix of values describing the bars which make up the plot. Not a data frame. So, if your data is structure like this:

> X <- matrix(c(12,25,35,10), nr=2)
> dimnames(X) <- list(Color=c("Y","N"), Person=c("Jenny","Jim"))
> X
     Person
Color Jenny Jim
    Y    12  35
    N    25  10

Which is a 2x2 table of counts, then you can plot that easily:

> barplot(X)

Of course R usually gives minimal output, including graphs, so to make it look more presentable, you'll need to add some arguments.

op <- par(mar=par("mar") + c(0,0,0,1)) # add some space for the legend on the right, saving the original pars
barplot(X, xlab="Person", ylab="Count", # add axis labels
        las=1, # make tick labels horizontal
        col=c("turquoise2","tomato"), border="white", # change colors
        legend=TRUE, # add a legend with some parameters...
        args.legend=list(x="right", title="Color", bt="n", border="white", inset=-0.2)
        )
par(op) # restore original graphical parameters

The result is similar to the default graph produced by ggplot, which requires a data frame, not a matrix.


问:
How do I calculate two text boxes and display the answer in another?
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions?
Here is my code!</p>

```<code>
    <br>
    <br>
    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>
    <br>
    <br>

    Number 1<input type="text" id="num1" <br>
    <br>
    Number 2<input type="text" id="num2" <br>
    <br>
    <button onclick="calculate()">Calculate</button>

    <script>
        function calculate() {
            var field1 = document.getElementById(num1).value;
            var field2 = document.getElementById(num2).value;

            var result = parseFloat(field1) + parseFloat(field2)

            if (!isNaN(result))

            {
                document.getElementById("answer").innerHTML = "The answer is " + result;

            }
    </script>
</code>```

答:
getElementById('num1') here id should be in quote, otherwise it will be treated as variable.

Also you forgot the } at the end

function calculate() {
            var field1 = document.getElementById('num1').value;
            var field2 = document.getElementById('num2').value;

            var result = parseFloat(field1) + parseFloat(field2);
            if (!isNaN(result))

            {
                document.getElementById("answer").textContent= "The answer is " + result;

            }
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br>
    <br>
    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>
    <br>
    <br>

    Number 1<input type="text" id="num1" <br>
    <br>
    Number 2<input type="text" id="num2" <br>
    <br>
    <button onclick="calculate()">Calculate</button></code>```

Body:
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions?
Here is my code!

    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>

    Number 1<input type="text" id="num1"

    Number 2<input type="text" id="num2"

    <button onclick="calculate()">Calculate</button>

Body:
getElementById('num1') here id should be in quote, otherwise it will be treated as variable.

Also you forgot the } at the end

function calculate() {
            var field1 = document.getElementById('num1').value;
            var field2 = document.getElementById('num2').value;

            var result = parseFloat(field1) + parseFloat(field2);
            if (!isNaN(result))

            {
                document.getElementById("answer").textContent= "The answer is " + result;

            }
      }

<br>
    <br>
    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>
    <br>
    <br>

    Number 1<input type="text" id="num1" <br>
    <br>
    Number 2<input type="text" id="num2" <br>
    <br>
    <button onclick="calculate()">Calculate</button>


问:
Format-Table in PowerShell inside a ForEach
Not sure what I am doing wrong here with this,  I know it has to do with the fact that it is inside a ForEach loop.  I have tried moving the below code around.  Even with the code half and half (half in and half out of the loop does not seem to work).  Still new to PowerShell and I know that I need to variables to $table each iteration or store them some where and read them later.

```<code>foreach ($gp in $GPINFO) {

    # Code that gets the values for $gp, $aclBefore and $aclAfter is here

    $table = new-object psobject -Property @{
        GPO_Name = $gp.DisplayName
        Old_Owner = $aclBefore
        New_Owner = $aclAfter
    }
    $table | Format-Table GPO_Name,Old_Owner,New_Owner
}
</code>```

If you can help me figure out what I am doing wrong that would be great, I know that every time the ForEach gets $gp out of the $GPINFO it is running the $table stuff and that is my problem.  So instead of one continuous table I end up with multiple tables with one set of data in each.

Thanks in advance

答:
You just can't pipe from foreach ().  It's an odd part of the language that comes up a lot.  Other ways:

Foreach-object:

```<code>$GPINFO | foreach-object {
    $gp = $_
    new-object psobject -Property @{
        GPO_Name = $gp.DisplayName
        Old_Owner = $aclBefore
        New_Owner = $aclAfter
    }
} | Format-Table GPO_Name,Old_Owner,New_Owner
</code>```

Call operator and scriptblock:

```<code>& {
  foreach ($gp in $GPINFO) {
      new-object psobject -Property @{
          GPO_Name = $gp.DisplayName
          Old_Owner = $aclBefore
          New_Owner = $aclAfter
      }
  }
} | Format-Table GPO_Name,Old_Owner,New_Owner
</code>```

Body:
Not sure what I am doing wrong here with this,  I know it has to do with the fact that it is inside a ForEach loop.  I have tried moving the below code around.  Even with the code half and half (half in and half out of the loop does not seem to work).  Still new to PowerShell and I know that I need to variables to $table each iteration or store them some where and read them later.

foreach ($gp in $GPINFO) {

    # Code that gets the values for $gp, $aclBefore and $aclAfter is here

    $table = new-object psobject -Property @{
        GPO_Name = $gp.DisplayName
        Old_Owner = $aclBefore
        New_Owner = $aclAfter
    }
    $table | Format-Table GPO_Name,Old_Owner,New_Owner
}

If you can help me figure out what I am doing wrong that would be great, I know that every time the ForEach gets $gp out of the $GPINFO it is running the $table stuff and that is my problem.  So instead of one continuous table I end up with multiple tables with one set of data in each.

Thanks in advance

Body:
You just can't pipe from foreach ().  It's an odd part of the language that comes up a lot.  Other ways:

Foreach-object:

$GPINFO | foreach-object {
    $gp = $_
    new-object psobject -Property @{
        GPO_Name = $gp.DisplayName
        Old_Owner = $aclBefore
        New_Owner = $aclAfter
    }
} | Format-Table GPO_Name,Old_Owner,New_Owner

Call operator and scriptblock:

& {
  foreach ($gp in $GPINFO) {
      new-object psobject -Property @{
          GPO_Name = $gp.DisplayName
          Old_Owner = $aclBefore
          New_Owner = $aclAfter
      }
  }
} | Format-Table GPO_Name,Old_Owner,New_Owner


问:
how to general search from [array] of string
I have a mongodb of recipes and I want to dynamically create a general search query resulting in:

```<code>{ $all: [/potato/i, /onion/i, /garlic/i, /chicken/i] }
</code>```

Without quotation marks from a string like:

```<code>const str = 'potato onion garlic chicken'
</code>```

I've attempted:

```<code>const arr = []
str.split(' ').forEach(element => {
  arr.push(`/${element}/i`)
})
console.log(arr)
</code>```

The problem is I end up with strings:

```<code>//[ '/potato/i', '/onion/i', '/garlic/i', '/chicken/i' ]
</code>```

How do can I dynamically create this query without stringifying?

答:
Try this

```<code>const str = 'potato onion garlic chicken'
const arr = []
str.split(' ').forEach(element => {
    // arr.push(`/${element}/i`)
    arr.push(new RegExp(element, 'i'))
})
console.log(arr)  // [ /potato/i, /onion/i, /garlic/i, /chicken/i ]
</code>```

You can test here

Body:
I have a mongodb of recipes and I want to dynamically create a general search query resulting in:

{ $all: [/potato/i, /onion/i, /garlic/i, /chicken/i] }

Without quotation marks from a string like:

const str = 'potato onion garlic chicken'

I've attempted:

const arr = []
str.split(' ').forEach(element => {
  arr.push(`/${element}/i`)
})
console.log(arr)

The problem is I end up with strings:

//[ '/potato/i', '/onion/i', '/garlic/i', '/chicken/i' ]

How do can I dynamically create this query without stringifying?

Body:
Try this

const str = 'potato onion garlic chicken'
const arr = []
str.split(' ').forEach(element => {
    // arr.push(`/${element}/i`)
    arr.push(new RegExp(element, 'i'))
})
console.log(arr)  // [ /potato/i, /onion/i, /garlic/i, /chicken/i ]

You can test here


问:
Rails 3 - Model Association Problems
I have a project where an User can own a Project and make part of a Project as a Team.

My models are like that:

```<code>class User
 has_many :projects, :foreign_key => "owner_id"
 has_many :project_memberships, :foreign_key => "member_id"
 has_many :shared_projects, :class_name => "Project", :through => :project_memberships, :foreign_key => "member_id"
end

class Project
 belongs_to :owner, :class_name => "User"
 has_many :project_memberships
 has_many :members, :class_name => "User", :through => "project_memberships", :foreign_key => "member_id"
end
</code>```

My question is: How can I create/delete etc a new Project so an User can own it since I'm not using nested resources?

Here is my Project Controller:

```<code>def new
@project = Project.new
end

def create
@owner = User.find(params[:user_id])
@project= @owner.projects.build(params[:project])
    ...
end
</code>```

Thanks in advance.

答:
If I understand your question correctly, you need to store current signed in user ID in session or use some authentication gem (like devise) which will do it for you.

Devise provides helper method current_user which returns an instance of User model. So you could do like so:

```<code>def create
@project= current_user.projects.build(params[:project])
    ...
end
</code>```

Update
If you pass user_id through form, you allow anyone to create project with another user's id. Actions that create something, that belong to current user should be constrained to current user on the serverside

Title: Rails 3 - Model Association Problems

Body:
I have a project where an User can own a Project and make part of a Project as a Team.

My models are like that:

class User
 has_many :projects, :foreign_key => "owner_id"
 has_many :project_memberships, :foreign_key => "member_id"
 has_many :shared_projects, :class_name => "Project", :through => :project_memberships, :foreign_key => "member_id"
end

class Project
 belongs_to :owner, :class_name => "User"
 has_many :project_memberships
 has_many :members, :class_name => "User", :through => "project_memberships", :foreign_key => "member_id"
end

My question is: How can I create/delete etc a new Project so an User can own it since I'm not using nested resources?

Here is my Project Controller:

def new
@project = Project.new
end

def create
@owner = User.find(params[:user_id])
@project= @owner.projects.build(params[:project])
    ...
end

Thanks in advance.

Body:
If I understand your question correctly, you need to store current signed in user ID in session or use some authentication gem (like devise) which will do it for you.

Devise provides helper method current_user which returns an instance of User model. So you could do like so:

def create
@project= current_user.projects.build(params[:project])
    ...
end

Update
If you pass user_id through form, you allow anyone to create project with another user's id. Actions that create something, that belong to current user should be constrained to current user on the serverside


问:
Generate random 128 bit decimal in given range in go
Let's say that we have a random number generator that can generate random 32 or 64 bit integers (like rand.Rand in the standard library)

Generating a random int64 in a given range [a,b] is fairly easy:

```<code>rand.Seed(time.Now().UnixNano())
n := rand.Int63n(b-a) + a
</code>```

Is it possible to generate random 128 bit decimal (as defined in specification IEEE 754-2008) in a given range from a combination of 32 or 64 bit random integers?

答:
It depends how many values you want to generate. If it's enough to have no more 10^34 values in a specified range - it's quite simple.

As I see the problem, a random value in the range min..max can be calculated as random(0..1)*(max-min)+min

Look like we need to generate only decimal128 value in range 0..1. So it's a random value in range 0..10^34-1 with exponent -34. This value can be generated with a golang standard random package.

To multiply, add and substruct float128 values can be used golang math/big package with values normalization.

Body:
Let's say that we have a random number generator that can generate random 32 or 64 bit integers (like rand.Rand in the standard library)

Generating a random int64 in a given range [a,b] is fairly easy:

rand.Seed(time.Now().UnixNano())
n := rand.Int63n(b-a) + a

Is it possible to generate random 128 bit decimal (as defined in specification IEEE 754-2008) in a given range from a combination of 32 or 64 bit random integers?


问:
How to enable auto-complete (intellisense) in Eclipse IDE for Java
I have Eclipse 2019-09 and I’m working on a Java application using some Collection classes.

I needed to see all the available methods for the Map interface but when I pressed “Ctrl+Space”, auto-complete didn’t work. “No default proposals” message came up.

How can I enable IntelliSense for Java in Eclipse IDE?

答:
I found a workaround to fix this issue in the below article.

Eclipse Java autocomplete not working

In Windows:

```<code>Window->Preferences->Java->Editor->Content Assist->Advanced
</code>```

In MacOSX:

```<code>Eclipse->Preferences->Java->Editor->Content Assist->Advanced
</code>```

Then, make sure the following options are ticked in both top (default content assist list) and bottom (Content Assist Cycling) sections.

```<code>Java Non-Type Proposals
Java Proposals
Java Type Proposals
</code>```

Body:
I found a workaround to fix this issue in the below article.

Eclipse Java autocomplete not working

In Windows:

Window->Preferences->Java->Editor->Content Assist->Advanced

In MacOSX:

Eclipse->Preferences->Java->Editor->Content Assist->Advanced

Then, make sure the following options are ticked in both top (default content assist list) and bottom (Content Assist Cycling) sections.

Java Non-Type Proposals
Java Proposals
Java Type Proposals


问:
How to add a 'default using' to all cshtml pages?
I'm creating my first MVC.Net application and I find myself including @using Gideon.Core.Mvc; on almost every page. Is it possible to add it by default to all pages?

In Asp.Net I'm able to add default stuff for controls to the web.config, hopefully it can be done for MVC.Net as well.

答:
Add them in the Views/Web.config. Add your namespace to the bottom:

```<code><system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Web.WebPages" />
            <add namespace="Gideon.Core.Mvc" />
        </namespaces>
    </pages>
</system.web.webPages.razor>
</code>```

Body:
Add them in the Views/Web.config. Add your namespace to the bottom:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Web.WebPages" />
            <add namespace="Gideon.Core.Mvc" />
        </namespaces>
    </pages>
</system.web.webPages.razor>


问:
How to show the bucket name when using RANGE_BUCKET in bigquery
Here is my query with public dataset in BigQuery:

```<code>SELECT RANGE_BUCKET(reputation, [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]) AS reputation_group, COUNT(*) AS count
FROM `bigquery-public-data.stackoverflow.users`
Where reputation > 200000
GROUP BY 1
ORDER By 1
</code>```

The result is below:

Instead of showing reputation_group as integer, how can I show the bucket's range:

```<code>0: [0-400000]
1: [400001-500000]
2: [500001-600000]
....
</code>```

Thank you very much.

UPDATE:
A big thank to Mikhail's answer with a minor change below:

```<code>SELECT bucket,
  FORMAT('%i - %i', IFNULL(ranges[SAFE_OFFSET(bucket - 1)] + 1, 0), ranges[SAFE_OFFSET(bucket)]) AS reputation_group,
  COUNT(*) AS COUNT
FROM `bigquery-public-data.stackoverflow.users`,
UNNEST([STRUCT([200000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] AS ranges)]),
UNNEST([RANGE_BUCKET(reputation, ranges)]) bucket
WHERE reputation > 200000
GROUP BY 1, 2
ORDER BY bucket
</code>```

Note an extra item 200000 is added to the STRUCT, which makes the result showing
200001 - 400000 instead of 0 - 400000

答:
Below is for BigQuery Standard SQL

#standardSQL
SELECT bucket,
  FORMAT('%i - %i', IFNULL(ranges[SAFE_OFFSET(bucket - 1)] + 1, 0), ranges[SAFE_OFFSET(bucket)]) AS reputation_group,
  COUNT(*) AS COUNT
FROM `bigquery-public-data.stackoverflow.users`,
UNNEST([STRUCT([400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] AS ranges)]),
UNNEST([RANGE_BUCKET(reputation, ranges)]) bucket
WHERE reputation > 200000
GROUP BY 1, 2
ORDER BY bucket

```

<p>with result   </p>

```Row bucket  reputation_group    COUNT
1   0       0 - 400000          198
2   1       400001 - 500000     23
3   2       500001 - 600000     13
4   3       600001 - 700000     12
5   4       700001 - 800000     4
6   5       800001 - 900000     5
7   6       900001 - 1000000    2
8   8       1100001 - 1200000   1
```

Body:
Here is my query with public dataset in BigQuery:

SELECT RANGE_BUCKET(reputation, [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]) AS reputation_group, COUNT(*) AS count
FROM `bigquery-public-data.stackoverflow.users`
Where reputation > 200000
GROUP BY 1
ORDER By 1

The result is below:

Instead of showing reputation_group as integer, how can I show the bucket's range:

0: [0-400000]
1: [400001-500000]
2: [500001-600000]
....

Thank you very much.

UPDATE:
A big thank to Mikhail's answer with a minor change below:

SELECT bucket,
  FORMAT('%i - %i', IFNULL(ranges[SAFE_OFFSET(bucket - 1)] + 1, 0), ranges[SAFE_OFFSET(bucket)]) AS reputation_group,
  COUNT(*) AS COUNT
FROM `bigquery-public-data.stackoverflow.users`,
UNNEST([STRUCT([200000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] AS ranges)]),
UNNEST([RANGE_BUCKET(reputation, ranges)]) bucket
WHERE reputation > 200000
GROUP BY 1, 2
ORDER BY bucket

Note an extra item 200000 is added to the STRUCT, which makes the result showing
200001 - 400000 instead of 0 - 400000

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT bucket,
  FORMAT('%i - %i', IFNULL(ranges[SAFE_OFFSET(bucket - 1)] + 1, 0), ranges[SAFE_OFFSET(bucket)]) AS reputation_group,
  COUNT(*) AS COUNT
FROM `bigquery-public-data.stackoverflow.users`,
UNNEST([STRUCT([400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] AS ranges)]),
UNNEST([RANGE_BUCKET(reputation, ranges)]) bucket
WHERE reputation > 200000
GROUP BY 1, 2
ORDER BY bucket

with result

Row bucket  reputation_group    COUNT
1   0       0 - 400000          198
2   1       400001 - 500000     23
3   2       500001 - 600000     13
4   3       600001 - 700000     12
5   4       700001 - 800000     4
6   5       800001 - 900000     5
7   6       900001 - 1000000    2
8   8       1100001 - 1200000   1


问:
Lubridate putting dates into the future in R
When I do this code:

```<code>library(lubridate)
df$date <- format(as.Date(df$date, "%m/%d/%y") , "%Y")
</code>```

Some of the dates that are meant to be in the 1900s, eg: 1960, turn to 2060. I'm not sure how to fix this. The date range I want is 1951 - 2014, and I have around 8000 observations.

答:
It seems that you have 2-digit years. From ?strptime

Year without century (00–99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 – that is the behaviour specified by the 2004 and 2008 POSIX standards, but they do also say ‘it is expected that in a future version the default century inferred from a 2-digit year will change’.

So all 2 digit years from 00-68 are prefixed with 20, hence 60 turns to 2060 and not 1960.

There could be various ways to handle this. One way would be to subtract 100 years from dates whose year is more than 2014 (since we know the range of years).

For example,

```<code>df <- data.frame(date = c('1/12/60', '1/12/78' ,'1/1/91', '1/1/54'))
df$date <- as.Date(df$date, "%m/%d/%y")
df
#        date
#1 2060-01-12
#2 1978-01-12
#3 1991-01-01
#4 2054-01-01

inds <- as.numeric(format(df$date, "%Y")) > 2014
df$date[inds] <- df$date[inds] - lubridate::years(100)
df
#        date
#1 1960-01-12
#2 1978-01-12
#3 1991-01-01
#4 1954-01-01
</code>```

Body:
When I do this code:

library(lubridate)
df$date <- format(as.Date(df$date, "%m/%d/%y") , "%Y")

Some of the dates that are meant to be in the 1900s, eg: 1960, turn to 2060. I'm not sure how to fix this. The date range I want is 1951 - 2014, and I have around 8000 observations.

Body:
It seems that you have 2-digit years. From ?strptime

Year without century (00–99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 – that is the behaviour specified by the 2004 and 2008 POSIX standards, but they do also say ‘it is expected that in a future version the default century inferred from a 2-digit year will change’.

So all 2 digit years from 00-68 are prefixed with 20, hence 60 turns to 2060 and not 1960.

There could be various ways to handle this. One way would be to subtract 100 years from dates whose year is more than 2014 (since we know the range of years).

For example,

df <- data.frame(date = c('1/12/60', '1/12/78' ,'1/1/91', '1/1/54'))
df$date <- as.Date(df$date, "%m/%d/%y")
df
#        date
#1 2060-01-12
#2 1978-01-12
#3 1991-01-01
#4 2054-01-01

inds <- as.numeric(format(df$date, "%Y")) > 2014
df$date[inds] <- df$date[inds] - lubridate::years(100)
df
#        date
#1 1960-01-12
#2 1978-01-12
#3 1991-01-01
#4 1954-01-01


问:
DOMException: Failed to set the 'adoptedStyleSheets' property on 'ShadowRoot': Sharing constructed stylesheets in multiple documents is not allowed
Encountered when using html2canvas：
DOMException: Failed to set the 'adoptedStyleSheets' property on 'ShadowRoot': Sharing constructed stylesheets in multiple documents is not allowed</p>

```<code> html2canvas(document.getElementById('qr-code-content'), {useCORS: true}).then(canvas => {
        document.getElementById('qr-code-content').append(canvas);
        this.base64ImgData = canvas.toDataURL();
        this.sharing = true;
      });
</code>```

答:
This PR address the issue. https://github.com/niklasvh/html2canvas/pull/2020

You can use the fork if you need a quick solution or wait until it gets merged and get it from the main repo.

Body:
Encountered when using html2canvas：
DOMException: Failed to set the 'adoptedStyleSheets' property on 'ShadowRoot': Sharing constructed stylesheets in multiple documents is not allowed

 html2canvas(document.getElementById('qr-code-content'), {useCORS: true}).then(canvas => {
        document.getElementById('qr-code-content').append(canvas);
        this.base64ImgData = canvas.toDataURL();
        this.sharing = true;
      });


问:
Connecting to RDS Postgres from remote machine
I have configured an RDS Postgres micro instance for testing but am having problem connecting. I have created a security group and allow all hosts (0.0.0.0/0) by default to port 5432 but for some reason I am not able to connect. I tried connecting to the port 5432 on the machine but it appears to be closed. Any ideas? I have verified that the security group is using the correct security group.

This is my configuration

```<code>TCP
Port (Service)  Source  Action
5432    0.0.0.0/0   Delete
</code>```

Here is how I am trying to connect to the rds service

```<code>psql -p 5432 -h example.cs945smhrv09.us-west-2.rds.amazonaws.com -U example example
</code>```

UPDATE

OK feel a little silly after figuring out that rds starts up on a private 172 subnet. I was able to connect from my ec2 instance.

Question now is there a way to put that on a public address that I can connect to? I would like to configure it with a security group that limits the source ip but then be able to connect to it with psql from my desktop.

Update 2

I don't remember all the details when I originally posted this question but it is no longer an issue. We now have a management vpc that we connect to using a vpn server. The management vpc network is trusted by the prod and devel security groups for the rds instances. We have no problem communicating with them without adding any public ips.

答:
You can simply use workbench recommended by aws but make sure your all postgres availibily is set to  everywhere..while adding PostgrSQL 5432

https://aws.amazon.com/getting-started/tutorials/create-connect-postgresql-db/

Body:
I have configured an RDS Postgres micro instance for testing but am having problem connecting. I have created a security group and allow all hosts (0.0.0.0/0) by default to port 5432 but for some reason I am not able to connect. I tried connecting to the port 5432 on the machine but it appears to be closed. Any ideas? I have verified that the security group is using the correct security group.

This is my configuration

TCP
Port (Service)  Source  Action
5432    0.0.0.0/0   Delete

Here is how I am trying to connect to the rds service

psql -p 5432 -h example.cs945smhrv09.us-west-2.rds.amazonaws.com -U example example

UPDATE

OK feel a little silly after figuring out that rds starts up on a private 172 subnet. I was able to connect from my ec2 instance.

Question now is there a way to put that on a public address that I can connect to? I would like to configure it with a security group that limits the source ip but then be able to connect to it with psql from my desktop.

Update 2

I don't remember all the details when I originally posted this question but it is no longer an issue. We now have a management vpc that we connect to using a vpn server. The management vpc network is trusted by the prod and devel security groups for the rds instances. We have no problem communicating with them without adding any public ips.


问:
How to Collect Credit Card Info and Charge the Winner of an Auction
We are looking into adding an auction feature  to our online service. Ideally, we would like to be able to ask for a users credit card information at the time of placing a bid and then only charge the selected winner.

Lots of this stuff seems to require PCI compliance so we must go through third party services, Paypal Vault and other services offer a way to store users card info, but we aren't sure if it's even possible to store this info and charge a selected winner programmatically?

Is there any service or combination of servies that would provide this functionality or are we limited to collecting credit card info and charging a user after the winner has been chosen?

答:
You are indeed looking for a vault or reference transaction feature.  They allow you to programmatically (i.e. via an API call) charge a user at an arbitrary later date.

PayPal's Braintree Gateway would likely be best suited to what you've stated so far.


问:
r dataTable save as RDS rather than jso
I'm trying to follow this example from the dataTable github which (as I understand it) saves a user edited dataTable to the server. However, I would like it to save as an RDS instead of a JSON file.

The DT example code:

```<code>library(shiny)
library(DT)
shinyApp(
  ui = fluidPage(
    DTOutput('x1')
  ),
  server = function(input, output, session) {
    x = iris
    x$Date = Sys.time() + seq_len(nrow(x))
    output$x1 = renderDT(x, selection = 'none', editable = TRUE)

    proxy = dataTableProxy('x1')

    observeEvent(input$x1_cell_edit, {
      info = input$x1_cell_edit
      str(info)
      i = info$row
      j = info$col
      v = info$value
      x[i, j] <<- DT::coerceValue(v, x[i, j])
      replaceData(proxy, x, resetPaging = FALSE)  # important
    })
  }
)
</code>```

I can read in my own RDS fine, and dataTable appears to edit it fine, but I can't figure out how to save the edits back to the original RDS. Any ideas?

A bit of background. I am trying to set up a settings file for my shiny app. I want the same settings to be persistent and to apply to all users (both of them) and for either user to be able to edit the settings file. Having an editable datatable appears to me to be the most obvious way to do it, but I'm open to other ideas.

答:
So turns out I'd mis-named my variables which was why it was failing. As A. Suliman pointed out above all that was needed was to add "saveRDS(x, ".rds")". As penance for my sins I'll provide a commented version of the code sample above with what I think is more intuitive variable names. Hopefully that may help other people.</p>

```<code>library(shiny)
library(DT)
library(textclean)

shinyApp(

  ui = fluidPage(
    DTOutput('tableObject') # name of table object
  ),

  server = function(input, output, session) {
    inputData = readRDS("somewhere.rds") #read data in
    output$tableObject = renderDT(inputData, selection = 'none', editable = TRUE)

    proxy = dataTableProxy('tableObject')

    observeEvent(input$tableObject_cell_edit, { # replace tableObject with your variable name eg. input$example_cell_edit
      info = input$tableObject_cell_edit # and again
      str(info)
      i = info$row
      j = info$col
      v = info$value
      saveRDS(sRego, # save timestamped copy of old data
        mgsub(paste('settings/Rego ', Sys.time(), '.rds', sep = ""),
              pattern = c(":", " "),
              replacement = c("-", "_")))
      inputData[i, j] <<- DT::coerceValue(v, inputData[i, j]) # replace variable
      replaceData(proxy, inputData, resetPaging = FALSE) # replace variable
      saveRDS(inputData, "somewhere.rds") # write new data out

    })
  }
)
</code>```

Title: r dataTable save as RDS rather than jso

Body:
I'm trying to follow this example from the dataTable github which (as I understand it) saves a user edited dataTable to the server. However, I would like it to save as an RDS instead of a JSON file.

The DT example code:

library(shiny)
library(DT)
shinyApp(
  ui = fluidPage(
    DTOutput('x1')
  ),
  server = function(input, output, session) {
    x = iris
    x$Date = Sys.time() + seq_len(nrow(x))
    output$x1 = renderDT(x, selection = 'none', editable = TRUE)

    proxy = dataTableProxy('x1')

    observeEvent(input$x1_cell_edit, {
      info = input$x1_cell_edit
      str(info)
      i = info$row
      j = info$col
      v = info$value
      x[i, j] <<- DT::coerceValue(v, x[i, j])
      replaceData(proxy, x, resetPaging = FALSE)  # important
    })
  }
)

I can read in my own RDS fine, and dataTable appears to edit it fine, but I can't figure out how to save the edits back to the original RDS. Any ideas?

A bit of background. I am trying to set up a settings file for my shiny app. I want the same settings to be persistent and to apply to all users (both of them) and for either user to be able to edit the settings file. Having an editable datatable appears to me to be the most obvious way to do it, but I'm open to other ideas.

Body:
So turns out I'd mis-named my variables which was why it was failing. As A. Suliman pointed out above all that was needed was to add "saveRDS(x, ".rds")". As penance for my sins I'll provide a commented version of the code sample above with what I think is more intuitive variable names. Hopefully that may help other people.

library(shiny)
library(DT)
library(textclean)

shinyApp(

  ui = fluidPage(
    DTOutput('tableObject') # name of table object
  ),

  server = function(input, output, session) {
    inputData = readRDS("somewhere.rds") #read data in
    output$tableObject = renderDT(inputData, selection = 'none', editable = TRUE)

    proxy = dataTableProxy('tableObject')

    observeEvent(input$tableObject_cell_edit, { # replace tableObject with your variable name eg. input$example_cell_edit
      info = input$tableObject_cell_edit # and again
      str(info)
      i = info$row
      j = info$col
      v = info$value
      saveRDS(sRego, # save timestamped copy of old data
        mgsub(paste('settings/Rego ', Sys.time(), '.rds', sep = ""),
              pattern = c(":", " "),
              replacement = c("-", "_")))
      inputData[i, j] <<- DT::coerceValue(v, inputData[i, j]) # replace variable
      replaceData(proxy, inputData, resetPaging = FALSE) # replace variable
      saveRDS(inputData, "somewhere.rds") # write new data out

    })
  }
)


问:
Finding Intersection of NSMutableArrays
I have three NSMutableArray containing names that are added to the lists according to different criterieas.

Here are my arrays pseudocode:

```<code>NSMutableArray *array1 = [@"Jack", @"John", @"Daniel", @"Lisa"];
NSMutableArray *array2 = [@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica"];
NSMutableArray *array3 = [@"Jack", @"Jerome", @"Dan", @"Lindsay", @"Lisa"];
</code>```

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

```<code>NSMutableArray *array4 = [@"Jack",@"Lisa"];
</code>```

Because all the three array have jack and lisa as an element. Is there way of simply doing this?

答:
Use NSMutableSet:

```<code>NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];
</code>```

The only issue with this is that you lose ordering of elements, but I think (in this case) that that's OK.

As has been pointed out in the comments (thanks, Q80!), iOS 5 and OS X 10.7 added a new class called NSOrderedSet (with a Mutable subclass) that allows you to perform these same intersection operations while still maintaining order.

Title: Finding Intersection of NSMutableArrays

Body:
I have three NSMutableArray containing names that are added to the lists according to different criterieas.

Here are my arrays pseudocode:

NSMutableArray *array1 = [@"Jack", @"John", @"Daniel", @"Lisa"];
NSMutableArray *array2 = [@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica"];
NSMutableArray *array3 = [@"Jack", @"Jerome", @"Dan", @"Lindsay", @"Lisa"];

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

NSMutableArray *array4 = [@"Jack",@"Lisa"];

Because all the three array have jack and lisa as an element. Is there way of simply doing this?

Body:
Use NSMutableSet:

NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];

The only issue with this is that you lose ordering of elements, but I think (in this case) that that's OK.

As has been pointed out in the comments (thanks, Q80!), iOS 5 and OS X 10.7 added a new class called NSOrderedSet (with a Mutable subclass) that allows you to perform these same intersection operations while still maintaining order.


问:
Remove elements of 2d array whose 1st column values are duplicates (Swift)
This query is a small twist on a commonly asked question.

The goal is to filter a 2d array to remove duplicate element pairs whose first-column values are duplicates. For example:

```<code>[[1, 1, 1,  2, 2,  3, 3, 3, 3], [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
     ->    [[1, 2, 3],[0.2, 0.1, 0.35]]
</code>```

Since the second-column values vary, there is obviously some discretion that needs to be applied when filtering: here, the last value of the set of duplicates is chosen.

One of the myriad answers to this related question -- a functional programming solution by Tim MB -- can be adapted to the task:

```<code>// Use FP-style filtering to eliminate repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = rawArray
    .transpose
    .enumerated()
    .filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }
    .map{ $0.1 }
    .transpose
</code>```

However, this solution is rather slow, which is unfortunate because it's elegant.

A faster solution that keeps the FP spirit is to use dictionary hashing:

```<code>// Use array -> dict -> array trick to remove repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = Array( Array(
    rawArray
        .transpose
        .reduce(into: [:], { dict, elements in
            dict[elements[0], default:(0,0)] = elements[1]
        } )
        .map{ ($0.key, $0.value) } )
    .sorted{ $0.0 < $1.0 }
    .map{ [$0.0, $0.1] }
    .transpose) as! Array2D
</code>```

My questions are:

Is this dictionary trick a good idea? Given that it uses floats as keys?

Why is the FP solution slow?  Can it be speeded up?

Are there better alternatives?

答:
Thanks to Alexander, here is solution adapted from Coeur's method in the long related thread.

```<code>let rawArray: [[Float]] = [[1, 1, 1,  2, 2,  3, 3, 3, 3],
                           [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
let filteredArray = rawArray
    .transpose
    .reversed()
    .map{ ($0[0],$0[1]) }
    .unique(for: \.0)
    .map{ [$0.0,$0.1] }
    .reversed()
    .transpose
</code>```

All that cruft arises because the data is a two-column float array rather than a 1d array of tuples, and because the last rather than the first duplicate value is required to be selected.

For this to work, Array needs to have the following extensions, the first courtesy of Alexander and Coeur, the second (revision) thanks to Leo Dabus:

```<code>extension RangeReplaceableCollection {
    /// Returns a collection containing, in order, the first instances of
    /// elements of the sequence that compare equally for the keyPath.
    func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> Self {
        var unique = Set<T>()
        return filter { unique.insert($0[keyPath: keyPath]).inserted }
    }
}

extension RandomAccessCollection where Element: RandomAccessCollection {
    /// Peform a transpose operation
    var transpose: [[Element.Element]] {
        guard !isEmpty,
            var index = first?.startIndex,
            let endIndex = first?.endIndex
            else { return [] }
        var result: [[Element.Element]] = []
        while index < endIndex {
            result.append(map{$0[index]})
            first?.formIndex(after: &index) }
        return result
    }
}
</code>```

Body:
This query is a small twist on a commonly asked question.

The goal is to filter a 2d array to remove duplicate element pairs whose first-column values are duplicates. For example:

[[1, 1, 1,  2, 2,  3, 3, 3, 3], [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
     ->    [[1, 2, 3],[0.2, 0.1, 0.35]]

Since the second-column values vary, there is obviously some discretion that needs to be applied when filtering: here, the last value of the set of duplicates is chosen.

One of the myriad answers to this related question -- a functional programming solution by Tim MB -- can be adapted to the task:

// Use FP-style filtering to eliminate repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = rawArray
    .transpose
    .enumerated()
    .filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }
    .map{ $0.1 }
    .transpose

However, this solution is rather slow, which is unfortunate because it's elegant.

A faster solution that keeps the FP spirit is to use dictionary hashing:

// Use array -> dict -> array trick to remove repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = Array( Array(
    rawArray
        .transpose
        .reduce(into: [:], { dict, elements in
            dict[elements[0], default:(0,0)] = elements[1]
        } )
        .map{ ($0.key, $0.value) } )
    .sorted{ $0.0 < $1.0 }
    .map{ [$0.0, $0.1] }
    .transpose) as! Array2D

My questions are:

Is this dictionary trick a good idea? Given that it uses floats as keys?

Why is the FP solution slow?  Can it be speeded up?

Are there better alternatives?

Body:
Thanks to Alexander, here is solution adapted from Coeur's method in the long related thread.

let rawArray: [[Float]] = [[1, 1, 1,  2, 2,  3, 3, 3, 3],
                           [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
let filteredArray = rawArray
    .transpose
    .reversed()
    .map{ ($0[0],$0[1]) }
    .unique(for: \.0)
    .map{ [$0.0,$0.1] }
    .reversed()
    .transpose

All that cruft arises because the data is a two-column float array rather than a 1d array of tuples, and because the last rather than the first duplicate value is required to be selected.

For this to work, Array needs to have the following extensions, the first courtesy of Alexander and Coeur, the second (revision) thanks to Leo Dabus:

extension RangeReplaceableCollection {
    /// Returns a collection containing, in order, the first instances of
    /// elements of the sequence that compare equally for the keyPath.
    func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> Self {
        var unique = Set<T>()
        return filter { unique.insert($0[keyPath: keyPath]).inserted }
    }
}

extension RandomAccessCollection where Element: RandomAccessCollection {
    /// Peform a transpose operation
    var transpose: [[Element.Element]] {
        guard !isEmpty,
            var index = first?.startIndex,
            let endIndex = first?.endIndex
            else { return [] }
        var result: [[Element.Element]] = []
        while index < endIndex {
            result.append(map{$0[index]})
            first?.formIndex(after: &index) }
        return result
    }
}


问:
How do I play a notification sound with max volume even in background?
I need to play a sound in Android, when a notification is received, even in background. This is like Uber Driver or other apps: they play sounds at max volume even if the phone is muted and the app is in background.

I tried this without luck:

```<code>AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
</code>```

Any suggestions?

答:
Check Code

notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

Body:
I need to play a sound in Android, when a notification is received, even in background. This is like Uber Driver or other apps: they play sounds at max volume even if the phone is muted and the app is in background.

I tried this without luck:

AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);

Any suggestions?


问:
I have a list of inputs type file and it accept image only .. How can i view an image when i add one?
i wrote this code and its working but when i choose image all inputs view the same image not only the one i added the image to ..

```<code><html lang="en">
<head>
    <title>Change image on select new image from file input</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<body>
    <ul>
        <li>
            <input type="file" name="file" class="profile-img">
            <img src="" class="profile-img-tag" width="200px" />
        </li>
        <li>
            <input type="file" name="file" class="profile-img">
            <img src="" class="profile-img-tag" width="200px" />
        </li>
        <li>
            <input type="file" name="file" class="profile-img">
            <img src="" class="profile-img-tag" width="200px" />
        </li>
    </ul>

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.profile-img-tag').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    $(".profile-img").change(function(){
        readURL(this);
    });
</script>

</body>
</html>
</code>```

Just cant make it for every input separatly.

答:
Just change attribute of image that is next to clicked input:

```<code>$(input).next().attr('src', e.target.result);
</code>```

<title>Change image on select new image from file input</title>

        <input type="file" name="file" class="profile-img">

        <input type="file" name="file" class="profile-img">

        <input type="file" name="file" class="profile-img">

```

Body:
i wrote this code and its working but when i choose image all inputs view the same image not only the one i added the image to ..

    <title>Change image on select new image from file input</title>

            <input type="file" name="file" class="profile-img">

            <input type="file" name="file" class="profile-img">

            <input type="file" name="file" class="profile-img">

Just cant make it for every input separatly.

Body:
Just change attribute of image that is next to clicked input:

$(input).next().attr('src', e.target.result);

<html lang="en">
<head>
<title>Change image on select new image from file input</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<ul>
    <li>
        <input type="file" name="file" class="profile-img">
        <img src="" class="profile-img-tag" width="200px" />
    </li>
    <li>
        <input type="file" name="file" class="profile-img">
        <img src="" class="profile-img-tag" width="200px" />
    </li>
    <li>
        <input type="file" name="file" class="profile-img">
        <img src="" class="profile-img-tag" width="200px" />
    </li>
</ul>

<script type="text/javascript">
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $(input).next().attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
$(".profile-img").change(function(){
    readURL(this);
});
</script>

</body>
</html>


问:
C programming function calling to return values
I'm a college student in my first year of software engineering. I am in the fourth week of my semester and am having trouble in my programming class. Currently, I was given this assignment in which I was given a function called "getNum()" and I had to use it in another function where the program user, would input a number and the function that I program (must be named isOdd()) would determine if the number is odd or even. Then the main function would print whether the number is odd or even. This is the way that my professor worded it:

" Write a program that uses the getNum() function provided to you in Assignment 2 to get anumber from the user (prompting them first, as always). Create and use a function called isOddwith parameters (the number) and return values (1 ifthe number is odd, 0 if the number is evenOR use a bool or boolean data type, your choice) to determine if thenumber is odd. In main(), tell the user (by displaying using printf()or cout) whether the number is evenor odd."

Now, the problem I am having is understanding programming as I am fairly new to it and some words confuse me, such as parameter and return value. To give you and idea of what I have written so far,

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

int isOdd(int numInput);
int getNum(void);

int main(void)
{
    int number = 0;
    while (number > -1)
    {
        if (isOdd(0))
        {
            printf("The number is even.\n");
        }
        else if (isOdd(1))
        {
            printf("The number is odd.\n");
        }
    }

    return 0;
}

int isOdd(int numInput)
{
    int myNumber = 0;
    printf("Please enter a number: ", numInput);
    myNumber = getNum();

    if (myNumber % 2 == 0)
    {
        myNumber == 0;
    }
    else
    {
        myNumber == 1;
    }
    return myNumber;
}

#pragma warning(disable: 4996)
int getNum(void)
{
    /* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */
    char record[121] = { 0 }; /* record stores the string */
    int number = 0;
    /* NOTE to student: indent and brace this function consistent with your others */
    /* use fgets() to get a string from the keyboard */
    fgets(record, 121, stdin);
    /* extract the number from the string; sscanf() returns a number
     * corresponding with the number of items it found in the string */
    if (sscanf(record, "%d", &number) != 1)
    {
        /* if the user did not enter a number recognizable by
         * the system, set number to -1 */
        number = -1;
    }
    return number;
}
</code>```

This is what I have written, trying to do things accordingly to my professor's instructions, as I do not yet know how to properly use booleans. As you can see, at the bottom is the getNum() function that my professor has said is mandatory for this assignment. As of now, everything I input, I am told is even. I am not asking for you guys to solve and do everything for me but I want to understand what I am doing wrong, what my thinking is doing wrong and to overall better my understanding for future programming. Thank you

答:
It's hard to help you without knowing why you did what you did. A lot of the code is just baffling:

```<code>    if (isOdd(0))
</code>```

Why are you passing a zero to isOdd?

```<code>printf("Please enter a number: ", numInput);
myNumber = getNum();
</code>```

Is numInput supposed to be the number they enter or is myNumber supposed to be?

```<code>if (myNumber % 2 == 0)
{
    myNumber == 0;
}
</code>```

The statement myNumber == 0 compares myNumber to zero to see if they're equal. It does nothing useful here since you ignore the result of the comparison.

Body:
I'm a college student in my first year of software engineering. I am in the fourth week of my semester and am having trouble in my programming class. Currently, I was given this assignment in which I was given a function called "getNum()" and I had to use it in another function where the program user, would input a number and the function that I program (must be named isOdd()) would determine if the number is odd or even. Then the main function would print whether the number is odd or even. This is the way that my professor worded it:

" Write a program that uses the getNum() function provided to you in Assignment 2 to get anumber from the user (prompting them first, as always). Create and use a function called isOddwith parameters (the number) and return values (1 ifthe number is odd, 0 if the number is evenOR use a bool or boolean data type, your choice) to determine if thenumber is odd. In main(), tell the user (by displaying using printf()or cout) whether the number is evenor odd."

Now, the problem I am having is understanding programming as I am fairly new to it and some words confuse me, such as parameter and return value. To give you and idea of what I have written so far,

#include <stdio.h>

int isOdd(int numInput);
int getNum(void);

int main(void)
{
    int number = 0;
    while (number > -1)
    {
        if (isOdd(0))
        {
            printf("The number is even.\n");
        }
        else if (isOdd(1))
        {
            printf("The number is odd.\n");
        }
    }

    return 0;
}

int isOdd(int numInput)
{
    int myNumber = 0;
    printf("Please enter a number: ", numInput);
    myNumber = getNum();

    if (myNumber % 2 == 0)
    {
        myNumber == 0;
    }
    else
    {
        myNumber == 1;
    }
    return myNumber;
}

#pragma warning(disable: 4996)
int getNum(void)
{
    /* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */
    char record[121] = { 0 }; /* record stores the string */
    int number = 0;
    /* NOTE to student: indent and brace this function consistent with your others */
    /* use fgets() to get a string from the keyboard */
    fgets(record, 121, stdin);
    /* extract the number from the string; sscanf() returns a number
     * corresponding with the number of items it found in the string */
    if (sscanf(record, "%d", &number) != 1)
    {
        /* if the user did not enter a number recognizable by
         * the system, set number to -1 */
        number = -1;
    }
    return number;
}

This is what I have written, trying to do things accordingly to my professor's instructions, as I do not yet know how to properly use booleans. As you can see, at the bottom is the getNum() function that my professor has said is mandatory for this assignment. As of now, everything I input, I am told is even. I am not asking for you guys to solve and do everything for me but I want to understand what I am doing wrong, what my thinking is doing wrong and to overall better my understanding for future programming. Thank you

Body:
It's hard to help you without knowing why you did what you did. A lot of the code is just baffling:

    if (isOdd(0))

Why are you passing a zero to isOdd?

printf("Please enter a number: ", numInput);
myNumber = getNum();

Is numInput supposed to be the number they enter or is myNumber supposed to be?

if (myNumber % 2 == 0)
{
    myNumber == 0;
}

The statement myNumber == 0 compares myNumber to zero to see if they're equal. It does nothing useful here since you ignore the result of the comparison.


问:
Application does not write file to internal storage [Android]
I am trying to create and then write a simple file called "thisisafile.txt" in Android. After I run the application, file does not exist in internal storage.

```<code>import java.io.*;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String fileName = "thisisafile.txt";
    writeFile(fileName, "Hello World!");
}

    public static void writeFile(String fileName, String text) {
        File file = new File (fileName);
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(text);
        out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Is the file written? If then where, because I can't find it. If not, what am I doing wrong in the code?

答:
```<code>For Read

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

For Write

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

Need Read / Write Permission On Manifest, Allow Storage Permission.

```<code>private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}
</code>```

Body:
I am trying to create and then write a simple file called "thisisafile.txt" in Android. After I run the application, file does not exist in internal storage.

import java.io.*;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String fileName = "thisisafile.txt";
    writeFile(fileName, "Hello World!");
}

    public static void writeFile(String fileName, String text) {
        File file = new File (fileName);
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(text);
        out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Is the file written? If then where, because I can't find it. If not, what am I doing wrong in the code?

Body:
For Read

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

For Write

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Need Read / Write Permission On Manifest, Allow Storage Permission.

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}