问:
Displaying Loading text while doing a WebRequest
I have a button on my webform. Clicking this button will do an HttpWebRequest during the onclick event handler. After the request we copy the response from the request into HttpContext.Current.Response and send that to the client.

This web request can take a while (up to 5 seconds, since it's generating a report). During this time the user has no indication that anything is going on, except for the browser progress bar and the spinning IE icon (if they're using IE). So I need a loading indicator while this is happening.

I've tried using javascript that fires during the button's onclick event (using OnClientClick) and while that works, I don't know how to find out when the web request is finished. Since we just send the response to the client, a full postback doesn't happen.

I've tried wrapping the button in an UpdatePanel and using the UpdateProgress, but when we send the response to HttpContext.Current.Response and call Response.End(), we get an error in the javascript, since the response isn't well formed (we're sending back an excel sheet for the user to download).

Since we're sending back a file for users to download, I don't want to pop-up a separate window, since then in IE they'd get the information bar blocking the download.

Any ideas here?

答:
The solution I'm presenting here is aimed to show a method to let a "Loading..." box to appear while you're server-side processing and to disappear when server-side processing is complete.

I'll do this with the very basic AJAX machinery (tested on FF, but IE should be ok either), i.e. not using a framework like Prototype or jQuery or Dojo, as you didn't specify your knowledge about them.

To let you better understand the trick, the following is just a small example and doesn't pretend to be an out-of-the-box solution. I tend not to be superficial, but I think a clearer example can explain better than many words.

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>First Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            .hidden {
                display: none;
            }
            .loadingInProgress {
                color: #FFFFFF;
                width: 75px;
                background-color: #FF0000;
            }
        </style>
    <script type="text/javascript">
        var httpRequest;
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            httpRequest.overrideMimeType('text/xml');
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {}
            }
        }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
        }

        httpRequest.onreadystatechange = function(){
            switch (httpRequest.readyState) {
            case 1: // Loading
                document.getElementById('loading').className = "loadingInProgress";
                break;
            case 4: // Complete
                document.getElementById('loading').className = "hidden";
                if (httpRequest.status == 200) {
                    // perfect!
                } else {
                    // there was a problem with the request,
                    // for example the response may be a 404 (Not Found)
                    // or 500 (Internal Server Error) response codes
                }
                break;
            }
        };

        function go() {
            httpRequest.open('GET', document.getElementById('form1').action, true);
            httpRequest.send('');
        }
    </script>

  </head>
  <body>
      <div id="loading" class="hidden">Loading...</div>
      <form id="form1" name="form1" action="doSomething.php">
          <input type="button" value="Click to submit:" onclick="go()" />
      </form>
  </body>
</html>
</code>```

As you can see, there's a
 which holds the "Loading..." message.

The principle is to show/hide the
 depending on the XMLHttpRequest object's readyState.

I've used the onreadystatechange handler of the XMLHttpRequest to trigger the readyState change.

The back-end php script I use (declared as the form's action) does just a sleep(5), to let the "Loading..." message appear for 5 secs.

```<code><?php
sleep(5);
header('Cache-Control: no-cache');
echo "OK";
?>
</code>```

The Cache-control: no-cache header is necessary, since usually if you don't set it the browser will cache the response avoiding to resubmit the request if you should need to.

A good source for "getting started" AJAX documentation is Mozilla MDC.

The whole thing could be much more gently handled by a Javascript framework like Prototype, taking advantage of its browser-safe approach, saving you hours of debug.

Edit:

I chose php 'cause I don't know ASP.NET nor ASP, sorry about that.

OwnerDisplayName: Ray

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ray

Body:
The solution I'm presenting here is aimed to show a method to let a "Loading..." box to appear while you're server-side processing and to disappear when server-side processing is complete.

I'll do this with the very basic AJAX machinery (tested on FF, but IE should be ok either), i.e. not using a framework like Prototype or jQuery or Dojo, as you didn't specify your knowledge about them.

To let you better understand the trick, the following is just a small example and doesn't pretend to be an out-of-the-box solution. I tend not to be superficial, but I think a clearer example can explain better than many words.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>First Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            .hidden {
                display: none;
            }
            .loadingInProgress {
                color: #FFFFFF;
                width: 75px;
                background-color: #FF0000;
            }
        </style>
    <script type="text/javascript">
        var httpRequest;
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            httpRequest.overrideMimeType('text/xml');
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {}
            }
        }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
        }

        httpRequest.onreadystatechange = function(){
            switch (httpRequest.readyState) {
            case 1: // Loading
                document.getElementById('loading').className = "loadingInProgress";
                break;
            case 4: // Complete
                document.getElementById('loading').className = "hidden";
                if (httpRequest.status == 200) {
                    // perfect!
                } else {
                    // there was a problem with the request,
                    // for example the response may be a 404 (Not Found)
                    // or 500 (Internal Server Error) response codes
                }
                break;
            }
        };

        function go() {
            httpRequest.open('GET', document.getElementById('form1').action, true);
            httpRequest.send('');
        }
    </script>

  </head>
  <body>
      <div id="loading" class="hidden">Loading...</div>
      <form id="form1" name="form1" action="doSomething.php">
          <input type="button" value="Click to submit:" onclick="go()" />
      </form>
  </body>
</html>

As you can see, there's a <div> which holds the "Loading..." message.

The principle is to show/hide the <div> depending on the XMLHttpRequest object's readyState.

I've used the onreadystatechange handler of the XMLHttpRequest to trigger the readyState change.

The back-end php script I use (declared as the form's action) does just a sleep(5), to let the "Loading..." message appear for 5 secs.

<?php
sleep(5);
header('Cache-Control: no-cache');
echo "OK";
?>

The Cache-control: no-cache header is necessary, since usually if you don't set it the browser will cache the response avoiding to resubmit the request if you should need to.

A good source for "getting started" AJAX documentation is Mozilla MDC.

The whole thing could be much more gently handled by a Javascript framework like Prototype, taking advantage of its browser-safe approach, saving you hours of debug.

Edit:

I chose php 'cause I don't know ASP.NET nor ASP, sorry about that.

OwnerDisplayName: Scarlet

LastEditorDisplayName: Scarlet


来源: stackexchange

问:
Why aren't changes in my remote master branch being pulled into my local master branch?
I have really been wracking my brain on this. I am using DevOps and the native Visual Studio Team Explorer interface.

I created a master branch and pushed it to the remote with.

I created a new branch that is also pushed to the remote.

I made many changes, updated the remote branch, and merged it into the master.

A colleague created a new branch, added some files, pushed it to remote, and merged it into the remote master.

The remote master correctly shows the combination of our work.

For the life of my I cannot seem to pull the changes from the origin/remote down to my local master branch.

I have tried Sync, pull, fetch, merge, and rebase.
The local master is bold, indicating it is selected.
I've tried creating new branches and updating just those.
When I am on the syncing menu, there are no incoming commits even though there are changes beyond what is in my local branch.
When I do sync or fetch/merge/pull the menu returns that my local branch is up to date.

I know there is something extremely simple that I'm missing here but after a few hours searching and a Udemy course I am still stumped!

答:
I wanted to update my question to say that I finally thought to just clone the repository down to a new folder and it revealed some folder pathing issues in the remote master that may have been a part of my problem. I am no longer seeking answer to this question. Thank you to any who considered it!

***edit: It turned out everything was working correctly but my colleague had somehow saved all his project in a subfolder so all the changes were being updated down in that subfolder. Essentially it caused there to be two whole projects in one. I finally got it sorted by copying out changes where they are supposed to go and pushed the correct project up to the remote master.

ContentLicense: CC BY-SA 4.0


问:
Efficient solution to codingBat riddle starOut in Java
The problem I am talking about is this

Problem statment:

Return a version of the given string, where for every star () in the string the star and the chars immediately to its left and right are gone. So "abcd" yields "ad" and "ab**cd" also yields "ad".

starOut("ab*cd") → "ad"

starOut("ab**cd") → "ad"

starOut("sm*eilly") → "silly"

The solution I got was a little messy I have used about 6 if statements and a handling for one particular case, looking for cleaner solutions with lesser ifs.

Please do not use more than 1 loop and collections or regex.

Below is my solution:

public String starOut(String str) {
  String result="";
  boolean currentFlag=false;

  if(str.length()==0)
  return result;

  for(int i=0;i+1<str.length();i++)
  {
    if(str.charAt(i)=='*')
    {
       i+=1;
       currentFlag=true;
       continue;
     }
     if(str.charAt(i+1)=='*')
     {
        i+=2;
        continue;
     }
     if((i>0)&&str.charAt(i-1)=='*')
     {
        continue;
     }
     result+=str.substring(i,i+1);
     currentFlag=false;

   }

  if(!(currentFlag)&&(str.length()==3)&&(str.charAt(1)=='*'))
      return "";

   if((str.charAt(str.length()-1)!='*')&!(currentFlag))
     return result+=str.charAt(str.length()-1);
    else
      return result;
}
```

答:
```<code>public String starOut(String str)
{
  String ret = "";
  int i;

  if (str.length() == 0 || str.equals("*")) return "";

  for (i = 0; str.charAt(i) == '*'; ++i)
    ;
  if (i > 0 && str.charAt(i-1) == '*')
    ++i;
  while (i < str.length()) {
    if (i == str.length()-1 || i < str.length()-1 && str.charAt(i+1) != '*')
      ret += str.charAt(i++);
    else {
      ++i;
      while (i < str.length() && str.charAt(i) == '*')
        ++i;
      ++i;
    }
  }
  return ret;
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Loading external .js (github) libraries in in codepen
Newbie question from a UX designer been trying to get this working for 2 days now.

I am trying to test out matthew dove's inject script in codepen
https://github.com/Matthew-Dove/Inject

I have copied the raw github file using jsdelivr into the Pen settings. When I click on the eye icon I can see the .js file.

I have copied the example code provided by Matthew  into the html panel.

But as you can see in the image above the website does not get injected.
My codepen is https://codepen.io/lisatw/pen/oNXxgMR

```<code><html lang="en">
<head>
<meta charset="utf-8">
<meta content="initial-scale=1,width=device-width" name="viewport">
<title>Inject</title>
</head>
<body>
<h4>Below this heading the world's first website will be injected</h4>

