text:
Q: Fatal error when using scripts through virtualenv - extra quotes around python.exe I am very new to Python and recently installed Python 2.7.6 x86 on Windows.  I am trying to create an environment via virtualenv.  I installed Python, then installed pip and virtualenv globally.  I then CD'd to the directory I wanted to create an environment in and ran virtualenv env.  Then I activated it with env\scripts\activate.  Now, when I try to run any of the scripts through virtualenv (pip, easy_install, etc.) I get the following error:
Fatal error in launcher: Unable to create process using
'""[dir]\env\Scripts\python.exe"" "[dir]\env\Scripts\pip.exe" --version'

Note the extra quotes around the python exe.  It has two sets of quotation marks, not just one set.
I have a feeling that this is a path error.  The path is getting set in activate.bat, but looks correct there - set "VIRTUAL_ENV=[dir]\env"
Let me reiterate that scripts work fine globally.  I am only seeing this error in virtualenv.
Where is that extra set of quotation marks coming from?  How can I get rid of it?

A: I had this problem, because i put my virtual env directory in a directory with .(dot) and spaces in name. When i renamed the parent dir, it worked.

A: Same error for me here. Until I tried the following (being inside of my venv) and it worked:
(venv) > python -m pip

or
(venv) > python -m easy_install

A: I was able to get over this error by creating my directory which will have virtual environment under C:\Python27 and it worked for me.

A: Reinstall python inside a folder without spaces and it should work.

A: I had this exact problem with respect to pip and had to upgrade my python installation to 2.7.6 and reinstall pip.

A: This issue is also present in virtualenvwrapper-win.
The system cannot find the path specified
Here's how they resolved it
"I changed WORKON_HOME to C:\PythonEnvs and it now works."
So, the advice on windows continues to be: no spaces in path names.

A: I could solve the same error using following command inside venv.
python -m easy_install pip

A: I had this problem after installing both python versions 2.7 and 3.4, fixed after upgrading virtualenv on python 3.4 version with command:
pip3 install --upgrade virtualenv


text:
Q: Counting Values based on certain criteria SQL I am trying to Write a View for some reporting in our CRM program and I'm having trouble with the counts. We are trying to count the number of referrals based on certain criteria. I feel like the way I wrote the view is incorrect. I am trying to use a CASE statement to make sure it counts the values that I want, but I the numbers I am getting I am not able to validate with reverse engineering.
Did I structure the CASE statement correctly?
(Note: I do realize that client is misspelled, unfortunately whoever wrote the database before I got it had some spelling issues.)
This is what I have written so far:
SELECT Comp_Name, Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Client' Then 1
                        ELSE NULL END) AS Client_Referrals,
      Count(Case WHEN lead_companyprimaryreferralsource IS NOT NULL Then 1 Else Null End) AS Target_Referrals,
      Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Prospect' Then 1 Else Null End) As Prospective_Client_Referral,
      Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Lost_Clent' Then 1 Else Null End) AS Lost_Client_Referral,
      Count(Case WHEN mcgr_companyid IS NOT NULL Then 1 Else NULL END) AS Intro_By_MCG

FROM Company

RIGHT JOIN Lead on Lead_PrimaryCompanyID = Comp_CompanyId
RIGHT JOIN MCGRelationships on mcgr_companyid = Comp_CompanyId
WHERE COMP_Name IS NOT NULL

Group By Comp_Name

Here is a Sample of What i'm getting:
  Client1      0    0   0   0   1
  Client2      0    0   0   0   2
  Client3      0    0   0   0   1
  Client4      0    0   0   0   1
  Client5      0    0   0   0   2
  Client6      0    0   0   0   2
  Client7      0    0   4   0   4
  Client8      0    0   0   0   2
  Client9      0    2   2   0   2
  Client10     12   6   0   0   12
  Client11     0    0   0   0   2

When I just run a query on the table where Client 10 is the Primary Referral source, I get nothing. So I can't account for those 12 instances.

A: I think your problem may be in the join to MCGRelationships, if each company record can have more than one relationship record. If I'm following you correctly, you want Intro_By_MCG to be 1 if that record exists in MCGRelationships, regardless of the number of times it appears there. By joining the table, your query would be counting a lead once for each MCGRelationship associated with the company the lead comes from. Try this and let us know if the result is different:
SELECT Comp_Name, Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Client' Then 1
                    ELSE NULL END) AS Client_Referrals,
  Count(Case WHEN lead_companyprimaryreferralsource IS NOT NULL Then 1 Else Null End) AS Target_Referrals,
  Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Prospect' Then 1 Else Null End) As Prospective_Client_Referral,
  Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Lost_Clent' Then 1 Else Null End) AS Lost_Client_Referral,
  Count(Case WHEN EXISTS (Select Comp_CompanyId FROM MCGRelationships WHERE mcgr_companyid = Comp_CompanyId) Then 1 Else NULL END) AS Intro_By_MCG

FROM Company

RIGHT JOIN Lead on Lead_PrimaryCompanyID = Comp_CompanyId
WHERE COMP_Name IS NOT NULL

Group By Comp_Name

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting Certificate Friendly Name Im trying to set the certificate friendly name during the certificate request/acceptance process. I understand that this a property of the microsoft store rather than the certificate and an wondering what .net/c# technique might be used to set it.

A: So here is a commmand line example of how to do this. You need CAPICOM from microsoft which wraps the CryptoAPI.
The friendly name is a property of the cert store rather than the certificate so this code imports a certificate to the cert store and sets the friendly name as it does so.
The code takes two parameters the path to the cert file and the friendly name you wish to set.
Code:-
using System;

using System.Collections.Generic;

using System.Text;

using CAPICOM;

using System.Collections;

using System.Runtime.InteropServices;

namespace CertTool

{

    class Program
    {
        const uint CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x20000;
        const int CAPICOM_PROPID_FRIENDLY_NAME = 11;
        const int CAPICOM_ENCODE_BINARY = 1;

        static private String _currStoreName = "My";
        static private String _FriendlyName = "Not Set";
        static private String _CertPath = "C:\\test.cer";
        static StoreClass _oCurrStore;
        static ExtendedPropertyClass _friendlyProp;
        static CertificateClass _certificate;
        static ExtendedProperties _extendedProp;

        static void Main(string[] args)
        {
            try
            {
                //Friendly name Argument
                if (args.Length > 0)
                {
                    _FriendlyName = args[0];
                }
                //Certpath argument
                if (args.Length > 1)
                {
                    _CertPath = args[1];
                }
                //Set and open the Store
                _oCurrStore = new StoreClass();
                _oCurrStore.Open(
                    CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE,
                    _currStoreName,
                    CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
                    CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
                //Call the import certificate function
                importCert();
            }
            catch(Exception ex){
                Console.WriteLine(ex.Message);
                Console.WriteLine(args[0]);
            }
        }
        //Function import the certificate to the machine store and sets the friendly name
        static bool importCert()
        {
            try
            {
                //Create Certificate Object
                _certificate = new CertificateClass();
                //Load the certificate into the obejct from file
                _certificate.Load(_CertPath, "", CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_EXPORTABLE, CAPICOM_KEY_LOCATION.CAPICOM_LOCAL_MACHINE_KEY);
                //Create extended property Class for friendly name
                _friendlyProp = new ExtendedPropertyClass();
                _friendlyProp.PropID =  CAPICOM_PROPID.CAPICOM_PROPID_FRIENDLY_NAME;
                _friendlyProp.set_Value(CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BINARY, _FriendlyName);

                //Add extendedProp on cert object
                _extendedProp = _certificate.ExtendedProperties();
                //Set extendded prop to friendly name object
                _extendedProp.Add(_friendlyProp);
                _oCurrStore.Add(_certificate);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(_CertPath);
                return true;
            }
        }
    }
}

A: Use X509Certificate2.FriendlyName. However, you must export the certificate as PFX/PKCS#12:
X509Certificate2 certificate = new X509Certificate2(...);
certificate.FriendlyName = "MyName";
File.WriteAllBytes(path, certificate.Export(X509ContentType.Pkcs12));

A: Ok, found an answer to that here:
Hi,
Please have a look at this to check if it suits your need:
When you run the .net Code in X64 Environment you will get the following error message.
" Failed --Retrieving the COM class factory for component with CLSID ...."
E.g. in CMS Export / Import server side .net code = "ExportSiteContentIncremental(...) Failed --Retrieving the COM class factory for component with CLSID {CA0752B3-021C-4F99-82E3-2C0F19C5E953} failed due to the following error: 80040154."
WORKAROUND:
The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)
ROOTCAUSE
The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.


text:
Q: no printing after python script, with no errors No errors just not printing the results. it is supposed to print out headlines from the url. the script runs but returns nothing whilst parsing for balancedheadlines. i can swap the tag i look for to p and return data but i believe i am no passing through the tags correctly to retrieve just the headlines.
import requests
from bs4 import BeautifulSoup

url = 'http://www.nytimes.com'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')

for ap in soup.find_all('h2', attrs = {"class" : "balancedheader"}):

    if ap.a:
        print(ap.a.text.replace(".n/", " "))
    else:
        print(ap.strip)

A: NY Times web site has no 'h2' element with class named 'balancedheader'.
The xpath '//h2[@class='balancedheader']' return an empty set.

A: I have fixed you issue, you are not indenting correctly and when you import something make sure the 'i' in "import" is not capital. Fixed Version:
import requests
from bs4 import BeautifulSoup

url = 'http://www.nytimes.com'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')

for ap in soup.find_all('h2', attrs = {"class" : "balancedheader"}):
    if ap.a:
        print(ap.a.text.replace(".n/", " "))
    else:
        print(ap.strip)

A: You said he script runs but returns nothing whilst parsing for balancedheadlines but trying to search balancedheader . There is no balancedheader in your site.You can see all h2 tags like :
h2_tags = soup.findAll('h2')
for allh2 in h2_tags:
    print allh2

Above code will return all h2 tags in your website.
I think you are trying to get title in balancedHeadline and its in Javascript so you need to use Selenium :
from selenium import webdriver

options = webdriver.ChromeOptions()
driver=webdriver.Chrome(chrome_options=options, executable_path=r'your driver path')
driver.get('https://www.nytimes.com/2019/02/24/world/europe/pope-vatican-sexual-abuse.html')

x = driver.find_elements_by_css_selector("span[class='balancedHeadline']")

for title in x:
    print title.text
driver.close()

OUTPUT:
Pope Francis Ends Landmark Meeting by Calling for 'All-Out Battle' to Fight Sexual Abuse


text:
Q: Joining two tables twice Writing a query for a basketball database, our table for games has as a winnerID and a loserID, each being a teamID. Tried the following two queries, each correctly giving me the number of wins but giving me the same number for losses.
SELECT team.name as Team_Name, COUNT(team.teamID=winner.winnerID) as Wins, COUNT(team.teamID=loser.loserID) as Losses
FROM team join games winner on winner.winnerID=team.teamID join games loser on loser.loserID=team.teamID
GROUP BY team.name
ORDER BY Wins, Team_Name;

