问:
IE looping infinitely when using Authorize
I'm developing a Facebook app, and i only want to allow access to certain views if the visitor is authorized through Facebook. This should be a pretty simple task, and i thought is was, until i tried it out in IE. The following code works fine in Chrome and Safari. I want to use Forms authentication, and therefore i have set

```<code><forms loginUrl="~/Account/Login" timeout="2880" />
</code>```

in web.config. This will direct the visitor to the following ActionResult when entering my app:

```<code>    public ActionResult Login(string returnUrl)
    {
        ManagerGame2.Utilities.StaticDataContent.InitStaticData();

        var oAuthClient = new FacebookOAuthClient();
        oAuthClient.AppId = FacebookApplication.Current.AppId;
        oAuthClient.RedirectUri = new Uri(redirectUrl);
        var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", returnUrl } });
        return Redirect(loginUri.AbsoluteUri);
    }
</code>```

Then the user is redirected to a Facebook page, and an access token is sent back into my OAuth ActionResult:

```<code>public ActionResult OAuth(string code, string state)
    {
        FacebookOAuthResult oauthResult;
        if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
        {
            if (oauthResult.IsSuccess)
            {
                var oAuthClient = new FacebookOAuthClient();
                oAuthClient.AppId = FacebookApplication.Current.AppId;
                oAuthClient.AppSecret = FacebookApplication.Current.AppSecret;
                oAuthClient.RedirectUri = new Uri(redirectUrl);
                dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                string accessToken = tokenResult.access_token;

                DateTime expiresOn = DateTime.MaxValue;

                if (tokenResult.ContainsKey("expires"))
                {
                    DateTimeConvertor.FromUnixTime(tokenResult.expires);
                }

                FacebookClient fbClient = new FacebookClient(accessToken);
                dynamic me = fbClient.Get("me?fields=id,name");
                long facebookID = Convert.ToInt64(me.id);

                Account acc = (from x in db.Account.OfType<Account>() where x.FaceBookID == facebookID select x).FirstOrDefault();
                if (acc == null)
                {
                    acc = CreateAccount(me);
                }
                acc.LatestLogin = DateTime.Now;
                db.Entry(acc).State = EntityState.Modified;
                db.SaveChanges();

                MemoryUserStore.CurrentAccount = acc;

                UserRoleProvider usp = new UserRoleProvider();
                usp.GetRolesForUser(acc.AccountID.ToString());
                FormsAuthentication.SetAuthCookie(acc.AccountID.ToString(), false);

                if (Url.IsLocalUrl(state))
                {
                    return Redirect(state);
                }
                return RedirectToAction("Details", "Account", new { id = acc.AccountID });
            }
        }

        return RedirectToAction("Index", "Account");
    }
</code>```

What i am trying to do here, is to first verify if the token i get back from the redirect is valid. If it is, then i pull some data about the visitor, like FacebookID and Name. I then match it with my database, to see if the user already exists, and if not, i create one. I also assign a role for the user in my custom Role provider, but i had the infinite loop problem before this. Then i set

```<code>FormsAuthentication.SetAuthCookie(acc.AccountID.ToString(), false);
</code>```

and i assume this is the core of keeping track of wheter a visitor is authorized or not. As far as i understand, when the visitor is trying to call a ActionResult that requires [Authorize] then the system will check for this cookie.

Well, could someone please clarify why the above code is working in Chrome/Safari, but keeps looping through Login and then OAuth infinitely in IE?

My app is using MVC 3, EF Code First and Facebook C# SDK 5.0.25

答: I know this seems obvious but are you sure cookies aren't disabled in IE? There is an option to disable cookies in developer tools.</p>

Body:
I'm developing a Facebook app, and i only want to allow access to certain views if the visitor is authorized through Facebook. This should be a pretty simple task, and i thought is was, until i tried it out in IE. The following code works fine in Chrome and Safari. I want to use Forms authentication, and therefore i have set

<forms loginUrl="~/Account/Login" timeout="2880" />

in web.config. This will direct the visitor to the following ActionResult when entering my app:

    public ActionResult Login(string returnUrl)
    {
        ManagerGame2.Utilities.StaticDataContent.InitStaticData();

        var oAuthClient = new FacebookOAuthClient();
        oAuthClient.AppId = FacebookApplication.Current.AppId;
        oAuthClient.RedirectUri = new Uri(redirectUrl);
        var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", returnUrl } });
        return Redirect(loginUri.AbsoluteUri);
    }

Then the user is redirected to a Facebook page, and an access token is sent back into my OAuth ActionResult:

public ActionResult OAuth(string code, string state)
    {
        FacebookOAuthResult oauthResult;
        if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
        {
            if (oauthResult.IsSuccess)
            {
                var oAuthClient = new FacebookOAuthClient();
                oAuthClient.AppId = FacebookApplication.Current.AppId;
                oAuthClient.AppSecret = FacebookApplication.Current.AppSecret;
                oAuthClient.RedirectUri = new Uri(redirectUrl);
                dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                string accessToken = tokenResult.access_token;

                DateTime expiresOn = DateTime.MaxValue;

                if (tokenResult.ContainsKey("expires"))
                {
                    DateTimeConvertor.FromUnixTime(tokenResult.expires);
                }

                FacebookClient fbClient = new FacebookClient(accessToken);
                dynamic me = fbClient.Get("me?fields=id,name");
                long facebookID = Convert.ToInt64(me.id);

                Account acc = (from x in db.Account.OfType<Account>() where x.FaceBookID == facebookID select x).FirstOrDefault();
                if (acc == null)
                {
                    acc = CreateAccount(me);
                }
                acc.LatestLogin = DateTime.Now;
                db.Entry(acc).State = EntityState.Modified;
                db.SaveChanges();

                MemoryUserStore.CurrentAccount = acc;

                UserRoleProvider usp = new UserRoleProvider();
                usp.GetRolesForUser(acc.AccountID.ToString());
                FormsAuthentication.SetAuthCookie(acc.AccountID.ToString(), false);

                if (Url.IsLocalUrl(state))
                {
                    return Redirect(state);
                }
                return RedirectToAction("Details", "Account", new { id = acc.AccountID });
            }
        }

        return RedirectToAction("Index", "Account");
    }

What i am trying to do here, is to first verify if the token i get back from the redirect is valid. If it is, then i pull some data about the visitor, like FacebookID and Name. I then match it with my database, to see if the user already exists, and if not, i create one. I also assign a role for the user in my custom Role provider, but i had the infinite loop problem before this. Then i set

FormsAuthentication.SetAuthCookie(acc.AccountID.ToString(), false);

and i assume this is the core of keeping track of wheter a visitor is authorized or not. As far as i understand, when the visitor is trying to call a ActionResult that requires [Authorize] then the system will check for this cookie.

Well, could someone please clarify why the above code is working in Chrome/Safari, but keeps looping through Login and then OAuth infinitely in IE?

My app is using MVC 3, EF Code First and Facebook C# SDK 5.0.25


来源: stackexchange

问:
When using .rotate() it leaves 1px Lines behind
I'm currently learning about the html5 canvas, and I was making a program that rotates a square around the center of the page using the .rotate() function, but it was leaving behind 1px lines from where the square used to be even though I was filling the canvas after every turn and nothing in the code was 1px. so can someone please explain why this is happening and how to stop it from happening

thanks!

const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")

canvas.width = 300;
canvas.height = 300;

//debugger;
/*
canvas.addEventListener("mousedown", mouseDown, false)
canvas.addEventListener("mouseup", mouseUp, false)
canvas.addEventListener("mousemove", mouseMove, false)
*/

ctx.fillStyle = "#303030";
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.translate(150, 150)

let turnSquare = setInterval(() =>{
 ctx.fillStyle = "#303030"
 ctx.fillRect(0, 0, canvas.width, canvas.height)

 ctx.rotate(degree(10))

 ctx.beginPath()
 ctx.fillStyle = "lime"
 ctx.fillRect(0, 0, 100, 100)

}, 1000 / 20)