<div data-inject-src="http://info.cern.ch/" style="height: 175px;"> </div>

<h4>Above this heading the world's first website will be injected</h4>

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

I have tried with and without the call to the .js library

```<code><script src="./inject.js"></script>
</code>```

Any help mightly appreciated.

答:
When you add a script on CodePen by URL, this URL will be injected as is before . There is no need to explicitly adding script like this:

```

<p>Because right after that, CodePen automatically adds another script:</p>

<pre class="lang-js prettyprint-override"><code><script src="https://cdn.jsdelivr.net/gh/Matthew-Dove/Inject@master/src/inject.js"></script>
</code>```

But the code doesn't work for another reason. This issue applies even to Matthew's https://rawgit.com/Matthew-Dove/Inject/master/src/example.html example, yahoo APIs (https://query.yahooapis.com/v1/public/yql) under the hood no longer available. https://twitter.com/ydn/status/1079785891558653952

Unfortunately, there is nothing you can do about it.

Body:
Newbie question from a UX designer been trying to get this working for 2 days now.

I am trying to test out matthew dove's inject script in codepen
https://github.com/Matthew-Dove/Inject

I have copied the raw github file using jsdelivr into the Pen settings. When I click on the eye icon I can see the .js file.

I have copied the example code provided by Matthew  into the html panel.

But as you can see in the image above the website does not get injected.
My codepen is https://codepen.io/lisatw/pen/oNXxgMR

<meta charset="utf-8">
<meta content="initial-scale=1,width=device-width" name="viewport">
<title>Inject</title>

Below this heading the world's first website will be injected

Above this heading the world's first website will be injected

I have tried with and without the call to the .js library

Any help mightly appreciated.

Body:
When you add a script on CodePen by URL, this URL will be injected as is before </body>. There is no need to explicitly adding script like this:

<script src="./inject.js"></script>

Because right after that, CodePen automatically adds another script:

<script src="https://cdn.jsdelivr.net/gh/Matthew-Dove/Inject@master/src/inject.js"></script>

But the code doesn't work for another reason. This issue applies even to Matthew's https://rawgit.com/Matthew-Dove/Inject/master/src/example.html example, yahoo APIs (https://query.yahooapis.com/v1/public/yql) under the hood no longer available. https://twitter.com/ydn/status/1079785891558653952

Unfortunately, there is nothing you can do about it.


问:
Why a program/browser running without GUI called Headless?
I'm curious about why headless means "without GUI". What is the etymology of headless? It seems there is no relationship between a head and GUI.

答:
Headless in this context would be referred to as "without sight". A chicken without a head, or a company without a head has no head therefore it has no sight, however it can still function. Selenium has headless browser modes for programmers who would like to test code without a browser ui to signify the functionality of a browser without the "consciousness of a user".

First Stack post! Rah!


问:
Switching b/w the Tabs in Android(Chrome) in crossbrowsertesting platform using Appium/Selenium
I am working on crossbrowsertesting platform in Android Chrome and facing a challenge in which I need to click on a link that opens up in new tab. I need to switch to that new tab and get its URL.
Problem is I am unable to switch to newly opened tab and get its URL.

Method used -
When using driver.switchTo().window(child_window) I am getting below error -

org.openqa.selenium.InvalidArgumentException: invalid argument: 'name'
  must be a string.

But the same is working fine in Windows based chrome (not Android chrome browser).

Platform Information :

crossbrowsertesting

"browserName", "Chrome"

"deviceName", "Galaxy S9"

"platformVersion", "9.0"

"platformName", "Android"

"deviceOrientation", "portrait"

答:
I found the solution:

My project involved both web and native view so below is what I did

1- used chromeDriver with compatible Android emulator version

2- Switch to proper view

3- used driver.switchTo().window()

Thanks everyone for answers.


问:
Java/MongoDB query by date
I stored a value as a java.util.Date() in my collection, but when I query to get values between two specific dates, I end up getting values outside of the range. Here's my code:

to insert

```<code>BasicDBObject object = new BasicDBObject();
...
object.put("dateAdded", new java.util.Date());
collection.insert(object);
</code>```

to query

```<code>BasicDBObject query = new BasicDBObject();
query.put("dateAdded", new BasicDBObject("$gte", fromDate));
query.put("dateAdded", new BasicDBObject("$lte", toDate));
collection.find(query).sort(new BasicDBObject("dateAdded", -1));
</code>```

when I query between Wed Jul 27 16:54:49 EST 2011 and Wed Jul 27 16:54:49 EST 2011 (basically fromDate = toDate), I get objects with dates like Tue Jul 26 09:43:37 EST 2011 which should definitely not be possible. What am I missing here?

答:
I approach the query like this</p>

```<code>new Document("datetime",Document.parse(
    "{$gte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(fromDate) + "'),
     $lte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(endDate) + "')}"
))
</code>```

Title: Java/MongoDB query by date

Body:
I stored a value as a java.util.Date() in my collection, but when I query to get values between two specific dates, I end up getting values outside of the range. Here's my code:

to insert

BasicDBObject object = new BasicDBObject();
...
object.put("dateAdded", new java.util.Date());
collection.insert(object);

to query

BasicDBObject query = new BasicDBObject();
query.put("dateAdded", new BasicDBObject("$gte", fromDate));
query.put("dateAdded", new BasicDBObject("$lte", toDate));
collection.find(query).sort(new BasicDBObject("dateAdded", -1));

when I query between Wed Jul 27 16:54:49 EST 2011 and Wed Jul 27 16:54:49 EST 2011 (basically fromDate = toDate), I get objects with dates like Tue Jul 26 09:43:37 EST 2011 which should definitely not be possible. What am I missing here?

Body:
I approach the query like this

new Document("datetime",Document.parse(
    "{$gte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(fromDate) + "'),
     $lte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(endDate) + "')}"
))


问:
Having issue with DNN 6 upgrade network path
So we are upgrading site and came across interesting problem. We have a 6.01 version we are using upgrade path upgrades. Going to 6.4 then 7 to 8 to 9 etc etc.

So far other version 7 sites upgrade fine, the version 6 sites as stated above fails. PLEASE NOTE: We CAN navigate to the site before moving upgrade files over and login as host, move around see the site etc, meaning the web.config database connectionstring is working. However once we move files over to upgrade and the upgrade wizard requires host login, hit next, it hangs and produces the "Network related error cannot connect to sql server blaa, blaa, blaa..."

Is there another area where the connection strig for the version 6 DNN is looking when upgrading other than the web.config? It's clear it's an issue with it can't find the SQL server, no that a login is wrong...

This is the error:

Line 215: Upgrade.Upgrade.UpgradeDNN(strProviderPath, DataProvider.Instance().GetVersion());

Win32Exception (0x80004005): The network path was not found
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found...

Possibly something with getting the path is wrong?
string strProviderPath = DataProvider.Instance().GetProviderPath(); in the install.aspx.cs?

答:
In case anyone else cares or needs this, in the DNN 6 version we had, way down in the web.config there is another "upgradeconnectionstring" that needs to match the main connection string. in our case the DNN WAS moved to a new server and the main connectionstrings were updated not the one below. All good now!

add name="SqlDataProvider" type="DotNetNuke.Data.SqlDataProvider, DotNetNuke.SqlDataProvider" connectionStringName="SiteSqlServer" upgradeConnectionString="Data Source=YOURSERVER;Initial Catalog=YOURDNNDB;User ID=matchtomainuser;Password=matchtomainpassword;Application Name=DNNCore;" providerPath="~\Providers\DataProviders\SqlDataProvider\" objectQualifier="" databaseOwner="dbo"


问:
Speed up T-SQL CTE by rebuilding only part of the tree you want?
I have a very simple table of a ParentID (int) and ChildID (int). The problem is that it's several thousand lines long and many of the ChildIDs are the ParentIDs of other ParentIDs.

All I'm interested in is building the hierarchy of all of these shared IDs. However, some branches may only be 2 or 3 levels deep while other may go 30+ levels deep.

While all of the data is important, only certain branches (and their sub-branches) are important at particular times.

My original attempt was to just 'bruteforce' it and build the whole tree, but it's incredibly inefficient and resource intensive.

Therefore, I was wondering how I could tweak my basic very simple/standard CTE (using the aforementioned simple table with only the two integer columns) to pick a particular branch of this very complicated tree and just recursively build the hierarchy of just the branch I want out to it's farthest point without having to build the rest of the tree and all of its branches.

Is this possible?

As a side note - because of the sheer volume of data combined with it's simplicity of only being numeric data, I have no ability to guess what would come after a certain branch (i.e., there is no sequential numbering or anything that provide hints, basically anything could be beyond the branch I want to I know I need to pull from all of the data, I just don't want to have to waste time/resources building branches I don't need).

EDIT: Here is my sample code:

```<code>;WITH CTE
AS (
Select ChildID
    ,ParentID
    ,cast(ParentID as varchar(max)) as IDpath
From #TempTable

UNION ALL

Select B.ChildID
    ,B.ParentID
    ,cast(B.ParentID as varchar(max)) + '>' + A.IDpath as IDpath
From CTE A
    Inner Join #TempTable B on A.ParentID=B.ChildID
)
Select Distinct IDpath
From CTE
Where IDpath is not null
</code>```

As far as data, parent ID and child ID are integers between 1-10,000. Some parents have children, some do not (ChildID is null in those cases).

So my output looks like:

ParentID>ID>ID>ID>ID>ID>ChildID (where the ID's in the middle are the children of their parent and then the parent of the subsequent child and so forth).

答:
So here is the code I used to fix my problem to pick ID with the number of 2220 being my "trunk" path and I was able to map this ID out through all of the Parent/Child ID's out to the farthest leafs of my branches of the hierarchy.

Now I'm not an expert at all in SQL coding. Quite frankly, I'm not even good at it so this may not be the best way to fix the issue (or even be a total fix, but given what I was expecting for results, it seems to be working for me).

Now, if 2220 was not a ChildID of another ParentID, I'm not sure if this would work. I may test that later, but as it stands, I'm getting the data I need. However, if this ends up being a problem, I can always do a check and insert it as a ChildID with a ParentID of 0 (as I know all of my ID's are positive integers).

Regardless, this is how I changed up my code to make it work for me:

```<code>;WITH CTE
AS (
Select 1 as Level
    ,ChildID
    ,ParentID
    ,cast(ChildID as varchar(max)) as IDpath
From #TempTable

UNION ALL

Select Level + 1 as Level
    ,B.ChildID
    ,B.ParentID
    ,A.IDpath + '>' + cast(B.ChildID as varchar(max)) as IDpath
From CTE A
    Inner Join #TempTable B on A.ChildID=B.ParentID
Where Level = 1
    or (Level > 1 and IDpath like '2220%')
)
Select Distinct IDpath
From CTE
Where left(IDPath,4) = '2220'
</code>```

Now, if there is someone with expertise that could comment on the quality of this "fix" and if it's reasonable (or if I'm missing something), I'd appreciate it. I don't want to accidentally poison the masses with a crap fix because of my naivety in assuming that this is a good (enough) fix.

Body:
I have a very simple table of a ParentID (int) and ChildID (int). The problem is that it's several thousand lines long and many of the ChildIDs are the ParentIDs of other ParentIDs.

All I'm interested in is building the hierarchy of all of these shared IDs. However, some branches may only be 2 or 3 levels deep while other may go 30+ levels deep.

While all of the data is important, only certain branches (and their sub-branches) are important at particular times.

My original attempt was to just 'bruteforce' it and build the whole tree, but it's incredibly inefficient and resource intensive.

Therefore, I was wondering how I could tweak my basic very simple/standard CTE (using the aforementioned simple table with only the two integer columns) to pick a particular branch of this very complicated tree and just recursively build the hierarchy of just the branch I want out to it's farthest point without having to build the rest of the tree and all of its branches.

Is this possible?

As a side note - because of the sheer volume of data combined with it's simplicity of only being numeric data, I have no ability to guess what would come after a certain branch (i.e., there is no sequential numbering or anything that provide hints, basically anything could be beyond the branch I want to I know I need to pull from all of the data, I just don't want to have to waste time/resources building branches I don't need).

EDIT: Here is my sample code:

;WITH CTE
AS (
Select ChildID
    ,ParentID
    ,cast(ParentID as varchar(max)) as IDpath
From #TempTable

UNION ALL

Select B.ChildID
    ,B.ParentID
    ,cast(B.ParentID as varchar(max)) + '>' + A.IDpath as IDpath
From CTE A
    Inner Join #TempTable B on A.ParentID=B.ChildID
)
Select Distinct IDpath
From CTE
Where IDpath is not null

As far as data, parent ID and child ID are integers between 1-10,000. Some parents have children, some do not (ChildID is null in those cases).

So my output looks like:

ParentID>ID>ID>ID>ID>ID>ChildID (where the ID's in the middle are the children of their parent and then the parent of the subsequent child and so forth).

Body:
So here is the code I used to fix my problem to pick ID with the number of 2220 being my "trunk" path and I was able to map this ID out through all of the Parent/Child ID's out to the farthest leafs of my branches of the hierarchy.

Now I'm not an expert at all in SQL coding. Quite frankly, I'm not even good at it so this may not be the best way to fix the issue (or even be a total fix, but given what I was expecting for results, it seems to be working for me).

Now, if 2220 was not a ChildID of another ParentID, I'm not sure if this would work. I may test that later, but as it stands, I'm getting the data I need. However, if this ends up being a problem, I can always do a check and insert it as a ChildID with a ParentID of 0 (as I know all of my ID's are positive integers).

Regardless, this is how I changed up my code to make it work for me:

;WITH CTE
AS (
Select 1 as Level
    ,ChildID
    ,ParentID
    ,cast(ChildID as varchar(max)) as IDpath
From #TempTable

UNION ALL

Select Level + 1 as Level
    ,B.ChildID
    ,B.ParentID
    ,A.IDpath + '>' + cast(B.ChildID as varchar(max)) as IDpath
From CTE A
    Inner Join #TempTable B on A.ChildID=B.ParentID
Where Level = 1
    or (Level > 1 and IDpath like '2220%')
)
Select Distinct IDpath
From CTE
Where left(IDPath,4) = '2220'

Now, if there is someone with expertise that could comment on the quality of this "fix" and if it's reasonable (or if I'm missing something), I'd appreciate it. I don't want to accidentally poison the masses with a crap fix because of my naivety in assuming that this is a good (enough) fix.


问:
HttpException Request Time out
i can past this url into my browser and get the server time, https://api.binance.je/api/v3/time

But i am unable to get a response using below code. How can i debug this

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Console.WriteLine(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}
</code>```

答:
I see that you are able to retrieve the json data from the website. Tested this on my side.
However if you are trying to get the value only you need to read the json string (responsefromServer). This can be done by using a nuget pakage called Newtonsoft.
Then you will have to add the following to your code.

Above namespace:

```<code>using Newtonsoft.Json.Linq;
</code>```

In main function before closing reader enz:

```<code>        //Create jsonObject object from the api call response
        JObject jObject = JObject.Parse(responseFromServer);
        //Read propertie called serverTime and convert this to string to match variabele set
        string time = jObject["serverTime"].ToString();
        //Write the given time
        Console.WriteLine(time);
</code>```

Your code will look like the following:

```<code>using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Create a request for the URL.
            WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Console.WriteLine(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);

            //Create jsonObject object from the api call response
            JObject jObject = JObject.Parse(responseFromServer);
            //Read propertie called serverTime and convert this to string to match variabele set
            string time = jObject["serverTime"].ToString();
            //Write the given time
            Console.WriteLine(time);

            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}
</code>```

Title: HttpException Request Time out

Body:
i can past this url into my browser and get the server time, https://api.binance.je/api/v3/time

But i am unable to get a response using below code. How can i debug this

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Console.WriteLine(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}

Body:
I see that you are able to retrieve the json data from the website. Tested this on my side.
However if you are trying to get the value only you need to read the json string (responsefromServer). This can be done by using a nuget pakage called Newtonsoft.
Then you will have to add the following to your code.

Above namespace:

using Newtonsoft.Json.Linq;

In main function before closing reader enz:

        //Create jsonObject object from the api call response
        JObject jObject = JObject.Parse(responseFromServer);
        //Read propertie called serverTime and convert this to string to match variabele set
        string time = jObject["serverTime"].ToString();
        //Write the given time
        Console.WriteLine(time);

Your code will look like the following:

using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Create a request for the URL.
            WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Console.WriteLine(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);

            //Create jsonObject object from the api call response
            JObject jObject = JObject.Parse(responseFromServer);
            //Read propertie called serverTime and convert this to string to match variabele set
            string time = jObject["serverTime"].ToString();
            //Write the given time
            Console.WriteLine(time);

            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}


问:
REST API Design, RESTful API Naming Conventions
I have resource Draft which has the following representation:

```<code>{
   "name": "name",
   "groups": ["group1", "group2"]
}
</code>```

I need to design endpoint which would allow to add new groups to groups.

For instance, lets say client wants to modify the resource above by adding two new groups: group3 and group4, then, after this operation, the resource should look like:

```<code>{
   "name": "name",
   "groups": ["group1", "group2", "grpoup3", "group4"]
}
</code>```

I'm not sure what should be the right URL structure and HTTP method for such operation.

Currently I'm considering the following option:

```<code>PATCH `/draft/groups/add`

{
    'groups': ["group3", "group4"]
}
</code>```

However, I'm not quite sure if that's the right choice.

Any help would be appreciated,

Thanks

答:
Seems like you're identifying your draft by its name, and you have several groups in each draft. If that's correct, then this would be the REST Naming Convention:

POST /drafts/{draftName}/groups/ HTTP/1.1 - to create;

PUT /drafts/{draftName}/groups/{groupId} HTTP/1.1 - to update;

GET /drafts/{draftName}/groups/{groupId} HTTP/1.1 - to get (groupId shouldn't be required in case of collection resource request).

Body:
I have resource Draft which has the following representation:

{
   "name": "name",
   "groups": ["group1", "group2"]
}

I need to design endpoint which would allow to add new groups to groups.

For instance, lets say client wants to modify the resource above by adding two new groups: group3 and group4, then, after this operation, the resource should look like:

{
   "name": "name",
   "groups": ["group1", "group2", "grpoup3", "group4"]
}

I'm not sure what should be the right URL structure and HTTP method for such operation.

Currently I'm considering the following option:

PATCH `/draft/groups/add`

{
    'groups': ["group3", "group4"]
}

However, I'm not quite sure if that's the right choice.

Any help would be appreciated,

Thanks


问:
How to use Joomla left sidebar position for a custom component menu
A client web site uses a Joomla template with lots of modules in the left column, but for the custom component I'm designing, those modules must be replaced by a vertical menu. The hack solution I came up with is to hide those modules with CSS:

```<code>div#leftpad > div {
    display:none;
}
</code>```

and then insert a
 in
 with javascript and set display:block. With jQuery, I could do

```<code>jQuery('#compmenu').appendTo('#leftpad').show();
</code>```

The component displays a google map, so javascript is required anyway. Any Joomla experts here know of a more elegant or straightforward method to achieve the same result?

答:
In Joomla, menu types are determined by the various Views specified by the installed components. If your component is properly coded to Joomla MVC standards, you should have at least one View, which will give you at least one menu type to choose from. As sra mentioned, even if you do not need a menu link, you should create a hidden menu so you can create a link so you have an itemID to work with and assign modules to.

There are a few extensions and websites that can help create the necessary files for a component so all you have to do is add a little code. Once you understand the Joomla MVC it's really not too difficult.

http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_1

Doing it this way will save you a lot of headache later when the end user has to figure out how to use your component.

Body:
A client web site uses a Joomla template with lots of modules in the left column, but for the custom component I'm designing, those modules must be replaced by a vertical menu. The hack solution I came up with is to hide those modules with CSS:

div#leftpad > div {
    display:none;
}

and then insert a
 in
 with javascript and set display:block. With jQuery, I could do

jQuery('#compmenu').appendTo('#leftpad').show();

The component displays a google map, so javascript is required anyway. Any Joomla experts here know of a more elegant or straightforward method to achieve the same result?


答:
Hope you are using correct syntax:
git pull --rebase origin master</p>

Title: Why aren't changes in my remote master branch being pulled into my local master branch?

Body:
I have really been wracking my brain on this. I am using DevOps and the native Visual Studio Team Explorer interface.

I created a master branch and pushed it to the remote with.

I created a new branch that is also pushed to the remote.

I made many changes, updated the remote branch, and merged it into the master.

A colleague created a new branch, added some files, pushed it to remote, and merged it into the remote master.

The remote master correctly shows the combination of our work.

For the life of my I cannot seem to pull the changes from the origin/remote down to my local master branch.

I have tried Sync, pull, fetch, merge, and rebase.
The local master is bold, indicating it is selected.
I've tried creating new branches and updating just those.
When I am on the syncing menu, there are no incoming commits even though there are changes beyond what is in my local branch.
When I do sync or fetch/merge/pull the menu returns that my local branch is up to date.

I know there is something extremely simple that I'm missing here but after a few hours searching and a Udemy course I am still stumped!


问:
how to not send equal data to database?
This code:

```<code><?php
  include_once 'dbh.inc.php';
  include_once 'variables.inc.php';

  $sql = "INSERT INTO status (temp, weather, precipitation, vindtype, WindSpeed, WindDirection) VALUES ('$temp*C', '$weather', '$precipitation  mm', '$Windtype', '$Windspeed m/s', '$Winddirection');";
  mysqli_query($conn, $sql);