SELECT team.name as Team_Name, COUNT(team.teamID=games.winnerID) as Wins, COUNT(team.teamID=games.loserID) as Losses
FROM (team INNER JOIN games on games.winnerID=team.teamID)
GROUP BY team.name
ORDER BY Wins, team.name;

Help?
EDIT: Forgot to mention, purpose of query is to get number of wins and number of losses of each team.

A: The COUNT aggregate gets a count of non-NULL values. That means it includes ones and zeros.
Evaluated in a numeric context, an equality comparison returns 1 for TRUE and returns 0 for FALSE, and only returns NULL if either side (or both sides) is NULL.
To add up the ones and ignore the zeros, you could use a SUM aggregate instead.
One of the big problems with the query is the potential to return duplicates, due to the cross join between winner and loser. If a team has 5 wins and 4 losses, the  query is going to generate an intermediate set of 20 (= 5 x 4) rows.
To get a count of wins and losses from that, we'd need a unique identifier for a game (for example, a gameid column in the game table that is the PRIMARY KEY.)  With that , we could get a count of distinct values of gameid. For example:
  COUNT(DISTINCT IF(winner.winnerid=team.teamid,winner.gameid,NULL)) AS wins

There are several query patterns that will get you the number of wins and the number of losses for each team.
Here's one example:
 SELECT t.name                                AS team_name
      , COUNT(IF(t.teamid=g.winnerid,1,NULL)  AS wins
      , COUNT(IF(t.teamid=g.loserid ,1,NULL)  AS losses
   FROM team
   LEFT
   JOIN games g
     ON ( g.winnerid = t.teamid OR g.loserid = t.teamid )
  GROUP
     BY t.name
  ORDER
     BY wins DESC
      , t.name

With this, we are only joining to the games table once, so we won't get a cross product. Also note that if teamid is not equal to winnerid, we return a NULL instead of a 0. So a COUNT will include only winners, not all of the rows.
We use an outer join (rather than an inner join), in case there are no related rows in games for the team. That allows us to return a team with counts of zero.
We could use a SUM aggregate instead of a COUNT,  For example:
 SELECT t.name                              AS team_name
      , IFNULL(SUM(t.teamid=g.winnerid),0)  AS wins
      , IFNULL(SUM(t.teamid=g.loserid) ,0)  AS losses
   FROM team
   LEFT
   JOIN games g
     ON ( g.winnerid = t.teamid OR g.loserid = t.teamid )
  GROUP
     BY t.name
  ORDER
     BY wins DESC
      , t.name

With a SUM() we have a potential to return NULL values. To get those converted to zeros, we use an IFNULL function.
And there are several other query patterns that would get you an equivalent result... e.g. instead of using joins, use correlated subqueries in the SELECT list...
SELECT t.name
     , ( SELECT COUNT(1)
           FROM game w
          WHERE w.winner_id = t.teamid
       ) AS wins
     , ( SELECT COUNT(1)
           FROM game l
          WHERE l.loserid = t.teamid
       ) AS losses
  FROM team t
 ORDER BY wins DESC
     , t.name


text:
Q: How to count elements with same name? XML -> Xquery i have a xml doc like:
<root>
<test>
    <humans>
        <names>Tim</names>
    </humans>
</test>
<test>
    <humans>
        <names>Jack</names>
        <names>Jones</names>
    </humans>
</test>
<test>
    <humans>
        <names>Tim</names>
    </humans>
</test>
</root>

and I want to count all names which are the same: Tim 2, Jack 1, Jones 1
and it should give an output like:
<x> Tim </x>

because TIM is the highest name
I hope you can help me... (sorry for my bad english)

A: In XPath 2.0, XSLT 2.0 and XQuery use (exactly the same solution):
(/*/*/*/names[for $v in .,
                    $cnt in count(/*/*/*/names[. eq $v])
                 return
                    $cnt
                   eq
                     max(for $n in distinct-values(/*/*/*/names)
                           return
                              count(/*/*/*/names[. eq $n])
                        )
                ]
    )[1]

You can also get this element easily with the following XSLT 1.0 transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:key name="kNamesByVal" match="names" use="."/>

 <xsl:template match="/">
  <xsl:for-each select=
   "*/*/*/names[generate-id()
               =
                generate-id(key('kNamesByVal',.)[1])
               ]">
   <xsl:sort select="count(key('kNamesByVal',.))"
    data-type="number" order="descending"/>

    <xsl:if test="position()=1">
      <xsl:copy-of select="."/>
    </xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

When the above XPath 2.0/XQuery expression or XSLT transformation are evaluated (applied) on the provided XML document:
<root>
    <test>
        <humans>
            <names>Tim</names>
        </humans>
    </test>
    <test>
        <humans>
            <names>Jack</names>
            <names>Jones</names>
        </humans>
    </test>
    <test>
        <humans>
            <names>Tim</names>
        </humans>
    </test>
</root>

the correct element is selected (produced):
<names>Tim</names>

A: let $xml := <!-- your xml document -->
return
(
  for $name in distinct-values($xml//names)
  order by count($xml//names[. = $name]) descending
  return <x>{$name}</x>
)[1]

A: The solution of Gunther is the best, and if you wanted to count every elements you could do:
xquery version "1.0";

for $x in
(
  for $name in distinct-values(//names)
  order by count(//names[. = $name]) descending
  return <x>{$name}</x>
) return fn:concat($x, ' - ',xs:string(count(//names[. = $x])))

With result Tim - 2 Jack - 1 Johons - 1


text:
Q: How to properly generate self signed certificates for use in Nginx I used openssl to generate the following certificates:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt -subj "/C=IT/ST=Mi/L=Milan/O=MyOrg/OU=RnD/CN=localhost/emailAddress=info@myorg.com"
openssl rsa -in server.key -out server.insicure.key
cat server.insicure.key > certificate.pem
cat server.crt >> certificate.pem

I then setup nginx to client-secure a site:
server {
    listen 80 ssl;
    root /var/www/site;

    index index.html;

    ssl_certificate         /root/server.crt;
    ssl_certificate_key     /root/server.key;

    ssl_client_certificate  /root/certificate.pem;

    ssl_verify_client on;
    ssl_verify_depth 2;

     location / {
            try_files $uri $uri/ =404;
    }
}

However, when I try to get the site with curl, it doesn't work as expected:
curl --cacert certificate.pem https://localhost:80

and I get the following error page from nginx:

<title>400 No required SSL certificate was sent</title>

400 Bad Request

No required SSL certificate was sent

nginx/1.14.0 (Ubuntu)

Anything I'm doing wrong? Thanks

A: You are instructing Nginx to request a client certificate with:
ssl_verify_client on;
ssl_verify_depth 2;

However, you've not told curl to use one (--cacert only tells curl where the CA certificate to use to verify the server certificate is located).  Nginx therefore correctly tells you that you haven't sent a client certificate.
If you only want the server to send a TLS certificate in order to get HTTPS working then simply comment out or remove the two lines above.
If you do want the client to send a certificate, then you should create a CA and use it to issue a client certificate.  Give the client certificate and private key to curl (use --cert and --key respectively) and configure the CA certificate in Nginx with ssl_client_certificate (without the private key!!).
This question/answer shows how to create a client certificate using OpenSSL.


text:
Q: Writing to files and \? I am trying to write some text to a html file using php. This text contains mathjax and therefore has a lot of \'s in it. However, when I look at the file it creates all the \'s have turned to \\'s and I can't seem to change them back to just single \'s. Any ideas?
For example
<?php
$content='$\vec B+\vec C$';
$myfile=fopen('file.html',"w");
fwrite($myfile,$content);
fclose($myfile);
?>

Will produce ' $\\vec B+ \\vec C$' in the html file.

A: http://php.net/manual/en/function.stripslashes.php
Return Values
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).


text:
Q: DELPHI 10.4, receive output result via Broadcast of Barcode Scanner I have a Sunmi L2s device, and I'm trying to receive the result of a barcode scan via a broadcast to an Android app. I would like to create an app that, when I push the hardware button for scan (orange button to the side of the phone), shows the barcode on a TLabel.Text in the app.
I've found code here on StackOverflow, but I can't make it receive the results, and I'm getting a message when the app starts that says "External exception 0".
I'm new to Delphi/Android development, so any help is welcome!
implementation

{$R *.fmx}

uses
  FMX.Platform.Android, Androidapi.JNI.JavaTypes, Androidapi.JNI.Net,
  Androidapi.JNI.Os, Androidapi.Helpers;

procedure TForm4.FormCreate(Sender: TObject);
var
  AppEventService: IFMXApplicationEventService;
begin
  if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, AppEventService) then
    AppEventService.SetApplicationEventHandler(HandleAppEvent);

  MainActivity.registerIntentAction(StringToJString('com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED'));
  TMessageManager.DefaultManager.SubscribeToMessage(TMessageReceivedNotification, HandleActivityMessage);
end;

procedure TForm4.HandleActivityMessage(const Sender: TObject; const M: TMessage);
begin
  if M is TMessageReceivedNotification then
    HandleIntentAction(TMessageReceivedNotification(M).Value);
end;

function TForm4.HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
var
  StartupIntent: JIntent;
begin
  Result := False;
  if AAppEvent = TApplicationEvent.BecameActive then
  begin
    StartupIntent := MainActivity.getIntent;
    if StartupIntent <> nil then
      HandleIntentAction(StartupIntent);
  end;
end;

function TForm4.HandleIntentAction(const Data: JIntent): Boolean;
var
  JStr: JString;
begin
  Result := False;
  if (Data <> nil) and Data.getAction.equals(StringToJString('com.sunmi.scanner')) then
  begin
    JStr := Data.getStringExtra(StringToJString('Data'));
    Label1.Text := JStringToString(JStr);
    Invalidate;
  end;
end;

end.

A: One issue I see that could be causing your "External exception" error is that in HandleIntentAction(), Data.getAction() can potentially return nil, which you are not checking for.  Also, you need to compare the complete action name, not a prefix of it.
Change this:
Data.getAction.equals(StringToJString('com.sunmi.scanner'))

To this instead:
StringToJString('com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED').equals(Data.getAction)

Other than that, the only other potential issue I see is in HandleAppEvent(), are you sure BecameActive is the best event to use to handle the StartupIntent? I would think FinishedLaunching would be a more appropriate event. An app can gain and lose focus multiple times during its lifetime, so you wouldn't want to handle the same startup Intent object over and over.  Otherwise, at the very least, after you have processed the StartupIntent, you could optionally call MainActivity.setIntent(nil) so that MainActivity.getIntent() won't return the same Intent object anymore on subsequent events.  Or, you could simply get rid of HandleAppEvent() and just handle the StartupIntent directly in your Form's OnCreate event.

A: The post is a bit old, however maybe you are querying the wrong key 'Data' instead of 'data' which seems to be the right default key for sunmi device :
JStr := Data.getStringExtra(StringToJString('Data'));

Replace it by
JStr := Data.getStringExtra(StringToJString('data'));


text:
Q: How to add already created figures to a subplot figure I created this function that generates the ROC_AUC, then I returned the figure created to a variable.
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
import matplotlib.pyplot as plt

def plot_multiclass_roc(clf, X_test, y_test, n_classes, figsize=(17, 6)):
    y_score = clf.decision_function(X_test)

    # structures
    fpr = dict()
    tpr = dict()
    roc_auc = dict()

    # calculate dummies once
    y_test_dummies = pd.get_dummies(y_test, drop_first=False).values
    for i in range(n_classes):
        fpr[i], tpr[i], _ = roc_curve(y_test_dummies[:, i], y_score[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])

    # roc for each class
    fig, ax = plt.subplots(figsize=figsize)
    ax.plot([0, 1], [0, 1], 'k--')
    ax.set_xlim([0.0, 1.0])
    ax.set_ylim([0.0, 1.05])
    ax.set_xlabel('False Positive Rate')
    ax.set_ylabel('True Positive Rate')
    ax.set_title('Receiver operating characteristic for Optimized SVC model')
    for i in range(n_classes):
        ax.plot(fpr[i], tpr[i], label='ROC curve (area = %0.2f) for label %i' % (roc_auc[i], i+1))
    ax.legend(loc="best")
    ax.grid(alpha=.4)
    sns.despine()
    plt.show()
    return fig

svc_model_optimized_roc_auc_curve = plot_multiclass_roc(svc_model_optimized, X_test, y_test, n_classes=3, figsize=(16, 10))

The resulting figure would look like somethin below:

I created 5 different ROC curves for 5 different models using the same function but returning their figures to separate variables.
Then I created a subplot figure that I thought would display all of them. The code is:
import matplotlib.pyplot as plt
%matplotlib inline

figs, ax = plt.subplots(
    nrows=3,
    ncols=2,
    figsize=(20, 20),
)

ax[0,0] = logmodel_roc_auc_curve
ax[0,1] = RandomForestModel_optimized_roc_auc_cruve
ax[1,0] = decisiontree_model_optimized_roc_auc_curve
ax[1,1] = best_clf_knn_roc_auc_curve
ax[2,0] = svc_model_optimized_roc_auc_curve

But the resulting figure produced is this:

There was a similar problem to this here
but it was solved by executing the functions again. But I would like to find a way if possible to just simply "paste" the figures I already have into the subplot.

A: You need exactly the same as in the linked solution. You can't store plots for later use. Note that in matplotlib a figure is the surrounding plot with one or more subplots. Each subplot is referenced via an ax.
Function plot_multiclass_roc needs some changes:

*

*it needs an ax as parameter, and the plot should be created onto that ax.

*fig, ax = plt.subplots(figsize=figsize) should be removed; the fig should be created previously, outside the function

*also plt.show() should be removed from the function

*it is not necessary to return anything

Outside the function, you create the fig and the axes.  In matplotlib there is a not-well-followed convention to use axs for the plural of ax (when referring to a subplot). So:
fig, axs = plt.subplots(nrows = 3,
                        ncols = 2,
                        figsize= (20, 20)
                       )
plot_multiclass_roc(...., ax=axs[0,0]) # use parameters for logmodel
plot_multiclass_roc(...., ax=axs[0,1]) # use parameters for Random Forest
plot_multiclass_roc(...., ax=axs[1,0]) # ...
plot_multiclass_roc(...., ax=axs[1,1]) # ...
plot_multiclass_roc(...., ax=axs[2,0]) # ...
axs[2,1].remove() # remove the unused last ax
plt.tight_layout()  # makes that labels etc. fit nicely
plt.show()


text:
Q: Positioning table header in div See my fiddle here.
I am trying to position the header inside the div like so:

Not having much luck. What's going on?  How do position within the table row header?

A: That div.headerContainer is not valid markup so the browser will try to correct it. Rather style the th 's and add classes for first and last. Here is an example. Another option would be to use an appropriately sized background image and apply it to the parent div (.geniusPicks)
HTH! :)


text:
Q: How can I do case insensitive string search with Linq and SQL Server? Here is my current code for searching tags:
    public JsonResult TagSearch(string term) {
        if (term == null || term == "")
            return Json("");

        var tags = (from t in _session.All<Tag>() where t.Name.Contains(term) select t.Name).Take(6).ToArray();

        return Json(tags);
    }

How could I do case insensitive string search instead?

A: The Contains() method is converted to case-insensitive operation in SQL. I think the code I posted is case insensitive.

A: Is changing the collation of the column out of the question?

A: Use the ToLower method. Like this:
var tags = (from t in _session.All<Tag>() where t.Name.ToLower().Contains(term.ToLower()) select t.Name).Take(6).ToArray();


text:
Q: Populating a datagridview from mysql database in c# Helllo,
I have a mySQL database and I want to pull information out of it via an SQL select query and then display this information in a datagride view. I have already written a database class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using MySql;
using MySql.Data;
using System.Data;
using Renci.SshNet;
using Renci.SshNet.Common;
using System.Windows.Forms;
using System.Net.NetworkInformation;

namespace ExpTrackNEA

{
    class DatabaseManager
    {

        private MySqlConnection _Conn;
        public MySqlCommand Cmd;
        private MySqlDataAdapter _da;
        private DataTable _dt;
        private MySqlDataReader _dr;

        // This is the Database connection function
        public bool DBConnection()
        {
            // First step is to create an SSH Tunnel. This is done by calling the SSHTunnelCreate function
            if (SSHTunnelCreate() == true)
            {
                try // Start of Database connection Try attempt
                {
                    // Define the connection cerdentials
                    string ConnectionString = null;
                    ConnectionString = "server=SERVER;" +  // Database Address
                        "               port=PORT;" +               // Port
                        "               database=DATABSAE;" + // Database Name
                        "               uid=USERNAME;" +              // Username
                        "               pwd=PASSWORd;";            // Password

                    // Define the connection
                    _Conn = new MySqlConnection(ConnectionString);

                    try // Attempt a connection
                    {
                        // Open the connection
                        _Conn.Open();

                        // Return true if connection is successful to the database
                        return true;

                    } // Rnd of database connection attempt

                    catch // Catach Database connection errors
                    {
                        // Return False if a connection to the Database can't be made
                        return false;

                    } // End of Database connection errors catach

                } // End of Database connection Try attempt
                catch
                {

                    // If the connection is not successful it returns FALSE as it can't connect
                    // to the database and the whole process is halted
                    return false;

                } // End of catch for Database Connection

            }// End of (SSHTunnelCreate() == true)
            else // If the SSH Tunnel Connection Failed
            {

                return false;

            }

        } // End of DBConnection Function

        private bool SSHTunnelCreate()
        {
            // Declaring the Connection string information
            ConnectionInfo ConnectionInformation = new ConnectionInfo(
                                                           "ssh.payneslan.co.uk",        // Host Name
                                                           22,                           // Connection Port
                                                           "UserNAME",                     // Username
                                                           new AuthenticationMethod[]{   // Define the Password
                                                            // Pasword based Authentication
                                                            // Define the connection information Username and Password respectfullt
                                                            new PasswordAuthenticationMethod("USERNAME","PASSWORD")
                                                           }
                                                         ); // End of ConnectionInformation

            using (var client = new SshClient(ConnectionInformation))
            {
                // Start an attempt to build an SSH Tunnel
                try
                { // SSH Tunnel Try Start
                    client.Connect();

                    if (client.IsConnected)
                    {
                        try
                        {
                            var PortFwdL = new ForwardedPortLocal("127.0.0.1", 3306, "localhost", 3306);
                            //ForwardedPortLocal PortFwdL = new ForwardedPortLocal("127.0.0.1", Convert.ToUInt32(22), "127.0.0.1", Convert.ToUInt32(3306));

                            client.AddForwardedPort(PortFwdL);
                            PortFwdL.Start();

                            // Checking Port Forwarding is working
                            if (PortFwdL.IsStarted)
                            {
                                return true;

                            }
                            else
                            {
                                return false;
                            }

                        }

                        catch
                        {
                            return false;
                        }

                    } // End of IF
                    else
                    {
                        // If the connection is not successful it returns FALSE as it now doesn't
                        // have a secure connection to the server and now the database connection will
                        // halt.
                        return false;

                    } // End of Else
                } // End of Try
                catch // connection catch for SSH Tunnel creation
                {
                    // If the connection is not successful it returns FALSE as it now has a
                    // secure connection to the server and now the database connection will
                    // halt
                    return false;

                } // End of connection catch for SSH Tunnel creation

            } // End of  using (var client = new SshClient(ConnectionInformation))

        } // End of SSHTunnelCreate Function.

        public void SQLQuery(string QueryText)
        {
            Cmd = new MySqlCommand(QueryText, _Conn);

        }

        public string strSQLQuery(string QueryText)
        {

            Cmd = new MySqlCommand(QueryText, _Conn);
            MySqlCommand cmd = new MySqlCommand(QueryText, _Conn);
          _dr = cmd.ExecuteReader();

           string _value = null;

            while (_dr.Read())
            {
                _value = _dr.GetString(0);
            }

            _dr.Close();
            return _value;

        }

        // For The select queries
        public DataGrid QueryEx(string QueryText)
        {
            MySqlDataAdapter adp = new MySqlDataAdapter("Select * from table1;", _Conn);

            DataSet ds = new DataSet();
            adp.Fill(ds);
            //change name according to your datagridview
            DataGrid dataGridView1 = new DataGrid();

            dataGridView1.DataSource = ds;
           // dataGridView1.DataBind();
            return dataGridView1;
        }

        // For Insert,Update and Delete etc.
        public void NonQueryEx()
        {
            try
            {
                Cmd.ExecuteNonQuery();
            }
            catch
            {
               MessageBox.Show("An error occured when trying to perform this databse action" + "\n" +
                        "Your action was not completed.",
                        "Error executing Action",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);

            }
        }

    } // End Of Class DatabaseManager
}

And the what I want to do is pass the SQL query into the method queryEx and get this method to get all of the fields and return it in a state so that on the form I can simply put something like this.
DGV_Users.DataSource = DataBase.QueryEx("SELECT * FROMUsers");
I have tried and failed to do this for a few days and have watched countless videos but I can't get any thing to work.
Thank you.

A: So instead of having everything inside separate functions and separate try/catch blocks, you can just have a single try/catch and use using statements.
Doing it this way also means that you can get rid of the large if/else statements and the following global variables:
private MySqlConnection _Conn;
public MySqlCommand Cmd;
private DataTable _dt;

So all in all your basic database query function should look like this:
public DataTable FillDataTable()
{
    DataTable table = new DataTable();

    try
    {
        // Define the connection credentials
        string ConnectionString = "server=SERVER;port=PORT;database=DATABSAE;uid=USERNAME;pwd=PASSWORd;";
        string commandString = "Select * from table1;";

        //Use the connection
        using(MySqlConnection connection = new MySqlConnection(ConnectionString))
        {
            connection.Open();

            //Pass in command text and connection string
            using(MySqlCommand command = new MySqlCommand(ConnectionString)
            {
                command.Connection = connection;
                command.Text = commandString;

                //Any parameters in command string, add here
                //command.Parameters.AddWithValue("@SomeValue", value)

                using(MySqlDataReader reader = command.ExecuteReader())
                {
                    table.Load(reader);
                }
            }
        }
    }
    catch(Exception ex)
    {
        //Catch any exceptions here
    }

    return table;
}

Then in your form class:
dataGridView1.DataSource = FillDataTable();

Still this isn't really the most optimal way. You could use the DbConnection class, so not to rely specifically on MySql.
Also you should clean up your code a bit more such as your variable naming conventions and your functions. For example what is the purpose of this function?
public void SQLQuery(string QueryText)
{
    Cmd = new MySqlCommand(QueryText, _Conn);

}


text:
Q: react.js got that : timestamp is assigned a value but never used I am using react.js with eslint and I got that :
'timestamp' is assigned a value but never used
the line is this one :
const { latitude, longitude, timestamp, accuracy, error } = usePosition();

but I don't know how can I do to solve that problem ...
Do you have any ideas ?
Thank you very much !

A: You have imported timestamp and haven't used it anywhere in the code.
If you don't need it, remove it from the code to avoid this warning.

A: It means that you have declared value for timestamp but not used it in a code. It is just a warning. To get rid of it, simply remove the variable .


text:
Q: can Durbin Watson be used for binary valued times series I have multiple time series and for each time series, each series is either one or 0. So for example, it is like the following:
id time value
 1  1   1
 1  2   1
 1  3   0
 2  1   1
 2  2   0
 ...
 ...

I am wondering if I want to detect if there is any trend in each of series, what I should do. The first one I think of is to use Durbin-Watson to test for autocorrelation but since the value is binary, I do not know if Durbin-Watson is appropriate. If I do not use Durbin-Watson, what other tests I may use.
To clarify a bit, what I mean by "trend" is to detect if there is some patterns in the values for each id. For example, if gradually, for one id, the value becomes all 0, or all 1, or some persistent alternations of 0 and 1. In other words, supposed a rolling mean for id's values series. I want to know for the rolling mean if there is an increase or decrease trend over time.
Here, in the context, id is user id, and value of 0, 1 means the how a person viewed an object as favorable (1) or unfavorable (0). A person views one object at a time.


text:
Q: Facebook Logout button in asp.net web application I am trying to create an asp.net web application, in which when user logins with Facebook through my application, the friends of that user will be displayed in the application.
Now i want to create a Facebook Logout button so that user can log out also. I tried one code
HTML:
<asp:ImageButton ID="imgLogout" runat="server" OnClientClick="FB_Logout()"     ImageUrl="~/logout.jpg"/>

Script:
<script type="text/javascript">
function FB_Logout() {

alert('Are you sure?')
FB.Connect.logoutAndRedirect("http://localhost:2708/List.aspx");

}

</script>

it was working fine. But now user can not logout. Clicking on Facebook Login Button directly opens the already logged in user.

A: I think you might be using an old SDK.
According to the recent JS SDK you would use FB.logout
as in: https://developers.facebook.com/docs/reference/javascript/FB.logout/
Also because you want to redirect you could either redirect straight after the logout code with
window.location='';

or hook on the logout event in Facebook and do the redirect. e.g.
 FB.Event.subscribe("auth.logout", function() {window.location = '/users/logout'});
{$callback}


text:
Q: How do I format a number in Excel so the decimal appears in a specific spot? I have two sets of numbers that correspond to the minimum and maximum values of an interval. In the database that I am pulling this data from, the numbers are formatted without decimal places, like 680, 1090, or 520000. I want to format them as I input them into an Excel file for a different project.
The first should be formatted as something like:

*

*680 => 0.0680

*1090 => 0.1090

The second set should be formatted like:

*

*520000 => 52.0000

*728750 => 72.8750

Is there a way I can set a column to have formatting that automatically converts the un-formatted number to one with a decimal in the right spot?
Thank you!
edit: reformatted my examples so they were easier to read :)


text:
Q: In WPF, when creating an object as a resource, how can you "bind" to a generic property? I have a "Busy" indicator that looks (and works) like so:
<Grid x:Key="BusyIndicator" Visibility="Hidden" Opacity="0">
        <Grid.Style>
            <Style TargetType="{x:Type Grid}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path = IsBusy}" Value="True">
                        <DataTrigger.EnterActions>
                            <BeginStoryboard Storyboard="{StaticResource FadeInStoryboard}"/>
                        </DataTrigger.EnterActions>
                        <DataTrigger.ExitActions>
                            <BeginStoryboard Storyboard="{StaticResource FadeOutStoryboard}"/>
                        </DataTrigger.ExitActions>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Style>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border Background="#90000000">
            <Image Width="25" Height="25" RenderTransformOrigin="0.5, 0.5">
                <Image.Source>
                    <BitmapImage UriSource="busy.png"/>
                </Image.Source>
                <Image.RenderTransform>
                    <RotateTransform Angle="0" />
                </Image.RenderTransform>
                <Image.Style>
                    <Style TargetType="{x:Type Image}">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path = IsBusy}" Value="True">
                                <DataTrigger.EnterActions>
                                    <BeginStoryboard Storyboard="{StaticResource RotateStoryboard}"/>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Image.Style>
            </Image>
        </Border>
    </Grid>

As you can see, the indicator is a grid that's "Hidden" and "Invisible", when the "IsBusy" property changes, the grid fades in, and reveals a rotating "busy.png" image.  When the "IsBusy" toggles off, the indicator fades to "Invisible" again, and disappears.
This all works.
What I can't seem to wrap my head around, is how do I make this control a resource in the App.xaml to be reused throughout the application?  Because it's bound to the IsBusy property, I find myself having to cut and paste this monstrosity into every page that needs to use the indicator.
Is there a way to get the same effect, but with a reusable resource?

Edit:
So it really was as simple as stuffing it into a UserControl.  Spent so much time trying to find the "WPF" solution, I forgot the basics.  As ASh said, by simply adding a dependency property in the code-behind, using the control in a page now looks like this:
<local:BusyIndicator IsBusy="{Binding Path=IsBusy}"/>

A: Looks like custom UserControl (e.g. named "BusyIndicator") with bool dependency property "IsBusy" will be the simplest solution in this case. Then you just insert <BusyIndicator/> in xaml and bind IsBusy attribute to some property in a view model (not necessary named "IsBusy"): <BusyIndicator IsBusy="{Binding Path=IsBusyViewModelProperty}"/> - and easily customize any other property
This post might help you to implement a usercontrol from existing resource


text:
Q: Import existing Gradle Git project into Eclipse I've installed eclipse gradle plugin from here
http://kaczanowscy.pl/tomek/2010-03/gradle-ide-integration-eclipse-plugin
Is there a simple way to import into eclipse gradle project using gui, not doing stuff
described here: http://gradle.org/docs/current/userguide/eclipse_plugin.html
?

A: Add the following to your build.gradle
apply plugin: 'eclipse'

and browse to the project directory
gradle eclipse

A: Usually it is a simple as adding apply plugin: "eclipse" in your build.gradle and running
cd myProject/
gradle eclipse

and then refreshing your Eclipse project.
Occasionally you'll need to adjust build.gradle to generate Eclipse settings in some very specific way.
There is gradle support for Eclipse if you are using STS, but I'm not sure how good it is.
The only IDE I know that has decent native support for gradle is IntelliJ IDEA. It can do full import of gradle projects from GUI. There is a free Community Edition that you can try.

A: I have gone through this question earlier but did not found complete gui based solution.Today I got a GUI based solution provided by spring.
In short we need to do only that much:
1.Install plugin in eclipse from update site:
site link
2.Import project as gradle and browse the .gradle file..that's it.
Complete documentation is here

A: The simpliest way is to use sts gradle integration and import project
http://static.springsource.org/sts/docs/2.7.0.M1/reference/html/gradle/gradle-sts-tutorial.html
Don't forget to click "Build Model" button.

A: You can do the following steps:

*

*Install the Buildship Gradle Integration using the Eclipse Marketplace. Simply type Buildship and click on search item. Now click on Install.

*Click on File -> Import ▸ Existing Gradle Project.

*Navigate to project root directory.

*Click on a finish to load your project.
Might be it will take some time for the first time to import Gradle project. So please be patient on it.

A: There is a simplest and quick way to import a Gradle project into Eclipse.
Just download the Gradle plugin for Eclipse from here.
https://marketplace.eclipse.org/content/gradle-integration-eclipse-0
And then from import select Gradle and your project would be imported. Then you have to click on Build Model to run it.

EDIT
Above link for Gradle plugin is no more valid. You can use the link as mentioned in the comment by @vikramvi
https://marketplace.eclipse.org/content/buildship-gradle-integration

A: Open eclipse and right click in the package explorer → import
Select gradle
Browse to the location where you checked out
Click "Build Model"
Select all the projects and hit finish

A: Go to the GitHub page where they are maintain the official repository:
https://github.com/spring-projects/eclipse-integration-gradle/blob/master/README.md
Copy the latest release link:
http://dist.springsource.com/release/TOOLS/gradle (latest release)
Use this in Eclipse->Help->Install New Software..->Paste the link in "Work With"->press enter->select the names of the extension->click next and agree the license and follow the prompts.
After you have installed just import the project as a grade project and eclipse will take of the rest.

A: I use another Eclipse plugin to import existing gradle projects.
You can install the Builship Gradle Gntegration 2.0 using the Eclipse Marketplace client.
Then you choose FIle ▸ Import ▸ Existing Gradle Project.
Finially, indicate your project root directory and click finish.

A: As of the time of answering this, Eclipse Version: 2020-06 (4.16.0) has a File --> Import --> Gradle --> Existing gradle project menu option.You can use this option to import gradle project into Eclipse directly.

A: Add the following to your build.gradle
apply plugin: 'eclipse'

and browse to the project directory
gradle eclipse

Once done, you could import the project from eclipse as simple Java Project.


text:
Q: Blank Private Browsing Page in Firefox I would like to write an WebExtension to have a blank private browsing page, inspired by an old extension: https://github.com/iPotable/BlankPrivateBrowsingPage
I thought I could use chrome_url_overrides for any chrome page. So I tried:
{
  "manifest_version": 2,
  "name": "Blank private browsing page",
    "chrome_url_overrides" : {
       "chrome://browser/content/aboutPrivateBrowsing.xhtml": "index.html"
  },
  "version": "0.1"
}

But it seems that it can be used only for certain chrome pages, right?
See: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/chrome_url_overrides
A second option that I tried was a UserScript:
// ==UserScript==
// @name Blank aboutPrivateBrowsing page
// @include chrome://browser/content/aboutPrivateBrowsing.xhtml
// ==/UserScript==

window.location.href="about:blank";

But seems that Greasemonkey can not handle chrome URLs.
Can anyone think of another solution?

A: Currently, you cannot override about:newtab in private mode. However, what you should be able to do inside a WebExtension:

*

*Listen for tab opens of about:privatebrowsing using the tabs API https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/onCreated

*Create a new tab using browser.tabs.create({}) (without URL, it will create an empty tab) and close the previous tab (using the tabid).

Then you will have more or less the same.
Code:
function handleUpdated(tabId, changeInfo, tabInfo) {
    if(changeInfo.favIconUrl){
        //console.log("favIconUrl updated is " + changeInfo.favIconUrl);

        if (tabInfo.incognito && changeInfo.favIconUrl.indexOf("privatebrowsing") > -1){
            //console.log("opening about:blank..");
            browser.tabs.update({url: "about:blank"});
        }
    }
}

browser.tabs.onUpdated.addListener(handleUpdated);

The code above sadly gives a noticable graphical glitch. Instead of favIconUrl you can probably use tab.title == "New Tab" as well (but that will only work for English versions of Firefox).


text:
Q: c# multiple if conditions in same lane I have a slight problem when working with c# and using IF statments with multiple conditions.
This is the most common occurance.
private void SomeFunction(string SomeString)
{

   if(SomeString != null && SomeString.Trim() != "")
   {
   }
}

In some languages like javascript if the first argument fails (SomeString != null) the second check wont be made. C# seems to check both arguments even if the first one fails and then the second one will throw an exception since you cannot use .Trim() on a null value.
Right now I am going over this by nesting my ifs which is messy work. Like this:
private void SomeFunction(string SomeString)
{

   if(SomeString != null)
   {
     if(SomeString.Trim() != "")
     {
      .....
     }
   }
}

Does anybody have any suggestions or best practices on a better way to solve this?

A:
C# seems to check both arguments even if the first one fails

That's not true, see && Operator (C# Reference) in MSDN.

A: There is a better way:
private void SomeFunction(string SomeString)
{
    if (!string.IsNullOrWhiteSpace(SomeString))
    {
        // your code
    }
}

A: Your assumption is totally wrong. When you use the conditional AND if the first condition is FALSE the second condition is never evaluated or executed. In the conditional OR if the first condition is TRUE the second one is never evaluated or executed.
In other words, if the compiler has enough info to determine the result of the expression it stops to consider the second part of the expression.
This is known as short-circuit evaluation.
It is a basic programming principle for C derived languages but also for every other major language.

A: if (!String.IsNullOrEmpty(SomeString))
{
}

A: if(!string.IsNullOrEmpty(SomeString))

similar to ProgramFOX prefer this if you insist on doing ".Trim()"


text:
Q: Performing POST method Using Axios and Pipe Function So I am currently learning about FP and the use of the Pipe operator which combines n functions and simply calls it from left to right. Currently, I am trying to make a POST call using Axios and then handle the data returned appropriately, but then the pending promise value always results to undefined. Here is what my code looks like.
The pipe function
const pipe = (...fns) => (initValue) => fns.reduce((v, f) => f(v), initValue)

Here is the first function that is passed to the pipe function
const dataToPost = ({ title, body, userId }) => {
  return {
    method: 'post',
    url: 'https://jsonplaceholder.typicode.com/posts',
    data: {
      title,
      body,
      userId,
    },
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
    },
  }
}

Here is how I implement the pipe function passing it the various arguments
const postTodoFunc = ({ pipe }) => {
  return async function postTodo({ title, body, userId }) {
    const callJSONAPI = pipe(dataToPost, axios, output) ///this line here

    const calledFunc = await callJSONAPI({
      title,
      body,
      userId,
    })
    return calledFunc
  }
}

The output function looks like this.
const output = (response) => {
  return response.data
}

The postTodoFunc is invoked like this
const postedTodo = postTodoFunc({ pipe })
const result = postedTodo({
  title: 'Rule the world',
  body: 'some random body',
  userId: 1,
})

console.log(result) // undefined

Now from my understanding, the dataToPost function is called first which returns an object that is equivalent to this
{
    method: 'post',
    url: 'https://jsonplaceholder.typicode.com/posts',
    data: {
      title,
      body,
      userId,
    },
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
    },
  }

This object is then passed to axios which is then equivalent to the following format
axios({
    method: 'post',
    url: 'https://jsonplaceholder.typicode.com/posts',
    data: {
      title,
      body,
      userId,
    },
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
    },
  })

The response from this axios call returns undefined. Because I thought the response will be passed to the next function which is this case output function. But that does not seem to be the case. How can I fix this and get the correct data? Initially from the JSONPlaceholder website, the response is meant to be like this
{
  id: 101,
  title: 'Rule the world',
  body: 'Some random body',
  userId: 1
}

but then again, I am getting undefined after the pending promise.


text:
Q: How to get microsoft.xrm.client.codegeneration.dll I am trying to set up references to the CRM 2011 sdk
Microsoft.Xrm.Sdk.dll
Microsoft.Xrm.Portal.dll
Microsoft.Xrm.Client.dll

While trying to use the CrmSvcUtil.exe to generate the early bound types for CRM, I get an error  Microsoft.Xrm.Client.CodeGeneration.dll cannot be located. I could not locate the dll in any of the packages that I downloaded using Nuget PM.
Can anybody advise on the usage and how to obtain this?

A: Use the Early Bound Generator in the XrmToolBox Tool Store. It contains the functionality to generate code using the Xrm.Client.  Or if you really just want to use the DLL and do everything by hand, it contains the DLL in the download.
Update
As of March 2020, the EBG no longer supports the deprecated Microsoft.Xrm.Client usage.  Hopefully you've transitioned off of that.  You can still download older versions of the EBG on NuGet if you're stuck on that client generation.


text:
Q: CSS Border Styling CSS, HTML & PHP I would like to add a border style of white to the bottom of td-fault table only.
My CSS CODE:
background, body{
background-color: black;
}

table-eng, p{
width: 650%;
font-size: 15pt;
color: #ffffff;
border-bottom-style: none;
}

table-cust, tr{
font-size: 13pt;
color: #4CBB17;
}

td-fault, td{
font-size: 11pt;
color: #ffffff;
border-bottom: 1px solid white;
}

Here is my HTML/PHP:

<link href="../css/job-board.css" rel="stylesheet">

<?php
include('connectionDB.php');
$sql = "SELECT * FROM [Support_DB].[dbo].['Job info$'] WHERE [Job Completed?]= 0 AND [Attended by]='James'";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $results=$stmt->fetchAll(PDO::FETCH_ASSOC);
        ?>

James

<?php foreach ($results as $row) {
echo "
";
echo"
";
echo"
";
echo"";
echo $row['Customer'];
echo"	";
echo"";
echo $row['Job Number'];
echo"	";
echo"
";
echo"
";
echo"
";
//echo"
";
echo"";
echo wordwrap($row['Fault'],85,"
\n",TRUE);
echo"	";
echo"
";
//echo"
";
 echo"
";
 //echo"
";
//echo"
";
        }?>

The company Name and job number need to be in white if possible on a continuous line so looks smoother as I nearly had it how I wanted it but I mucked up and couldn't get it correct again.

A: The reason is because you're missing the . for td-fault in your CSS.
Try the following:
.td-fault {
  font-size: 11pt;
  color: #ffffff;
  border-bottom: 1px solid white;
}

Also table-eng and table-cust is missing # like so
#table-eng and #table-cust


text:
Q: Windows typeperf and pound signs I'm currently trying to use typeperf to access some Windows performance counters.  Unfortunately, a few of the instances I'm trying to check are of the format service#1.
The command
 typeperf "\\server\Process(service#1)\Working Set Peak"

is unfortunately returning the data for \\server\Process(service)\Working Set Peak rather than the data for the instance service#1.  This holds true for any of the services that have pound signs in the counter string.  Does anyone know of a method to get around this problem?
Sample output:
I:\>typeperf -s server "\Process(service#1)\Working Set"

"(PDH-CSV 4.0)","\\server\Process(service)\Working Set"
"10/08/2009 09:37:29.070","1643274240.000000"
"10/08/2009 09:37:30.070","1643274240.000000"
"10/08/2009 09:37:31.070","1643274240.000000"

The command completed successfully.

I:\>typeperf -s server "\Process(service#2)\Working Set"

"(PDH-CSV 4.0)","\\server\Process(service)\Working Set"
"10/08/2009 09:37:39.273","1643274240.000000"
"10/08/2009 09:37:40.273","1643274240.000000"
"10/08/2009 09:37:41.273","1643274240.000000"
"10/08/2009 09:37:42.273","1643274240.000000"
"10/08/2009 09:37:43.273","1643274240.000000"

The command completed successfully.

I can confirm in PerfMon that the Working Set value "1643274240.000000" is incorrect for both service#1 and service#2.
I am running Windows XP Service Pack 2, but a co-worker who is running Windows Server 2003 was having the same troubles.

A: Interesting, I'm having similar issues. However, my behavior is different.
For me, the # signs are recognized properly under Windows Server 2003 (SP2) and Vista. But I have the same issue with XP SP2.
An interesting thing to note as well, typeperf can seem to list or output the counters with # signs, it just can't seem to report them when you supply them as input, from the command line or a counter input file.
Perfmon can report them fine. I wonder why all this difference.
Too bad there is not enough typeperf users out there to get this resolved or looked into by Microsoft or others.


text:
Q: safeAreaLayoutGuide guide not working from another viewcontroller As suggested by some experts like @DonMag , i design the view in a separate controller, while trying to do so , every thing works, but when i use a navigation controller and there is a navigation bar at top, if i try and design in separate controller and then add its view to another controller the safeAreaLayoutGuide does not work and the view is attached to top of screen ignoring the safearea
SOLUTION as per @Mohammad Azam, DonMag solutions works as well , thanks
import UIKit

class NotesDesign: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func commonInit(){
               let notesTitle = UITextField()
               let notesContent = UITextView()

               let font = UIFont(name: "CourierNewPS-ItalicMT", size: 20)
               let fontM = UIFontMetrics(forTextStyle: .body)
               notesTitle.font = fontM.scaledFont(for: font!)

               notesContent.font = fontM.scaledFont(for: font!)

               notesTitle.widthAnchor.constraint(greaterThanOrEqualToConstant:250).isActive = true
               notesTitle.heightAnchor.constraint(equalToConstant: 30).isActive = true
               notesTitle.borderStyle = .line
               notesContent.widthAnchor.constraint(greaterThanOrEqualToConstant:250).isActive = true
               notesContent.heightAnchor.constraint(greaterThanOrEqualToConstant: 100).isActive = true
               notesContent.layer.borderWidth = 1
               let notesStack = UIStackView()
               notesStack.axis = .vertical
               notesStack.spacing = 20
               notesStack.alignment = .top
               notesStack.distribution = .fill

               notesStack.addArrangedSubview(notesTitle)
               notesStack.addArrangedSubview(notesContent)
               // Do any additional setup after loading the view.

               notesStack.translatesAutoresizingMaskIntoConstraints = false
               addSubview(notesStack)

               notesStack.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
               notesStack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
               notesStack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
               notesStack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -40).isActive = true

    }

}