function degree(input){
 return 2 * Math.PI / 360 * input
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></code>```

答:
Use a let deg = 0 variable

Use clearRect before repainting the canvas

.save() the context before rotating it

Rotate and translate the context before painting the square

.restore() the context

let deg = 0; // Prepare degrees
const degree = input => 2 * Math.PI / 360 * input;
const ctx = document.getElementById("canvas").getContext("2d");

ctx.canvas.width = 300;
ctx.canvas.height = 300;

const rotateSquare = () => {
    deg += degree(10); // Increment degrees
    deg %= 360;        // Loop degrees
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    // BACKGROUND:
    ctx.fillStyle = "#303030"
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)

    // SQUARE:
    ctx.save();
        ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);
        ctx.rotate(deg);
        ctx.fillStyle = "lime";
        ctx.fillRect(0, 0, 100, 100);
    ctx.restore();
}

let turnSquare = setInterval(rotateSquare, 1000 / 20)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently learning about the html5 canvas, and I was making a program that rotates a square around the center of the page using the .rotate() function, but it was leaving behind 1px lines from where the square used to be even though I was filling the canvas after every turn and nothing in the code was 1px. so can someone please explain why this is happening and how to stop it from happening

thanks!

const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")

canvas.width = 300;
canvas.height = 300;

//debugger;
/*
canvas.addEventListener("mousedown", mouseDown, false)
canvas.addEventListener("mouseup", mouseUp, false)
canvas.addEventListener("mousemove", mouseMove, false)
*/

ctx.fillStyle = "#303030";
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.translate(150, 150)

let turnSquare = setInterval(() =>{
 ctx.fillStyle = "#303030"
 ctx.fillRect(0, 0, canvas.width, canvas.height)

 ctx.rotate(degree(10))

 ctx.beginPath()
 ctx.fillStyle = "lime"
 ctx.fillRect(0, 0, 100, 100)

}, 1000 / 20)

function degree(input){
 return 2 * Math.PI / 360 * input
}

<canvas id="canvas">

Body:
Use a let deg = 0 variable

Use clearRect before repainting the canvas

.save() the context before rotating it

Rotate and translate the context before painting the square

.restore() the context

let deg = 0; // Prepare degrees
const degree = input => 2 * Math.PI / 360 * input;
const ctx = document.getElementById("canvas").getContext("2d");

ctx.canvas.width = 300;
ctx.canvas.height = 300;

const rotateSquare = () => {
    deg += degree(10); // Increment degrees
    deg %= 360;        // Loop degrees
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    // BACKGROUND:
    ctx.fillStyle = "#303030"
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)

    // SQUARE:
    ctx.save();
        ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);
        ctx.rotate(deg);
        ctx.fillStyle = "lime";
        ctx.fillRect(0, 0, 100, 100);
    ctx.restore();
}

let turnSquare = setInterval(rotateSquare, 1000 / 20)

<canvas id="canvas"></canvas>


问:
RecyclerView scrolls to top after adding items
I have a RecyclerView that I use to display items in an activity. When I scroll to the bottom, I make another API call to fetch an additional set of data. When the items load, my RecyclerView scrolls to the top. I have tried the other solutions listed without success. I have attempted many if not all of the suggestions mentioned in similar threads. None of them worked for me.

activity_see_more.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/see_more_frameLayout" />
</LinearLayout>
</code>```

In the SeeMoreActivity.java I override the following method from the MvpView

```<code>@Override
public void loadPropertiesForCategory(List<Property> propertyList) {
    Preferences sharedPref = new Preferences(this);
    if (!properties.containsAll(propertyList)) {
        properties.addAll(propertyList);
    }
    sharedPref.setFilterList(properties);
    ResultListFragment fragment = ResultListFragment.setTag("see_more_filter");
    getSupportFragmentManager().beginTransaction().add(R.id.see_more_frameLayout, fragment, "search").commit();
}
</code>```

ResultListFragment.java

```<code>private void setListOfCategoryProperties() {
    page = 2;
    mSearchList = mPreferences.getFilterList();
    setListAdapter(false, false, View.VISIBLE, View.GONE, false);
    mResultRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (linearLayoutManager != null && linearLayoutManager.findLastVisibleItemPosition() == mSearchList.size() - 1) {
                ((SeeMoreActivity) getActivity()).setLoadPropertiesParamsAndCallApi(page);
                if (mSearchList.size() != mPreferences.getFilterList().size()) {
                    page++;
                    mSearchList = mPreferences.getFilterList();
                    //mAdapter.notifyDataSetChanged();
                    mAdapter.notifyItemInserted(mSearchList.size() - 1);
                }
            }
        }
    });
}

public void listAdapter() {
    mResultRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
    mResultRecycleView.setItemAnimator(new DefaultItemAnimator());
    mResultRecycleView.setNestedScrollingEnabled(true);
    mResultRecycleView.setAdapter(mAdapter);
}

private void setListAdapter(boolean showDeleteButton, boolean changeVisibility, int showNoResult, int showNoSavedSearch, boolean reverseFavorite) {
        if (mSearchList != null && mSearchList.size() != 0) {
            if (changeVisibility) {
                setVisibility(View.VISIBLE, View.GONE, View.GONE);
            }
            mAdapter = new SearchListAdapter(R.layout.item_single_element, mSearchList, showDeleteButton, this, reverseFavorite);
            listAdapter();
        } else {
            setVisibility(View.GONE, showNoSavedSearch, showNoResult);
        }
    }

public void handleTags() {
        switch (mTag) {
            case "result_search":
                setListAdapterForHomeSearch();
                break;
            case "see_more_filter":
                setListOfCategoryProperties();
                break;
            case Constants.USER_FAVORITES_KEY:
                setListOfUserFavoriteProperties();
                break;
        }
    }
</code>```

答: Issue was  that I was creating a new instance of my fragment every time I made an API call. Now that I create only one instance and update the list by just adding new elements to it, everything works correctly.</p>

Body:
I have a RecyclerView that I use to display items in an activity. When I scroll to the bottom, I make another API call to fetch an additional set of data. When the items load, my RecyclerView scrolls to the top. I have tried the other solutions listed without success. I have attempted many if not all of the suggestions mentioned in similar threads. None of them worked for me.

activity_see_more.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/see_more_frameLayout" />
</LinearLayout>

In the SeeMoreActivity.java I override the following method from the MvpView

@Override
public void loadPropertiesForCategory(List<Property> propertyList) {
    Preferences sharedPref = new Preferences(this);
    if (!properties.containsAll(propertyList)) {
        properties.addAll(propertyList);
    }
    sharedPref.setFilterList(properties);
    ResultListFragment fragment = ResultListFragment.setTag("see_more_filter");
    getSupportFragmentManager().beginTransaction().add(R.id.see_more_frameLayout, fragment, "search").commit();
}

ResultListFragment.java

private void setListOfCategoryProperties() {
    page = 2;
    mSearchList = mPreferences.getFilterList();
    setListAdapter(false, false, View.VISIBLE, View.GONE, false);
    mResultRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (linearLayoutManager != null && linearLayoutManager.findLastVisibleItemPosition() == mSearchList.size() - 1) {
                ((SeeMoreActivity) getActivity()).setLoadPropertiesParamsAndCallApi(page);
                if (mSearchList.size() != mPreferences.getFilterList().size()) {
                    page++;
                    mSearchList = mPreferences.getFilterList();
                    //mAdapter.notifyDataSetChanged();
                    mAdapter.notifyItemInserted(mSearchList.size() - 1);
                }
            }
        }
    });
}

public void listAdapter() {
    mResultRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
    mResultRecycleView.setItemAnimator(new DefaultItemAnimator());
    mResultRecycleView.setNestedScrollingEnabled(true);
    mResultRecycleView.setAdapter(mAdapter);
}

private void setListAdapter(boolean showDeleteButton, boolean changeVisibility, int showNoResult, int showNoSavedSearch, boolean reverseFavorite) {
        if (mSearchList != null && mSearchList.size() != 0) {
            if (changeVisibility) {
                setVisibility(View.VISIBLE, View.GONE, View.GONE);
            }
            mAdapter = new SearchListAdapter(R.layout.item_single_element, mSearchList, showDeleteButton, this, reverseFavorite);
            listAdapter();
        } else {
            setVisibility(View.GONE, showNoSavedSearch, showNoResult);
        }
    }

public void handleTags() {
        switch (mTag) {
            case "result_search":
                setListAdapterForHomeSearch();
                break;
            case "see_more_filter":
                setListOfCategoryProperties();
                break;
            case Constants.USER_FAVORITES_KEY:
                setListOfUserFavoriteProperties();
                break;
        }
    }


问:
GitVersion appending '-pullrequest1089-0002' to build number
I have a build pipeline set up on Azure Devops for building a Nuget Package.

So far I have been using only the master branch, after each push to the master branch and then manually triggering the build, the build number got correctly incremented.

Yesterday I decided to create a feature branch, implemented some changes and created a PR. After it got approved and merged into master I manually trigger a new build but this time the build version contains the '-pullrequest1089-0002' string as well. This means that this new version is not available in NuGet package manager for me to install.

I need to somehow configure this so this won't get appended.

This is how my gitversion.yml file looks like:

```<code>mode: MainLine
next-version: 1.0.0
</code>```

答:
For this issue , agree with rbennett485 , since the format 1.0.32-xxx is the format of pre-release nuget packages. To get it to display in nuget package manager, you just need to enable the Include prerelease checkbox.

You can compare the two pictures below to see the difference:

Body:
I have a build pipeline set up on Azure Devops for building a Nuget Package.

So far I have been using only the master branch, after each push to the master branch and then manually triggering the build, the build number got correctly incremented.

Yesterday I decided to create a feature branch, implemented some changes and created a PR. After it got approved and merged into master I manually trigger a new build but this time the build version contains the '-pullrequest1089-0002' string as well. This means that this new version is not available in NuGet package manager for me to install.

I need to somehow configure this so this won't get appended.

This is how my gitversion.yml file looks like:

mode: MainLine
next-version: 1.0.0


问:
How resource requests maps into streams in HTTP/2
I could not found this RFC, and I'm wondering are there any rules regarding how resource requests from HTTP/2 Client are mapped into HTTP/2 streams.

Is it one-to-one, where each stream represents data for one resource request (e.g. image, js, html) or it is possible to use one stream to transfer multiple resources ?

How stream priories differs from stream dependencies (for me both are directly influencing final order of resource retrieval) ?
Are there any general strategies how browsers are handling streams and streams dependencies ?

Many thanks for help!

答:
I could not found this RFC, and I'm wondering are there any rules regarding how resource requests from HTTP/2 Client are mapped into HTTP/2 streams.

Is it one-to-one, where each stream represents data for one resource request (e.g. image, js, html) or it is possible to use one stream to transfer multiple resources ?

From the HTTP/2 RFC:

Multiplexing of requests is achieved by having each HTTP request/response exchange associated with its own stream (Section 5).

and also later:

Stream identifiers cannot be reused.

As to your next questions:

How stream priories differs from stream dependencies (for me both are directly influencing final order of resource retrieval) ?