?>
</code>```

sends the current weather report to the database. MS Task scheduler does this process automatically every 10 minutes.

I want to only send the data only if any variable has changed. So basically: Check every 10 min if something has changed, if yes then send to the database, if not don't send.

Any help is greatly appreciated!

答:
You can check if the same values are not already in the database before you insert.
Like this:

```<code><?php
  include_once 'dbh.inc.php';
  include_once 'variables.inc.php';

  $sql = "if not exists(select * from status where temp = '$temp*C' and weather = '$weather' and precipitation = '$precipitation  mm' and vindtype = '$Windtype' and WindSpeed = '$Windspeed m/s' and WindDirection = '$Winddirection')
begin
INSERT INTO status (temp, weather, precipitation, vindtype, WindSpeed, WindDirection) VALUES ('$temp*C', '$weather', '$precipitation  mm', '$Windtype', '$Windspeed m/s', '$Winddirection');
end;";
  mysqli_query($conn, $sql);

?>
</code>```

Note I have not tested this code, but this should work for you

Title: how to not send equal data to database?

Body:
This code:

<?php
  include_once 'dbh.inc.php';
  include_once 'variables.inc.php';

  $sql = "INSERT INTO status (temp, weather, precipitation, vindtype, WindSpeed, WindDirection) VALUES ('$temp*C', '$weather', '$precipitation  mm', '$Windtype', '$Windspeed m/s', '$Winddirection');";
  mysqli_query($conn, $sql);

?>

sends the current weather report to the database. MS Task scheduler does this process automatically every 10 minutes.

I want to only send the data only if any variable has changed. So basically: Check every 10 min if something has changed, if yes then send to the database, if not don't send.

Any help is greatly appreciated!

Body:
You can check if the same values are not already in the database before you insert.
Like this:

<?php
  include_once 'dbh.inc.php';
  include_once 'variables.inc.php';

  $sql = "if not exists(select * from status where temp = '$temp*C' and weather = '$weather' and precipitation = '$precipitation  mm' and vindtype = '$Windtype' and WindSpeed = '$Windspeed m/s' and WindDirection = '$Winddirection')
begin
INSERT INTO status (temp, weather, precipitation, vindtype, WindSpeed, WindDirection) VALUES ('$temp*C', '$weather', '$precipitation  mm', '$Windtype', '$Windspeed m/s', '$Winddirection');
end;";
  mysqli_query($conn, $sql);

?>

Note I have not tested this code, but this should work for you


问:
Flutter floatingActionButton with textfield is not fully above keyboard. Need something like facebook messanger
I have a curious problem that i have no idea how to fix. I created a custom floatingActionButton with TextField and i set the floatingActionButtonLocation to FloatingActionButtonLocation.centerDocked. But when the textfield is expanded it goes under the keyboard. Can anyone help me with this problem pleas ?

```<code> Widget build(BuildContext context) {
    return Scaffold(
      appBar: GameDetailAppBar(
          widget.model.selectedGame.name,
          widget.model.selectedGame.currentUserMetadata['isOwner'],
          widget.model),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: showGamePageBottomBar
          ? GamePageBottomBar(widget.model)
          : _buildCommentBox(),
      backgroundColor: Colors.white,
      body: Container(
        child: _buildGamePage(),
      ),
    );
  }

  Widget _buildCommentBox() {
return Container(
  margin: EdgeInsets.only(bottom: 55),
  width: screenWidth(context),
  color: Colors.white,
  child: Container(
    margin: EdgeInsets.only(top: 5, bottom: 5, right: 27, left: 27),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(6),
      border: Border.all(
        color: createColor('#FFBF00'),
      ),
    ),
    child: Padding(
      padding: const EdgeInsets.only(left: 11, right: 11),
      child: new TextFormField(
        controller: _commentController,
        // focusNode: commentFocusNode,
        maxLines: 5,
        minLines: 1,
        decoration: new InputDecoration(
          border: InputBorder.none,
          suffix: Text(
            'Post',
            style: WidgetUtils.me.getLatoMedium(
              16,
              createColor('#0DB630'),
            ),
          ),
        ),
      ),
    ),
  ),
);
}
</code>```

This margin in _buildCommentBox should be somehow dynamic basec on _commentController lines. Without the margin part of the container is under keyboard even if the textfield has 1 line.

This is how my floatingActionButton looks like without text:

Need to fix this behaviour when text is on multilines(you can't see bottom border it is under keyboard) :

This is what i want:

答:
You should have a look at those two ways of doing it (I will link to questions I found that might help you solve this issue):

using resizeToAvoidBottomPadding: true in your Scaffold Widget (https://stackoverflow.com/a/53800595/12020274)

or

using

```<code>padding: EdgeInsets.only(
             bottom: MediaQuery.of(context).viewInsets.bottom));
</code>```

on your Padding Widget
(https://stackoverflow.com/a/53605734/12020274)

Body:
I have a curious problem that i have no idea how to fix. I created a custom floatingActionButton with TextField and i set the floatingActionButtonLocation to FloatingActionButtonLocation.centerDocked. But when the textfield is expanded it goes under the keyboard. Can anyone help me with this problem pleas ?

 Widget build(BuildContext context) {
    return Scaffold(
      appBar: GameDetailAppBar(
          widget.model.selectedGame.name,
          widget.model.selectedGame.currentUserMetadata['isOwner'],
          widget.model),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: showGamePageBottomBar
          ? GamePageBottomBar(widget.model)
          : _buildCommentBox(),
      backgroundColor: Colors.white,
      body: Container(
        child: _buildGamePage(),
      ),
    );
  }

  Widget _buildCommentBox() {
return Container(
  margin: EdgeInsets.only(bottom: 55),
  width: screenWidth(context),
  color: Colors.white,
  child: Container(
    margin: EdgeInsets.only(top: 5, bottom: 5, right: 27, left: 27),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(6),
      border: Border.all(
        color: createColor('#FFBF00'),
      ),
    ),
    child: Padding(
      padding: const EdgeInsets.only(left: 11, right: 11),
      child: new TextFormField(
        controller: _commentController,
        // focusNode: commentFocusNode,
        maxLines: 5,
        minLines: 1,
        decoration: new InputDecoration(
          border: InputBorder.none,
          suffix: Text(
            'Post',
            style: WidgetUtils.me.getLatoMedium(
              16,
              createColor('#0DB630'),
            ),
          ),
        ),
      ),
    ),
  ),
);
}

This margin in _buildCommentBox should be somehow dynamic basec on _commentController lines. Without the margin part of the container is under keyboard even if the textfield has 1 line.

This is how my floatingActionButton looks like without text:

Need to fix this behaviour when text is on multilines(you can't see bottom border it is under keyboard) :

This is what i want:

Body:
You should have a look at those two ways of doing it (I will link to questions I found that might help you solve this issue):

using resizeToAvoidBottomPadding: true in your Scaffold Widget (https://stackoverflow.com/a/53800595/12020274)

or

using

padding: EdgeInsets.only(
             bottom: MediaQuery.of(context).viewInsets.bottom));

on your Padding Widget
(https://stackoverflow.com/a/53605734/12020274)


问:
In JSX why is this invalid: {...{ type: 'button', ...props }}
I want to use the attribute type if it is provided in the props, if not I want to provide button to the attribute type.

```<code>    <button
      {...{ type: 'button', ...props }}
    />
</code>```

This does not work and provides Cannot read property 'name' of undefined.

If I do this it works fine:

```<code>const newProps = {type: 'button', ...props}

  //...
  <button
    {...newProps}
</code>```

I am now doing this instead, just curious why the first example doesn't work, but the second example does:

```<code>  <button
    {...props}
    type="button"
  />
</code>```

答:
You should just write:

```<code><button
   { type: 'button', ...props }
/>
</code>```

However, I would go with your last approach (my best practice):

```<code>  <button
    {...props}
    type="button"
  />
