问:
How do I "apply" to results of a parameter-less function
This works:

```<code>List(3, 1, 2).sorted apply 1
res1: Int = 2
</code>```

And this works:

```<code>var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2
</code>```

but this doesn't:

```<code>List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^
</code>```

And even parentheses don't clue the parser in to what I want:

```<code>(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)
</code>```

It seems like a natural expression.  What am I doing wrong?

答:
This works:

(Listed(3, 1, 2).sorted _)(1),

but I'm not sure whether it is much more convenient to use than:

Listed(3, 1, 2).sorted apply 1.

I'd go for the latter anyways.

Body:
This works:

List(3, 1, 2).sorted apply 1
res1: Int = 2

And this works:

var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2

but this doesn't:

List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^

And even parentheses don't clue the parser in to what I want:

(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)

It seems like a natural expression.  What am I doing wrong?


来源: stackexchange

问:
SQL Server, trying to add constraint while creating table, wherein there is a field 'ssn_nr' for ssn's
I have created a table with a column ssn_nr. I have inserted ssn's with 9 digits. However, there are ssn's starting from '0' have removed itself, which resultant few ssn's showing with only 8 digits.

Example: I tried to insert ssn's like: 089562715,985624851...(having 9 digits), data type was used 'int' not null. Execution was successful, but ssn's start's with '0' automatically got removed.

Desired result: I want all ssn's should be in 9 digits, no matter if any ssn start's with having single or multiple '0' (exm for ssn: 002154698, 025489635, 000548965).

答:
You cannot insert zeros in a int field, you could use varchar(9) or treat it in the select with something like:</p>

```<code>RIGHT('000000000'+ISNULL(ssn_nr,''),9)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You cannot insert zeros in a int field, you could use varchar(9) or treat it in the select with something like:

RIGHT('000000000'+ISNULL(ssn_nr,''),9)


问:
AJAX Submit Form and Time Without Refresh
I have a simple form that submits some data to a Google Sheet via AJAX, this is working successfully.

I need to send the current time. The time value does send, but unless the page is refreshed, it remains the same.

Presumably because I am using PHP in order to store the time and date in hidden inputs, and these values won't update until I refresh the page.

I'm unable to refresh the page, it must remain static.

How can I store the date and time values as real-time and send with the AJAX?

My code is below;

HTML / PHP

```<code><form id="feedbackFormGood" name="feedbackFormGood">
    <input hidden="true" name="Feedback" type="text" value="GOOD">
    <input hidden="true" name="Date" type="text" value="<?php echo date('j/n/Y'); ?>">
    <input hidden="true" name="Time" type="text" value="<?php echo date('H:i:s'); ?>">
    <input src="images/feedback/happy.png" type="image">
</form>
</code>```

AJAX

```<code>$(document).ready(function() {
    var request;
    $("#feedbackFormGood").submit(function(event)
    {
        event.preventDefault();
        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        request = $.ajax(
        {
            url: "MyURL", // this is a Google Sheet
            type: "post",
            data: serializedData
        });
    });
});
</code>```

Any advice is appreciated.

答:
Try adding the date and time using JavaScript</p>

```<code>$(document).ready(function() {
    var request;
    $("#feedbackFormGood").submit(function(event)
    {
        event.preventDefault();
        var today = new Date();
        var date = today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear();
        var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()
        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        request = $.ajax(
        {
            url: "MyURL", // this is a Google Sheet
            type: "post",
            data: serializedData + '&Date=' + date + '&Time=' + time
        });
    });
});
</code>```

Body:
I have a simple form that submits some data to a Google Sheet via AJAX, this is working successfully.

I need to send the current time. The time value does send, but unless the page is refreshed, it remains the same.

Presumably because I am using PHP in order to store the time and date in hidden inputs, and these values won't update until I refresh the page.

I'm unable to refresh the page, it must remain static.

How can I store the date and time values as real-time and send with the AJAX?

My code is below;

HTML / PHP

<form id="feedbackFormGood" name="feedbackFormGood">
    <input hidden="true" name="Feedback" type="text" value="GOOD">
    <input hidden="true" name="Date" type="text" value="<?php echo date('j/n/Y'); ?>">
    <input hidden="true" name="Time" type="text" value="<?php echo date('H:i:s'); ?>">
    <input src="images/feedback/happy.png" type="image">
</form>

AJAX

$(document).ready(function() {
    var request;
    $("#feedbackFormGood").submit(function(event)
    {
        event.preventDefault();
        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        request = $.ajax(
        {
            url: "MyURL", // this is a Google Sheet
            type: "post",
            data: serializedData
        });
    });
});

Any advice is appreciated.

Body:
Try adding the date and time using JavaScript

$(document).ready(function() {
    var request;
    $("#feedbackFormGood").submit(function(event)
    {
        event.preventDefault();
        var today = new Date();
        var date = today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear();
        var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()
        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        request = $.ajax(
        {
            url: "MyURL", // this is a Google Sheet
            type: "post",
            data: serializedData + '&Date=' + date + '&Time=' + time
        });
    });
});


问:
.net data reader in background worker
I am trying to query a DB in a background worker in order for my form not to be frozen while the query is being processed. However since I moved to this solution, the data reader only retrieves the first result of the query instead of 400.000+ ...

```<code>Public Class Form5
    Public con As OdbcConnection = Form1.con
    Public cmd As New OdbcCommand
    Public dr As OdbcDataReader

    Dim bw As BackgroundWorker = New BackgroundWorker
    Public Delegate Sub PictureVisibilityDelegate(ByVal visibility As
    Boolean)
    Dim ChangePictureVisibility As PictureVisibilityDelegate

    Private Sub Form5_Load(sender As Object, e As EventArgs) Handles
        MyBase.Load
        AddHandler bw.DoWork, AddressOf bw_DoWork
        AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
        ChangePictureVisibility = AddressOf ChangeVisibility

        bw.RunWorkerAsync()

    End Sub

    Public Sub ChangeVisibility(ByVal visibility As Boolean)
        PictureLoader.Visible = visibility
        PictureLoader.SendToBack()
    End Sub

    Private Sub bw_DoWork(sender As Object, e As DoWorkEventArgs)
        Me.Invoke(ChangePictureVisibility, True)

        Dim SQL As String = "SELECT xxx, xxx, xxx from xxx.xxx where xxx.xxx
        = """ & dt1.Rows(Form1.line).Item(4) & """"
        cmd = New OdbcCommand(SQL, con)

        dr = cmd.ExecuteReader

        While dr.Read()
           DataGridView1.Rows.Add(New String()
           {dr(0).ToString,dr(1).ToString & " %", dr(2).ToString})
        End While

     End Sub

    Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As
    RunWorkerCompletedEventArgs)
        Me.Invoke(ChangePictureVisibility, False)
    End Sub

End Class
</code>```

I really can't wrap my head around that and couldn't find any similar problem on the net, so any comment would be really appreciated...

答:
Populate a DataTable in your DoWork event handler and assign that to e.Result.  Get it back from e.Result in the RunWorkerCompleted event handler and bind it to your grid.

The DoWork event handler is where you do the background work. Anything to do with the UI is NOT background work. The RunWorkerCompleted event handler is executed on the UI thread, so that's where you update the UI once the background work is done.

In the DoWork event handler:

```<code>Dim table As New DataTable