And where i call it
import UIKit

class AddNotesViewController: UIViewController {
   var design = NotesDesign()
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        view.addSubview(design)
        design.translatesAutoresizingMaskIntoConstraints = false
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveData))
    }

    @objc func saveData() {

    }

}

And this is what i get

A: If you are taking a view from its ViewController and adding it as a subview to another view, you need to constrain it just like you would with any other added subview:
class AddNotesViewController: UIViewController {
    var design = NotesViewDesign()
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        view.addSubview(design.view)

        // a view loaded from a UIViewController has .translatesAutoresizingMaskIntoConstraints = true
        design.view.translatesAutoresizingMaskIntoConstraints = false

        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([
            // constrain the loaded view
            design.view.topAnchor.constraint(equalTo: g.topAnchor),
            design.view.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            design.view.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            design.view.bottomAnchor.constraint(equalTo: g.bottomAnchor),
        ])

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveData))
    }

    @objc func saveData() {

    }

}


text:
Q: Log file not created I am trying to create a log file as follows:
 logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %
(message)s')

the second method is:
logging.basicConfig(filename='sample11.log', format='%(asctime)s | %(levelname)s: %
(message)s', level=logging.info)

 logging.info(str(size_df))

size_df is just len(df)
When I was applying this before the logging did work. Would anyone know the problem?

A: Try:
logging.basicConfig(filename='sample11.log', format='%(asctime)s | %(levelname)s: % (message)s', level=logging.INFO)

The logging levels need to be UPPERCASE.


text:
Q: why does it say that class myPair has no member of out? it works well when I define the function in the class #include <iostream>

using namespace std;

class myPair {
private:
    int x, y;
public:
    myPair(int x = 3, int y = 2) {};
    friend void out(string a) {};
};

void out(string a) {
    myPair p;
    cout << a << "x equals " << p.x << "and " << a << "y equals " << p.y;
};

int main() {
    myPair A(5, 3);
    A.out("A : ");
}

this code is supposed to print out info about myPair class object but for some reason compiler tells me that there is not any member with the name of out() in myPair

A: You declare a function friend to the class so that this function can access the private data members of the class. And remember you cannot call friend function like A.out as it just an external function with special privileges and does not have this pointer. So it cannot be called that way.
And further, when you put {} in the front of the function signatures it becomes a definition. So You have to obey ODR(One Definition Rule). While declaring the friend function you cannot put {} otherwise you will get an error.
One more thing your constructor is not constructing the object properly, it is just taking parameters and doing nothing.
To let your friend do something to an object is to pass the object in the friend function.
You can see below the correct version of your code:
#include <iostream>

using namespace std;

class myPair {
private:
    int x, y;
public:
    myPair(int _x = 3, int _y = 2): x(_x), y(_y) {};
    friend void out(const string& a, myPair& p);
};

void out(const string& a, myPair& p) {
    //myPair p;
    cout << a << "x equals " << p.x << "and " << a << "y equals " << p.y;
};

int main() {
    myPair A(5, 3);
    out("A : ", A);
}

This is not a method, so You need to pass your object into out("", myPair). It works as expected.

A: The behaviour of your code is undefined. This is because you don't set the member variables in myPair and then subsequently read their values.
Rather than your out function, it's idiomatic C++ to define the << operator for ostream and your class. In that way you can use it directly in a cout statement. Here are the changes, including the fix to your constructor:
#include <iostream>

class myPair {
private:
    int x;
    int y;
public:
    myPair(int x = 3, int y = 2) : x(x), y(y) /*there is no ambiguity here bizarrely*/
    {
    };
    friend std::ostream& operator<<(std::ostream& os, const myPair& p);
};

std::ostream& operator<<(std::ostream& os, const myPair& p){
    os << "x equals " << p.x << " and y equals " << p.y;
    return os;
}

int main() {
    myPair A(5, 3);
    std::cout << "A: " << A;
}

A: You are declaring out as a friend function not a member. So your code should look like,
#include <iostream>

using namespace std;

class myPair {
private:
    int x, y;
public:
    myPair(int x = 3, int y = 2) : x(x), y(y){};
    void out(string);
};

void myPair::out(string a) {
    cout << a << "x equals " << this->x << "and " << a << "y equals " << this->y;
};

int main() {
    myPair A(5, 3);
    A.out("A : ");
}

If you want friend functions you can do,
#include <iostream>

using namespace std;

class myPair {
private:
    int x, y;
public:
    myPair(int x = 3, int y = 2) : x(x), y(y) {};
    friend void out(myPair p, string a);
};

void out(myPair p, string a) {
    cout << a << "x equals " << p.x << "and " << a << "y equals " << p.y;
};

int main() {
    myPair A(5, 3);
    out(A, "A : ");
}


text:
Q: Проверить покупателей за каждый месяц Есть задание, вывести покупателей, стоимость покупки и кол-во покупок за каждый месяц.
SELECT C.CONTACT_LAST, S.TOTAL_VALUE, S.QTY_ORDERED
FROM CUSTOMER C
JOIN SALES S ON S.CUST_NO = C.CUST_NO
WHERE (S.TOTAL_VALUE = (SELECT MIN(S.TOTAL_VALUE) FROM SALES S)
AND S.PAID = 'y'
AND EXTRACT(YEAR From S.ORDER_DATE) = '1993')
OR (S.TOTAL_VALUE = (SELECT MAX(S.TOTAL_VALUE) FROM SALES S)
AND S.PAID = 'y' AND EXTRACT(YEAR From S.ORDER_DATE) = '1993')
ORDER BY S.TOTAL_VALUE ASC;

Подскажите, как проверить каждый месяц?


text:
Q: iOS 13 Fatal Exception: NSInternalInconsistencyException I've been looking for a solution to an error that I couldn't solve since in firebase it doesn't give me any information.
Fatal Exception: NSInternalInconsistencyException
0  CoreFoundation                 0x1aa0b2a48 __exceptionPreprocess
1  libobjc.A.dylib                0x1a9dd9fa4 objc_exception_throw
2  CoreFoundation                 0x1a9fb4e88 +[_CFXNotificationTokenRegistration keyCallbacks]
3  Foundation                     0x1aa3ea6c4 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:]
4  FrontBoardServices             0x1af21ba4c -[FBSSerialQueue assertOnQueue]
5  FrontBoardServices             0x1af1d0ec8 -[FBSSceneImpl updateClientSettings:withTransitionContext:]
6  FrontBoardServices             0x1af1d1130 -[FBSSceneImpl updateClientSettingsWithTransitionBlock:]
7  FrontBoardServices             0x1af1d1038 -[FBSSceneImpl updateClientSettingsWithBlock:]
8  UIKitCore                      0x1adcb87f4 -[FBSScene(UIApp) updateUIClientSettingsWithBlock:]
9  UIKitCore                      0x1adda2508 -[UIDevice(Private) _enableDeviceOrientationEvents:]
10 UIKitCore                      0x1adda31a4 -[UIDevice beginGeneratingDeviceOrientationNotifications]
11 WebRTC                         0x105476898 (Falta)
12 libdispatch.dylib              0x1a9d7e610 _dispatch_call_block_and_release
13 libdispatch.dylib              0x1a9d7f184 _dispatch_client_callout
14 libdispatch.dylib              0x1a9d2b404 _dispatch_lane_serial_drain$VARIANT$mp
15 libdispatch.dylib              0x1a9d2bdf8 _dispatch_lane_invoke$VARIANT$mp
16 libdispatch.dylib              0x1a9d35314 _dispatch_workloop_worker_thread
17 libsystem_pthread.dylib        0x1a9dceb88 _pthread_wqthread
18 libsystem_pthread.dylib        0x1a9dd1760 start_wqthread