</code>```

My best because firstly defined attribute is always takes first place in html.

Body:
I want to use the attribute type if it is provided in the props, if not I want to provide button to the attribute type.

    <button
      {...{ type: 'button', ...props }}
    />

This does not work and provides Cannot read property 'name' of undefined.

If I do this it works fine:

const newProps = {type: 'button', ...props}

  //...
  <button
    {...newProps}

I am now doing this instead, just curious why the first example doesn't work, but the second example does:

  <button
    {...props}
    type="button"
  />

Body:
You should just write:

<button
   { type: 'button', ...props }
/>

However, I would go with your last approach (my best practice):

  <button
    {...props}
    type="button"
  />

My best because firstly defined attribute is always takes first place in html.


问:
Getting ORA-00918: column ambiguously defined error which try to open django admin page after upgrading to django 3.03 from 2.0
Getting django.db.utils.DatabaseError: ORA-00918: column ambiguously defined error when I try to open Django admin page. Here is the error:

raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 514, in execute
    return self.cursor.execute(query, self._param_generator(params))
django.db.utils.DatabaseError: ORA-00918: column ambiguously defined

Query is

```<code>SELECT "DJANGO_ADMIN_LOG"."ID",
       "DJANGO_ADMIN_LOG"."ACTION_TIME",
       "DJANGO_ADMIN_LOG"."USER_ID",
       "DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_REPR",
       "DJANGO_ADMIN_LOG"."ACTION_FLAG",
       "DJANGO_ADMIN_LOG"."CHANGE_MESSAGE",
       "AUTH_USER"."ID",
       "AUTH_USER"."PASSWORD",
       "AUTH_USER"."LAST_LOGIN",
       "AUTH_USER"."IS_SUPERUSER",
       "AUTH_USER"."USERNAME",
       "AUTH_USER"."FIRST_NAME",
       "AUTH_USER"."LAST_NAME",
       "AUTH_USER"."EMAIL",
       "AUTH_USER"."IS_STAFF",
       "AUTH_USER"."IS_ACTIVE",
       "AUTH_USER"."DATE_JOINED",
       "DJANGO_CONTENT_TYPE"."ID",
       "DJANGO_CONTENT_TYPE"."APP_LABEL",
       "DJANGO_CONTENT_TYPE"."MODEL"
  FROM "DJANGO_ADMIN_LOG"
  INNER JOIN "AUTH_USER"
    ON ("DJANGO_ADMIN_LOG"."USER_ID" = "AUTH_USER"."ID")
  LEFT OUTER JOIN "DJANGO_CONTENT_TYPE"
    ON ("DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID" = "DJANGO_CONTENT_TYPE"."ID")
  WHERE "DJANGO_ADMIN_LOG"."USER_ID" = :arg0
  ORDER BY "DJANGO_ADMIN_LOG"."ACTION_TIME" DESC
  FETCH FIRST 10 ROWS ONLY
</code>```

答:
You're fetching DJANGO_ADMIN_LOG.ID, AUTH_USER.ID, and DJANGO_CONTENT_TYPE.ID, so you're trying to have three ID columns in your result set. This is not allowed. I suggest you alias these columns so you can distinguish between them:

```<code>SELECT l.ID AS DJANGO_ADMIN_LOG_ID,
       l.ACTION_TIME,
       l.USER_ID,
       l.CONTENT_TYPE_ID,
       l.OBJECT_ID,
       l.OBJECT_REPR,
       l.ACTION_FLAG,
       l.CHANGE_MESSAGE,
       u.ID AS AUTH_USER_ID,
       u.PASSWORD,
       u.LAST_LOGIN,
       u.IS_SUPERUSER,
       u.USERNAME,
       u.FIRST_NAME,
       u.LAST_NAME,
       u.EMAIL,
       u.IS_STAFF,
       u.IS_ACTIVE,
       u.DATE_JOINED,
       t.ID AS DJANGO_CONTENT_TYPE_ID,
       t.APP_LABEL,
       t.MODEL
  FROM DJANGO_ADMIN_LOG l
  INNER JOIN AUTH_USER u
    ON l.USER_ID = u.ID
  LEFT OUTER JOIN DJANGO_CONTENT_TYPE t
    ON l.CONTENT_TYPE_ID = t.ID
  WHERE l.USER_ID = :arg0
  ORDER BY l.ACTION_TIME DESC
  FETCH FIRST 10 ROWS ONLY
</code>```

I also suggest you use white space and table aliases to make the query easier to read.

Body:
Getting django.db.utils.DatabaseError: ORA-00918: column ambiguously defined error when I try to open Django admin page. Here is the error:

raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 514, in execute
    return self.cursor.execute(query, self._param_generator(params))
django.db.utils.DatabaseError: ORA-00918: column ambiguously defined

Query is

SELECT "DJANGO_ADMIN_LOG"."ID",
       "DJANGO_ADMIN_LOG"."ACTION_TIME",
       "DJANGO_ADMIN_LOG"."USER_ID",
       "DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_REPR",
       "DJANGO_ADMIN_LOG"."ACTION_FLAG",
       "DJANGO_ADMIN_LOG"."CHANGE_MESSAGE",
       "AUTH_USER"."ID",
       "AUTH_USER"."PASSWORD",
       "AUTH_USER"."LAST_LOGIN",
       "AUTH_USER"."IS_SUPERUSER",
       "AUTH_USER"."USERNAME",
       "AUTH_USER"."FIRST_NAME",
       "AUTH_USER"."LAST_NAME",
       "AUTH_USER"."EMAIL",
       "AUTH_USER"."IS_STAFF",
       "AUTH_USER"."IS_ACTIVE",
       "AUTH_USER"."DATE_JOINED",
       "DJANGO_CONTENT_TYPE"."ID",
       "DJANGO_CONTENT_TYPE"."APP_LABEL",
       "DJANGO_CONTENT_TYPE"."MODEL"
  FROM "DJANGO_ADMIN_LOG"
  INNER JOIN "AUTH_USER"
    ON ("DJANGO_ADMIN_LOG"."USER_ID" = "AUTH_USER"."ID")
  LEFT OUTER JOIN "DJANGO_CONTENT_TYPE"
    ON ("DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID" = "DJANGO_CONTENT_TYPE"."ID")
  WHERE "DJANGO_ADMIN_LOG"."USER_ID" = :arg0
  ORDER BY "DJANGO_ADMIN_LOG"."ACTION_TIME" DESC
  FETCH FIRST 10 ROWS ONLY

Body:
You're fetching DJANGO_ADMIN_LOG.ID, AUTH_USER.ID, and DJANGO_CONTENT_TYPE.ID, so you're trying to have three ID columns in your result set. This is not allowed. I suggest you alias these columns so you can distinguish between them:

SELECT l.ID AS DJANGO_ADMIN_LOG_ID,
       l.ACTION_TIME,
       l.USER_ID,
       l.CONTENT_TYPE_ID,
       l.OBJECT_ID,
       l.OBJECT_REPR,
       l.ACTION_FLAG,
       l.CHANGE_MESSAGE,
       u.ID AS AUTH_USER_ID,
       u.PASSWORD,
       u.LAST_LOGIN,
       u.IS_SUPERUSER,
       u.USERNAME,
       u.FIRST_NAME,
       u.LAST_NAME,
       u.EMAIL,
       u.IS_STAFF,
       u.IS_ACTIVE,
       u.DATE_JOINED,
       t.ID AS DJANGO_CONTENT_TYPE_ID,
       t.APP_LABEL,
       t.MODEL
  FROM DJANGO_ADMIN_LOG l
  INNER JOIN AUTH_USER u
    ON l.USER_ID = u.ID
  LEFT OUTER JOIN DJANGO_CONTENT_TYPE t
    ON l.CONTENT_TYPE_ID = t.ID
  WHERE l.USER_ID = :arg0
  ORDER BY l.ACTION_TIME DESC
  FETCH FIRST 10 ROWS ONLY

I also suggest you use white space and table aliases to make the query easier to read.


问:
Hide Open Program With CMD
Hello I would like to know if someone can help me I would like to know how to open a program and this is hidden (not shown in the taskbar) I was testing the following but it did not work Anyone have any other ideas?

Start /b "Título" "word.exe"

答:
To run it hide use VBScript:</p>

```<code>Echo Dim sh : Set sh = CreateObject^(Wscript.Shell^) : sh.run """Winword.exe Full Path""", 0, False >tmp.vbs
Cscript //nologo tmp.vbs
Del tmp.vbs
</code>```

Title: Hide Open Program With CMD

Body:
To run it hide use VBScript:

Echo Dim sh : Set sh = CreateObject^(Wscript.Shell^) : sh.run """Winword.exe Full Path""", 0, False >tmp.vbs
Cscript //nologo tmp.vbs
Del tmp.vbs


问:
Pyqt widget FigureCanvas border and content coexist
i want a widget,it can use matplotlib drawing an image and it can setting it's border.

so i'm create a class，it's parent is FigureCanvas,that i can drawing image.
It seems that setting a border must be rewrite paintEvent method，so i do.
But i find when i rewrite paintEvent method，drawing failed.

When i note the paintEvent method method，drawing success.

Who can help me improve the code or give me some tips.

```<code>import pydicom
from PyQt4 import QtGui
from matplotlib.backends.backend_template import FigureCanvas
from matplotlib.pylab import *
from PyQt4.QtGui import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class InstancesFC(FigureCanvas):
    def __init__(self):
        self.figure = plt.figure(figsize=(2, 2))
        super(InstancesFC, self).__init__(self.figure)
        self.update_area()
        self.setObjectName('InstancesFC')
        self.ax = self.figure.add_subplot(111)
        plt.axis('off')
        x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        y = [23, 21, 32, 13, 3, 132, 13, 3, 1]
        self.ax.plot(x, y)

    def update_area(self):
        self.setStyleSheet("""
            #InstancesFC{
                          border-width: 1px;
             border-style: solid;
             border-color: red;
             min-width:%s;
             max-width:%s;
             min-height:%s;
             max-height:%s;
             padding:0px;
             margin:1px;
            }
        """ % ('300px', '300px', '300px', '300px'))

    def paintEvent(self, event):
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        h = QtGui.QHBoxLayout()
        h.addWidget(InstancesFC())
        self.setLayout(h)
        self.setGeometry(100, 100, 500, 500)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