They are part of the same prioritisation scheme. Dependencies allow for certain resources to be sent in preference to others, whereas priority weighting allows resources to be sent at same time but weighted to proportion more of the available bandwidth to some resources.

Are there any general strategies how browsers are handling streams and streams dependencies ?

They all handle streams the same way but dependencies are handled completely differently.

Chrome uses dependencies a lot and creates a long chain on single dependencies that should be resolved in order where possible. Higher priority resources are added further up the chain. Chrome does not use weighting a.

Safari does the opposite and sends all requests without dependencies but with appropriate weighting.

Firefox creates a complex dependency tree using both weighting’s and dependencies.

Old Edge does no prioritisation so uses HTTP/2 default of equally weighed resources with no dependencies. New Edge is based on Chrome so follows that.

It’s generally accepted Chrome is usually better, but suffers when downloading resources that would be better downloaded in parallel (e.g. images - especially progressive JPEGs). Firefox does better here but is slightly less optimal for resources that need to be downloaded in its entirety (e.g. critical CSS and JS). Safari’s only OK and usually worse than both. And old Edge was the absolute worst. This is a good talk on the state of affairs: https://m.youtube.com/watch?v=sgjxuhFQktE

For HTTP/3 they are looking at changing their complex model. Good talk on that here: https://m.youtube.com/watch?v=nH4iRpFnf1c&feature=youtu.be


问:
How can I convert byte size into a human-readable format in Java?
How can I convert byte size into a human-readable format in Java?

Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".

I am kind of sick of writing this utility method for each project. Is there a static method in Apache Commons for this?

答:
Here is the conversion from aioobe converted to Kotlin:

```<code>/**
 * https://stackoverflow.com/a/3758880/1006741
 */
fun Long.humanReadableByteCountBinary(): String {
    val b = when (this) {
        Long.MIN_VALUE -> Long.MAX_VALUE
        else -> abs(this)
    }
    return when {
        b < 1024L -> "$this B"
        b <= 0xfffccccccccccccL shr 40 -> "%.1f KiB".format(Locale.UK, this / 1024.0)
        b <= 0xfffccccccccccccL shr 30 -> "%.1f MiB".format(Locale.UK, this / 1048576.0)
        b <= 0xfffccccccccccccL shr 20 -> "%.1f GiB".format(Locale.UK, this / 1.073741824E9)
        b <= 0xfffccccccccccccL shr 10 -> "%.1f TiB".format(Locale.UK, this / 1.099511627776E12)
        b <= 0xfffccccccccccccL -> "%.1f PiB".format(Locale.UK, (this shr 10) / 1.099511627776E12)
        else -> "%.1f EiB".format(Locale.UK, (this shr 20) / 1.099511627776E12)
    }
}
</code>```

Body:
Here is the conversion from aioobe converted to Kotlin:

/**
 * https://stackoverflow.com/a/3758880/1006741
 */
fun Long.humanReadableByteCountBinary(): String {
    val b = when (this) {
        Long.MIN_VALUE -> Long.MAX_VALUE
        else -> abs(this)
    }
    return when {
        b < 1024L -> "$this B"
        b <= 0xfffccccccccccccL shr 40 -> "%.1f KiB".format(Locale.UK, this / 1024.0)
        b <= 0xfffccccccccccccL shr 30 -> "%.1f MiB".format(Locale.UK, this / 1048576.0)
        b <= 0xfffccccccccccccL shr 20 -> "%.1f GiB".format(Locale.UK, this / 1.073741824E9)
        b <= 0xfffccccccccccccL shr 10 -> "%.1f TiB".format(Locale.UK, this / 1.099511627776E12)
        b <= 0xfffccccccccccccL -> "%.1f PiB".format(Locale.UK, (this shr 10) / 1.099511627776E12)
        else -> "%.1f EiB".format(Locale.UK, (this shr 20) / 1.099511627776E12)
    }
}


问:
Remove Duplicate object from Array Deep Check
I have a array of objects, like:

```<code>[{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}]
</code>```

I want this array to be unique on the basis of offerId. If offerId is the same, then I want to remove that object from the array.

答:
You can just use a Map, with reduce, and grab the values from the map:

const arr = [{
    actionType: 10,
    orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
    productComponentAction: {
      productComponent: {
        offerId: 10002839,
        parentOfferId: 10003058,
        adoptableProdCompId: undefined
      }
    }
  },
  {
    actionType: 10,
    orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
    productComponentAction: {
      productComponent: {
        offerId: 10002839,
        parentOfferId: 10003058,
        adoptableProdCompId: undefined
      }
    }
  }
]

const filtered = Array.from(arr.reduce((a, v) => {
  const id = v.productComponentAction.productComponent.offerId
  if(!a.has(id)) a.set(id, v)
  return a
}, new Map()).values())

console.log(filtered)```

Body:
I have a array of objects, like:

[{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}]

I want this array to be unique on the basis of offerId. If offerId is the same, then I want to remove that object from the array.


问:
JSONDecodeError: Expecting value: line 1 column 1 (char 0) for Keras+Rest API Application
I am trying to return an HTTP response from my keras model.

```<code>@app.route("/predict", methods=["POST"])
def predict():
    # initialize the data dictionary that will be returned from the
    # view
    data = {"success": False}

    # ensure an image was properly uploaded to our endpoint
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            # read the image in PIL format
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            # preprocess the image and prepare it for classification
            image = prepare_image(image, target=(224, 224))

            proba = model.predict(image)[0]
            idx = np.argmax(proba)
            label = lb.classes_[idx]
            r = {"label": label, "probability": float(proba[idx] * 100)}
            y = json.dumps(r)

    # return the data dictionary as a JSON response
    return y

if __name__ == "__main__":
    print(("* Loading Keras model and Flask starting server..."
        "please wait until server has fully started"))
    load_my_model()
    app.run()

import requests

# initialize the Keras REST API endpoint URL along with the input
# image path
KERAS_REST_API_URL = "http://localhost:5000/my_predict"
IMAGE_PATH = "dog.jpg"

# load the input image and construct the payload for the request
image = open(IMAGE_PATH, "rb").read()
payload = {"image": image}

# submit the request
r = requests.post(KERAS_REST_API_URL, files=payload).json()

# ensure the request was successful
if r["success"]:
    # loop over the predictions and display them
    for (i, result) in enumerate(r["predictions"]):
        print("{}. {}: {:.4f}".format(i + 1, result["label"],
            result["probability"]))