This is the information I receive from Firebase. What happens is that when receiving an incoming call from my app when it is completely closed and the call is accepted it closes and gives this error, if the app is in the background or open it does not close.
Thanks for the help.


text:
Q: Pattern of regular expressions while using Look Behind or Look Ahead Functions to find a match I am trying to split a sentence correctly bases on normal grammatical rules in python.
The sentence I want to split is
s = """Mr. Smith bought cheapsite.com for 1.5 million dollars,
i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a
probability of .9 it isn't."""

The expected output is
Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it.

Did he mind?

Adam Jones Jr. thinks he didn't.

In any case, this isn't true...

Well, with a probability of .9 it isn't.

To achieve this I am using regular , after a lot of searching I came upon the following regex which does the trick.The new_str was jut to remove some \n from 's'
m = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s',new_str)

for i in m:
    print (i)

Mr. Smith bought cheapsite.com for 1.5 million dollars,i.e. he paid a lot for it.
Did he mind?
Adam Jones Jr. thinks he didn't.
In any case, this isn't true...
Well, with aprobability of .9 it isn't.

So the way I understand the reg ex is that we are first selecting
1) All the characters like i.e
2) From the filtered spaces from the first selection ,we select those characters
which dont have words like Mr. Mrs. etc
3) From the filtered 2nd step we select only those subjects where we have either dot or question and are preceded by a space.
So I tried to change the order as below
1) Filter out all the titles first.
2) From the filtered step select those that are preceded by space
3) remove all phrases like i.e
but when I do that the blank after is also split
m = re.split(r'(?<![A-Z][a-z]\.)(?<=\.|\?)\s(?<!\w\.\w.)',new_str)