table.Load(dr)
e.Result = table
</code>```

In the RunWorkerCompleted event handler:

```<code>DataGridView1.DataSource = e.Result
</code>```

Title: .net data reader in background worker

Body:
I am trying to query a DB in a background worker in order for my form not to be frozen while the query is being processed. However since I moved to this solution, the data reader only retrieves the first result of the query instead of 400.000+ ...

Public Class Form5
    Public con As OdbcConnection = Form1.con
    Public cmd As New OdbcCommand
    Public dr As OdbcDataReader

    Dim bw As BackgroundWorker = New BackgroundWorker
    Public Delegate Sub PictureVisibilityDelegate(ByVal visibility As
    Boolean)
    Dim ChangePictureVisibility As PictureVisibilityDelegate

    Private Sub Form5_Load(sender As Object, e As EventArgs) Handles
        MyBase.Load
        AddHandler bw.DoWork, AddressOf bw_DoWork
        AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
        ChangePictureVisibility = AddressOf ChangeVisibility

        bw.RunWorkerAsync()

    End Sub

    Public Sub ChangeVisibility(ByVal visibility As Boolean)
        PictureLoader.Visible = visibility
        PictureLoader.SendToBack()
    End Sub

    Private Sub bw_DoWork(sender As Object, e As DoWorkEventArgs)
        Me.Invoke(ChangePictureVisibility, True)

        Dim SQL As String = "SELECT xxx, xxx, xxx from xxx.xxx where xxx.xxx
        = """ & dt1.Rows(Form1.line).Item(4) & """"
        cmd = New OdbcCommand(SQL, con)

        dr = cmd.ExecuteReader

        While dr.Read()
           DataGridView1.Rows.Add(New String()
           {dr(0).ToString,dr(1).ToString & " %", dr(2).ToString})
        End While

     End Sub

    Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As
    RunWorkerCompletedEventArgs)
        Me.Invoke(ChangePictureVisibility, False)
    End Sub

End Class

I really can't wrap my head around that and couldn't find any similar problem on the net, so any comment would be really appreciated...

Body:
Populate a DataTable in your DoWork event handler and assign that to e.Result.  Get it back from e.Result in the RunWorkerCompleted event handler and bind it to your grid.

The DoWork event handler is where you do the background work. Anything to do with the UI is NOT background work. The RunWorkerCompleted event handler is executed on the UI thread, so that's where you update the UI once the background work is done.

In the DoWork event handler:

Dim table As New DataTable

table.Load(dr)
e.Result = table

In the RunWorkerCompleted event handler:

DataGridView1.DataSource = e.Result


问:
java.lang.IllegalArgumentException for specific URL
I am getting this error when calling API, but this error is not coming to the app the API URLs.

java.lang.IllegalArgumentException: Illegal character in scheme
  specific part at index 6: https:

答:
This problem with come if URL having space ,so please check your API URL is it having space , and try like this

```<code>String URL=URLEncoder.encode(path,."UTF-8");
</code>```

And finally use the above URL for API call.

Body:
This problem with come if URL having space ,so please check your API URL is it having space , and try like this

String URL=URLEncoder.encode(path,."UTF-8");

And finally use the above URL for API call.


问:
How can I prevent duplicates from printing
In the following code, I would like to remove the duplicates inside the columns cd,id,se,nt,dd. Usually, when duplicates appear, the appear in the NT column with a "-" first. But in general they are duplicates in all columns. Thanks in advance!</p>

```<code>PROC PRINT DATA=data.data2;
var cd id SE NT DD;
format notional commax32.;
run;
</code>```

答:
You could just add a proc sort before the print with the nodupkey option to remove any duplicates:

```<code>proc sort data=data.data2 nodupkey;
  by cd id se nt dd;
run;
</code>```

Or, if you want to preserve your original data, you can output the result of the proc sort to a new table:

```<code>proc sort data=data.data2 out=data3 nodupkey;
  by cd id se nt dd;
run;

PROC PRINT DATA=data3;
var cd id SE NT DD;
format notional commax32.;
run;
</code>```

Body:
In the following code, I would like to remove the duplicates inside the columns cd,id,se,nt,dd. Usually, when duplicates appear, the appear in the NT column with a "-" first. But in general they are duplicates in all columns. Thanks in advance!

PROC PRINT DATA=data.data2;
var cd id SE NT DD;
format notional commax32.;
run;

Body:
You could just add a proc sort before the print with the nodupkey option to remove any duplicates:

proc sort data=data.data2 nodupkey;
  by cd id se nt dd;
run;

Or, if you want to preserve your original data, you can output the result of the proc sort to a new table:

proc sort data=data.data2 out=data3 nodupkey;
  by cd id se nt dd;
run;

PROC PRINT DATA=data3;
var cd id SE NT DD;
format notional commax32.;
run;


问:
How can I get n items of IPublishedContent in Umbraco 7
In my Umbraco app I need to get 3 news feed items on my homepage.

I am able to get the full list by doing:

IEnumerable<IPublishedContent> newsItems = CurrentPage.newsRootPage.Children as IEnumerable<IPublishedContent>;

I tried using Linq to get 3 items using the Take method:

IEnumerable<IPublishedContent> newsItems = CurrentPage.newsRootPage.Children.Take(3) as IEnumerable<IPublishedContent>;

but I get an exception saying:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Collections.Generic.List' does not contain a definition for 'Take''

I have tried importing the Linq namespace at the top of the razor view (@using System.Linq;) but this doesn't help.

Can anyone help?

答:
Although you didn't say so, I assume that CurrentPage.newsRootPage.Children is a List. Although a List implements IEnumerable, it doesn't implement IEnumerable<T>.

However, if you are certain that every child implements IPublishedContent you can easily convert your sequence to an IEnumerable<IPublishedContent>. This is done using Enumerable.Cast. After that you can use Enumerable.Take:

```<code>IEnumerable<IPublishedContent> newsItems = CurrentPage.newsRootPage.Children
    .Cast<IPublishedContent>()
    .Take(3)
</code>```

Body:
Although you didn't say so, I assume that CurrentPage.newsRootPage.Children is a List. Although a List implements IEnumerable, it doesn't implement IEnumerable<T>.

However, if you are certain that every child implements IPublishedContent you can easily convert your sequence to an IEnumerable<IPublishedContent>. This is done using Enumerable.Cast. After that you can use Enumerable.Take:

IEnumerable<IPublishedContent> newsItems = CurrentPage.newsRootPage.Children
    .Cast<IPublishedContent>()
    .Take(3)


问:
Hosting WCF Service within WinForm Application doesn't work when running the application executable

Over the past few weeks I have developed a 64-bit WinForms application that needs to communicate with a 32-bit DLL (job specs require it).

After doing some reading around the internet and finding out that there is not going to be any fun way of doing this, I decided to go with hosting a WCF Service Application within my WinForms application for communicating to the 32-bit DLL... or so I thought I was doing.

During development (while running within Visual Studio) it has been working really well, but of course, now that I need to deploy, I am running into problems. I am having trouble getting a strong enough understanding of WCF Services to know if I am going about this in a terrible way or if I am just missing some minute detail.

I created the project as Admin. After development was finished I tried to run the WinForm executable (both debug and release), WindowsFormsApplication1.exe. The application started up, but after I tried to complete a task involving the use of the WCF service, an exception was thrown:

This has led me to believe that Visual Studio was doing the hosting of the service during development instead of the WinForm application, or my configs and/or directory structures are incorrect.

[UPDATED] WCF Service Web.config:

```<code><?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="2147483647"/>
  </system.web>

  <system.net>
    <defaultProxy>
      <proxy usesystemdefault="False"/>
    </defaultProxy>
  </system.net>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="xml"
           type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="C:\logs\Traces.svclog" />
    </sharedListeners>
  </system.diagnostics>

  <system.serviceModel>
    <diagnostics wmiProviderEnabled="true">
      <messageLogging
           logEntireMessage="true"
           logMalformedMessages="true"
           logMessagesAtServiceLevel="true"
           logMessagesAtTransportLevel="true"
           maxMessagesToLog="3000"
       />
    </diagnostics>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadadiscovery>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

<services>
  <service name="ServiceReference1.Service1" behaviorConfiguration="metadadiscovery">
    <endpoint address="" binding="basicHttpBinding" contract="ServiceReference1.IService1"></endpoint>
  </service>
</services>

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="false"/>
  </system.webServer>

</configuration>
</code>```

WinForm App.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2"
        name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3"
        name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
        name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
  <appSettings>
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>
</code>```

Directory Where EXE resides:

The directory containing the WCF Service resides within the directory WcfService1 from the image above.

I have mostly been using the following method of instantiating the service:

```<code>ServiceReference1.Service1Client = new ServiceReference1.SErvice1Client();
</code>```

Once I tried to switch to using a service host (below), but when I used that method, the service would timeout whenever it tried to communicate to the DLL.

```<code>Uri address = new Uri("http://localhost:44848/Service1.svc");
ServiceHost host = new ServiceHost(typeof(ServiceReference1.Service1Client), address);
host.Open();
</code>```

And then I closed the host later. At this point, I am willing to try anything to get this working.

[EDIT] Below is the code of my WindowsFormsApplication1.exe.config file. All three contracts are giving the warning that they're "invalid according to its datatype 'clientContractType'". I think this could be the source of my problems, but I do not know why it is showing this warning:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2" name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3" name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
</configuration>
</code>```

Thank you for any help and guidance you can provide.

答:
There is no endpoint configured for your service.

```<code>    <behaviors>
          <serviceBehaviors>
            <behavior name="metadadiscovery">
              <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
     <service name="ServiceReference2.Yourimplementingservice" behaviorConfiguration="metadadiscovery">
      <endpoint address="" binding="basicHttpBinding" contract="ServiceReference2.IService2">
       </endpoint>