# otherwise, the request failed
else:
    print("Request failed”)
</code>```

The first part runs:

Loading Keras model and Flask starting server...please wait until server has fully started

Serving Flask app "main" (lazy loading)

Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.

Debug mode: off

Running on http://127.0.0.1:5000/

But the next part Gives me: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

答:
You can take a look at this, an example on how to send an image over a post request, You don't need to send a json, just the image:
    import cv2

```<code># prepare headers for http request
content_type = 'image/jpeg'
headers = {'content-type': content_type}

img = cv2.imread('lena.jpg')
# encode image as jpeg
_, img_encoded = cv2.imencode('.jpg', img)
# send http request with image and receive response
response = requests.post(url, data=img_encoded.tostring(), headers=headers)
# decode response
print(json.loads(response.text))
</code>```

to decode the image on the flask server just:

```<code>import cv2

# convert string of image data to uint8
nparr = np.fromstring(flask.request.data, np.uint8)
# decode image
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

# do some fancy processing here....
</code>```

Body:
I am trying to return an HTTP response from my keras model.

@app.route("/predict", methods=["POST"])
def predict():
    # initialize the data dictionary that will be returned from the
    # view
    data = {"success": False}

    # ensure an image was properly uploaded to our endpoint
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            # read the image in PIL format
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            # preprocess the image and prepare it for classification
            image = prepare_image(image, target=(224, 224))

            proba = model.predict(image)[0]
            idx = np.argmax(proba)
            label = lb.classes_[idx]
            r = {"label": label, "probability": float(proba[idx] * 100)}
            y = json.dumps(r)

    # return the data dictionary as a JSON response
    return y

if __name__ == "__main__":
    print(("* Loading Keras model and Flask starting server..."
        "please wait until server has fully started"))
    load_my_model()
    app.run()

import requests

# initialize the Keras REST API endpoint URL along with the input
# image path
KERAS_REST_API_URL = "http://localhost:5000/my_predict"
IMAGE_PATH = "dog.jpg"

# load the input image and construct the payload for the request
image = open(IMAGE_PATH, "rb").read()
payload = {"image": image}

# submit the request
r = requests.post(KERAS_REST_API_URL, files=payload).json()

# ensure the request was successful
if r["success"]:
    # loop over the predictions and display them
    for (i, result) in enumerate(r["predictions"]):
        print("{}. {}: {:.4f}".format(i + 1, result["label"],
            result["probability"]))

# otherwise, the request failed
else:
    print("Request failed”)

The first part runs:

Loading Keras model and Flask starting server...please wait until server has fully started

Serving Flask app "main" (lazy loading)

Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.

Debug mode: off

Running on http://127.0.0.1:5000/

But the next part Gives me: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Body:
You can take a look at this, an example on how to send an image over a post request, You don't need to send a json, just the image:
    import cv2

# prepare headers for http request
content_type = 'image/jpeg'
headers = {'content-type': content_type}

img = cv2.imread('lena.jpg')
# encode image as jpeg
_, img_encoded = cv2.imencode('.jpg', img)
# send http request with image and receive response
response = requests.post(url, data=img_encoded.tostring(), headers=headers)
# decode response
print(json.loads(response.text))

to decode the image on the flask server just:

import cv2

# convert string of image data to uint8
nparr = np.fromstring(flask.request.data, np.uint8)
# decode image
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

# do some fancy processing here....


答:
You can use a temporary Map, keyed by whatever you want to be unique. Its constructor accepts [key,value] pairs:

let data = [{actionType: 10, orderItemId: "3205ae52-ab00-4823-a004-da0cda639065", productComponentAction:{productComponent:{ offerId: 10002839, parentOfferId: 10003058,     adoptableProdCompId: undefined } }},{actionType: 10,orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae", productComponentAction:{ productComponent:{ offerId: 10002839,      parentOfferId: 10003058, adoptableProdCompId: undefined  }  }}];

let uniques = Array.from(new Map(
     data.map(item => [item.productComponentAction.productComponent.offerId, item])
).values());

console.log(uniques);```

Title: Remove Duplicate object from Array Deep Check


问:
react-aad-msal clearing localstorage. passing state around
So I've been hitting a wall over this last 2 days.
I haven't play around with ract/front end work for close to 2 years so please bear with me.

Scenario:

- load page

- throw stuff in localstorage (query string params)

- navigate to login authorization page (using react-aad-msal for this)

- get back to the main page

- try to retrieve data from localstorage and the keys I've added are missing. There are msal tokens etc present.

Enviroment:

- Chrome

- React plugin for debug

Unexpected twist: this happens at random. For the best part of yesterday it was working. and than the keys I've added started to go awol. Same thing this morning.

To my understanding - if I put something in localstorage, it stays there unless requested to be removed, programmatically or other way.

So what is going on here?

答:
Ok think I got it. It must be behavior of the msal - be it react-aad-msal or actual msal.js it is wrapping around. Anyway, solution proved to be to pass query string in state parameter on AuthenticationParameters when creating the provider omitting the local storage issue all together.

I just pass the query string from component:

```<code><AzureAD
 provider={authProviderWithState(this.props.queryString)}
 reduxStore={this.props.reduxStore}
 forceLogin={false}>
</code>```

Which is then glued on the top of defaults

```<code>export const authProviderWithState = (state) => {
    whichAuthParams.state = state;
    return new MsalAuthProvider(whichConfig, whichAuthParams, LoginType.Redirect);
};
</code>```

State is simply appended to the callback url used by the authorization endpoint so it works as I need it.

Body:
Ok think I got it. It must be behavior of the msal - be it react-aad-msal or actual msal.js it is wrapping around. Anyway, solution proved to be to pass query string in state parameter on AuthenticationParameters when creating the provider omitting the local storage issue all together.

I just pass the query string from component:

<AzureAD
 provider={authProviderWithState(this.props.queryString)}
 reduxStore={this.props.reduxStore}
 forceLogin={false}>

Which is then glued on the top of defaults

export const authProviderWithState = (state) => {
    whichAuthParams.state = state;
    return new MsalAuthProvider(whichConfig, whichAuthParams, LoginType.Redirect);
};

State is simply appended to the callback url used by the authorization endpoint so it works as I need it.


问:
How to create your own loss function for tf.keras that uses additional parameter?
My need:

I would like to modify my loss function in Neural Network by adding sample weights. (I am aware that .fit method has sample_weight parameter).

My idea was to create additional input to my Neural Network with precomputed weights for each train data row like this:

```<code># Generating mock data
train_X = np.random.randn(100, 5)
train_Y = np.random.randn(100, 1)
train_sample_weights = np.random.randn(*train_Y.shape)

# Designing loss function that uses my pre-computed weights
def example_loss(y_true, y_pred, sample_weights_):
    return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_

# Two inputs for neural network, one for data, one for weights
input_tensor = Input(shape=(train_X.shape[1],))
weights_tensor = Input(shape=(train_sample_weights.shape[1],))

# Model uses only 'input_tensor'
x = Dense(100, activation="relu")(input_tensor)
out = Dense(1)(x)

# The 'weight_tensor' is inserted into example_loss() functon
loss_function = partial(example_loss, sample_weights_=weights_tensor)

# Model takes as an input both data and weights
model = Model([input_tensor, weights_tensor], out)
model.compile("Adam", loss_function)
model.fit(x=[train_X, train_sample_weights], y=train_Y, epochs=10)
</code>```

My problem:

Following code works when I use Keras 2.2.4 imports to run it:

```<code>import numpy as np
from functools import partial

import keras.backend as K
from keras.layers import Input, Dense
from keras.models import Model

</code>```

Following code crashes when I use tf.keras 2.2.4-tf imports to run it:

```<code>import numpy as np
from functools import partial

import tensorflow.keras.backend as K
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
</code>```

With the following error:

TypeError: example_loss() got an unexpected keyword argument
  'sample_weight'

My questions:

Why this happens?

How could I rewrite the code so such architecture could also work on 2.2.4-tf?

Proposition that works on both Keras/tf.keras frameworks is also an acceptable answer for me.

Error is easy to reproduce. Just need to copy the code and run.

答:
You can rewrite your loss like this:

```<code># Designing loss function that uses my pre-computed weights
def example_loss(sample_weights_):
    def loss(y_true, y_pred):
        return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_
</code>```

As you see, here we have a function that takes the sample weights, and returns another function (the actual loss) that has the sample weights embedded into it. You can use it as:

```<code>model.compile(optimizer="adam", loss=example_loss(weights_tensor))
</code>```

Body:
My need:

I would like to modify my loss function in Neural Network by adding sample weights. (I am aware that .fit method has sample_weight parameter).

My idea was to create additional input to my Neural Network with precomputed weights for each train data row like this:

# Generating mock data
train_X = np.random.randn(100, 5)
train_Y = np.random.randn(100, 1)
train_sample_weights = np.random.randn(*train_Y.shape)

# Designing loss function that uses my pre-computed weights
def example_loss(y_true, y_pred, sample_weights_):
    return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_

# Two inputs for neural network, one for data, one for weights
input_tensor = Input(shape=(train_X.shape[1],))
weights_tensor = Input(shape=(train_sample_weights.shape[1],))

# Model uses only 'input_tensor'
x = Dense(100, activation="relu")(input_tensor)
out = Dense(1)(x)

# The 'weight_tensor' is inserted into example_loss() functon
loss_function = partial(example_loss, sample_weights_=weights_tensor)

# Model takes as an input both data and weights
model = Model([input_tensor, weights_tensor], out)
model.compile("Adam", loss_function)
model.fit(x=[train_X, train_sample_weights], y=train_Y, epochs=10)

My problem:

Following code works when I use Keras 2.2.4 imports to run it:

import numpy as np
from functools import partial

import keras.backend as K
from keras.layers import Input, Dense
from keras.models import Model

Following code crashes when I use tf.keras 2.2.4-tf imports to run it:

import numpy as np
from functools import partial

import tensorflow.keras.backend as K
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model

With the following error:

TypeError: example_loss() got an unexpected keyword argument
  'sample_weight'

My questions:

Why this happens?

How could I rewrite the code so such architecture could also work on 2.2.4-tf?

Proposition that works on both Keras/tf.keras frameworks is also an acceptable answer for me.

Error is easy to reproduce. Just need to copy the code and run.

Body:
You can rewrite your loss like this:

# Designing loss function that uses my pre-computed weights
def example_loss(sample_weights_):
    def loss(y_true, y_pred):
        return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_

As you see, here we have a function that takes the sample weights, and returns another function (the actual loss) that has the sample weights embedded into it. You can use it as:

model.compile(optimizer="adam", loss=example_loss(weights_tensor))


问:
Images in ViewPager don't fill the screen
I am receiving a set of URL images from API to show as slider so I am using viewpager to do my job and when I am trying to set Images in viewpager to fill screen according to imagesize this doesn't happen at all.

All the red line is huge spacing.. I am not sure why this there?

I am trying do the following in XML:

```<code><RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/noData"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="@string/nointernet"
                android:textColor="#000000"
                android:textSize="14sp"
                android:textStyle="italic"
                android:visibility="gone" />

            <android.support.v4.view.ViewPager
                android:id="@+id/myviewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </android.support.v4.view.ViewPager>

            <FrameLayout
                android:id="@+id/progressContainer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:visibility="gone"
                android:layout_centerVertical="true">

                <com.ylg.librarys.ProgressWheel xmlns:wheel="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/progress_wheel"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:visibility="visible"
                    app:matProg_barColor="@color/colorPrimary"
                    app:matProg_progressIndeterminate="true" />
            </FrameLayout>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/pagerLayoutIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pagerIndicator"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="2dp">

            <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:fillColor="@color/orangeText"
                app:pageColor="@color/whitetext"
                app:strokeColor="@color/orangeText" />
        </RelativeLayout>
</code>```

PageAdapter looks like this:

```<code>@Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            progressContainer.setVisibility(View.GONE);

            wheel_layout.setVisibility(View.GONE);

            noData = (TextView)rootView.findViewById(R.id.noData);
            noData.setVisibility(View.GONE);

            ImageView imageView = new ImageView(getActivity());
            imageLoader.DisplayImage(bannerItems.get(position).getbannerImage(), 0, imageView);

            LayoutParams imageParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            imageView.setLayoutParams(imageParams);

            LinearLayout layout = new LinearLayout(getActivity());
            layout.setOrientation(LinearLayout.VERTICAL);
            LayoutParams layoutParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            layout.setLayoutParams(layoutParams);
            layout.addView(imageView);

            final int page = position;
            layout.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(),
                            "Page " + page + " clicked",
                            Toast.LENGTH_LONG).show();
                }});

            container.addView(layout);

            return layout;
        }
</code>```

Strangely If I don't give the height for the relativeLayout in which viewpager is sitting I don't see the image at all. that is If I set:

```<code>       <RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">
</code>```

I only get PageIndicator. Above ViewPager with image is not shown at all.

Not sure why this happening? How do I set the image match_parent so that it shows full without any gap?

答:
There can't be fulfill your need.if a view pager contains an imageview, it needs a fixed height and width to imageview.you can set the scaletype as fitStart or fitEnd to make the gap before the image or after the image.it will solve a little gap problem.

Thank you.

ContentLicense: CC BY-SA 3.0

Body:
I am receiving a set of URL images from API to show as slider so I am using viewpager to do my job and when I am trying to set Images in viewpager to fill screen according to imagesize this doesn't happen at all.

All the red line is huge spacing.. I am not sure why this there?

I am trying do the following in XML:

<RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/noData"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="@string/nointernet"
                android:textColor="#000000"
                android:textSize="14sp"
                android:textStyle="italic"
                android:visibility="gone" />

            <android.support.v4.view.ViewPager
                android:id="@+id/myviewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </android.support.v4.view.ViewPager>

            <FrameLayout
                android:id="@+id/progressContainer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:visibility="gone"
                android:layout_centerVertical="true">

                <com.ylg.librarys.ProgressWheel xmlns:wheel="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/progress_wheel"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:visibility="visible"
                    app:matProg_barColor="@color/colorPrimary"
                    app:matProg_progressIndeterminate="true" />
            </FrameLayout>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/pagerLayoutIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pagerIndicator"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="2dp">

            <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:fillColor="@color/orangeText"
                app:pageColor="@color/whitetext"
                app:strokeColor="@color/orangeText" />
        </RelativeLayout>

PageAdapter looks like this:

@Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            progressContainer.setVisibility(View.GONE);

            wheel_layout.setVisibility(View.GONE);

            noData = (TextView)rootView.findViewById(R.id.noData);
            noData.setVisibility(View.GONE);

            ImageView imageView = new ImageView(getActivity());
            imageLoader.DisplayImage(bannerItems.get(position).getbannerImage(), 0, imageView);

            LayoutParams imageParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            imageView.setLayoutParams(imageParams);

            LinearLayout layout = new LinearLayout(getActivity());
            layout.setOrientation(LinearLayout.VERTICAL);
            LayoutParams layoutParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            layout.setLayoutParams(layoutParams);
            layout.addView(imageView);

            final int page = position;
            layout.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(),
                            "Page " + page + " clicked",
                            Toast.LENGTH_LONG).show();
                }});

            container.addView(layout);

            return layout;
        }