答:
When you override the paintEvent() method and if you don't call the parent method then you will eliminate the default behavior causing the problem you are observing. The solution is to call the paintEvent() method of the parent.

```<code>def paintEvent(self, event):
    <b>super(InstancesFC, self).paintEvent(event)</b>
    opt = QStyleOption()
    opt.initFrom(self)
    painter = QPainter(self)
    painter.setRenderHint(QPainter.Antialiasing)
    self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)</code>```

Body:
i want a widget,it can use matplotlib drawing an image and it can setting it's border.

so i'm create a class，it's parent is FigureCanvas,that i can drawing image.
It seems that setting a border must be rewrite paintEvent method，so i do.
But i find when i rewrite paintEvent method，drawing failed.

When i note the paintEvent method method，drawing success.

Who can help me improve the code or give me some tips.

import pydicom
from PyQt4 import QtGui
from matplotlib.backends.backend_template import FigureCanvas
from matplotlib.pylab import *
from PyQt4.QtGui import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class InstancesFC(FigureCanvas):
    def __init__(self):
        self.figure = plt.figure(figsize=(2, 2))
        super(InstancesFC, self).__init__(self.figure)
        self.update_area()
        self.setObjectName('InstancesFC')
        self.ax = self.figure.add_subplot(111)
        plt.axis('off')
        x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        y = [23, 21, 32, 13, 3, 132, 13, 3, 1]
        self.ax.plot(x, y)

    def update_area(self):
        self.setStyleSheet("""
            #InstancesFC{
                          border-width: 1px;
             border-style: solid;
             border-color: red;
             min-width:%s;
             max-width:%s;
             min-height:%s;
             max-height:%s;
             padding:0px;
             margin:1px;
            }
        """ % ('300px', '300px', '300px', '300px'))

    def paintEvent(self, event):
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        h = QtGui.QHBoxLayout()
        h.addWidget(InstancesFC())
        self.setLayout(h)
        self.setGeometry(100, 100, 500, 500)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
When you override the paintEvent() method and if you don't call the parent method then you will eliminate the default behavior causing the problem you are observing. The solution is to call the paintEvent() method of the parent.

def paintEvent(self, event):
    super(InstancesFC, self).paintEvent(event)
    opt = QStyleOption()
    opt.initFrom(self)
    painter = QPainter(self)
    painter.setRenderHint(QPainter.Antialiasing)
    self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)


问:
How to make the radio buttons not to change when switching the activities?
i've got an android app with 2 scenes. mainactivity and settings. When I go from the mainactivity to the settingsactivity and change a radiobutton and go back to the mainactivity and than again back, the button goes back to default. Thats because it always goes to the oncreate method. how do I have to place/write the Intent, that the radiobuttons don't go back to default?</p>

答:
You should save state of radio buttons once it changed in some persistance. For the settings, SharedPreferences is the optimal choice.
So,

Create collection of possible RadioButtons in the group (after setContent statement in onCreate method):

```<code>RadioGroup rGroup = findViewById(R.id.radioGroup1);

List<RadioButton> buttons = new ArrayList();
buttons.add(rGroup.findViewById(R.id.radioButton1);
buttons.add(rGroup.findViewById(R.id.radioButton2);
// ...
}
</code>```

Once state is changed (so, in OnCheckedChangeListener of the RadioGroup) , save it in the SharedPreferences:

// find RadioButton
RadioGroup rGroup = findViewById(R.id.radioGroup1);
RadioButton checkedRadioButton = rGroup.findViewById(rGroup.getCheckedRadioButtonId());

// define selected option value
int selectedOption = 0;
for (int i = 0; i < buttons.size(); i++) {
  if (checkedRadioButton.getId() == buttons.get(i).getId()) {
    selectedOption = i;
    break;
  }
}

// write state to SP
getSharedPreferences("my_settings", Context.MODE_PRIVATE).edit().putInt("sel_option", selectedOption).apply()
```

<ol start="2">
<li>In the <code>onCreate</code> of settings activity: read previously saved state and update UI accordingly:</li>
</ol>

```int option = getSharedPreferences("my_settings", Context.MODE_PRIVATE).getInt("sel_option", 0);

// set checked for the specific button
buttons.get(option).setChecked(true);

```

Body:
You should save state of radio buttons once it changed in some persistance. For the settings, SharedPreferences is the optimal choice.
So,

Create collection of possible RadioButtons in the group (after setContent statement in onCreate method):

RadioGroup rGroup = findViewById(R.id.radioGroup1);

List<RadioButton> buttons = new ArrayList();
buttons.add(rGroup.findViewById(R.id.radioButton1);
buttons.add(rGroup.findViewById(R.id.radioButton2);
// ...
}

Once state is changed (so, in OnCheckedChangeListener of the RadioGroup) , save it in the SharedPreferences:

// find RadioButton
RadioGroup rGroup = findViewById(R.id.radioGroup1);
RadioButton checkedRadioButton = rGroup.findViewById(rGroup.getCheckedRadioButtonId());

// define selected option value
int selectedOption = 0;
for (int i = 0; i < buttons.size(); i++) {
  if (checkedRadioButton.getId() == buttons.get(i).getId()) {
    selectedOption = i;
    break;
  }
}

// write state to SP
getSharedPreferences("my_settings", Context.MODE_PRIVATE).edit().putInt("sel_option", selectedOption).apply()

In the onCreate of settings activity: read previously saved state and update UI accordingly:

int option = getSharedPreferences("my_settings", Context.MODE_PRIVATE).getInt("sel_option", 0);

// set checked for the specific button
buttons.get(option).setChecked(true);


问:
Regular expression range 1 25
Hello can someone help me creating a regex for numeric range from 1 to 25, I wouldn't like 01 02 etc just 1 2 3 ....
Thanks

My failed attempt /^([1-2]{1,2}[0-9])$/

答:
This is the "simple to understand" way

/^([1-9]|1[0-9]|2[0-5])$/

Breakdown:-

|: or operator

[1-9]: match 1 to 9

1[0-9]: match 10 to 19

2[0-5]: match 20 to 25

Title: Regular expression range 1 25


问:
How to call another project's method where DI is implemented
I think I implemented a poor architecture. Try to follow me on this please.

I have project1 that is a simple scraper. Whenever it receive a response from its scraping process, it want to save the scraped data into the database. It has its own DI container.

I have project2 which is the one responsible for executing DB migrations and I placed also the logic to access and modify the database in here. I wanted to keep all the logic to manage the DB in one place only. It has its own DI container.

Finally, I have project3 which is an API that whenever asked, serves the data stored in the DB. It has its own DI container.

As you can see project2 is in the middle, it gets used both by the scraper project when saving data and the API project for serving the data.
In project2 my DI registration looks like this:

```<code>private static IServiceCollection ConfigureServices(IConfiguration Configuration)
{
    IServiceCollection services = new ServiceCollection();

    // Inject IOptions<T>
    services.AddOptions();
    var dbSettings = Configuration.GetSection("Settings");
    services.Configure<DbSettings>(dbSettings);

    return services;
}
</code>```

What it does is that looks into the appsettings (there is only a connectionString towards the database saved) and prepares IOption to be injected where needed.
So in project2 there is a for example a method to check if the DB is empty.

```<code>public class DbClient : IDbClient
{
    private readonly IOptions<DbSettings> _dbSettings;
    public DbClient(IOptions<DbSettings> dbSettings)
    {
        _dbSettings = dbSettings;
    }

    public bool IsDbEmpty()
    {
        using (SqlConnection connection = new SqlConnection(_dbSettings.Value.ConnectionString))
        {
            var isEmpty = connection.QueryFirst<string>("SELECT COUNT(1) WHERE EXISTS (SELECT * FROM Test)");
            Console.ReadLine();
        }
    }
}
</code>```

Guess where the problem is? Whenever I try to call this method from either project1 (the scraper) or project3 (the API) the IOptions is not injected, because I haven't called the container of project2. How do I solve this? Thanks in advance!

答:
One approach is to have your shared project ("project2") expose some functionality for configuration that can be used by consuming applications ("project1" and "project3").

With .NET Core, you can do this by defining IServiceCollection extension methods in your shared project ("project2"):

```<code>public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddProject2(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddOptions();
        var dbSettings = configuration.GetSection("Settings");
        services.Configure<DbSettings>(dbSettings);

        return services;
    }
}
</code>```

And then calling this from the startup of the consuming projects ("project1" and "project3"):

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddProject2(Configuration);

    ...
}
</code>```

Note that you can then define the configuration required for "project2" within any project that is consuming it.

Body:
I think I implemented a poor architecture. Try to follow me on this please.

I have project1 that is a simple scraper. Whenever it receive a response from its scraping process, it want to save the scraped data into the database. It has its own DI container.

I have project2 which is the one responsible for executing DB migrations and I placed also the logic to access and modify the database in here. I wanted to keep all the logic to manage the DB in one place only. It has its own DI container.

Finally, I have project3 which is an API that whenever asked, serves the data stored in the DB. It has its own DI container.

As you can see project2 is in the middle, it gets used both by the scraper project when saving data and the API project for serving the data.
In project2 my DI registration looks like this:

private static IServiceCollection ConfigureServices(IConfiguration Configuration)
{
    IServiceCollection services = new ServiceCollection();

    // Inject IOptions<T>
    services.AddOptions();
    var dbSettings = Configuration.GetSection("Settings");
    services.Configure<DbSettings>(dbSettings);

    return services;
}

What it does is that looks into the appsettings (there is only a connectionString towards the database saved) and prepares IOption to be injected where needed.
So in project2 there is a for example a method to check if the DB is empty.

public class DbClient : IDbClient
{
    private readonly IOptions<DbSettings> _dbSettings;
    public DbClient(IOptions<DbSettings> dbSettings)
    {
        _dbSettings = dbSettings;
    }