</code>```

Above I have configured for Service2 ,similarly you have to configure for Service1 and Service3.

Body:
Over the past few weeks I have developed a 64-bit WinForms application that needs to communicate with a 32-bit DLL (job specs require it).

After doing some reading around the internet and finding out that there is not going to be any fun way of doing this, I decided to go with hosting a WCF Service Application within my WinForms application for communicating to the 32-bit DLL... or so I thought I was doing.

During development (while running within Visual Studio) it has been working really well, but of course, now that I need to deploy, I am running into problems. I am having trouble getting a strong enough understanding of WCF Services to know if I am going about this in a terrible way or if I am just missing some minute detail.

I created the project as Admin. After development was finished I tried to run the WinForm executable (both debug and release), WindowsFormsApplication1.exe. The application started up, but after I tried to complete a task involving the use of the WCF service, an exception was thrown:

This has led me to believe that Visual Studio was doing the hosting of the service during development instead of the WinForm application, or my configs and/or directory structures are incorrect.

[UPDATED] WCF Service Web.config:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="2147483647"/>
  </system.web>

  <system.net>
    <defaultProxy>
      <proxy usesystemdefault="False"/>
    </defaultProxy>
  </system.net>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="xml"
           type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="C:\logs\Traces.svclog" />
    </sharedListeners>
  </system.diagnostics>

  <system.serviceModel>
    <diagnostics wmiProviderEnabled="true">
      <messageLogging
           logEntireMessage="true"
           logMalformedMessages="true"
           logMessagesAtServiceLevel="true"
           logMessagesAtTransportLevel="true"
           maxMessagesToLog="3000"
       />
    </diagnostics>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadadiscovery>

          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

<services>
  <service name="ServiceReference1.Service1" behaviorConfiguration="metadadiscovery">
    <endpoint address="" binding="basicHttpBinding" contract="ServiceReference1.IService1"></endpoint>
  </service>
</services>

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>

    <directoryBrowse enabled="false"/>
  </system.webServer>

</configuration>

WinForm App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2"
        name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3"
        name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
        name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
  <appSettings>
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

Directory Where EXE resides:

The directory containing the WCF Service resides within the directory WcfService1 from the image above.

I have mostly been using the following method of instantiating the service:

ServiceReference1.Service1Client = new ServiceReference1.SErvice1Client();

Once I tried to switch to using a service host (below), but when I used that method, the service would timeout whenever it tried to communicate to the DLL.

Uri address = new Uri("http://localhost:44848/Service1.svc");
ServiceHost host = new ServiceHost(typeof(ServiceReference1.Service1Client), address);
host.Open();

And then I closed the host later. At this point, I am willing to try anything to get this working.

[EDIT] Below is the code of my WindowsFormsApplication1.exe.config file. All three contracts are giving the warning that they're "invalid according to its datatype 'clientContractType'". I think this could be the source of my problems, but I do not know why it is showing this warning:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2" name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3" name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
</configuration>

Thank you for any help and guidance you can provide.

Body:
There is no endpoint configured for your service.

    <behaviors>
          <serviceBehaviors>
            <behavior name="metadadiscovery">
              <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
     <service name="ServiceReference2.Yourimplementingservice" behaviorConfiguration="metadadiscovery">
      <endpoint address="" binding="basicHttpBinding" contract="ServiceReference2.IService2">
       </endpoint>

Above I have configured for Service2 ,similarly you have to configure for Service1 and Service3.


问:
Need to display dynamic text generated from server onto UI within a TextArea(with syntax highlighting)

I am trying to push a randomly generated string onto a textarea on UI. New to HTML/Shiny/JS but I know a few basics.

My end goal is to use CodeMirror (Whole download) or ShinyAce editor classes to add syntax highlighting to the textarea but I am unable to output strings from server into the textarea. I wish to push a certain R Code in textStringToDisplay and need syntax highlighting.

Please put the following files in the www folder of the app.R:

codemirror.css

cobalt.css

codemirror.js (I could not find
    this file on GitHub, please use the download link above, extract and
    look in the lib folder)

r.js

Please let me know if you need more information or if I should rephrase any parts of this. Thanks in advance.

```<code>library(shiny)