Strangely If I don't give the height for the relativeLayout in which viewpager is sitting I don't see the image at all. that is If I set:

       <RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">

I only get PageIndicator. Above ViewPager with image is not shown at all.

Not sure why this happening? How do I set the image match_parent so that it shows full without any gap?


问:
PHP trouble json_decoding multi level json array
I am trying to parse json from Amazon SNS using PHP and json_decode.

I am storing the json from Amazon in a mysql database, and then looping through the rows to hopefully display a table of all notifications.

This is the original json that comes in:

```<code>{
"Type": "Notification",
"MessageId": "4ecca6d5-3095-5d5c-a0f0-f013dc59f33e",
"TopicArn": "arn:aws:sns:eu-west-1:826492718737:Email_Notifications",
"Message": "{\"notificationType\":\"Delivery\",\"mail\":{\"timestamp\":\"2020-02-19T07:58:03.541Z\",\"source\":\"do-not-reply@supplyplus.org.uk\",\"sourceArn\":\"arn:aws:ses:eu-west-1:826492718737:identity/do-not-reply@supplyplus.org.uk\",\"sourceIp\":\"82.68.110.206\",\"sendingAccountId\":\"826492718737\",\"messageId\":\"010201705c743115-5bc7fc12-f36d-425a-8ff8-14ea0acf073b-000000\",\"destination\":[\"edward.hall@setsquaresolutions.com\"]},\"delivery\":{\"timestamp\":\"2020-02-19T07:58:04.226Z\",\"processingTimeMillis\":685,\"recipients\":[\"edward.hall@setsquaresolutions.com\"],\"smtpResponse\":\"250 2.0.0 OK  1582099084 z21si661666ejr.129 - gsmtp\",\"remoteMtaIp\":\"209.85.202.27\",\"reportingMTA\":\"a4-7.smtp-out.eu-west-1.amazonses.com\"}}",
"Timestamp": "2020-02-19T07:58:04.286Z",
"SignatureVersion": "1",
"Signature": "XjCUN+iogrinljvfc32wG55UUT1WUVhhIpXYPZtW9IcBiJfBnlQETy2LNlLPnGjtqcKKuV8IKQbC06DIW3EeiKGzfxeQE8OthJJOEGexcA1qr6EbMPLalhDRSmmoUC8a6vY4d3Gn/R98lzaij5UUbT9y4Oesuq8NFR98m8WpOZqMwBdjsRRhZuN676c/or9x6ibU1kWExXKxw/Cw77hhkT5Hd52gNsg2nla+V6oVWXfn/jCmUWByrJRFdxe1nUm+WbcNT4nCkqKxUBT/NTA5RkD72Mr+X/470WNXBJZ6OP/4tbby3bcn7BxzZBA780c2OBtRlseD2MvKJGE8qss2og==",
"SigningCertURL": "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-a86cb10b4e1f29c941702d737128f7b6.pem",
"UnsubscribeURL": "https://sns.eu-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-west-1:826492718737:Email_Notifications:b584a2d6-c9e3-4401-a029-7b6fd4603274"
</code>```

}

The json after it has been inserted into the database looks like this:

```<code>{
  "Type" : "Notification",
  "MessageId" : "3ce843a7-13c2-54f8-a445-1561121fd162",
  "TopicArn" : "arn:aws:sns:eu-west-1:826492718737:Email_Notifications",
  "Message" : "{"notificationType":"Delivery","mail":{"timestamp":"2020-02-18T15:15:40.879Z","source":"do-not-reply@example.com","sourceArn":"arn:aws:ses:eu-west-1:826492718737:identity/do-not-reply@example.com","sourceIp":"12.34.56.78","sendingAccountId":"826492718737","messageId":"0102017058de7ccf-55c4a34d-fcd1-449c-a82a-9946b316e551-000000","destination":["user@example.com"]},"delivery":{"timestamp":"2020-02-18T15:15:41.527Z","processingTimeMillis":648,"recipients":["user@example.com"],"smtpResponse":"250 2.0.0 OK  1582038941 p17si2420323wma.126 - gsmtp","remoteMtaIp":"12.34.56.78","reportingMTA":"a4-8.smtp-out.eu-west-1.amazonses.com"}}",
  "Timestamp" : "2020-02-18T15:15:41.574Z",
  "SignatureVersion" : "1",
  "Signature" : "UTzy1PLgzxyz7wczh/3ZrcKiT9MCFe7pcmeOLH3whZ6tRbq1B6pjv+cEjTFKR3RnH4D9CkDQq04vpTyj3ATwJ5ZSxVOuNmGEo1KuOjH8TveaB3PzQTpwQlsVg1fzW5wCmhND9dvDuXiTGc86Lvy4e9AlmGNHTrfbAa5fZIfFfP9PzEhHF8zcyIvZd//2Ni4hmAvx4MKtdlke/m2Uacn9bSF61pVD/QCZOsFkV7ovfqiRZZmdXOaFb8dTZeBlU98jJLvIwDk5C5lKG7Ru8V+Gs8g13iQyS3v7xI35lVQUo52U+srk5Ndc5AdR6C3COW2r12g7eWacypP+phU2vr8uTA==",
  "SigningCertURL" : "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-a86cb10b4e1f29c941702d737128f7b6.pem",
  "UnsubscribeURL" : "https://sns.eu-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-west-1:826492718737:Email_Notifications:b584a2d6-c9e3-4401-a029-7b6fd4603274"
}
</code>```

When I try to convert this to a php array using:

```<code>var_dump(json_decode($json, true));
</code>```

It returns null, I have discovered that this only happens when I include the "Message" which includes sub-arrays. If I remove the "Message" part, then the php array returns correctly.

How can I correctly convert this json to a PHP associative array?

I am losing the backslashes after the json has been inserted into the database, if I can prevent that then this should work.

Edit:

I am inserting the json into the database like this, I have also tried json_encode and decode on the file_get_contents before inserting it:

```<code>$json = file_get_contents('php://input');

$mysqli->query("INSERT INTO `log` (json) VALUES('{$json}'));
</code>```

答:
By escaping the backslashes that exist within the json before inserting it into the database I have managed to get this to work:</p>

```<code>$json = str_replace('\\', '\\\\', $json);

$mysqli->query("INSERT INTO `log` (json) VALUES('{$json}')");
</code>```

Body:
I am trying to parse json from Amazon SNS using PHP and json_decode.

I am storing the json from Amazon in a mysql database, and then looping through the rows to hopefully display a table of all notifications.

This is the original json that comes in:

{
"Type": "Notification",
"MessageId": "4ecca6d5-3095-5d5c-a0f0-f013dc59f33e",
"TopicArn": "arn:aws:sns:eu-west-1:826492718737:Email_Notifications",
"Message": "{\"notificationType\":\"Delivery\",\"mail\":{\"timestamp\":\"2020-02-19T07:58:03.541Z\",\"source\":\"do-not-reply@supplyplus.org.uk\",\"sourceArn\":\"arn:aws:ses:eu-west-1:826492718737:identity/do-not-reply@supplyplus.org.uk\",\"sourceIp\":\"82.68.110.206\",\"sendingAccountId\":\"826492718737\",\"messageId\":\"010201705c743115-5bc7fc12-f36d-425a-8ff8-14ea0acf073b-000000\",\"destination\":[\"edward.hall@setsquaresolutions.com\"]},\"delivery\":{\"timestamp\":\"2020-02-19T07:58:04.226Z\",\"processingTimeMillis\":685,\"recipients\":[\"edward.hall@setsquaresolutions.com\"],\"smtpResponse\":\"250 2.0.0 OK  1582099084 z21si661666ejr.129 - gsmtp\",\"remoteMtaIp\":\"209.85.202.27\",\"reportingMTA\":\"a4-7.smtp-out.eu-west-1.amazonses.com\"}}",
"Timestamp": "2020-02-19T07:58:04.286Z",
"SignatureVersion": "1",
"Signature": "XjCUN+iogrinljvfc32wG55UUT1WUVhhIpXYPZtW9IcBiJfBnlQETy2LNlLPnGjtqcKKuV8IKQbC06DIW3EeiKGzfxeQE8OthJJOEGexcA1qr6EbMPLalhDRSmmoUC8a6vY4d3Gn/R98lzaij5UUbT9y4Oesuq8NFR98m8WpOZqMwBdjsRRhZuN676c/or9x6ibU1kWExXKxw/Cw77hhkT5Hd52gNsg2nla+V6oVWXfn/jCmUWByrJRFdxe1nUm+WbcNT4nCkqKxUBT/NTA5RkD72Mr+X/470WNXBJZ6OP/4tbby3bcn7BxzZBA780c2OBtRlseD2MvKJGE8qss2og==",
"SigningCertURL": "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-a86cb10b4e1f29c941702d737128f7b6.pem",
"UnsubscribeURL": "https://sns.eu-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-west-1:826492718737:Email_Notifications:b584a2d6-c9e3-4401-a029-7b6fd4603274"

}

The json after it has been inserted into the database looks like this:

{
  "Type" : "Notification",
  "MessageId" : "3ce843a7-13c2-54f8-a445-1561121fd162",
  "TopicArn" : "arn:aws:sns:eu-west-1:826492718737:Email_Notifications",
  "Message" : "{"notificationType":"Delivery","mail":{"timestamp":"2020-02-18T15:15:40.879Z","source":"do-not-reply@example.com","sourceArn":"arn:aws:ses:eu-west-1:826492718737:identity/do-not-reply@example.com","sourceIp":"12.34.56.78","sendingAccountId":"826492718737","messageId":"0102017058de7ccf-55c4a34d-fcd1-449c-a82a-9946b316e551-000000","destination":["user@example.com"]},"delivery":{"timestamp":"2020-02-18T15:15:41.527Z","processingTimeMillis":648,"recipients":["user@example.com"],"smtpResponse":"250 2.0.0 OK  1582038941 p17si2420323wma.126 - gsmtp","remoteMtaIp":"12.34.56.78","reportingMTA":"a4-8.smtp-out.eu-west-1.amazonses.com"}}",
  "Timestamp" : "2020-02-18T15:15:41.574Z",
  "SignatureVersion" : "1",
  "Signature" : "UTzy1PLgzxyz7wczh/3ZrcKiT9MCFe7pcmeOLH3whZ6tRbq1B6pjv+cEjTFKR3RnH4D9CkDQq04vpTyj3ATwJ5ZSxVOuNmGEo1KuOjH8TveaB3PzQTpwQlsVg1fzW5wCmhND9dvDuXiTGc86Lvy4e9AlmGNHTrfbAa5fZIfFfP9PzEhHF8zcyIvZd//2Ni4hmAvx4MKtdlke/m2Uacn9bSF61pVD/QCZOsFkV7ovfqiRZZmdXOaFb8dTZeBlU98jJLvIwDk5C5lKG7Ru8V+Gs8g13iQyS3v7xI35lVQUo52U+srk5Ndc5AdR6C3COW2r12g7eWacypP+phU2vr8uTA==",
  "SigningCertURL" : "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-a86cb10b4e1f29c941702d737128f7b6.pem",
  "UnsubscribeURL" : "https://sns.eu-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-west-1:826492718737:Email_Notifications:b584a2d6-c9e3-4401-a029-7b6fd4603274"
}

When I try to convert this to a php array using:

var_dump(json_decode($json, true));

It returns null, I have discovered that this only happens when I include the "Message" which includes sub-arrays. If I remove the "Message" part, then the php array returns correctly.

How can I correctly convert this json to a PHP associative array?

I am losing the backslashes after the json has been inserted into the database, if I can prevent that then this should work.

Edit:

I am inserting the json into the database like this, I have also tried json_encode and decode on the file_get_contents before inserting it:

$json = file_get_contents('php://input');