    public bool IsDbEmpty()
    {
        using (SqlConnection connection = new SqlConnection(_dbSettings.Value.ConnectionString))
        {
            var isEmpty = connection.QueryFirst<string>("SELECT COUNT(1) WHERE EXISTS (SELECT * FROM Test)");
            Console.ReadLine();
        }
    }
}

Guess where the problem is? Whenever I try to call this method from either project1 (the scraper) or project3 (the API) the IOptions is not injected, because I haven't called the container of project2. How do I solve this? Thanks in advance!

Body:
One approach is to have your shared project ("project2") expose some functionality for configuration that can be used by consuming applications ("project1" and "project3").

With .NET Core, you can do this by defining IServiceCollection extension methods in your shared project ("project2"):

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddProject2(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddOptions();
        var dbSettings = configuration.GetSection("Settings");
        services.Configure<DbSettings>(dbSettings);

        return services;
    }
}

And then calling this from the startup of the consuming projects ("project1" and "project3"):

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddProject2(Configuration);

    ...
}

Note that you can then define the configuration required for "project2" within any project that is consuming it.


答:
If a GET request on /draft gives you a list of groups, I would feel that it's probably the most logical to also use a HTTP method on that same endpoint to make changes to the representation.

So given that, I think my first guess on how to change groups in your API would probably be a PUT or PATCH request on /draft itself.

Title: REST API Design, RESTful API Naming Conventions

Body:
I have resource Draft which has the following representation:

{
   "name": "name",
   "groups": ["group1", "group2"]
}

I need to design endpoint which would allow to add new groups to groups.

For instance, lets say client wants to modify the resource above by adding two new groups: group3 and group4, then, after this operation, the resource should look like:

{
   "name": "name",
   "groups": ["group1", "group2", "grpoup3", "group4"]
}

I'm not sure what should be the right URL structure and HTTP method for such operation.

Currently I'm considering the following option:

PATCH `/draft/groups/add`

{
    'groups': ["group3", "group4"]
}

However, I'm not quite sure if that's the right choice.

Any help would be appreciated,

Thanks


问:
too many values to unpack (expected 2) in array
```<code>for image_x, image_y in (training_low_imgs, training_high_imgs):
</code>```

The below error is getting in the above line.

too many values to unpack (expected 2)

Please note that both the shapes of training_low_imgs and training_high_imgs are (10, 256, 256, 3)

答:
You forgot about zip:

for image_x, image_y in zip(training_low_imgs, training_high_imgs):
```

Body:
for image_x, image_y in (training_low_imgs, training_high_imgs):

The below error is getting in the above line.

too many values to unpack (expected 2)

Please note that both the shapes of training_low_imgs and training_high_imgs are (10, 256, 256, 3)


答:
you can use the built-in function zip:

```<code>for image_x, image_y in zip(training_low_imgs, training_high_imgs):
</code>```

Title: too many values to unpack (expected 2) in array

Body:
you can use the built-in function zip:

for image_x, image_y in zip(training_low_imgs, training_high_imgs):


问:
Create record for another model when account is created?
I have a multi-tenant application. When an account is created, the account belongs to an owner and also creates a user record for the owner. This owner can invite other users through a memberships join table. All users except for account owners have memberships to the account.

For users with memberships (not owners of accounts) the account/users/:id show page shows up. I would like the same for account owners, but am receiving the following error message:

```<code>ActiveRecord::RecordNotFound in Accounts::UsersController#show
Couldn't find User with 'id'=2 [WHERE "memberships"."account_id" = $1]

def show
  @user = current_account.users.find(params[:id])
end
</code>```

I can add a membership to the owner user in the admin panel and this error goes away, however I would like to add the membership to the owner/user when they create their account.

Any ideas?

Adding @account.memberships.build(user_id: current_user, account_id: current_account) before if @account.save in the accounts controller below does not seem to work.

controllers

user.rb

```<code>module Accounts
  class UsersController < Accounts::BaseController
    before_action :authorize_owner!, only: [:edit, :show, :update, :destroy]

    def show
      @user = current_account.users.find(params[:id])
    end

    def destroy
      user = User.find(params[:id])
      current_account.users.delete(user)
      flash[:notice] = "#{user.email} has been removed from this account."
      redirect_to users_path
    end
  end
end
</code>```

accounts_controller.rb

```<code>class AccountsController < ApplicationController
  def new
    @account = Account.new
    @account.build_owner
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      sign_in(@account.owner)
      flash[:notice] = "Your account has been created."
      redirect_to root_url(subdomain: @account.subdomain)
    else
      flash.now[:alert] = "Sorry, your account could not be created."
      render :new
    end
  end

  private

    def account_params
      params.require(:account).permit(:name, :subdomain,
        { owner_attributes: [:email, :password, :password_confirmation
        ]}
      )
    end
end
</code>```

Models

user.rb

```<code>class User < ApplicationRecord
  has_many :memberships
  has_many :accounts, through: :memberships

  def owned_accounts
    Account.where(owner: self)
  end

  def all_accounts
    owned_accounts + accounts
  end
end
</code>```

account.rb

```<code>class Account < ApplicationRecord
  belongs_to :owner, class_name: "User"
  accepts_nested_attributes_for :owner

  validates :subdomain, presence: true, uniqueness: true

  has_many :memberships
  has_many :users, through: :memberships
end
</code>```

membership.rb

```<code>class Membership < ApplicationRecord
  belongs_to :account
  belongs_to :user
end
</code>```

答:
Ended up answering this question by putting this line under if @account.save:

```<code>if @account.save
  @account.memberships.create(user_id: @account.owner.id, account_id: @account.id)
</code>```

Probably not ideal, but it works for now. I might end up making a service or something like that for it, though.

Body:
I have a multi-tenant application. When an account is created, the account belongs to an owner and also creates a user record for the owner. This owner can invite other users through a memberships join table. All users except for account owners have memberships to the account.

For users with memberships (not owners of accounts) the account/users/:id show page shows up. I would like the same for account owners, but am receiving the following error message:

ActiveRecord::RecordNotFound in Accounts::UsersController#show
Couldn't find User with 'id'=2 [WHERE "memberships"."account_id" = $1]

def show
  @user = current_account.users.find(params[:id])
end

I can add a membership to the owner user in the admin panel and this error goes away, however I would like to add the membership to the owner/user when they create their account.

Any ideas?

Adding @account.memberships.build(user_id: current_user, account_id: current_account) before if @account.save in the accounts controller below does not seem to work.

controllers

user.rb

module Accounts
  class UsersController < Accounts::BaseController
    before_action :authorize_owner!, only: [:edit, :show, :update, :destroy]

    def show
      @user = current_account.users.find(params[:id])
    end

    def destroy
      user = User.find(params[:id])
      current_account.users.delete(user)
      flash[:notice] = "#{user.email} has been removed from this account."
      redirect_to users_path
    end
  end
end

accounts_controller.rb

class AccountsController < ApplicationController
  def new
    @account = Account.new
    @account.build_owner
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      sign_in(@account.owner)
      flash[:notice] = "Your account has been created."
      redirect_to root_url(subdomain: @account.subdomain)
    else
      flash.now[:alert] = "Sorry, your account could not be created."
      render :new
    end
  end

  private

    def account_params
      params.require(:account).permit(:name, :subdomain,
        { owner_attributes: [:email, :password, :password_confirmation
        ]}
      )
    end
end

Models

user.rb

class User < ApplicationRecord
  has_many :memberships
  has_many :accounts, through: :memberships

  def owned_accounts
    Account.where(owner: self)
  end

  def all_accounts
    owned_accounts + accounts
  end
end

account.rb

class Account < ApplicationRecord
  belongs_to :owner, class_name: "User"
  accepts_nested_attributes_for :owner

  validates :subdomain, presence: true, uniqueness: true

  has_many :memberships
  has_many :users, through: :memberships
end

membership.rb

class Membership < ApplicationRecord
  belongs_to :account
  belongs_to :user
end

Body:
Ended up answering this question by putting this line under if @account.save:

if @account.save
  @account.memberships.create(user_id: @account.owner.id, account_id: @account.id)

Probably not ideal, but it works for now. I might end up making a service or something like that for it, though.


问:
Module 'pytextrank' has no attribute 'parse_doc'
I am performing a nlp task. I have written the following code. While executing, it is showing the following error. Any suggestion to resolve the error will be helpful. I am having python 3 env in google colab .

```<code># Pytextrank
import pytextrank
import json

# Sample text
sample_text = 'I Like Flipkart. He likes Amazone. she likes Snapdeal. Flipkart and amazone is on top of google search.'

# Create dictionary to feed into json file

file_dic = {"id" : 0,"text" : sample_text}
file_dic = json.dumps(file_dic)
loaded_file_dic = json.loads(file_dic)

# Create test.json and feed file_dic into it.
with open('test.json', 'w') as outfile:
json.dump(loaded_file_dic, outfile)

path_stage0 = "test.json"
path_stage1 = "o1.json"

# Extract keyword using pytextrank
with open(path_stage1, 'w') as f:
for graf in pytextrank.parse_doc(pytextrank.json_iter(path_stage0)):
f.write("%s\n" % pytextrank.pretty_print(graf._asdict()))

print(pytextrank.pretty_print(graf._asdict()))
</code>```

I am getting the following error :

```<code>  AttributeError                            Traceback (most recent call last)
  <ipython-input-33-286ce104df34> in <module>()
       20 # Extract keyword using pytextrank
       21 with open(path_stage1, 'w') as f:
  ---> 22   for graf in
  pytextrank.parse_doc(pytextrank.json_iter(path_stage0)):
       23     f.write("%s\n" % pytextrank.pretty_print(graf._asdict()))
       24     print(pytextrank.pretty_print(graf._asdict()))

      AttributeError: module 'pytextrank' has no attribute 'parse_doc'
</code>```

答:
Implementation of TextRank in Python for use in spaCy pipelines </p>

```<code>import spacy
import pytextrank
nlp = spacy.load('en_core_web_sm')
tr = pytextrank.TextRank()
nlp.add_pipe(tr.PipelineComponent, name='textrank', last=True)
# Sample text
sample_text = 'I Like Flipkart. He likes Amazone. she likes Snapdeal. Flipkart and amazone is on top of google search.'
#funct
for p in doc._.phrases:
    print(p.text)