if (interactive()) {

  ui <- shinyUI(
    fluidPage(
      tags$head(tags$title("Title"),
                tags$link(rel = "stylesheet", href = "codemirror.css"),
                tags$link(rel = "stylesheet", href = "cobalt.css"),
                tags$script(src = "codemirror.js"),
                tags$script(src = "r.js")
      ),
      tags$textarea(id="textBox", name = "Feedback", textOutput(outputId = "textStringToDisplay")),
      tags$script(
        'var editorR = CodeMirror.fromTextArea(textBox, {
        mode: "r",
        lineNumbers: true,
        smartindent: true
});
        editorR.setOption("theme", "cobalt");
        editorR.setSize("50%","100%");')))

  server <- function(input, output){
    output$textStringToDisplay <- renderText(paste0(sample(letters,15),collapse = ""))
  }

  shinyApp(ui = ui, server = server)
}
</code>```

答:
Hi I have commented out you css and java scripts because I don't the where the problem. Your problem is the same as in this question

How to create a variable hyperlink in an R Shiny App

Here is a working version of your code

```<code>library(shiny)

if (interactive()) {

  ui <- shinyUI(
    fluidPage(
      tags$head(tags$title("Title")
                # tags$link(rel = "stylesheet", href = "codemirror.css"),
                # tags$link(rel = "stylesheet", href = "cobalt.css"),
                # tags$script(src = "codemirror.js"),
                # tags$script(src = "r.js")
      ),
      uiOutput(outputId = "textStringToDisplay")
#       tags$script(
#         'var editorR = CodeMirror.fromTextArea(textBox, {
#         mode: "r",
#         lineNumbers: true,
#         smartindent: true
# });
#         editorR.setOption("theme", "cobalt");
#         editorR.setSize("50%","100%");')
))

  server <- function(input, output){
    output$textStringToDisplay <- renderUI(
      tags$textarea(id="textBox", name = "Feedback", paste0(sample(letters,15),collapse = "")))
  }

  shinyApp(ui = ui, server = server)
}
</code>```

Body:
I am trying to push a randomly generated string onto a textarea on UI. New to HTML/Shiny/JS but I know a few basics.

My end goal is to use CodeMirror (Whole download) or ShinyAce editor classes to add syntax highlighting to the textarea but I am unable to output strings from server into the textarea. I wish to push a certain R Code in textStringToDisplay and need syntax highlighting.

Please put the following files in the www folder of the app.R:

codemirror.css

cobalt.css

codemirror.js (I could not find
    this file on GitHub, please use the download link above, extract and
    look in the lib folder)

r.js

Please let me know if you need more information or if I should rephrase any parts of this. Thanks in advance.

library(shiny)

if (interactive()) {

  ui <- shinyUI(
    fluidPage(
      tags$head(tags$title("Title"),
                tags$link(rel = "stylesheet", href = "codemirror.css"),
                tags$link(rel = "stylesheet", href = "cobalt.css"),
                tags$script(src = "codemirror.js"),
                tags$script(src = "r.js")
      ),
      tags$textarea(id="textBox", name = "Feedback", textOutput(outputId = "textStringToDisplay")),
      tags$script(
        'var editorR = CodeMirror.fromTextArea(textBox, {
        mode: "r",
        lineNumbers: true,
        smartindent: true
});
        editorR.setOption("theme", "cobalt");
        editorR.setSize("50%","100%");')))

  server <- function(input, output){
    output$textStringToDisplay <- renderText(paste0(sample(letters,15),collapse = ""))
  }

  shinyApp(ui = ui, server = server)
}

Body:
Hi I have commented out you css and java scripts because I don't the where the problem. Your problem is the same as in this question

How to create a variable hyperlink in an R Shiny App

Here is a working version of your code

library(shiny)

if (interactive()) {

  ui <- shinyUI(
    fluidPage(
      tags$head(tags$title("Title")
                # tags$link(rel = "stylesheet", href = "codemirror.css"),
                # tags$link(rel = "stylesheet", href = "cobalt.css"),
                # tags$script(src = "codemirror.js"),
                # tags$script(src = "r.js")
      ),
      uiOutput(outputId = "textStringToDisplay")
#       tags$script(
#         'var editorR = CodeMirror.fromTextArea(textBox, {
#         mode: "r",
#         lineNumbers: true,
#         smartindent: true
# });
#         editorR.setOption("theme", "cobalt");
#         editorR.setSize("50%","100%");')
))

  server <- function(input, output){
    output$textStringToDisplay <- renderUI(
      tags$textarea(id="textBox", name = "Feedback", paste0(sample(letters,15),collapse = "")))
  }

  shinyApp(ui = ui, server = server)
}


问:
Non-static method calling inside a class is not Deprecated in PHP?
As PHP manual stated

As of PHP 7.0.0 calling a non-static method statically has been
  generally deprecated (even if called from a compatible context).

To check this statement-

I am calling a Non-static method outside a class then its generating error

```<code>class A{
    public function foo(){
        echo "testing<br/>";
    }
}
A::foo();
</code>```

Deprecated: Non-static method A::foo() should not be called statically

But when I am calling a Non-static method inside a class then its not generating Deprecated error

```<code>class A{
    public function foo(){
        echo "testing<br/>";
    }

    public function Display(){
        A::foo();    //calling a Non-static method inside statically
        self::foo(); //calling a Non-static method inside statically
    }
}
$obj=new A();
$obj->Display();
</code>```

Does it deprecated only when calling statically from outside the class?

答:
The Scope Resolution operator, or the double colon operator, isn't just used for static calls.

Inside a class the operator can be used to reference the class itself in a non-static way.

This is what you have done for self::foo() and A::foo();
 To make a static call inside the class you need to use the static::<methodName> statement

Take a look here: http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

Body:
As PHP manual stated

As of PHP 7.0.0 calling a non-static method statically has been
  generally deprecated (even if called from a compatible context).

To check this statement-

I am calling a Non-static method outside a class then its generating error

class A{
    public function foo(){
        echo "testing
";
    }
}
A::foo();

Deprecated: Non-static method A::foo() should not be called statically

But when I am calling a Non-static method inside a class then its not generating Deprecated error

class A{
    public function foo(){
        echo "testing
";
    }

    public function Display(){
        A::foo();    //calling a Non-static method inside statically
        self::foo(); //calling a Non-static method inside statically
    }
}
$obj=new A();
$obj->Display();

Does it deprecated only when calling statically from outside the class?


问:
The export/import issue in TypeScript
I'm learning TypeScript and want to use export/import mechanism. I have 3 .ts files and the code looks as following:

1) MyClass.ts:

```<code>/// <reference path="../Scripts/jquery.d.ts" />
/// <reference path="../Scripts/dx.all.d.ts" />
/// <reference path="../Scripts/go.d.ts" />

export class MyClass {
    render(divId: string, text: string): void {
        ...
    }
    getData(): void {
        ...
    }
}
</code>```

2) Caller.ts:

```<code>import { MyClass } from './MyClass';

export class Caller {
    execute() {
        let myClass: MyClass = new MyClass();
        myClass.render("content", "Hello World");
        myClass.getData();
    }
}
</code>```

3) Main.ts:

```<code>import { Caller } from './Caller';

window.onload = () => {
    let caller: Caller = new Caller();
    caller.execute();
};
</code>```

4) HTML:

```<code><script src="~/Scripts/MyClass.js"></script>
<script src="~/Scripts/Caller.js"></script>>
<script src="~/Scripts/Main.js"></script>
</code>```

But, nothing is displayed.

There are 3 errors:

Uncaught SyntaxError: Unexpected token export (for MyClass.js)

Uncaught SyntaxError: Unexpected token import (for Caller.js)

Uncaught SyntaxError: Unexpected token import (for Main.js)

答: Seeing the

Title: The export/import issue in TypeScript

Body:
I'm learning TypeScript and want to use export/import mechanism. I have 3 .ts files and the code looks as following:

1) MyClass.ts:

/// <reference path="../Scripts/jquery.d.ts" />
/// <reference path="../Scripts/dx.all.d.ts" />
/// <reference path="../Scripts/go.d.ts" />

export class MyClass {
    render(divId: string, text: string): void {
        ...
    }
    getData(): void {
        ...
    }
}

2) Caller.ts:

import { MyClass } from './MyClass';

export class Caller {
    execute() {
        let myClass: MyClass = new MyClass();
        myClass.render("content", "Hello World");
        myClass.getData();
    }
}

3) Main.ts:

import { Caller } from './Caller';

window.onload = () => {
    let caller: Caller = new Caller();
    caller.execute();
};

4) HTML:

>

But, nothing is displayed.

There are 3 errors:

Uncaught SyntaxError: Unexpected token export (for MyClass.js)

Uncaught SyntaxError: Unexpected token import (for Caller.js)

Uncaught SyntaxError: Unexpected token import (for Main.js)

Body:
Seeing the <script>, I guess it's in a web application. And the files are using ES6 modules syntax.

Currently, I think that only Google Chrome supports natively ES6 modules. No other browser support any kind of module (ES6, CommonJS, AMD, SystemJs, UMD, ...). If the app is meant to be executed only in Chrome, you can set the tsconfig option module='ES6'.

Else, use either:

TypeScript namespaces instead of modules

recommended for a small project and/or short life cycle

a module loader like SystemJs to load your main script and its dependancies

a bit more complicated

implies more HTTP requests to load the HTML page

a module bundler like WebPack or the new in the place Rollup to compile in advance your ES6 modules into plain javascript file(s) understandable by any browser

the more complicated solution

see this tutorial for help


问:
I can not access phpMyAdmin on XAMPP
I have my XAMMP installed on WINDOWS 8. I can access my localhost like thislocalhost:800 I am trying to access phpmyadmin from XAMPP but when I am clicking on the button or type in  http://localhost:800/phpmyadmin/  I am just getting a white homepage without anything on it?! Does anyone know whats gonig on? It worked fine yesterday.

答:
Open phpMyAdmin>config.inc.php in your favourite text editor.

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

browse localhost/phpmyadmin.
and username will be root, no password

Title: I can not access phpMyAdmin on XAMPP


问:
css input corner triangle label with border radius
I would like to create an triangle label inside input (text) element exactly like this:

What I managed to do so far is this:

How can I put this triangle "under" the input border to, let's just say, keep border radius from input cutting the edge of this triangle?

This is my code:

```<code><div class="input">
   <label>email adress</label>
   <div class="note">
      <p>*</p>
      <input type="text" placeholder="Enter your email adress">
   </div>
</div>

.input {
   display: flex;
   flex-direction: column;
   width: 100%;
}
.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}
</code>```

I imagine there is no way to give border-radius to this triangle itself without losing its shape, am I right?

答:
I added position absolute for your P tag and postioned it in the corner.
The border radius is achieved by adding a border radius to your .note wrapper and setting overflow:hidden.

.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
   border-radius: 5px;
   overflow:hidden;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
   z-index:0;

}
.note p{
  position: absolute;
  right: 5px;
  top: 5px;
  color:white;
  z-index:1;
  margin:0;
  padding:0;
}

label {
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input">
   <label>email address</label>
   <div class="note">
      <p>*</p>
      <input type="text" placeholder="Enter your email adress">
   </div>
</div></code>```

Body:
I would like to create an triangle label inside input (text) element exactly like this:

What I managed to do so far is this:

How can I put this triangle "under" the input border to, let's just say, keep border radius from input cutting the edge of this triangle?

This is my code:

   email adress

*

      <input type="text" placeholder="Enter your email adress">

.input {
   display: flex;
   flex-direction: column;
   width: 100%;
}
.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}

I imagine there is no way to give border-radius to this triangle itself without losing its shape, am I right?

Body:
I added position absolute for your P tag and postioned it in the corner.
The border radius is achieved by adding a border radius to your .note wrapper and setting overflow:hidden.

.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
   border-radius: 5px;
   overflow:hidden;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
   z-index:0;

}
.note p{
  position: absolute;
  right: 5px;
  top: 5px;
  color:white;
  z-index:1;
  margin:0;
  padding:0;
}

label {
  display:block;
}

<div class="input">
   <label>email address</label>
   <div class="note">
      <p>*</p>
      <input type="text" placeholder="Enter your email adress">
   </div>
</div>

ContentLicense: CC BY-SA 4.0


问:
looping through an array backwards from current position
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

```<code>// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}
</code>```