for i in m:
    print (i)

Mr. Smith bought cheapsite.com for 1.5 million dollars,i.e.
he paid a lot for it.
Did he mind?
Adam Jones Jr. thinks he didn't.
In any case, this isn't true...
Well, with aprobability of .9 it isn't.

Shouldn't the last step in the modified procedure be capable in identifying phrases like i.e ,why is it failing to detect it ?

A: First, the last . in (?<!\w\.\w.) looks suspicious, if you need to match a literal dot with it, escape it ((?<!\w\.\w\.)).
Coming back to the question, when you use r'(?<![A-Z][a-z]\.)(?<=\.|\?)\s(?<!\w\.\w.)' regex, the last negative lookbehind checks if the position after a whitespace is not preceded with a word char, dot, word char, any char (since the . is unescaped).  This condition is true, because there are a dot, e, another . and a space before that position.
To make the lookbehind work that same way as when it was before \s, put the \s into the lookbehind pattern, too:
(?<![A-Z][a-z]\.)(?<=\.|\?)\s(?<!\w\.\w.\s)

See the regex demo
Another enhancement can be using a character class in the second lookbehind: (?<=\.|\?) -> (?<=[.?]).


text:
Q: converting TForm win32 app to Win7 gadget (delphi) What is the process of converting win32 application (a small popup window actually) to win7 gadget?
Do I need to convert my exe to activex component, can I still use TForm ?
it would be nice to have support for both Win7 + Vista.