$mysqli->query("INSERT INTO `log` (json) VALUES('{$json}'));

Body:
By escaping the backslashes that exist within the json before inserting it into the database I have managed to get this to work:

$json = str_replace('\\', '\\\\', $json);

$mysqli->query("INSERT INTO `log` (json) VALUES('{$json}')");


问:
A simple "javac" style command-line C/C++ compiler for Windows 7
Over the last couple of months I practiced console programming with Java just with the help of JDK and a text editor of my choice (Notepad++). And I loved the simplicity as a program can be compiled from the command line plainly using javac and run using java.

Now, I'm looking for similar compiler for C/C++, such that I create a .c or .cpp file and compile it in the command prompt, and all it does is create a "native" executable that can be run directly from the command prompt. Thus, without any need of bloated IDE. The reason I'm looking for such simple compiler is because it is going to be used by high-school students so I'm advised to avoid any IDE as far as possible, so students can practice all the concepts of C/C++ languages without having to go for IDE. Which compiler can I use that does this job? also, I must work across all the versions Windows starting from Windows XP.

答: MinGW GCC is definitely the way go, but I would recomend the nuwen.net distro (http://nuwen.net/mingw.html). Haven't used it in a while (yay unix!), but if IIRC, it comes with everything ready to go after unpacking. The official distribution is ... very hard to get working.


问:
Your connection attempt failed for user 'root' to the MySQL server at localhost:3306 but succeed in terminal

Solved after restart

I was trying to connect to localhost on mysql workbench and got this message:

Your connection attempt failed for user 'root' to the MySQL server at
  localhost:3306:   Unable to connect to localhost:3306

Please: 1 Check that MySQL is running on address localhost 2 Check
  that MySQL is reachable on port 3306 (note: 3306 is the default, but
  this can be changed) 3 Check the user root has rights to connect to
  localhost from your address (MySQL rights define what clients can
  connect to the server and from which machines)  4 Make sure you are
  both providing a password if needed and using the correct password for
  localhost connecting from the host address you're connecting from

However, when I tried on terminal, the connection was successful:

```<code>$ mysql -u root -p -h localhost -P 3306
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 8.0.19 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> quit
</code>```

Was there a problem of my workbench configuration or something?

答: You can try an ip adresse 127.0.0.1.</p>

Body:
Solved after restart

I was trying to connect to localhost on mysql workbench and got this message:

Your connection attempt failed for user 'root' to the MySQL server at
  localhost:3306:   Unable to connect to localhost:3306

Please: 1 Check that MySQL is running on address localhost 2 Check
  that MySQL is reachable on port 3306 (note: 3306 is the default, but
  this can be changed) 3 Check the user root has rights to connect to
  localhost from your address (MySQL rights define what clients can
  connect to the server and from which machines)  4 Make sure you are
  both providing a password if needed and using the correct password for
  localhost connecting from the host address you're connecting from

However, when I tried on terminal, the connection was successful:

$ mysql -u root -p -h localhost -P 3306
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 8.0.19 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> quit

Was there a problem of my workbench configuration or something?

Body: You can try an ip adresse 127.0.0.1.


答:
You need to define your loss like that in order to pass new parameters to it :

```<code>def custom_loss(sample_weights_):

    def example_loss(y_true, y_pred):
        return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_

    return example_loss
</code>```

and call it like that :

```<code>model.compile("Adam", custom_loss(weights_tensor))
</code>```

Title: How to create your own loss function for tf.keras that uses additional parameter?

Body:
You need to define your loss like that in order to pass new parameters to it :

def custom_loss(sample_weights_):

    def example_loss(y_true, y_pred):
        return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_

    return example_loss

and call it like that :

model.compile("Adam", custom_loss(weights_tensor))


问:
Teradata SQL returning previous two months, based on CURRENT_DATE
TLDR:
I want to get a table with the previous two months in Teradata, based on CURRENT_DATE. Currently I can only get the previous month:

```<code>SELECT
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM') MM;
</code>```

Expected output is:

```<code>+--------+
|   MM   |
+--------+
| 2020-01|
| 2019-12|
+--------+
</code>```

Long version:
I want something, that could be used in a bigger query like this, valid for every day of the year, without hardcoding the dates. The bigger query with the hardcoded dates looks like this:

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN ('2020-01', '2019-12')
</code>```

and it works perfectly. The below one returns results ok, but only for 1 month.

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
)
</code>```

Tried to add a comma and add the same line with -2, did not work:

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM'),
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
)
</code>```

the error is:

SELECT Failed 3706: Syntax error: expected something between ')' and '.'.

答:
Your calculation is too compliated:

```<code>TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
= To_Char(Add_Months(Current_Date, -1), 'YYYY-MM')

TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
= To_Char(Add_Months(Current_Date, -2), 'YYYY-MM')
</code>```

But your approach to compare YYYY_MM is totally wrong.

Assumimg SOME_DATE is actually a DATE CASTing it to a string results in loosing statistics and a Full Table Scan if the table is partition by that date. Both can possibly lead to a bad plan.

You should keep the date column as-is and do all calculation on CURRENT_DATE:

```<code>WHERE som_date BETWEEN Trunc(Add_Months(Current_Date, -2), 'mon')
                   AND Current_Date - Extract(DAY From Current_Date)
</code>```

Body:
TLDR:
I want to get a table with the previous two months in Teradata, based on CURRENT_DATE. Currently I can only get the previous month:

SELECT
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM') MM;

Expected output is:

+--------+
|   MM   |
+--------+
| 2020-01|
| 2019-12|
+--------+

Long version:
I want something, that could be used in a bigger query like this, valid for every day of the year, without hardcoding the dates. The bigger query with the hardcoded dates looks like this:

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN ('2020-01', '2019-12')

and it works perfectly. The below one returns results ok, but only for 1 month.

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
)

Tried to add a comma and add the same line with -2, did not work:

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM'),
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
)

the error is:

SELECT Failed 3706: Syntax error: expected something between ')' and '.'.

Body:
Your calculation is too compliated:

TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
= To_Char(Add_Months(Current_Date, -1), 'YYYY-MM')

TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
= To_Char(Add_Months(Current_Date, -2), 'YYYY-MM')

But your approach to compare YYYY_MM is totally wrong.

Assumimg SOME_DATE is actually a DATE CASTing it to a string results in loosing statistics and a Full Table Scan if the table is partition by that date. Both can possibly lead to a bad plan.

You should keep the date column as-is and do all calculation on CURRENT_DATE:

WHERE som_date BETWEEN Trunc(Add_Months(Current_Date, -2), 'mon')
                   AND Current_Date - Extract(DAY From Current_Date)


问:
Resolving net::ERR_TUNNEL_CONNECTION_FAILED at Ubuntu Server
I'm running puppeteer scraper at Digital Ocean droplet.

Server is Ubuntu 18.04

ufw is enabled and ssh, http, https ports enabled.

This scraper has been running by pm2

This is the current output and Code snip.

0|server   | 2019-12-23T09:09:27.266Z: [openPage] Error:
  net::ERR_TUNNEL_CONNECTION_FAILED at https://xxxx/xxxx

```<code>...
const browser = await puppeteer.launch({
     headless: false,
     args:["--no-sandbox", "--proxy-server=zproxy.lum-superproxy.io:22225"]
});
page = await browser.newPage()

// set random agent to page
await page.setUserAgent(agents[Math.floor(Math.random() * agents.length)])

await page.authenticate({
  username: process.env.USERNAME,
  password: process.env.PWD
})
....
</code>```

plus env variables are working correctly. I checked this out by console.log(process.env.USERNAME)

答:
Ensure that your proxy DOES support HTTPS/SSL if you'd like Puppeteer to scrape HTTPS content.

You can easily test if your proxy supports SSL with:

```<code>curl --proxy [ip]:[port] https://ipinfo.io/ip
</code>```

Body:
I'm running puppeteer scraper at Digital Ocean droplet.

Server is Ubuntu 18.04

ufw is enabled and ssh, http, https ports enabled.

This scraper has been running by pm2

This is the current output and Code snip.

0|server   | 2019-12-23T09:09:27.266Z: [openPage] Error:
  net::ERR_TUNNEL_CONNECTION_FAILED at https://xxxx/xxxx

...
const browser = await puppeteer.launch({
     headless: false,
     args:["--no-sandbox", "--proxy-server=zproxy.lum-superproxy.io:22225"]
});
page = await browser.newPage()

// set random agent to page
await page.setUserAgent(agents[Math.floor(Math.random() * agents.length)])

await page.authenticate({
  username: process.env.USERNAME,
  password: process.env.PWD
})
....

plus env variables are working correctly. I checked this out by console.log(process.env.USERNAME)

Body:
Ensure that your proxy DOES support HTTPS/SSL if you'd like Puppeteer to scrape HTTPS content.

You can easily test if your proxy supports SSL with:

curl --proxy [ip]:[port] https://ipinfo.io/ip


问:
handle mutliple dropdown menus
I have multiple buttons where a menu drops down when you click on one button AND all the other dropdown menus will be closed. I currently have 9 of those and corresponding 9 functions for that purpose:

```<code>function myFunction5() {
    document.getElementById("myDropdown1").classList.remove("show");
    document.getElementById("myDropdown2").classList.remove("show");
    document.getElementById("myDropdown3").classList.remove("show");
    document.getElementById("myDropdown4").classList.remove("show");
    document.getElementById("myDropdown5").classList.toggle("show");
    document.getElementById("myDropdown6").classList.remove("show");
    document.getElementById("myDropdown7").classList.remove("show");
    document.getElementById("myDropdown9").classList.remove("show"); }
</code>```

This opens dropdown menu 5 and closes all others.

I would like to have only one function for that instead of 9. How do i do that?

EDIT:

Complete code example:

```<code><!DOCTYPE html>
<html>
<head>
<style>
.dropbtn {
  background-color: #3498DB;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
  background-color: #2980B9;
}

.dropdown {
  position: relative;
  display: inline-block;
}

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

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}
</style>
</head>
<body>

<div class="dropdown">
  <button onclick="myFunction1()" class="dropbtn">Dropdown</button>
  <div id="myDropdown1" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

<div class="dropdown">
  <button onclick="myFunction2()" class="dropbtn">Dropdown</button>
  <div id="myDropdown2" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

<script>
function myFunction1() {
  document.getElementById("myDropdown1").classList.toggle("show");
  document.getElementById("myDropdown2").classList.remove("show");
}

function myFunction2() {
  document.getElementById("myDropdown1").classList.remove("show");
  document.getElementById("myDropdown2").classList.toggle("show");
}

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

Imagine this 9 times...

答: Have you tried creating a nodelist containing all of your menus then passing in the menu you want to open as a parameter into a function which then iterates over your nodelist and closes each menu except the one that is passed to it?</p>

Title: handle mutliple dropdown menus

Body:
I have multiple buttons where a menu drops down when you click on one button AND all the other dropdown menus will be closed. I currently have 9 of those and corresponding 9 functions for that purpose:

function myFunction5() {
    document.getElementById("myDropdown1").classList.remove("show");
    document.getElementById("myDropdown2").classList.remove("show");
    document.getElementById("myDropdown3").classList.remove("show");
    document.getElementById("myDropdown4").classList.remove("show");
    document.getElementById("myDropdown5").classList.toggle("show");
    document.getElementById("myDropdown6").classList.remove("show");
    document.getElementById("myDropdown7").classList.remove("show");
    document.getElementById("myDropdown9").classList.remove("show"); }

This opens dropdown menu 5 and closes all others.

I would like to have only one function for that instead of 9. How do i do that?

EDIT:

Complete code example:

<!DOCTYPE html>

  <button onclick="myFunction1()" class="dropbtn">Dropdown</button>

    Home
    About
    Contact

  <button onclick="myFunction2()" class="dropbtn">Dropdown</button>

    Home
    About
    Contact

Imagine this 9 times...


问:
Website nav links not working on IE9
My website: http://botvps.com

The text on the button is not appearing.
I have already made an IE css for IE 8 or lower.

What do I need to do?

Regards,
LB

答:
you can use this meta tag line and put it inside the  tag:

```<code><meta http-equiv="X-UA-Compatible" content="IE=8" />
</code>```

this will make ie9 work in compatibility mode to ie8 and will solve the problem if you don't

have problems in ie8 stylesheet

Title: Website nav links not working on IE9

Body:
you can use this meta tag line and put it inside the <head> tag:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

this will make ie9 work in compatibility mode to ie8 and will solve the problem if you don't

have problems in ie8 stylesheet


问:
Swtiching between menu resource files in NavigationDrawer
Is it possible to switch between menu resource files for a NavigationDrawer? I am using SharedPreferences to store the data about the user, and I would like to implement a different menu for a logged user, different from the menu that's supposed to apper if the user is not logged.
This is how I use the Navigation Drawerat the start of the activity:

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
</code>```

I am aiming at something like:

```<code> if (SharedPrefManager.getInstance(this).isLoggedIn()) {
        ...
        //Set the logged menu resource file
 }
 else{
        //Set the normal menu resource file
 }
</code>```

答:
You can achieve this via inflateMenu

```<code> int menu = R.menu.user_menu;
 if (SharedPrefManager.getInstance(this).isLoggedIn()) {
     //Set the logged menu resource file
     menu = R.menu.loggedin;
 }
 navigationView.inflateMenu(menu);