Main Activity.java

```<code>     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }
</code>```

答:
You need to don't mess logic of your application with view logic, decouple them.
Just make class Question able to provide previous and next questions. Also according to oop principles (solid, grasp) fetch information from class and make decision outside is wrong, make class to do it's work. Oop it's about telling classes to do things, not work instead of them.

```<code>class Questions {
    private int index = 0;

    private String[] mQuestions;

    //better to don't hardcode and provide questions in constructor
    public Question(String[] questions) {
        this.questions = questions;

    }

    //we don't need this method
    int getLength(){
        return mQuestions.length;
    }

    //provide human readable information about current position in question list
    // when you want to provide this information to user introduce label field in activity
    public String currentPosition() {
        int questionPosition = index + 1;
        int questionsLength = mQuestions.length;
        return String.format("current question number is %d from %d" , questionPosition, questionsLength);
    }

    //return next question when available, if next not available returns last question from array
    public String next() {
        int lastIndex = mQuestions.length - 1;
        if(index < lastIndex) {
            index++;
        }
        return mQuestions[index];
    }

    //return current question
    public String current() {
        return mQuestions[index];
    }

    //return previous question when available, if previous not available returns first question from array
    public String previous() {
        int firstIndex = 0;
        if(index > firstIndex) {
            index--;
        }
        return mQuestions[index];

    }

}
</code>```

And how to use it in Activity:

```<code>public class MainActivity extends AppCompatActivity {
    //better to don't hardcode here, but provide this class from
    //constructor of MainActivity just like questions array provide
    // to constructor in Questions class
    private Questions questions = new Questions(new String[]{"q1","q2"});
    private Button mPrevious;
    private Button mNext;
    private TextView mQuestionText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_beginner_review);
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        Intent intent = getIntent();

        //when create Activity populate question field with first question
        mQuestionText.setText(questions.current());

        mNext.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mQuestionText.setText(questions.next());
            }
        });

        mPrevious.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mQuestionText.setText(questions.previous());
            }
        });
    }
}
</code>```

p.s. you may improve this code further in way to introduce Observer pattern, Activity is a view, Questions is model.

Body:
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}

Main Activity.java

     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }

Body:
You need to don't mess logic of your application with view logic, decouple them.
Just make class Question able to provide previous and next questions. Also according to oop principles (solid, grasp) fetch information from class and make decision outside is wrong, make class to do it's work. Oop it's about telling classes to do things, not work instead of them.

class Questions {
    private int index = 0;

    private String[] mQuestions;

    //better to don't hardcode and provide questions in constructor
    public Question(String[] questions) {
        this.questions = questions;

    }

    //we don't need this method
    int getLength(){
        return mQuestions.length;
    }

    //provide human readable information about current position in question list
    // when you want to provide this information to user introduce label field in activity
    public String currentPosition() {
        int questionPosition = index + 1;
        int questionsLength = mQuestions.length;
        return String.format("current question number is %d from %d" , questionPosition, questionsLength);
    }

    //return next question when available, if next not available returns last question from array
    public String next() {
        int lastIndex = mQuestions.length - 1;
        if(index < lastIndex) {
            index++;
        }
        return mQuestions[index];
    }

    //return current question
    public String current() {
        return mQuestions[index];
    }

    //return previous question when available, if previous not available returns first question from array
    public String previous() {
        int firstIndex = 0;
        if(index > firstIndex) {
            index--;
        }
        return mQuestions[index];

    }

}

And how to use it in Activity:

public class MainActivity extends AppCompatActivity {
    //better to don't hardcode here, but provide this class from
    //constructor of MainActivity just like questions array provide
    // to constructor in Questions class
    private Questions questions = new Questions(new String[]{"q1","q2"});
    private Button mPrevious;
    private Button mNext;
    private TextView mQuestionText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_beginner_review);
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        Intent intent = getIntent();

        //when create Activity populate question field with first question
        mQuestionText.setText(questions.current());

        mNext.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mQuestionText.setText(questions.next());
            }
        });

        mPrevious.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mQuestionText.setText(questions.previous());
            }
        });
    }
}

p.s. you may improve this code further in way to introduce Observer pattern, Activity is a view, Questions is model.


问:
What does "-" do in Powershell
I'm new to powershell and I'm still trying to understand the syntax.
In a command like this

```<code>Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }
</code>```

What does - actually do?
Sometimes it is there, sometimes not, and I just don't understand what purpose it has xD

答:
The hyphen character in PowerShell has a variety of uses that are context specific. It is primarily used in cmdlet names, parameters, operators and of course as a character literal.

CMDLet names

It is commonly used as a verb-noun separator e.g. Get-ChildItem. This is an encouraged practice when making custom functions and cmdlets as well.

Parameters

Used to tell the parser that a word denotes a parameter e.g. Rename-Item -NewName. In the example it is -NewName

Operators

This is a broad section but you will see the hyphen denote operators like -replace in your code sample. It does not always have a keyword associated either which is the case with arithmetic operators (-) and assignment operators (-=). You will also see the hyphen with comparison, containment, pattern-matching/text and logical/bitwise operators.

Title: What does "-" do in Powershell

Body:
I'm new to powershell and I'm still trying to understand the syntax.
In a command like this

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }

What does - actually do?
Sometimes it is there, sometimes not, and I just don't understand what purpose it has xD


问:
$(find) not working consistently
I have a search box on a website that uses an AJAX extender with a webservice.
It works perfectly on the home page.
http://www.as-technology.co.uk.

I have the same control on a subsection page at
https://www.as-technology.co.uk/toner-cartridges/printer/brother

This is the exact same control, but the page is one level lower in the file hierarchy(not in the root folder but a sub folder).

I have narrowed down the problem to do with the $(find) javascript function as in the second webpage it can't find the AJAX extender called "dp1". In the first page example(default page) it does.

The javascript function called UpdateControl

```<code><script type="text/javascript">
function UpdateControl(value) {
    var behavior = $find('dp1');
    if (behavior) {
        behavior.populate(value);
    }
    return false;
}
function ClearSearch() {
    var lbl = $(this).find('lblSearchResults');
    lbl.value = "";
    return false;
}
</code>```

 On the second page the var "behaviour" is null and so the populate doesn't work.

The control's code is this.

```<code> <%@ Control Language="C#" AutoEventWireup="true"
    CodeFile="SearchBoxWithService.ascx.cs"
    Inherits="MB.ASTechnology.UI.Controls.SearchBoxWithService" %>
    <%@ Import Namespace="MB.ASTechnology.UI" %>

    <script type="text/javascript">
    function UpdateControl(value) {
        var behavior = $find('dp1');
        if (behavior) {
            behavior.populate(value);
        }
        return false;
    }
    function ClearSearch() {
        var lbl = $find('lblSearchResults');
        lbl.value = "";
        return false;
    }
     </script>

    <asp:Panel ID="Panel1" runat="server" DefaultButton="btnGetHtml"
    style="float:left;" >

    <div class="input-append">
        <input class="span2" id="txtGetHtml" type="text"  placeholder="Brand & printer model or cartridge code" style="width: 250px;height:35px;"  />
        <asp:Button  CssClass="btn btn-primary" ID="btnGetHtml" UseSubmitBehavior="true"  runat="server" OnClientClick="return UpdateControl(txtGetHtml.value)" Text="Search" />
        <asp:Button  CssClass="btn btn-default" ID="btnClearSearch" UseSubmitBehavior="true"  runat="server" OnClientClick="return ClearSearch" Text="Clear" />
    </div>

    <asp:Button  CssClass="btn" ID="Button1" UseSubmitBehavior="true"  runat="server"  Text="Search" visible="false"/>
</asp:Panel>
<asp:Label ID="lblSearchResults" runat="server" Text=""></asp:Label>
<ajaxToolkit:DynamicPopulateExtender ID="dp1" runat="server" BehaviorID="dp1"
    TargetControlID="lblSearchResults" ServicePath="~/TextSearchService.asmx" ServiceMethod="DynamicPopulateMethod"
    ClearContentsDuringUpdate="true" PopulateTriggerControlID="Button1">
</ajaxToolkit:DynamicPopulateExtender>
</code>```

答: I have solved the problem. I failed to have the ajax toolscriptmanager on the page that was not working. Instead I had an ordinary asp scriptmanager. I then put line back to $find('dp1') and it worked.</p>

Title: $(find) not working consistently