</code>```

Body:
I am performing a nlp task. I have written the following code. While executing, it is showing the following error. Any suggestion to resolve the error will be helpful. I am having python 3 env in google colab .

# Pytextrank
import pytextrank
import json

# Sample text
sample_text = 'I Like Flipkart. He likes Amazone. she likes Snapdeal. Flipkart and amazone is on top of google search.'

# Create dictionary to feed into json file

file_dic = {"id" : 0,"text" : sample_text}
file_dic = json.dumps(file_dic)
loaded_file_dic = json.loads(file_dic)

# Create test.json and feed file_dic into it.
with open('test.json', 'w') as outfile:
json.dump(loaded_file_dic, outfile)

path_stage0 = "test.json"
path_stage1 = "o1.json"

# Extract keyword using pytextrank
with open(path_stage1, 'w') as f:
for graf in pytextrank.parse_doc(pytextrank.json_iter(path_stage0)):
f.write("%s\n" % pytextrank.pretty_print(graf._asdict()))

print(pytextrank.pretty_print(graf._asdict()))

I am getting the following error :

  AttributeError                            Traceback (most recent call last)
  <ipython-input-33-286ce104df34> in <module>()
       20 # Extract keyword using pytextrank
       21 with open(path_stage1, 'w') as f:
  ---> 22   for graf in
  pytextrank.parse_doc(pytextrank.json_iter(path_stage0)):
       23     f.write("%s\n" % pytextrank.pretty_print(graf._asdict()))
       24     print(pytextrank.pretty_print(graf._asdict()))

      AttributeError: module 'pytextrank' has no attribute 'parse_doc'

Body:
Implementation of TextRank in Python for use in spaCy pipelines

import spacy
import pytextrank
nlp = spacy.load('en_core_web_sm')
tr = pytextrank.TextRank()
nlp.add_pipe(tr.PipelineComponent, name='textrank', last=True)
# Sample text
sample_text = 'I Like Flipkart. He likes Amazone. she likes Snapdeal. Flipkart and amazone is on top of google search.'
#funct
for p in doc._.phrases:
    print(p.text)


问:
How to access and process @ViewChildren?
I have below hierarchy of components:

product-list.component.ts

```<code><product-list>

    <ng-content></ng-content>

</product-list>
</code>```

product.component.ts

```<code><product>

    <ng-content></ng-content>

</product>
</code>```

Demo.component.ts

```<code>       <product-list>

                <product>

                    <product-rating></product-rating>

                </product>

        </product-list>

        <button label="Submit" (click)="submit()"></button>
</code>```

On Submit, I have to access product-rating component and depending on rating have to change the color of corresponding product component. What is the best way to access and process this?

Demo.component.ts

```<code>@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;
</code>```

product.component.ts

```<code>@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;
</code>```

Is there any better way to access product-rating component?

Any help would be appreciated.

答:
Even though you have what looks like a relatively complex component structure, you can still achieve what you want to with standard @Output and @Input events and properties.

Your starting point is to decide which component is "controlling" everything. In your case it's the demo component. Demo component is deciding what the component hierarchy is. Next you need to work out the desired flow of data. In your case, it will look a bit like this:

product-rating -> demo -> product

A rating is determined by product-rating, and needs to get to product via the controller.

So you need to add an @Output event to product rating that the control can subscribe to:

```<code>@Output() ratingChange: EventEmitter<number> = new EventEmitter<number>();

// this is some event handler that handles the user-driven rating change
onRatingChange(): void {
  // Emit the rating. I am guessing here that the rating is stored in some property
  // It might come into this function as an event arg - that's up to your design.
  this.ratingChange.emit(this.rating);
}
</code>```

So now the demo component can handle the rating change events and send it to the product:

demo.component.html

```<code><product [rating]="rating">
  <product-rating (ratingChange)="onRatingChange($event)"></product-rating>
</product>
</code>```

demo.component.ts

```<code>rating: number;

onRatingChange(rating: number): void {
  this.rating = rating;
}
</code>```

Body:
I have below hierarchy of components:

product-list.component.ts

<product-list>

    <ng-content></ng-content>

</product-list>

product.component.ts

<product>

    <ng-content></ng-content>

</product>

Demo.component.ts

       <product-list>

                <product>

                    <product-rating></product-rating>

                </product>

        </product-list>

        <button label="Submit" (click)="submit()"></button>

On Submit, I have to access product-rating component and depending on rating have to change the color of corresponding product component. What is the best way to access and process this?

Demo.component.ts

@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;

product.component.ts

@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;

Is there any better way to access product-rating component?

Any help would be appreciated.

Body:
Even though you have what looks like a relatively complex component structure, you can still achieve what you want to with standard @Output and @Input events and properties.

Your starting point is to decide which component is "controlling" everything. In your case it's the demo component. Demo component is deciding what the component hierarchy is. Next you need to work out the desired flow of data. In your case, it will look a bit like this:

product-rating -> demo -> product

A rating is determined by product-rating, and needs to get to product via the controller.

So you need to add an @Output event to product rating that the control can subscribe to:

@Output() ratingChange: EventEmitter<number> = new EventEmitter<number>();

// this is some event handler that handles the user-driven rating change
onRatingChange(): void {
  // Emit the rating. I am guessing here that the rating is stored in some property
  // It might come into this function as an event arg - that's up to your design.
  this.ratingChange.emit(this.rating);
}

So now the demo component can handle the rating change events and send it to the product:

demo.component.html

<product [rating]="rating">
  <product-rating (ratingChange)="onRatingChange($event)"></product-rating>
</product>

demo.component.ts

rating: number;

onRatingChange(rating: number): void {
  this.rating = rating;
}


问:
how can I make category and subcategory buttons in flutter
how can i make this possible in flutter that when I hit the button e.g. communicate it will expand reveal several subcategory buttons pushing other main buttons down like the photo under

答:
Use ExpansionTile

ExpansionTiles can be used to produce two-level or multi-level lists

```<code>import 'package:flutter/material.dart';

class ExpansionTileSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      title: const Text('ExpansionTile'),
    ),
    body: ListView.builder(
      itemBuilder: (BuildContext context, int index) =>
          EntryItem(data[index]),
      itemCount: data.length,
    ),
  ),
);
  }
}

// One entry in the multilevel list displayed by this app.
class Entry {
  Entry(this.title, [this.children = const <Entry>[]]);

  final String title;
  final List<Entry> children;
}

// The entire multilevel list displayed by this app.
final List<Entry> data = <Entry>[
  Entry(
'Chapter A',
<Entry>[
  Entry(
    'Section A0',
    <Entry>[
      Entry('Item A0.1'),
      Entry('Item A0.2'),
      Entry('Item A0.3'),
    ],
  ),
  Entry('Section A1'),
  Entry('Section A2'),
],
  ),
  Entry(
'Chapter B',
<Entry>[
  Entry('Section B0'),
  Entry('Section B1'),
],
  ),
  Entry(
'Chapter C',
<Entry>[
  Entry('Section C0'),
  Entry('Section C1'),
  Entry(
    'Section C2',
    <Entry>[
      Entry('Item C2.0'),
      Entry('Item C2.1'),
      Entry('Item C2.2'),
      Entry('Item C2.3'),
    ],
  ),
],
  ),
];

// Displays one Entry. If the entry has children then it's displayed
// with an ExpansionTile.
class EntryItem extends StatelessWidget {
  const EntryItem(this.entry);

  final Entry entry;

  Widget _buildTiles(Entry root) {
if (root.children.isEmpty) return ListTile(title: Text(root.title));
return ExpansionTile(
  key: PageStorageKey<Entry>(root),
  title: Text(root.title),
  children: root.children.map(_buildTiles).toList(),
);
  }

  @override
  Widget build(BuildContext context) {
return _buildTiles(entry);
  }
}

void main() {
  runApp(ExpansionTileSample());
}
</code>```

Body:
Use ExpansionTile

ExpansionTiles can be used to produce two-level or multi-level lists

import 'package:flutter/material.dart';

class ExpansionTileSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      title: const Text('ExpansionTile'),
    ),
    body: ListView.builder(
      itemBuilder: (BuildContext context, int index) =>
          EntryItem(data[index]),
      itemCount: data.length,
    ),
  ),
);
  }
}

// One entry in the multilevel list displayed by this app.
class Entry {
  Entry(this.title, [this.children = const <Entry>[]]);

  final String title;
  final List<Entry> children;
}

// The entire multilevel list displayed by this app.
final List<Entry> data = <Entry>[
  Entry(
'Chapter A',
<Entry>[
  Entry(
    'Section A0',
    <Entry>[
      Entry('Item A0.1'),
      Entry('Item A0.2'),
      Entry('Item A0.3'),
    ],
  ),
  Entry('Section A1'),
  Entry('Section A2'),
],
  ),
  Entry(
'Chapter B',
<Entry>[
  Entry('Section B0'),
  Entry('Section B1'),
],
  ),
  Entry(
'Chapter C',
<Entry>[
  Entry('Section C0'),
  Entry('Section C1'),
  Entry(
    'Section C2',
    <Entry>[
      Entry('Item C2.0'),
      Entry('Item C2.1'),
      Entry('Item C2.2'),
      Entry('Item C2.3'),
    ],
  ),
],
  ),
];

// Displays one Entry. If the entry has children then it's displayed
// with an ExpansionTile.
class EntryItem extends StatelessWidget {
  const EntryItem(this.entry);

  final Entry entry;

  Widget _buildTiles(Entry root) {
if (root.children.isEmpty) return ListTile(title: Text(root.title));
return ExpansionTile(
  key: PageStorageKey<Entry>(root),
  title: Text(root.title),
  children: root.children.map(_buildTiles).toList(),
);
  }

  @override
  Widget build(BuildContext context) {
return _buildTiles(entry);
  }
}

void main() {
  runApp(ExpansionTileSample());
}