</code>```

Note: Existing items in the menu will not be modified or removed

Body:
Is it possible to switch between menu resource files for a NavigationDrawer? I am using SharedPreferences to store the data about the user, and I would like to implement a different menu for a logged user, different from the menu that's supposed to apper if the user is not logged.
This is how I use the Navigation Drawerat the start of the activity:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

I am aiming at something like:

 if (SharedPrefManager.getInstance(this).isLoggedIn()) {
        ...
        //Set the logged menu resource file
 }
 else{
        //Set the normal menu resource file
 }

Body:
You can achieve this via inflateMenu

 int menu = R.menu.user_menu;
 if (SharedPrefManager.getInstance(this).isLoggedIn()) {
     //Set the logged menu resource file
     menu = R.menu.loggedin;
 }
 navigationView.inflateMenu(menu);

Note: Existing items in the menu will not be modified or removed


问:
How to write diffrent code for ios and android in xamarin.forms?
I created a xamarin.forms project. Suppose I have a button, and I want this button to call different platforms' APIs (third-party ios / android skd) on different platforms.

How to import jar for xamarin.android/ios sdk for xamarin.ios?

Assuming this button is in a page of xamarin.forms, how do I bind different events for different platforms so that it can call different APIs on different platforms?

Project structure:

答:
Xamarin has documentation about binding native libraries. You can find android here and ios here.

You can do different things in button click event for different platforms with using Xamarin.Forms Device Class.

```<code> private void Button_Clicked(object sender, EventArgs e)
    {
        switch (Device.RuntimePlatform)
        {
            case Device.iOS:
               //Do iOS thing
                break;
            case Device.Android:
                //Do Android thing
                break;
            default:
                break;
        }
    }
</code>```

3.If you want to work with different platform api then you can use Dependency Service just like Adlorem's answer. Documentation is here.

Body:
Xamarin has documentation about binding native libraries. You can find android here and ios here.

You can do different things in button click event for different platforms with using Xamarin.Forms Device Class.

 private void Button_Clicked(object sender, EventArgs e)
    {
        switch (Device.RuntimePlatform)
        {
            case Device.iOS:
               //Do iOS thing
                break;
            case Device.Android:
                //Do Android thing
                break;
            default:
                break;
        }
    }

3.If you want to work with different platform api then you can use Dependency Service just like Adlorem's answer. Documentation is here.


问:
Executing Assembly Code on Windows XP?
I'm running a WINXP, and I'm quite curious as to how you run or execute assembly code. Is there some sort of application I need, or do I need to run it from a terminal...?</p>

答:
You want to use MASM or NASM:

http://en.wikipedia.org/wiki/Microsoft_Macro_Assembler

Title: Executing Assembly Code on Windows XP?


问:
Can more than one scss be used for one SPFx Web Part?
I am new to The SharePoint Framework (SPFx). I am trying to convert old Content Type Web Part into SPFx Web Part. Earlier we have used multiple css files and included into html page. But for SPFx Web Part, I got stuck for how to use more than one scss for one Web Part. I searched but found suggestions on how to give give names of scss for your Web Part but no where i found like it allows only one scss or something.

So i would like to know whether it is possible to have multiple scss file for one web part or not? And if yes then how?

答:
This should be quite easy to accomplish. Just add a new .module.scss file to your solution and reference it with a unique identifier.

Example:

```<code>import styles from './Existing.module.scss'; // this is the one you already have
import additionalStyles from './Example.module.scss'; // your new module
</code>```

Then you can reference these like

Body:
This should be quite easy to accomplish. Just add a new .module.scss file to your solution and reference it with a unique identifier.

Example:

import styles from './Existing.module.scss'; // this is the one you already have
import additionalStyles from './Example.module.scss'; // your new module

Then you can reference these like <div className={additionalStyles.awesomeClass} />


问:
How to solve a RAW stream playback problem with GStreamer and VAAPi
I am currently experiencing a small problem with GStreamer, here are more details:

Configuration:

Intel i7-6700

Intel HD Graphics 530

Ubuntu 18.04 LTS

GStreamer1.0

VAAPI plugin

I receive a UDP stream from a video source, this stream is sent in RAW UYVY format. Here is my command line to decode it:

gst-launch-1.0 -v udpsrc port="1234" caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)RAW, sampling=(string)YCbCr-4:2:2, depth=(string)8, width=(string)1920, height=(string)1080, colorimetry=(string)BT709-2, payload=(int)96, ssrc=(uint)1188110121, timestamp-offset=(uint)4137478200, seqnum-offset=(uint)7257, a-framerate=(string)25" ! rtpvrawdepay ! decodebin ! queue ! videoconvert ! xvimagesink

Problem as we can see on the screenshot below, the CPU load (right) is far too high for this kind of task and we can see the GPU load (left) which is almost zero.

To overcome this problem, I want to use the VAAPI graphics acceleration as I did in a previous project with H264 of which here is the command line below:

gst-launch-1.0 -v udpsrc port=1234 caps= "application/x-rtp, media\=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, packetization-mode=(string)1, profile-level-id=(string)640028, payload=(int)96, ssrc=(uint)2665415388, timestamp-offset=(uint)3571350145, seqnum-offset=(uint)18095, a-framerate=(string)25" ! rtph264depay ! queue !  vaapih264dec low-latency=1 ! autovideosink

The line above works perfectly and the CPU has almost no more loads. So I adapt this command line to use it with a RAW stream, here is the command:

gst-launch-1.0 -v udpsrc port="1234" caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)RAW, sampling=(string)YCbCr-4:2:2, depth=(string)8, width=(string)1920, height=(string)1080, colorimetry=(string)BT709-2, payload=(int)96, ssrc=(uint)1188110121, timestamp-offset=(uint)4137478200, seqnum-offset=(uint)7257, a-framerate=(string)25" ! rtpvrawdepay ! vaapidecodebin ! videoconvert ! xvimagesink

It is the same line as the one at the beginning but I changed the element decodebin by vaapidecodebin as I had replaced avdec_h264 by vaapih264dec for my H264 stream. Unfortunately it doesn't work and I end up with this error:

WARNING: wrong pipeline: unable to connect rtpvrawdepay0 to vaapidecodebin0

How I can solve this problem? Do you have any leads to solve this problem?

答:
What exactly are you trying to accelerate here? The CPU load is probably either due to the videoconvert as this is run in software to convert UYVY into a format your renderer supports (Hopefully that's another YUV format and not RGB) or it is the data transfer of the uncompressed data from CPU memory to GPU memory.

Note that transferring uncompressed image data is a much higher data rate than compressed H.264 video.

If you think the videoconvert is the expensive part you may want to try to use OpenGL for convert and displaying: .. ! glupload ! glcolorconvert ! glimagesink.

Maybe vaapipostproc can help you with color conversion if you don't want to go the OpenGL route.


问:
How to create a random logical vector with specific numbers of TRUE / FALSE entries
I would like to create a logical vector that has 10 rows, with each row randomly assigned either TRUE or FALSE.  However, I want there to only be 3 FALSE and 7 TRUE.

Example of desired outcome (logical vector with three randomly assigned FALSE entries and 7 randomly assigned TRUE entries):

```<code>> vector
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "TRUE" "TRUE" "TRUE"
[10] "TRUE"
</code>```

I can create a logical vector of size 10 that has TRUE or FALSE, but I don't know how to specify I want three FALSE entries and 7 TRUE entries.

```<code>vector <- sample(x = c("TRUE","FALSE"), size = 10, replace = TRUE)
</code>```

This produces:

```<code>> train
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
[10] "TRUE"
</code>```

Which has the incorrect number of TRUE and FALSE entries (4 TRUE and 6 FALSE).

答:
Like Wimpel and PKumar combined:</p>

```<code>vector <- sample(c(rep(TRUE, 7), rep(FALSE, 3)), 10 ,replace = F)
</code>```

Body:
I would like to create a logical vector that has 10 rows, with each row randomly assigned either TRUE or FALSE.  However, I want there to only be 3 FALSE and 7 TRUE.

Example of desired outcome (logical vector with three randomly assigned FALSE entries and 7 randomly assigned TRUE entries):

> vector
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "TRUE" "TRUE" "TRUE"
[10] "TRUE"

I can create a logical vector of size 10 that has TRUE or FALSE, but I don't know how to specify I want three FALSE entries and 7 TRUE entries.

vector <- sample(x = c("TRUE","FALSE"), size = 10, replace = TRUE)

This produces:

> train
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
[10] "TRUE"

Which has the incorrect number of TRUE and FALSE entries (4 TRUE and 6 FALSE).

Body:
Like Wimpel and PKumar combined:

vector <- sample(c(rep(TRUE, 7), rep(FALSE, 3)), 10 ,replace = F)


问:
How can I bind the enter key to a command while having a button do the same thing?
I have a function whiten class. There is also a button which activates the function. I also want to make it so the user can press the enter key and it would run the function.

my current code looks something like this (simplified)

```<code>myButton = Button(text = "My Button", command = self.myFunction)
root.bind('<Return>', self.myFunction2)

def myFunction(self):
   pass

def myFunction(self, event):
   pass
</code>```

I am using 2 functions because another answer on here said that it would work if I added another argument to one of the function (called event in this case)

This code works but I want to find a more efficient way to do this as each function is quite long and it is a hassle to change both of them when Im making a change.

if I try bind the enter key to myFunction(self), I get an error saying that 2 positional retirements wee given.

答:
Define your function as

```<code>def myFunction(self, event=None):
</code>```

This will accept being called with or without the event argument. None is used as the default value for event when it isn't passed.

Body:
I have a function whiten class. There is also a button which activates the function. I also want to make it so the user can press the enter key and it would run the function.

my current code looks something like this (simplified)

myButton = Button(text = "My Button", command = self.myFunction)
root.bind('<Return>', self.myFunction2)

def myFunction(self):
   pass

def myFunction(self, event):
   pass

I am using 2 functions because another answer on here said that it would work if I added another argument to one of the function (called event in this case)

This code works but I want to find a more efficient way to do this as each function is quite long and it is a hassle to change both of them when Im making a change.

if I try bind the enter key to myFunction(self), I get an error saying that 2 positional retirements wee given.

Body:
Define your function as

def myFunction(self, event=None):

This will accept being called with or without the event argument. None is used as the default value for event when it isn't passed.