A: The Windows Vista/7 gadgets are essentially mini-HTML applications. The user interface is composed of pages containing regular HTML, CSS ,images and potentially ActiveX controls.
So the only way to use your win32 application into a gadget is convert the application to a Activex Control.
You can read these articles
Activex

*

*Building ActiveX Controls with Delphi (This article is old but is still useful)

*Delphi and Active Forms

*Converting a standard Delphi Form to an ActiveForm
Gadgets

*

*Introduction to the Gadget Platform

*Developing a Gadget for Windows Sidebar
Bye.

A: If you are able to read German, there is a tutorial at www.delphipraxis.net. Perhaps someone may translate it to English...


text:
Q: Why does bar graph get inverted when I use it in a infobox? The code for the page is
{{Infobox course
| course_code = PH31011
| course_name = Quantum Mechanics I
| department = [[Physics]]
| credits = 4
| ltp = {{Data bars
         | columns = 6 | Jan| Feb| Mar| Apr| May| Jun
         | blue|Berries|  65|  38|  72|  47|  20|  30
        }}
}}

{{Data bars
| columns = 6 | Jan| Feb| Mar| Apr| May| Jun
| blue|Berries|  65|  38|  72|  47|  20|  30
}}

Why does the graph display inverted bars when used in the infobox?