Body:
I have a search box on a website that uses an AJAX extender with a webservice.
It works perfectly on the home page.
http://www.as-technology.co.uk.

I have the same control on a subsection page at
https://www.as-technology.co.uk/toner-cartridges/printer/brother

This is the exact same control, but the page is one level lower in the file hierarchy(not in the root folder but a sub folder).

I have narrowed down the problem to do with the $(find) javascript function as in the second webpage it can't find the AJAX extender called "dp1". In the first page example(default page) it does.

The javascript function called UpdateControl

    <asp:Panel ID="Panel1" runat="server" DefaultButton="btnGetHtml"
    style="float:left;" >

        <input class="span2" id="txtGetHtml" type="text"  placeholder="Brand & printer model or cartridge code" style="width: 250px;height:35px;"  />
        <asp:Button  CssClass="btn btn-primary" ID="btnGetHtml" UseSubmitBehavior="true"  runat="server" OnClientClick="return UpdateControl(txtGetHtml.value)" Text="Search" />
        <asp:Button  CssClass="btn btn-default" ID="btnClearSearch" UseSubmitBehavior="true"  runat="server" OnClientClick="return ClearSearch" Text="Clear" />

    <asp:Button  CssClass="btn" ID="Button1" UseSubmitBehavior="true"  runat="server"  Text="Search" visible="false"/>
</asp:Panel>
<asp:Label ID="lblSearchResults" runat="server" Text=""></asp:Label>
<ajaxToolkit:DynamicPopulateExtender ID="dp1" runat="server" BehaviorID="dp1"
    TargetControlID="lblSearchResults" ServicePath="~/TextSearchService.asmx" ServiceMethod="DynamicPopulateMethod"
    ClearContentsDuringUpdate="true" PopulateTriggerControlID="Button1">
</ajaxToolkit:DynamicPopulateExtender>


问:
Guarantee Multiple Instances of an Object
I really don't know how to proper name this question. I have a certain scenario where I have an object that should be disposed of whenever used. The reasons for this are twofold:

I must guarantee that every member variable (field) is initialized before any new use.

I must guarantee that there aren't two methods of this object being called at the same time, since it's not thread-safe.

Both reasons could be covered in the object, having every public method lock the same mutex and initializing every variable on a private method, which is also called on every public method.

This solution is error prone and has a side effect of serializing the access on a multi-thread scenario, since I'll be locking the object before use. Of course, the call site could then create a new instance before calling a method (removing the side effect), but it's also error prone.

So I came up with a solution that I find both clean and very weird:

My object expose static methods, that have as parameters the variables necessary to both create a new instance of the object and execute the method. This static method create a instance of the object and then call the necessary method.

Of course, the constructor is private.

The first thing that I noticed when looking at this solution is that my object is looking a lot like a procedural method, of course, since every new method call requires a new object. But the responsibilities of the object fits nicely this scheme.

My questions (finally!, I know) are:

Is there a pattern that would adhere to my requirements (always using a new instance of an object)?

Is there a pattern describing my approach? Or is it a anti-pattern?

Besides the fact that the object seems like a collection of procedural functions, is there any other reason for me not having this approach?

Thanks for any comments.

答:
There is no built-in way to ensure objects are not reused, but I can think of a number of ways you can try to encourage it.  All of thse could be gotten around if the user wanted to.

If the object has a single method that you call on it one time, then you can set a "state" inside the object when it's created, then you set the state to a "used" state after you call the method.  This has various problems, but is a possible solution.

You can force the user to "get a token" to use the object.  Then, when the object is used they have to pass that token, the object then compares the token to a "used token" list and only allows it to function if it's not there.  Again, the problem is that it basically only works if you have a single method you only call once.

Call dispose inside the object itself, essentially destorying whatever resources you create, so a second use would throw exceptions...

ContentLicense: CC BY-SA 2.5


问:
Value Error:unsupported format character 'd' (0x64) at index %Id
I tried to insert integer values in my table, But i was subjected to "Value Error"

```<code>import psycopg2

def connect():
    con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
    cur=con.cursor()
    cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL)")
    con.commit()
    con.close()

def insert(title,author,year,isbn):
    con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432'")
    cur=con.cursor()
    cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%d,%d)",(title,author,year,isbn))
    con.commit()
    con.close()

connect()
insert("the sun","helen",1997,23456777)
</code>```

答:
From  the Psycopg FAQ:

Q: I can’t pass an integer or a float parameter to my query: it says a
  number is required, but it is a number!

A: In your query string, you always have to use %s placeholders, even when passing a number. All Python objects are converted by Psycopg in
  their SQL representation, so they get passed to the query as strings.
  See Passing parameters to SQL queries.

So I guess you just have to replace the %d with %s.

Body:
I tried to insert integer values in my table, But i was subjected to "Value Error"

import psycopg2

def connect():
    con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
    cur=con.cursor()
    cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL)")
    con.commit()
    con.close()

def insert(title,author,year,isbn):
    con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432'")
    cur=con.cursor()
    cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%d,%d)",(title,author,year,isbn))
    con.commit()
    con.close()

connect()
insert("the sun","helen",1997,23456777)


问:
Print lower triangular packed matrix in Fortran 77
I have a matrix of real*8 numbers saved in an array as a packed lower triangular matrix:

```<code>|1  *   *   *   *   *|
|2  7   *   *   *   *|
|3  8  12   *   *   *|
|4  9  13  16   *   *| => [1,2,3,4,5,6,7,8,9...21]
|5 10  14  17  19   *|
|6 11  15  18  20  21|
</code>```

I want to be able to print it in the following format:

```<code> [row|col]   1  2   3   4   5
     1       1  *   *   *   *
     2       2  7   *   *   *
     3       3  8  12   *   *
     4       4  9  13  16   *
     5       5  10 14  17  19
     6       6  11 15  18  20

 [row|col]   6
     1       *
     2       *
     3       *
     4       *
     5       *
     6       6
</code>```

The problem I have is that I don't know how to loop into the matrix elements without the need to creating extra arrays to save the elements by columns and then print them. this is what I have tried so far

```<code>      Implicit Real*8 (A-H,O-Z)

      INTEGER      ARRAY(21)

      10 Format(5X,'[Row|Col]',5(8X,I6))
      Icol=6
      Num1=1
C     Test array
      DO  K=1,21
      Array(K)=K*1.0d0
      ENDO

C     Print the elements row-by-row.
44    Num2=Icol-Num1
      Num=Num2
      If ((Num2).gt.5) Num=5
      Write(*,10) (I,I=Num1,Num1+Num)
      INum1=INum1+Num
      if (Inum1.ne.Icol) goto 44
      STOP
      END
</code>```

答:
The key is to identify the formula designating the non-zero elements of the lower triangular matrix. If i and j are running indices for rows and columns respectively, then (j < i) elements will be in the lower triangular part. Here is the code:

```<code>PROGRAM print_low_tri_matrix
IMPLICIT NONE
INTEGER :: i,j,n,m,p
REAL ,ALLOCATABLE, DIMENSION(:,:) :: a
REAL, ALLOCATABLE, DIMENSION(:) :: r

n = 6
p = n*(n+1)/2   ! Number of non-zero elements in a lower triangular matrix of size n by n

ALLOCATE(a(n,n),r(p))

DO i = 1, p
        r(i) = i*1.0    ! Array containing the non-zero elements
END DO

m = 1          ! Index tracking the non-zero elements array r
DO j = 1,n
        DO i = 1,n
                IF(j .LE. i) THEN       ! Non-zero indices of the matrix
                        a(i,j) = r(m)
                        m = m + 1
                ELSE
                        a(i,j) = 0.
                END IF
        END DO
END DO

!       Printing the full matrix a - uncomment for checking
!         DO i = 1,n
!                         WRITE(*,*) (a(i,j),j=1,n)
!         END DO

!       Printing the matrix a as needed
DO i = 1,n
        DO j = 1,n
                IF(j .LE. i) THEN
                        WRITE(*,'(F12.4)',ADVANCE="NO") a(i,j)
                ELSE
                        WRITE(*,'(A12)',ADVANCE="NO") '*'
                END IF

                IF (j .EQ. n ) WRITE(*,*)
        END DO
END DO

END PROGRAM print_low_tri_matrix
</code>```

And the output will be:

```<code>1.0000           *           *           *           *           *
2.0000      7.0000           *           *           *           *
3.0000      8.0000     12.0000           *           *           *
4.0000      9.0000     13.0000     16.0000           *           *
5.0000     10.0000     14.0000     17.0000     19.0000           *
6.0000     11.0000     15.0000     18.0000     20.0000     21.0000
</code>```

Of course, you can change the matrix into an integer array if you wanted.

P.S :- To make this work in f77, you can change the format specifiers as  WRITE(*,'(F12.4)',ADVANCE="NO") a(i,j) to WRITE(*,'(F12.4,$)') a(i,j). The allocations of the arrays should be removed and defined directly.

Body:
I have a matrix of real*8 numbers saved in an array as a packed lower triangular matrix:

|1  *   *   *   *   *|
|2  7   *   *   *   *|
|3  8  12   *   *   *|
|4  9  13  16   *   *| => [1,2,3,4,5,6,7,8,9...21]
|5 10  14  17  19   *|
|6 11  15  18  20  21|

I want to be able to print it in the following format:

 [row|col]   1  2   3   4   5
     1       1  *   *   *   *
     2       2  7   *   *   *
     3       3  8  12   *   *
     4       4  9  13  16   *
     5       5  10 14  17  19
     6       6  11 15  18  20

 [row|col]   6
     1       *
     2       *
     3       *
     4       *
     5       *
     6       6

The problem I have is that I don't know how to loop into the matrix elements without the need to creating extra arrays to save the elements by columns and then print them. this is what I have tried so far

      Implicit Real*8 (A-H,O-Z)

      INTEGER      ARRAY(21)

      10 Format(5X,'[Row|Col]',5(8X,I6))
      Icol=6
      Num1=1
C     Test array
      DO  K=1,21
      Array(K)=K*1.0d0
      ENDO

C     Print the elements row-by-row.
44    Num2=Icol-Num1
      Num=Num2
      If ((Num2).gt.5) Num=5
      Write(*,10) (I,I=Num1,Num1+Num)
      INum1=INum1+Num
      if (Inum1.ne.Icol) goto 44
      STOP
      END

Body:
The key is to identify the formula designating the non-zero elements of the lower triangular matrix. If i and j are running indices for rows and columns respectively, then (j < i) elements will be in the lower triangular part. Here is the code:

PROGRAM print_low_tri_matrix
IMPLICIT NONE
INTEGER :: i,j,n,m,p
REAL ,ALLOCATABLE, DIMENSION(:,:) :: a
REAL, ALLOCATABLE, DIMENSION(:) :: r

n = 6
p = n*(n+1)/2   ! Number of non-zero elements in a lower triangular matrix of size n by n

ALLOCATE(a(n,n),r(p))

DO i = 1, p
        r(i) = i*1.0    ! Array containing the non-zero elements
END DO

m = 1          ! Index tracking the non-zero elements array r
DO j = 1,n
        DO i = 1,n
                IF(j .LE. i) THEN       ! Non-zero indices of the matrix
                        a(i,j) = r(m)
                        m = m + 1
                ELSE
                        a(i,j) = 0.
                END IF
        END DO
END DO

!       Printing the full matrix a - uncomment for checking
!         DO i = 1,n
!                         WRITE(*,*) (a(i,j),j=1,n)
!         END DO

!       Printing the matrix a as needed
DO i = 1,n
        DO j = 1,n
                IF(j .LE. i) THEN
                        WRITE(*,'(F12.4)',ADVANCE="NO") a(i,j)
                ELSE
                        WRITE(*,'(A12)',ADVANCE="NO") '*'
                END IF

                IF (j .EQ. n ) WRITE(*,*)
        END DO
END DO

END PROGRAM print_low_tri_matrix

And the output will be:

1.0000           *           *           *           *           *
2.0000      7.0000           *           *           *           *
3.0000      8.0000     12.0000           *           *           *
4.0000      9.0000     13.0000     16.0000           *           *
5.0000     10.0000     14.0000     17.0000     19.0000           *
6.0000     11.0000     15.0000     18.0000     20.0000     21.0000

Of course, you can change the matrix into an integer array if you wanted.

P.S :- To make this work in f77, you can change the format specifiers as  WRITE(*,'(F12.4)',ADVANCE="NO") a(i,j) to WRITE(*,'(F12.4,$)') a(i,j). The allocations of the arrays should be removed and defined directly.


问:
How to get the result if forgot to name a function or object
I have a very big function which takes hours to give me the result. I forgot to name it. Is there any way that I can show the result of my function?

Thanks in advance.

答:
You can rescue objects from drowning in the console with .Last.Value. See the following example.

```<code>sum(c(2,2,3,4))
#[1] 11
y <- .Last.value
y
#[1] 11
</code>```

We learn from ?.Last.Value that

The value of the internal evaluation of a top-level R expression is always assigned to .Last.value (in package:base) before further processing (e.g., printing).

This also works for functions:

```<code>function(x){
  sqrt(x)
}

.Last.value
# function(x){
#   sqrt(x)
# }
</code>```

Interesting note from lmo in the comments:

As a side note, RStudio users can see this value in their environment panel by going to Tools > Global Options > General and then checking the box labelled "Show .Last.value in environment listing"

Body:
You can rescue objects from drowning in the console with .Last.Value. See the following example.

sum(c(2,2,3,4))
#[1] 11
y <- .Last.value
y
#[1] 11

We learn from ?.Last.Value that

The value of the internal evaluation of a top-level R expression is always assigned to .Last.value (in package:base) before further processing (e.g., printing).

This also works for functions:

function(x){
  sqrt(x)
}

.Last.value
# function(x){
#   sqrt(x)
# }

Interesting note from lmo in the comments:

As a side note, RStudio users can see this value in their environment panel by going to Tools > Global Options > General and then checking the box labelled "Show .Last.value in environment listing"


问:
Multivalued attributes in MySQL
I am working on a database in MySQL to show multivalued attributes. I am trying to find a way to create a parent and child table. The idea that I am working with is having an employee table and a hobby table. The hobbies in the hobby table would be considered the multivalued attributes since employees can have more than one hobby. My question would be, when creating these tables, should I use 3NF and add a 3 table to show the relation between the two or is there a way to implement this idea with simply two tables. I’m not very familiar with multivalued attributes so I need help creating the tables as far as what kind of keys each would use, as well as the end form. I believe I would need to make it in 3NF form and have the hobbies as the multivalued attribute, but have the hobby id from the hobby table as a primary key and the employee id as another primary key and then making the relational table contain both the employee id and hobby id as foreign keys referencing the other two tables. Any help or suggestions to show multivalued attributes would be greatly appreciated!</p>

答:
mva is not very good for mysql .

and best way to store it depend from price you can pay and accessibility need . if you need index , because database is big , and highly loaded , then possible you will need 2 tables .

```<code>employee( id , name )
employee_hobbies ( id , employeeid , hobbyid )
</code>```

but in simplest case , or if you need good accessibility, you can just add text field to employee table , store there comma separated hobbyid , and then select by FIND_IN_SET() function .

e.q. single table

```<code>employee( id , name , MVA VARCHAR(512) )
</code>```

you need be sure that all ids comma separated will fit into fields , side .

```<code>SELECT * from employee where FIND_IN_SET(some_hobbyid , MVA)
</code>```

advantage of this method is less queries ,
disadvantage - may slower then 1st .

also there is advantages for high load system , when import into sphinx ... but this is another story ...

Title: Multivalued attributes in MySQL

Body:
mva is not very good for mysql .

and best way to store it depend from price you can pay and accessibility need . if you need index , because database is big , and highly loaded , then possible you will need 2 tables .

employee( id , name )
employee_hobbies ( id , employeeid , hobbyid )

but in simplest case , or if you need good accessibility, you can just add text field to employee table , store there comma separated hobbyid , and then select by FIND_IN_SET() function .

e.q. single table

employee( id , name , MVA VARCHAR(512) )

you need be sure that all ids comma separated will fit into fields , side .

SELECT * from employee where FIND_IN_SET(some_hobbyid , MVA)

advantage of this method is less queries ,
disadvantage - may slower then 1st .

also there is advantages for high load system , when import into sphinx ... but this is another story ...


问:
iPhone Attributed String
Any ideas on how to get the functionality of an attributed string on an iPhone.

Specifically, I am writing out chemical compounds and want to properly display subscripts:  for example:

H2O   (the 2 should be a subscript)

Thanks for any suggestions

答:
You may find it more convenient to use the Unicode characters set up for subscripts:

SUBSCRIPT TWO is U+2082: H₂0