*

*Both Graphs Images

*Demo page

A: This is a CSS issue, and not really related to MediaWiki itself, but to a stylesheet created by the Wikimedia community. There is a css rule in MediaWiki:Common.css (user created CSS loaded for all skins) on that wiki that looks like this:
.infobox th[scope=row], .infobox td {
   vertical-align: top;
}

That rule overrides the vertical align of the bar. A quick and dirty fix would be to change vertical-align: bottom; to vertical-align: bottom !important; for each column in Template:Data_bars.
As always, you risk messing up some other edge case if you do that on a production wiki, so you should probably raise the question on the talk page first.


text:
Q: Empy a dictionary and a list in Python I know that a list/dictionary can be emptied by re-initializing new objects, but I want to keep the initial objects.

*

*Also in Python 3 a list can be empty(removed) all elements, by using clear(). But how can be done in Python 2.7 ?

*Remove all keys from a dictionary ?

A: for a list:
l[:] = []

keeps the same object but empties the contents


text:
Q: idempotent functions in the space of continuous functions Question. $X$ is a connected iff the zero and identity functions are the only idempotent function in $C(X)$.
Answer. If $f\in C(X)$ is idempotent then $f(x)^2=f(x),\ \forall x\in X $,
then $f(x) =0 $ or $1$ which implies Im($f$) is a subset of $\{0,1\}$.
Let $X$ be connected. Then Im($f)=\{0\}$ or $\{1\}$ hence $f$ has two choices: the zero function or the identity function.
How to prove the reverse part and are my above arguments true?

A: A more conceptual proof: Establish a bijection between the idempotent elements of $C(X)$ (i.e. $\{0,1\}$-valued continuous functions) and the clopen subsets of $X$. It maps a clopen subset $C \subseteq X$ to its characteristic function. This is very simple: Use the known bijection between functions $X \to \{0,1\}$ and subsets of $X$, and observe that a function is continuous iff the corresponding subset is clopen.


text:
Q: Is there any possible way to run select sql query by jquery or javascript Is there any possible way to excute the select sql query using javascript or jquery.
for ex : i want to run the query like
select * from abc

So, can I excute this query using javascript or jquery.
If yes then please guide me.
If no then please give me the reason.
ThankYou

A: From browser-side JavaScript, no, not really.
You can use server-side Node.js JavaScript, but you'll want to do the query directly from the server with some language (literally any server-side language).
Running queries from the client is not only technically difficult, but it's also a huge security risk as your users could run any query.

A: You shouldn´t use client javascript to access databases, mostly because security.
but a example:
( from How to connect to SQL Server database from JavaScript in the browser?)
var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close;

Better way is call ajax function to a code behind method and query from there.

A: Simply you can use AJAX. To perform any action.


text:
Q: Splitting URL in three parts in htaccess - regex I'm trying to split any URL that would show up on my website into three parts:

*

*Language (optional)

*Hierarchical structure of the page (parents)

*Current page

Right now I operate with 1 and 3 but I need to develop a way to allow for the pages to have the same names if they have different parents and therefore full URL is unique.
Here are the types of URL I may have:
(nothing)
en
en/test
en/parent/test
test
parent/test
ggparent/gparent/parent/test

I thought about extending my current directive:
RewriteRule ^(?:([a-z]{2})(?=\/))?.*(?:\/([\w\-\,\+]+))$ /index.php?lang=$1&page=$2 [L,NC]

to the following:
(?:([a-z]{2})(?=\/))?(.*)\/([^\/]*)?$
Which then I could translate to index.php?lang=$1&tree=$2&page=$3 but the difficulty I have is that the second capturing group captures the slash from the beginning.
I believe I can't (based on my search so far) dynamically have all the strings between slashes to be returned and make the last one to always be first, without repeating the same regex. I thought I would capture anything between language and current page and process the tree in PHP.
However my current regex has some problems and I can't figure them out:

*

*If language is on its own, it doesn't get captured

*The second group captures the slash betwen language and the tree

Link to Regex101: https://regex101.com/r/ecHBQT/1

A: I hope I've understood your question right. You can try this regex:
^([a-z]{2}(?=\/|$))?(?:\/?(.+)\/)?(.*)

Regex demo.

This will match 3 groups: first the language (two characters), then the parents and the last group is last part of the URL (after /).

A: This likely does it: Split the URL by slash into lang, tree, and page at the proper place, with all three parts possibly empty:
RewriteRule ^([a-z]{2}\b)?\/?(?:\/?(.+)\/)?(.*)$ /index.php?lang=$1&tree=$2&page=$3 [L,NC]

Testcase in JavaScript using this regex:

const regex = /^([a-z]{2}\b)?\/?(?:\/?(.+)\/)?(.*)$/;
[
  '',
  'en',
  'en/test',
  'en/parent/test',
  'test',
  'parent/test',
  'ggparent/gparent/parent/test'
].forEach(str => {
  let rewritten = str.replace(regex, '/index.php?lang=$1&tree=$2&page=$3');
  console.log('"' + str + '" ==>', rewritten);
})

Output:
"" ==> /index.php?lang=&tree=&page=
"en" ==> /index.php?lang=en&tree=&page=
"en/test" ==> /index.php?lang=en&tree=&page=test
"en/parent/test" ==> /index.php?lang=en&tree=parent&page=test
"test" ==> /index.php?lang=&tree=&page=test
"parent/test" ==> /index.php?lang=&tree=parent&page=test
"ggparent/gparent/parent/test" ==> /index.php?lang=&tree=ggparent/gparent/parent&page=test

Notes:

*

*This assumes that a page and parent must not be exactly two chars long (you could specify an explicit or-list of all languages you have)

*Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex


text:
Q: How to remove a very large portion of DOM with IE in small amount of time? When user push a refresh buttton I must remove a table from the actual page and then reload via ajax a new one, and then show the new one.
I enclosed the ajax-loaded TABLE into a DIV with a known id.
When user push the Refresh button, i simply do this:
document.getElementById('result_div').innerHTML = '';

Actually FF takes 1 seconds, Chrome 2 and IE about 10 seconds and it's freezing, so my users are very very angry because of this problem.
Is there a faster whay to remove an entire very large table from the page?

A: At the very end, I'm using this solution.
First I remove from the TBODY every single TR
container = document.getElementById('result_table_body');
if (container) {
    var len = container.childNodes.length;
    while (len--) {
        container.removeChild(container.lastChild);
    };
}

Then I removed in bulk what is remaining in the div used as results container
$('#result_div').html('');

I found this snippet here: http://jsperf.com/jquery-empty-vs-html/14
I didn't want to believe, but it's faster than emptying innerHTML, and it's faster than jQuery empty() function (this in IE 11, my pecific critical case, FF doesn't have any problem with 1 milion cells to remove using empty, innerHTML or waht else... ).