OwnerDisplayName: Corey

Title: iPhone Attributed String

OwnerDisplayName: rpetrich


问:
determining whether a window is in desktop bounds c++
I wrote some code to determinate whether a certain window is inside the desktop bounds.

Somehow, it doesn't work. For every window, regardless whether it is inside or outside the desktop, false is returned. Something is terribly wrong here, but after staring at this piece of code for 3 hours now, I still don't know where the problem is. If I try to read a RECT struct from the pointer sent in the PMSG's WPARAM, I get a AccessViolationException. Why is this happening?

My code look like this, and always returns false:

```<code>static bool IsInBounds(HWND window)
{
    DEVMODE d;
    d.dmSize = sizeof(DEVMODE);
    BOOL b = EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &d);
    if(b == FALSE)
    {
        PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"FMSG"), (WPARAM)window, NULL);
    }
    RECT R;
    GetWindowRect(window, &R);
    POINT p = POINT();
    p.x = (LONG)d.dmPelsWidth;
    p.y = (LONG)d.dmPelsHeight;
    PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth);
    if(R.right < 0 || R.bottom < 0 || R.left > (LONG)d.dmPelsWidth || R.top > (LONG)d.dmPelsHeight)
    {
        return false;
    }
    return true;
}
</code>```

EDIT:
after calling IsInBounds, which returned an error number 1400 (Invalid window handle), but before returning from the hook callback, I called IsWindow(window), to see, if my handle is still valid. The truth is: it is in deed a valid handle! How can it be that GetWindowRect says its an invalid handle?

EDIT:
I tried MonitorFromWindow as sujested, but it returned NULL, and calling GetLastError resulted in error no. 1400, which is already familiar to me. Looks like MonitorFromWindow implicitly calls GetWindowRect. I don't care about the size, but is there another way to get window coordinates from a handle?

答:
PostMessage() is asynchronous and you're sending a pointer to a local variable of your function (RECT R). That local variable is most likely gone by the time the receiver gets around to processing the message.

Also, you ought to be checking the return value of GetWindowRect() to make sure it didn't fail.

Another thing, you should probably return if EnumDisplaySettings() has failed. The tests at line 16 will be nonsensical if DEVMODE d hasn't been filled in.

Body:
I wrote some code to determinate whether a certain window is inside the desktop bounds.

Somehow, it doesn't work. For every window, regardless whether it is inside or outside the desktop, false is returned. Something is terribly wrong here, but after staring at this piece of code for 3 hours now, I still don't know where the problem is. If I try to read a RECT struct from the pointer sent in the PMSG's WPARAM, I get a AccessViolationException. Why is this happening?

My code look like this, and always returns false:

static bool IsInBounds(HWND window)
{
    DEVMODE d;
    d.dmSize = sizeof(DEVMODE);
    BOOL b = EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &d);
    if(b == FALSE)
    {
        PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"FMSG"), (WPARAM)window, NULL);
    }
    RECT R;
    GetWindowRect(window, &R);
    POINT p = POINT();
    p.x = (LONG)d.dmPelsWidth;
    p.y = (LONG)d.dmPelsHeight;
    PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth);
    if(R.right < 0 || R.bottom < 0 || R.left > (LONG)d.dmPelsWidth || R.top > (LONG)d.dmPelsHeight)
    {
        return false;
    }
    return true;
}

EDIT:
after calling IsInBounds, which returned an error number 1400 (Invalid window handle), but before returning from the hook callback, I called IsWindow(window), to see, if my handle is still valid. The truth is: it is in deed a valid handle! How can it be that GetWindowRect says its an invalid handle?

EDIT:
I tried MonitorFromWindow as sujested, but it returned NULL, and calling GetLastError resulted in error no. 1400, which is already familiar to me. Looks like MonitorFromWindow implicitly calls GetWindowRect. I don't care about the size, but is there another way to get window coordinates from a handle?


问:
How to Include a count(*) as additional result field of a query in LINQ
Given a table of players (users) with several fields. One of this is their rating with respect other players.

I'd like to implement via LINQ following SQL query:

```<code>SELECT p.*,
    (select COUNT(*) from Users where (Rating > p.Rating)) as Rank
FROM Users as p
ORDER BY p.Rating DESC
</code>```

In other words, last field (RANK) should give the rank of each user with respect the others:

```<code>Id  Username  ... Rating     Rank
43  player41  ... 1002,333  0
99  player97  ... 1002      1
202 player200 ... 1002      1
53  player51  ... 1000,667  2
168 player166 ... 1000,667  2
56  player54  ... 1000      3
32  player30  ... 999,342   4
</code>```

This attempt does not work:

```<code>var q = from u in Users
        orderby u.Rating descending
        group u by u.Id into g
        select new
        {
            MyKey = g.Key,
            User = g.First(),
            cnt = Users.Count(uu => uu.Rating > g.First().Rating) + 1
        };
</code>```

Just for your knowledge, note that the table Users is mapped to a EF entity named User with a 'NotMapped' int? field named Rank where I'd like to manually copy the rank:

```<code>class User {
    ...
    [NotMapped]
    public virtual int? Rank { get; internal set; }
}
</code>```

答:
You'll want something like:

```<code>var rankedUsers = db.Users
    .Select(user => new
    {
        User = user,
        Rank = db.Users.Count(innerQueryUser => innerQueryUser.Rating > user.Rating)
    })
    .ToList();
</code>```

Which will give you a list of users and their Rank as an anonymous type.
You'll then be able to do something like:

```<code>List<User> users = rankedUsers.Select(rankedUser=>
{
    rankedUser.User.Rank = rankedUser.Rank;
    return rankedUser.User;
})
.ToList();
</code>```

Body:
Given a table of players (users) with several fields. One of this is their rating with respect other players.

I'd like to implement via LINQ following SQL query:

SELECT p.*,
    (select COUNT(*) from Users where (Rating > p.Rating)) as Rank
FROM Users as p
ORDER BY p.Rating DESC

In other words, last field (RANK) should give the rank of each user with respect the others:

Id  Username  ... Rating     Rank
43  player41  ... 1002,333  0
99  player97  ... 1002      1
202 player200 ... 1002      1
53  player51  ... 1000,667  2
168 player166 ... 1000,667  2
56  player54  ... 1000      3
32  player30  ... 999,342   4

This attempt does not work:

var q = from u in Users
        orderby u.Rating descending
        group u by u.Id into g
        select new
        {
            MyKey = g.Key,
            User = g.First(),
            cnt = Users.Count(uu => uu.Rating > g.First().Rating) + 1
        };

Just for your knowledge, note that the table Users is mapped to a EF entity named User with a 'NotMapped' int? field named Rank where I'd like to manually copy the rank:

class User {
    ...
    [NotMapped]
    public virtual int? Rank { get; internal set; }
}

Body:
You'll want something like:

var rankedUsers = db.Users
    .Select(user => new
    {
        User = user,
        Rank = db.Users.Count(innerQueryUser => innerQueryUser.Rating > user.Rating)
    })
    .ToList();

Which will give you a list of users and their Rank as an anonymous type.
You'll then be able to do something like:

List<User> users = rankedUsers.Select(rankedUser=>
{
    rankedUser.User.Rank = rankedUser.Rank;
    return rankedUser.User;
})
.ToList();


问:
How to create an reusable element similar to Selenium extend elements in Cypress.io?
In Selenium, it's possible to extend elements. This makes it possible to have a set of reusable custom elements for testing.

For example, we can have a getText method added.

```<code>public static string GetText(this IWebDriver driver)
{
    return driver.FindElement(By.TagName("body")).Text;
}
</code>```

And re-use it as follows:

myElement.getText();

This example is detailed here: http://www.vcskicks.com/selenium-extensions.php

Is there a way to replicate this behavior in Cypress.io? Or do we need to query and call the same methods to get the data?

答: I think that Custom Commands is what you're looking for.  However, note the Cypress Best Practices.  The basic commands are very powerful and you can accomplish a lot with them.</p>

Body:
In Selenium, it's possible to extend elements. This makes it possible to have a set of reusable custom elements for testing.

For example, we can have a getText method added.

public static string GetText(this IWebDriver driver)
{
    return driver.FindElement(By.TagName("body")).Text;
}

And re-use it as follows:

myElement.getText();

This example is detailed here: http://www.vcskicks.com/selenium-extensions.php

Is there a way to replicate this behavior in Cypress.io? Or do we need to query and call the same methods to get the data?