text:
Q: C# export to XLS issue I'm tring to export data to a formated XLS, but I seem to have some kind of limit issue. It exports some datasets and some it doesn't.
I've gone through the resulted XML and commented most of the rows, then unkommented them one after one until the document opened sussesfully. I know of the row and column limitations but the resulted document fails to open in Excel far before those. I'm talking about failing when more then 34 excel rows (about 500 formated XML lines).
Here is my full export code:
private void GenerateConfigReport(HttpContext context)
{
    GIS34PortalService client = new GIS34PortalService();
    DataTable features = client.GetFeatures(objectId, "id");
    string filename = "ConfigRapport";

    #region header

    StringBuilder header = new StringBuilder();
    header.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    header.AppendLine("<?mso-application progid=\"Excel.Sheet\"?>");
    header.AppendLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
    header.AppendLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
    header.AppendLine("  <Author>Amit Bracha</Author>");
    header.AppendLine("  <LastAuthor>Amit Bracha</LastAuthor>");
    header.AppendLine("  <Created>" + DateTime.Now + "</Created>");
    header.AppendLine("  <LastSaved>" + DateTime.Now + "</LastSaved>");
    header.AppendLine("  <Company>Landinspektørfirmaet LE34 A/S</Company>");
    header.AppendLine("  <Version>12.00</Version>");
    header.AppendLine(" </DocumentProperties>");
    header.AppendLine(" <OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">");
    header.AppendLine("  <RemovePersonalInformation/>");
    header.AppendLine(" </OfficeDocumentSettings>");
    header.AppendLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
    header.AppendLine("  <WindowHeight>7875</WindowHeight>");
    header.AppendLine("  <WindowWidth>14895</WindowWidth>");
    header.AppendLine("  <WindowTopX>360</WindowTopX>");
    header.AppendLine("  <WindowTopY>300</WindowTopY>");
    header.AppendLine("  <ProtectStructure>False</ProtectStructure>");
    header.AppendLine("  <ProtectWindows>False</ProtectWindows>");
    header.AppendLine(" </ExcelWorkbook>");

    #endregion

    #region styles

    StringBuilder styles = new StringBuilder();
    styles.AppendLine(" <Styles>");
    ...
    styles.AppendLine(" </Styles>");

region

    #region title

    StringBuilder title = new StringBuilder();
    title.AppendLine(" <Worksheet ss:Name=\"Ark1\">");
    title.AppendLine("  <Names>");
    title.AppendLine("   <NamedRange ss:Name=\"GIS34_Skade_V1_alle_koder\" ss:RefersTo=\"=Ark1!R5C2:R28C2\"/>");
    title.AppendLine("  </Names>");
    title.AppendLine("  <Table ss:ExpandedColumnCount=\"16\" ss:ExpandedRowCount=\"34\" x:FullColumns=\"1\" x:FullRows=\"1\" ss:StyleID=\"s16\" ss:DefaultRowHeight=\"15\">");
    title.AppendLine("   <Column ss:StyleID=\"s16\" ss:AutoFitWidth=\"0\" ss:Width=\"30\"/>");
    title.AppendLine("   <Column ss:StyleID=\"s16\" ss:AutoFitWidth=\"0\" ss:Width=\"135\" ss:Span=\"2\"/>");
    title.AppendLine("   <Column ss:Index=\"5\" ss:StyleID=\"s19\" ss:AutoFitWidth=\"0\" ss:Width=\"30\"/>");
    title.AppendLine("   <Column ss:StyleID=\"s16\" ss:AutoFitWidth=\"0\" ss:Width=\"135\"/>");
    title.AppendLine("   <Column ss:StyleID=\"s19\" ss:AutoFitWidth=\"0\" ss:Width=\"30\"/>");
    title.AppendLine("   <Column ss:StyleID=\"s16\" ss:AutoFitWidth=\"0\" ss:Width=\"135\"/>");
    title.AppendLine("   <Column ss:StyleID=\"s19\" ss:AutoFitWidth=\"0\" ss:Span=\"3\"/>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\" ss:Height=\"30\" ss:StyleID=\"s18\">");
    title.AppendLine("    <Cell ss:StyleID=\"s33\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s126\"><Data ss:Type=\"String\">LE34</Data></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s87\"><Data ss:Type=\"String\">Kunde:</Data></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s32\"><Data ss:Type=\"String\">Assens Kommune</Data></Cell>");
    title.AppendLine("   </Row>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\" ss:Height=\"30\" ss:StyleID=\"s18\">");
    title.AppendLine("    <Cell ss:StyleID=\"s33\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s128\"><Data ss:Type=\"String\">GIS34</Data></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s87\"><Data ss:Type=\"String\">Kodeliste:</Data></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s32\"><Data ss:Type=\"String\">" + objectName + "</Data></Cell>");
    title.AppendLine("   </Row>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\">");
    title.AppendLine("    <Cell ss:StyleID=\"s33\"/>");
    title.AppendLine("    <Cell ss:MergeAcross=\"6\" ss:StyleID=\"s37\"><Data ss:Type=\"String\">Udformning af lagkontrol: </Data></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("   </Row>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\">");
    title.AppendLine("    <Cell ss:StyleID=\"s33\"/>");
    title.AppendLine("    <Cell ss:MergeAcross=\"6\" ss:StyleID=\"s37\"><Data ss:Type=\"String\">Lagkontrollen kan udformes så den give en meningsfuld oversigt over opgaverne.</Data></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("   </Row>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\">");
    title.AppendLine("    <Cell ss:StyleID=\"s33\"/>");
    title.AppendLine("    <Cell ss:MergeAcross=\"6\" ss:StyleID=\"s37\"><Data ss:Type=\"String\">Der defineres de lag som matcher de teams som skal løse opgaverne.</Data><NamedCell ss:Name=\"GIS34_Skade_V1_alle_koder\"/></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("   </Row>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\">");
    title.AppendLine("    <Cell ss:StyleID=\"s33\"/>");
    title.AppendLine("    <Cell ss:Index=\"5\" ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:Index=\"7\" ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:Index=\"9\" ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
    title.AppendLine("   </Row>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\" ss:Height=\"20.0625\" ss:StyleID=\"s17\">");
    title.AppendLine("    <Cell ss:StyleID=\"s33\"/>");
    title.AppendLine("    <Cell ss:StyleID=\"s24\"><Data ss:Type=\"String\">Features</Data><NamedCell ss:Name=\"GIS34_Skade_V1_alle_koder\"/></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s25\"><Data ss:Type=\"String\">Attributter</Data></Cell>");
    title.AppendLine("    <Cell ss:StyleID=\"s26\"><Data ss:Type=\"String\">Menu items</Data></Cell>");
    title.AppendLine("    <Cell ss:Index=\"6\" ss:StyleID=\"s27\"><Data ss:Type=\"String\">Lagkontrol</Data></Cell>");
    title.AppendLine("    <Cell ss:Index=\"8\" ss:StyleID=\"s28\"><Data ss:Type=\"String\">WebGIS</Data></Cell>");
    title.AppendLine("   </Row>");
    title.AppendLine("   <Row ss:AutoFitHeight=\"0\" ss:StyleID=\"s17\"/>");

    #endregion

    #region content

    StringBuilder content = new StringBuilder();

    foreach (DataRow feature in features.Rows)
    {
        content.AppendLine("   <Row ss:AutoFitHeight=\"0\">");
        content.AppendLine("    <Cell ss:Index=\"2\" ss:MergeAcross=\"2\" ss:StyleID=\"s36\"><Data ss:Type=\"String\">" + (feature["name"].ToString() + " (" + feature["geometry_type"].ToString().ToLower() + ")") + "</Data></Cell>");
        content.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
        content.AppendLine("    <Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\"></Data></Cell>");
        content.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
        content.AppendLine("    <Cell ss:StyleID=\"s22\"><Data ss:Type=\"String\"></Data></Cell>");
        content.AppendLine("   </Row>");

        DataTable attributtes = client.GetAttributes(feature["id"].ToString(), "id");

        foreach (DataRow attributte in attributtes.Rows)
        {
            content.AppendLine("   <Row ss:AutoFitHeight=\"0\">");
            content.AppendLine("    <Cell ss:Index=\"2\" ss:StyleID=\"s29\"></Cell>");
            content.AppendLine("    <Cell ss:StyleID=\"s30\"><Data ss:Type=\"String\">" + (attributte["name"].ToString() + " (" + attributte["type"].ToString().ToLower() + ")") + "</Data></Cell>");
            content.AppendLine("    <Cell ss:StyleID=\"s30\"/>");
            content.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
            content.AppendLine("    <Cell ss:StyleID=\"s20\"/>");
            content.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
            content.AppendLine("    <Cell ss:StyleID=\"s20\"/>");
            content.AppendLine("   </Row>");

            if (attributte["type"].ToString().ToLower() == "menu")
            {
                DataTable menuItems = client.GetAttributeInfo(attributte["id"].ToString(), attributte["type"].ToString(), "id");

                foreach (DataRow menuItem in menuItems.Rows)
                {
                    content.AppendLine("   <Row ss:AutoFitHeight=\"0\">");
                    content.AppendLine("    <Cell ss:Index=\"2\" ss:StyleID=\"s29\"></Cell>");
                    content.AppendLine("    <Cell ss:StyleID=\"s30\"/>");
                    content.AppendLine("    <Cell ss:StyleID=\"s30\"><Data ss:Type=\"String\">" + (menuItem["name"].ToString() + (menuItem["value"].ToString().ToLower().Contains("true") ? " (default)" : "")) + "</Data></Cell>");
                    content.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
                    content.AppendLine("    <Cell ss:StyleID=\"s20\"/>");
                    content.AppendLine("    <Cell ss:StyleID=\"s16\"/>");
                    content.AppendLine("    <Cell ss:StyleID=\"s20\"/>");
                    content.AppendLine("   </Row>");
                }
            }
        }
    }
    content.AppendLine("  </Table>");

    #endregion

    #region footer

    StringBuilder footer = new StringBuilder();
    footer.AppendLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
    footer.AppendLine("   <PageSetup>");
    footer.AppendLine("    <Header x:Margin=\"0.3\"/>");
    footer.AppendLine("    <Footer x:Margin=\"0.3\"/>");
    footer.AppendLine("   </PageSetup>");
    footer.AppendLine("   <Selected/>");
    footer.AppendLine("   <FreezePanes/>");
    footer.AppendLine("   <FrozenNoSplit/>");
    footer.AppendLine("   <SplitHorizontal>7</SplitHorizontal>");
    footer.AppendLine("   <TopRowBottomPane>7</TopRowBottomPane>");
    footer.AppendLine("   <ProtectObjects>False</ProtectObjects>");
    footer.AppendLine("   <ProtectScenarios>False</ProtectScenarios>");
    footer.AppendLine("  </WorksheetOptions>");
    footer.AppendLine(" </Worksheet>");
    footer.AppendLine("</Workbook>");

    #endregion

    context.Response.ContentType = "application/excel";
    context.Response.AddHeader("Content-disposition", "attachment; filename=\"report.xls\"");
    string excel = header.ToString() + styles.ToString() + title.ToString() + content.ToString() + footer.ToString();
    HttpContext.Current.Response.BinaryWrite(UTF8Encoding.UTF8.GetBytes(excel));
}

Here is the result XML: http://www.gis34.dk/docs/report.xls
Does anyone have a clue to why Excel won't open this document?

A: I don't think it is a limitation as we know Excel is not limited at such few number of rows. It is almost certainly a problem with the data/escaping of special characters... The way you are adding lines with AppendLine is not safe... Aren't there '<' or other invalid XML characters in your data?
I would advise you to use a proper XLS component so that all this problems would be taken care of... There are LOTs of free, open-source and commercial offers out there.
Take a look at this: http://nugetmusthaves.com/Tag/Excel

A: ExpandedRowCount is your issue.  Apparently it doesn't match the actual number of rows.
I removed it, and it opened just fine.
A better option would be to output the actual number of rows.


text:
Q: Nested SELECT using results from first SELECT I need to list all customers who were referred to a bookstore by another customer, listing each customer's last name and the customer# who made the referral.
Easy enough, but I'm trying to add onto the query by also listing the referring customer's first and last name from the same table and data.
Referred column is the customer# of the person who referred them.
SELECT lastname, a.referred || ' ' || a.firstname || ' ' || a.lastname "Referred By:"
  FROM customers
    WHERE referred =
    (SELECT a.firstname, a.lastname FROM customers WHERE customer# = a.referred);

My expected result is something like
Lastname: Referred By:

Gina      1003 Leila Smith

Getting this error:
ORA-00904: "A"."LASTNAME": invalid identifier

00904. 00000 -  "%s: invalid identifier"

Am I correct in thinking I might need to do the nested select in the SELECT clause itself?
Thank you.

A: You can self-join the table.
Assuming that the  customers table has a column called referred that contains the customer# of the referring customer:
SELECT
    c.lastname,
    c.referred || ' ' || r.firstname || ' ' || r.lastname "Referred By:"
FROM customers c
INNER JOIN customers r ON r.customer# = c.referred

A: It is much easier using CONNECT BY clause -
SELECT PRIOR lastname,
       referred || ' ' || firstname || ' ' || lastname "Referred By:"
FROM customers
CONNECT BY PRIOR customer# = referred