text:
Q: how to display multple columns in listview columns? is it possible to display the two database column in one row column in listview in vb.net using mysql.data.mysqlclient?
 Listview:              where in database:
 ---------------            *Firstname: John
 |  Full Name  |            *Lastname: Smith
 |_____________|
 |             |
 |  John Smith |
 |_____________|

here's my code:
For i = 0 To table.Rows.Count - 1
    With lvlistview
        .Items.Add(table.Rows(i)("dte"))
        With .Items(.Items.Count - 1).SubItems
            .Add(table.Rows(i)("tran_no"))
            .Add(table.Rows(i)("comp_type"))
            .Add(table.Rows(i)("status"))
            .Add(table.Rows(i)("sys_name"))
            .Add(table.Rows(i)("mod_name"))
            .Add(table.Rows(i)("err_desc"))
            .Add(table.Rows(i)("trigg"))
            .Add(table.Rows(i)("fname" . "lname")) **How i gonna combine this two database column in only one listview column**
        End With
    End With
Next

A: You simply need to concatenate the values from the two DB columns together.  If you were using data-binding, the simplest solution would be to alter your SQL command so that the values are concatenated by the DB engine and returned to you as a single column.  However, since you are adding the items yourself, you can, alternatively, just concatenate the two columns in your code before adding the item to the ListView, for instance:
With .Items(.Items.Count - 1).SubItems
    .Add(table.Rows(i)("tran_no"))
    .Add(table.Rows(i)("comp_type"))
    .Add(table.Rows(i)("status"))
    .Add(table.Rows(i)("sys_name"))
    .Add(table.Rows(i)("mod_name"))
    .Add(table.Rows(i)("err_desc"))
    .Add(table.Rows(i)("trigg"))
    .Add(table.Rows(i)("fname") & " " & table.Rows(i)("lname"))
End With

The & character is the standard string-concatenation operator in VB.NET.  You can also use the + operator, but you have to be more careful of your type casting when you use the + operator with strings.  Since the & operator is a little safer and it's slightly more self-documenting, it's typically the preferred operator for strings.
For more complicated concatenations, you may also want to consider using String.Join, String.Format or the StringBuilder class.


text:
Q: Tip/Advice/Question box with a symbol on the left Some books contain boxes with additional advice, tips or questions which have a signaling symbol on the left (like a question mark, an exclamation mark, a light bulb etc.). Is there a package which offers something like this?

A: Here's a version with the powerful tcolorbox and using an underlay, drawing the symbol left of the box -- I chose the bombe symbol from bclogo package, but basically anything can be placed there.
\documentclass{article}

\usepackage{bclogo}
\usepackage[most]{tcolorbox}

\newtcolorbox{attentionbox}[1][]{%
  enhanced jigsaw,
  sharp corners,
  colframe={red},
  underlay={%
    \path[draw=none] (interior.south west) rectangle node[white]{\bcbombe} ([xshift=-10mm]interior.north west);
    },
  #1
}

\usepackage{blindtext}

\begin{document}

\begin{attentionbox}
\blindtext
\end{attentionbox}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: type 'int' is not a subtype of type 'String' but everthing is integer I know it seens duplicate, but its not, the answers from the other topics is nothing like i am facing here.
I really dont know whats going on, everthing is integer but stills aplies as string...
The problem occur on the FOR LOOP (if i print the somaModulos it shows the math correctly, only if i print inside the FOR LOOP, if i print outsite the FOR, it brings the errow below).
Everthing later dont execute because the problem "type 'int' is not a subtype of type 'String'"
      var textModulos = modulosNecessarios.toString();

      int somaModulos = 0;
      void recalcularModulos() {
        print(modulosConfig);
        print(int.parse(modulosConfig[0][0]) * int.parse(modulosConfig[0][1])); //THIS WORKS

        for (var i = 0; i < modulosConfig.length; i++) { // THIS DONT WORK
          somaModulos +=
              int.parse(modulosConfig[i][0]) * int.parse(modulosConfig[i][1]);
        }

        /*
        setState(() {
          textModulos = (modulosNecessarios - somaModulos).toString();
        });
        */
      }

The results of the prints:
1º
[[20, 3, colonial, retrato], [0, 0, colonial, retrato]]

2º
60

A: Well, it seens that the array type values changed on the textField onChange.
Even the text input type was a number, it changes to string if i put it on the onChange method, i was not paying attetion to that (i am new to dart).
The items in the list was always creating with int values, but it changed to string in the middle of the process...
              TextField(
                keyboardType: TextInputType.number,
                decoration: InputDecoration(labelText: "Quantidade de módulos"),
                style: TextStyle(fontSize: 18),
                controller: _controllerQnt,
                onChanged: (String value) {
                  setState(() {
                    modulosConfig[itemUtilized][0] = value;
                  });
                },

To make it work, i changed the array incremention from:
modulosConfig.insert(indexStart, [0, 0, 'colonial', 'retrato']);

To:
modulosConfig.insert(indexStart, ['0', '0', 'colonial', 'retrato']);

Or change the TextField onChange method integer.
I choose to change the incremention to all string and then parse it on the FOR LOOP.


text:
Q: find a matching values from 2 arrays, one array having an html element present in it-Javascript I want to compare 2 arrays and find the matching values from it, ideally this question has been asked before and seems like it partially works in my case.
lets say I have:
var array1 = ["test-123", "id-859","hi-8098", "hello-9090"];
var array2= ["Welcome test-123", "Welcome33 id-859","How are you hi-8098", "Geat hello-9090", "see ya nono-58758"];

In my case I have html element span and I want to match the values that are inside the  and return as o/p:
var newArray= ["Welcome", "Welcome33 ","How are you ", "Geat "];

so basically the values inside array1 matches to all the values inside array2 except the last one"see ya nono-58758". Using filter I can get the matching values, but these values are pretty straight forward,
newArray = array1.filter(e => array2.indexOf(e) !== -1); // in my case its undefined, as it does not recognize the html element in it.

any ideas on how to get matching values when an html element is present inside an array?
Thanks!

A: indexOf don't use with Array but String . So you need to make string first

var array1 = ["test-123", "id-859","hi-8098", "hello-9090"];
var array2= ["Welcome test-123", "Welcome33 id-859","How are you hi-8098", "Geat hello-9090", "see ya nono-58758"];

var newArr =[];
for(var i of array1) {
  for(var j of array2) {
    var split = j.split("");
    if(split[1].indexOf(i) > -1) {
      newArr.push(split[0]);
    }
  }
}
//newArray = array1.filter(e => array2.indexOf(e) != -1);you don't need this
console.log(newArr);

A: this works too

var array1 = ["test-123", "id-859","hi-8098", "hello-9090"];
var array2= ["Welcome test-123", "Welcome33 id-859","How are you hi-8098", "Geat hello-9090", "see ya nono-58758"];

var k=[];
array2.forEach(a=>{
  array1.forEach(b=>{
if(a.indexOf(b)!=-1){
k.push(a);
}

  })

})

let j=k.reduce((o,a)=>{
 let i= a.split("");
 o.push(i[0]);
 return o;
},[])

console.log(j)

A: STEPS:

*

*Iterate through array1

*For each string in array1, interate array2

*Extract the desired text to search by string in array1 (Here I use split)

*Compare each string from array1 to every extracted text in array2

*Push the front text if match

*Trim (optional)

var array1 = ["test-123", "id-859","hi-8098", "hello-9090"]
var array2= ["Welcome test-123", "Welcome33 id-859","How are you hi-8098", "Geat hello-9090", "see ya nono-58758"]

let result = []
array1.forEach(searchStr => {
  array2.forEach(dataStr => {
    let stringInTag = dataStr.split('')[1].split('')[0]
    if (searchStr === stringInTag){
      let text = dataStr.split('')[0]
      result.push(text.trim())
    }
  })
})
console.log(result)


text:
Q: How to start for-each loop from the beginning? I'm writing the For-each loop and inside the for-each loop I,m checking a condition. I want to restart the loop if that condition is met. Is there any keyword like continue or break for start the loop from the beginning
 for (PoDetails items : ordersItemList) {
    if (nextPosition == incrementPosition) {
        if (some condition){
            break;
        } else{
            if (some condition){
                continue;
            } else{
                //I want to restart the for-each loop here
            }
         }
    } else {
        nextPosition++;
    }
 }

A: You can use an index in the for loop, Then when you need to restart the loop set this index to zero.
for (int i = 0; i < ordersItemList.size(); i++) {
    PoDetails item = ordersItemList.get(i);
    if (nextPosition == incrementPosition) {
        if (some condition) {
            break;
        } else {
            if (some condition) {
                continue;
            }else{
                //I want to restart the for-each loop here
                i = 0; // set the index to zero here, then it will start the loop from the begnning
            }
        }
    } else {
        nextPosition++;
    }
}

A: OUTER: //outer label
for (PoDetails items : ordersItemList) {
    if (nextPosition == incrementPosition) {
        if (some condition){
            break;
        } else{
            if (some condition){
                continue;
            } else{
                continue OUTER:; // This will call the loop from OUTER:
            }
        }
    } else {
        nextPosition++;
    }
}


text:
Q: How to Resolve ActiveMerchant Authorize.net Gateway Issue I get a segmentation fault whenever I try to call authorize on the Authorize.net gateway whether I am using test or live credentials. I am using the latest version of the ActiveMerchant gem. Any ideas on resolving this?
credit_card = ActiveMerchant::Billing::CreditCard.new(:first_name => "First", :last_name => "Last", :number => "4007000000027", :month => "07", :year => "2012", :verification_value => "111", :type => 'visa')
options = { :billing_address => {:name => "First Last", :address1 => "12 Candy Ln", :city => "Sugarville", :state => "IL", :zip => "12345", :country => "USA" }, :description => "00001" }
gateway = ActiveMerchant::Billing::AuthorizeNetGateway.new(:login => 'scraped', :password => 'scraped', :test => true)

/Users/foo/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/1.8/net/http.rb:586: [BUG] Segmentation fault
ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10.4.0]

A: For me, the fix for this with an RVM version of ruby is to install it with the RVM OpenSSL package: http://rvm.beginrescueend.com/packages/openssl/
In particular, I used the following to install ruby 1.8.7-p174:
rvm package install iconv
rvm package install openssl
rvm install 1.8.7-p174 --with-openssl-dir=$HOME/.rvm/usr --with-iconv-dir=$rvm_path/usr


text:
Q: Delphi: DateTimeToStr output with zero time (midnight) I have found a similar question here, but it is unrelated to what I am trying to do.  I have done a lot of research on the Internet and I have determined that Delphi is working as designed or intended, where it omits the time if the time is zero.  I have an application which displays the date & time in a listview, and when the time is midnight, it doesn't show 00:00:00, and therefore making the results look uneven and out of place.
The way I've gotten around this which is still locale independant is to add a microsecond to the time, see sample code:
program Test11;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils, Winapi.Windows;

begin
  try
    Writeln(DateTimeToStr(44167, TFormatSettings.Create(GetThreadLocale)));
    Writeln(DateTimeToStr(44167.00000001, TFormatSettings.Create(GetThreadLocale)));
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

end.

And subsequent output:
02/12/2020
02/12/2020 00:00:00

The question is - is there a better, more programatically correct way to do achieve this?
Running Delphi XE6

A: You can use FormatDateTime function for more control over date time formatting.
FormatDateTime('ddddd tt', 44167, TFormatSettings.Create);

Note: There is no need to call TFormatSettings.Create(GetThreadLocale) with locale parameter because plain TFormattSettings.Create call will internally use GetThreadLocale on Windows platform.

A: This is "normal" behavior of VCL. Look at the related code from System.SysUtils (it is from Seattle, but I think it hasn't much changes since XE6).
function DateTimeToStr(const DateTime: TDateTime;
  const AFormatSettings: TFormatSettings): string;
begin
  DateTimeToString(Result, '', DateTime, AFormatSettings);
end;

procedure DateTimeToString(var Result: string; const Format: string;
  DateTime: TDateTime; const AFormatSettings: TFormatSettings);
begin
  ...
  if Format <> '' then AppendFormat(Pointer(Format)) else AppendFormat('C');
  ...

//This is another related part of DateTimeToString.
case Token of
  'C':
    begin
      GetCount;
      AppendFormat(Pointer(AFormatSettings.ShortDateFormat));
      GetTime;
      if (Hour <> 0) or (Min <> 0) or (Sec <> 0) or (MSec <> 0) then
      begin
        AppendChars(' ', 1);
        AppendFormat(Pointer(AFormatSettings.LongTimeFormat));
      end;
    end;

If time part of datetime value equals to zero, then only date will be in result string.
If you want always show datetime in single format, better use FormatDateTime as suggested by other answers.


text:
Q: create a function with dot: myfunc.print("Hello World") in python how do you define dotted function?
i try this:
def myfunc.print(value)
  print(value);

but it's said "Invalid syntax"

A: Here's one way:
>>> class myfunc:
...     print = print
...
>>> myfunc.print("foo")
foo

In this example, myfunc is actually a class, and print is a class attribute (which is initialized to point to the print function).

A: In python, and in many other languages, the "dot" syntax is a product of code organizational structure.  So, X.Y tells python to look for Y inside of X.  There are actually a few ways to do this.  You can define a class which organizes a set of functions and properties within the class or its associated objects (as @Samwise's answer shows).  You can also create a new file "myfunc.py", and have one of the functions defined in that file be def print(): pass - then when you import myfunc in another file you can access myfunc.print.  In any case, the dot represents a "belonging" relationship, so you need to have your print function "belong" to the myfunc containing structure in some way.


text:
Q: Force Windows to use pagefile I would like to know if there is a way to instruct Windows to utilize a portion of the pagefile on demand. Like an API or something. I'm currently working on a monitoring system with a function to check the amount of pagefile being used. There are test machines that aren't busy so their pagefile isn't being used aggressively. I need a way to spike the pagefile usage for my automated tests.
Thank you in advance.

A: Pagefile is usually used when there is not enough free RAM available.
So in order to create a spike in pagefile usage open something heavy like a browser with 100 tabs or so on.


text:
Q: c++ type/value mismatch at argument 1 in template parameter list #include <iostream>
using namespace std;

template<class T>
class people{
    public:
    virtual void insert(T item)=0;
    virtual T show(T info)=0;
};

template<class T>
class name
{
    private:
     T fname;
     T lname;
     public:
      name(T first, T last);
    //  bool operator== (name & p1, name &p2)
};
template <class T>
name<T>::name(T first, T last){
    fname = first;
    lname = last;
}
template <class T>
class person : public people<T>
{
    private:
    T a[1];
    int size;
    public:
    person();
    virtual void insert(T info);
    virtual T show();
};
template<class T>
person<T>::person(){
    size = 0;
}
template<class T>
void person<T>::insert(T info){
    a[0] =info;
}
template<class T>
T person<T>::show(){
      return a[0];
 }
int main(){
    string first("Julia"), last("Robert");
    name<string> temp(first,last);
    people<name>* aPerson = new person();
    aPerson-> insert(temp);
    aPerson->show();
    return 0;
}

These are the errors I keep getting and I can't pinpoint what really is the problem:
test.cpp:52: error: type/value mismatch at argument 1 in template parameter list for 'template<class T> class people'
test.cpp:52: error:   expected a type, got 'name'
test.cpp:52: error: invalid type in declaration before '=' token
test.cpp:52: error: expected type-specifier before 'person'
test.cpp:52: error: expected ',' or ';' before 'person'
test.cpp:53: error: request for member 'insert' in '* aPerson', which is of non-class type 'int'
test.cpp:54: error: request for member 'show' in '* aPerson', which is of non-class type 'int'

A: name is a templated class, so you must specify the template:
people<name<string>>* aPerson = new person<name<string>>();


text:
Q: Converting XLS/XLSX files in a folder to CSV I have written the following code in VBA. When debugging, I am not able to find any problems. It is not creating nor converting any file into .CSV.
Sub SaveToCSVs()
    Dim fDir As String
    Dim Wb As Workbook
    Dim wS As Worksheet
    Dim csvWs As String, csvWb As String
    Dim extFlag As Long '0 = .xls & 1 = .xlsx extension types
    Dim fPath As String
    Dim sPath As String, dd() As String
    fPath = "C:\Users\DA00358662\Documents\XLSCONV\*.*"

    sPath = "C:\Users\DA00358662\Documents\XLSCONV\"
    fDir = Dir(fPath)
    extFlag = 2
    Do While (fDir <> "")
        If Right(fDir, 4) = ".xls" Or Right(fDir, 5) = ".xlsx" Then
            extFlag = 0
        Else
            extFlag = 2
        End If
        On Error Resume Next
        If extFlag = 0 Then
            fDir = Dir
            Set Wb = Workbooks.Open(fPath & fDir)
            csvWb = Wb.Name
            dd = Split(csvWb, ".")
            For Each wS In Wb.Sheets
                wS.SaveAs dd(0) & wS.Name & ".csv", xlCSV
            Next wS
            Wb.Close False
            Set Wb = Nothing
            fDir = Dir
            On Error GoTo 0
        End If
    Loop
End Sub

A: with this code (standard for my use) you can find that you need (modify as your need).
In short the code ask which directory to loop and for each file, with the corresponding extension, in this directory it open file, save as csv in the some directory, and close the original file.
Sub SaveAsCsv()
Dim wb As Workbook
Dim sh As Worksheet
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then Exit Sub

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
    Set wb = Workbooks.Open(Filename:=myPath & myFile)
    nameWb = myPath & Left(myFile, InStr(1, myFile, ".") - 1) & ".csv"
    ActiveWorkbook.SaveAs Filename:=nameWb, FileFormat:=xlCSV
    ActiveWorkbook.Close savechanges:=False
    'Get next file name
      myFile = Dir
  Loop
'Reset Macro Optimization Settings
  Application.ScreenUpdating = True
  Application.EnableEvents = True
  Application.Calculation = xlCalculationAutomatic
End Sub

A: The Moment you concatenate fPath and fDir to open your Workbook, you get something like:
"C:\Users\DA00358662\Documents\XLSCONV\*.*MyWorkbook.xls"

Note *.* in the middle ruining your day. I think you want to use sPath here?


text:
Q: Problem in Publishing my ASP.NET MVC project using Visual Studio 2017 I am uisng Vsiual Studio 2017 for my project, and when I want to publish the project I get the below error: any one please help.

Publish has encountered and error! publish failed due to build errors.
     A diagnostic  log has been written to the following location:  "C:\Users\ABC\AppData\Local\Temp\tem413.temp"

The output log for tem413.temp is

System.AggregateException: One or more errors occurred. ---> System.Exception: Publish failed due to build errors. Check the error list for more details.
     --- End of inner exception stack trace ---
     at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
     at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
     at Microsoft.VisualStudio.Web.Publish.PublishService.VsWebProjectPublish.<>c__DisplayClass40_0.b__2()
     at System.Threading.Tasks.Task`1.InnerInvoke()
     at System.Threading.Tasks.Task.Execute()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.VisualStudio.ApplicationCapabilities.Publish.ViewModel.ProfileSelectorViewModel.d__108.MoveNext()
  ---> (Inner Exception #0) System.Exception: Publish failed due to build errors. Check the error list for more details.<---

Thanks


text:
Q: Finding the steady-state temperature given temperature along the rim of unit disk Consider the unit disk in the plane. We fix the temperature along the rim by the function:
$u(e^{i\theta}) = sin(\theta)$ if $0 \le\theta \le\pi$, $0$ otherwise. Find the steady-state temperature at $z=\frac{1}{7}$
I believe the approach is to use Dirichlet or Poisson formula, but I'm not exactly sure.


text:
Q: How do I look at an object in Xcode's debugger? I have a simple question about debugging on Xcode and GDB.
I often run into an error:
unrecognized selector sent to instance 0x1081ad0

which makes the program load into GDB. Is there an easy way to examine what instance is located in that memory from GDB?

A: Steven is correct — the gdb command po is a shortcut for print-object, which actually calls -debugDescription (not -description, as you might expect) on the object provided as an argument. In many cases you'll see the same result from both methods, since one calls the other unless overridden. (See the related Note: callout on this Apple technote for details. Note that in their code sample, po $r3 prints the contents of a PowerPC register, but you can use any object pointer/reference, including Intel registers, etc.)
Also, be aware that print-object will only work on valid objects that haven't been deallocated. It won't help at all if you're sending a message to a borked pointer. Given the error you cited, though, it would seem that it's a valid object instance, it just doesn't implement the method you're trying to invoke.
It's also remotely possible that the object has already been destroyed. This answer should help in that case.

Edit:
There are other ways to "examine" objects in the debugger. I asked this SO question about Xcode data formatters, which is one way you can determine how a custom class appears in the Summary column of the debugger. The documentation linked from that question explain how it works. I've found the summary approach to help a lot with seeing the state of an object.

A: There are a couple of things you can do.

*

*You can insert a break point that will trigger every time you have an exception, so basically create a break point for this (go to breakpoints and create a new one): -[NSException raise]

*Alternatively, you can actually see what the object at that mem location is:
info symbol 0x1081ad0 or
info line *0x1081ad0
There's more info at the cocoadev wiki entry for exceptionhandling and debugging tips for objective C at cocoawithlove.

A: po 0x1081ad0
po = Print Object.
You can even call methods, like
po [myArray objectAtIndex:0]
Note that it only works on objects, so
po 1
will crash your program.

A: Your instance is not valid.  You have release the object somewhere else, but you did not clear out your pointer...  enable Zombie detection.


text: Q: Modified convexity definition on manifolds allowing non-unique minimising geodesics I am interested in subsets $A \subset M$ of a connected, complete Riemannian manifold $(M,g)$ with the following property: for every $p,q \in A$, at least one minimising geodesic from $p$ to $q$ in $M$ is contained in $A$. Is there a name for this property? It is more general than convexity and weak convexity as defined in Chavel's Riemannian Geometry: A Modern Introduction, since it includes e.g. `bands' on a cylinder.


text:
Q: I want to get hour ranges of a dataframe I want to demonstrate the hour ranges of a dataframe which has index column as date.
For example, I have as the following data:
Date                   col1
2019-10-10 00:00:00    person1
2019-10-10 01:00:00    person1
2019-10-10 02:00:00    person1
2019-10-10 03:00:00    person2
2019-10-10 04:00:00    person2
2019-10-10 05:00:00    person2
2019-10-10 06:00:00    person2
2019-10-10 07:00:00    person2
2019-10-10 08:00:00    person3
2019-10-10 09:00:00    person3
2019-10-10 10:00:00    person3
2019-10-10 11:00:00    person3
2019-10-10 12:00:00    person3

I want to this data like this:
Hour               col2
00:00 - 02:00      person1
03:00 - 07:00      person2
08:00 - 12:00      person3

How can I do this?

A: Use DataFrame.groupby + Series.dt.time:
new_df=df.groupby('col1')['Date'].apply(lambda x: x.dt.time.iloc[0].strftime("%H:%M")+ '-'+x.dt.time.iloc[len(x)-1].strftime("%H:%M")).rename('Hour').reset_index()
print(new_df)

      col1         Hour
0  person1  00:00-02:00
1  person2  03:00-07:00
2  person3  08:00-12:00


text:
Q: How to create a SimpleDate from ayear String in Java I have a set of strings. This strings are actually "year"s. for example: "1967","1872","2012",...
I want to create a SimpleDate instance from each of these. Is there a way to create a SimpleDate from a year String?
I have a rather hacky solution for this, which is attaching "-00-00" to my year strings and parsing it into a a SimpleDate. I need a more non-hacky way of doing this.
Thx

A: I am not sure but maybe you asking about something like this
SimpleDateFormat sdf=new SimpleDateFormat();
sdf.applyPattern("YYYY");
Date d=null;
try {
    d = sdf.parse("1999");
} catch (ParseException e) {
    e.printStackTrace();
}
System.out.println(d);

A:     Calendar calendar = Calendar.getInstance();
    calendar.set(Integer.parseInt(year), 0, 1);
    calendar.getTime();

A: You could use SimpleDateFormat.
String str_date="1997";
Date date;
try {
  DateFormat formatter = new SimpleDateFormat("yyyy");
  date = (Date)formatter.parse(str_date);
} catch (ParseException e) {
  // handle exception (date will be null)
}


text:
Q: How to declare implicit arguments in higher order functions? I want IMPLICIT args in a higher order function, like:
func(arg1) { implicit (x, y) => x * y }
But the compiler says:
error: expected start of definition
val a = func("2", "4") { implicit (x, y) =>
                                  ^

*

*java version "1.7.0_40"

*Scala code runner version 2.10.2-RC2 -- Copyright 2002-2013, LAMP/EPFL

The runnable sample code:
object Test extends App {
    new Test().run
}

class Test {
    def run = {
        val a = func("2", "4") { (x, y) => // It's OK
            x * y
        }
        println("a: " + a)

        val b = gunc("2", "4") { implicit x => { implicit y => // It's OK
            x * y
        }}
        println("b: " + b)
    }

    def func(x: String, y: String)(f: (Int, Int) => Int) = f(x.toInt, y.toInt)
    def gunc(x: String, y: String)(g: Int => Int => Int) = g(x.toInt)(y.toInt)
    def hunc(x: String, y: String)(h: Tuple2[Int, Int] => Int) = h((x.toInt, y.toInt))
}

[ADD COMMENT]
I wonder...
We can declare as "implicit x => ..." with one arg.
It seems there is no way to declare two implicit args.

A: Try adding:
val c = hunc("2", "4") { implicit pair => pair._1 * pair._2 }

A: When you say implicit y => y * 2 you're not
   declaring an implicit argument but mark the function as implicit,
    so you make an analog to this:
implicit val f1 = (y: Int) => y * 2
def func1(x: String, y: String)(f: Int => Int) = f(1)
func1("", "")(f1)

When you want to mark a function with two
   arguments as implicit you can do it this way:
implicit val f2 = (x: Int, y: Int) => y * 2
def func2(x: String, y: String)(f: (Int, Int) => Int) = f(1, 2)
func2("", "")(f2)

But you cannot do it so:
func2("", "")(implicit (x, y) => x), in this particular case I just don't see any meaning to use implicits.
Also you can see this question, maybe you'll find some useful information there


text:
Q: MKNetworkkit: Fetching JSONArray from server I am using MKNewtworkkit for networking operation is my ios app. I have JSONInterface in server through which i can retrieve JSONArray. I am able to fetch data in android app and browser as well, But when i try to ftech data using MKNetworkkit  [completedOperation responseJSON] is returning nil. Could you please help me
MKNetworkEngine *network_engine= [[MKNetworkEngine alloc] initWithHostName:@"****.com"];
 NSMutableDictionary* params=[[NSMutableDictionary alloc] initWithCapacity:3];
[params setObject:[self.userName text] forKey:@"user"];
[params setObject:[self.password text] forKey:@"password"];
[params setObject:@" " forKey:@"meters"];
MKNetworkOperation* operation =[network_engine operationWithPath:@"q/out" params:params httpMethod:@"GET" ssl:NO];
[operation onCompletion:^(MKNetworkOperation *completedOperation) {
    NSLog(@"response: %@",[completedOperation responseString]);
    @try {
        NSArray *data_array=[completedOperation responseJSON];
        for (int i=0; i<[data_array count]; i++) {
            NSDictionary *dict=[data_array objectAtIndex:i];
            NSString *id=[dict valueForKey:@"mid"];
            NSString *location=[dict valueForKey:@"location"];
            NSLog(@"id:%@ , location:%@",id,location);
        }
    }

    @catch (NSException *exception) {
        NSLog(@"Exception: %@",[exception name]);
    }

} onError:^(NSError *error) {
         NSLog(@"Couldn't make network call");
}];
[network_engine enqueueOperation:operation];

A: I know this is an old post but in case anyone else comes across this...
It looks like you are casting the 'responseJSON' as an NSArray but it should be a NSDictionary.
This works for me ->
    MKNetworkOperation *op = [mkNetworkEngine operationWithURLString:CONFIG_FILE_URL];
[op setShouldNotCacheResponse:YES];

[op addCompletionHandler:^(MKNetworkOperation *completedOperation) {

    NSLog(@"** Success downloading config file...");

    NSDictionary* responseJSON = completedOperation.responseJSON;

} errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {

    NSLog(@"** Failed downloading config file - error: %@",error);

}];

[mkNetworkEngine enqueueOperation:op];


text:
Q: Почему для выбора ряда в таблице необходимо двойной клик? Всем привет. У меня есть страничка на которой находиться выпадающий список с именами кастомеров. При выборе кастомера динамически подгружается таблица (используется ajax) с конфигурациями для этого кастомера.

Выбор конфигурации осуществляеться кликом на соответсвующий ряд:

Когда таблица имеет более чем 5 рядов она скролиться, т.е. имеет ползунок (максимальное количество рядов в таблице пять). Когда таблица имееет более чем пять рядов она меняет свой стиль:

Почему это происходит я не знаю.
Если мы нажием на какой либо ряд в таблице (таблица имеет более чем 5 рядов) или вообще по любой области на странице, сначала выпадающий список расфокусируется а потом (или раньше) таблица меняет свой стиль:

И таким образом, для того чтобы выбрать конфигурации в таблице с более чем 5 рядов необходимо кликать дважды. (надо чтобы выбиралось только с одного клика)
js код:
function changeCustomerName(customerName) {
        getConfigurationsForSpecifiedCustomer(customerName);
    }

function createTableForConfiguration(data){
    fillTable(data);
    $('#configurationTable').show();
}

function fillTable(data){
    $('#tableBody').empty();
    data.forEach(function(item) {
        $('#tableBody').append(
            '
' +
            '' +
            item.id +
            '	' +
            '' +
            item.name +
            '	' +
            '
'
        )
    });
}

function getConfigurationsForSpecifiedCustomer(customerName) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/getConfigurationsForSpecifiedCustomer",
        data: JSON.stringify(customerName),
        dataType: 'json',
        success: function(response) {
            createTableForConfiguration(response);
        },
        error: function(e){
            // alert('Error from getConfigurationsForSpecifiedCustomer' + e);
            console.log('Error from getConfigurationsForSpecifiedCustomer' + e);
            $('#configurationTable').hide();
        }
    });
}

$(document).ready(function(){

$('#secondTable').on("click", '#tableBody tr', function(){
    var selected = $(this).hasClass("highlight");
    $("#tableBody tr").removeClass("highlight");
    if(!selected)
        $(this).addClass("highlight");
    $("[name='configuration']").val($(this).context.children[0].innerText);
});

});

html:

                    id
                    Configuration Name
                    Product Name
                    Product Version
                    Solution Build
                    Customer Name
                    GP Code
                    Oracle DB Version
                    Configuration Version

Style:
body {
    font-size: 1em;
}

h1 {
    font-size: 2em;
}

table.tableBorder {
    width: 100%;
    border: 1px solid black;
    border-collapse: collapse;
}

table.tableBorder th, table.tableBorder td {
    padding: 4px 3px;
    border: 1px solid black;
}

.scroll{
    width: 100%;
    max-height: 150px;
    overflow: auto;
}

.highlight { background-color: grey; }

Ajax response:

В Ajax response возвращается List. Configuration - это POJO класс.
Заметил, что если передавать List то все работает нормально, стиль таблицы не меняется и двойного нажатия не требует.
Контроллер который отвечает на ajax call:
@RequestMapping(value = "/getConfigurationsForSpecifiedCustomer", method=RequestMethod.POST)
public @ResponseBody List<Configuration> getConfigurationsForSpecifiedCustomer(@RequestBody String customer) {
    if("".equals(customer))
        return null;
    return configurationService.getConfigurationsOfCustomer(customer.replaceAll("\"", ""));
}

Configuration class:
@Builder
@AllArgsConstructor
@Data
public class Configuration {
    private final int version;
    private final UUID id;
    private final String name;
    private final String author;
    private final String comment;
    private Map<String, String> customerInfo;
    private Collection<Rule> rules;
    private Collection<WhiteListItem> whiteList;
}

Версия jquery^
/static/js/jquery-2.1.1.min.js

В чем тут проблема понять не могу, да и мозг отказывается. Буду рад вашим предположениям.

A: Похоже на то, что появляется скролл, из-за этого меняется ширина таблицы и из-за этого меняется отображение таблицы.
Попробуйте задать ширину таблицы побольше.


text:
Q: Mollifying Green's functions with heat kernel and conformal invariance For domain D consider Green's fcn $G_{D}(x,y)$ and heat kernel $H_{D}$ and mollify
$$K_{D}(x,y,t)=\int_{D}\int_{D}H_{D}(x,w,t)H_{D}(u,y,t)G_{D}(w,u)d^{2}wd^{2}u.$$
The green's fcn satisfies $G_{D}(x,y)=G_{f(D)}(f(x),f(y))$ for conformal $f:D\to f(D)$.
Q1 I am wondering if $K_{D}$ (or some other Green's fcn mollification) satisfies any invariance property for possibly different types of maps.
Q2 Does $K_{D}$ have any interesting properties? Any papers or books where it was studied?
Attempts on Q1
1)By expressing the kernels in  $L^{2}$-basis $\phi_{k}$ and $\nabla-$basis $f_{k}=\phi_{k}/\lambda_{k}^{1/2}$ (i.e. $\int \nabla f_{k}\nabla f_{m}=\delta_{km}$) we have $H_{D}=\sum \phi_{k}(x)\phi_{k}(y)e^{-\lambda_{k}t}$, $G_{D}=\sum f_{k}(x)f_{k}(y)$ and
$$K_{D}(x,y,t)=\sum f_{k}(x)f_{k}(y)e^{-2\lambda_{k}t}.$$
By conformal invariance of $\nabla-$basis we have that $f_{k}^{f(D)}\circ f(x)$ is a $\nabla$ basis for $D$ and so  $G_{D}(x,y)=G_{f(D)}(f(x),f(y))$. However, I think it is still a conjecture that
$$\sum e^{-\lambda_{k}^{f(\mathbb{D})}t}\geq \sum e^{-\lambda_{k}^{\mathbb{D}}t}.$$
2)We want some f(x,t) s.t. $K_{D}(x,y,t)=K_{f(D,t)}(f(x,t),f(y,t),t)$.  One way would be if
$$H_{D}(x,w,t)=H_{f(D,t)}(f(x,t),f(w,t),t)|f'(w)|^{2}.$$
Since the LHS satisfies the heat eqn, one possible constraint for the RHS is $|f'|^{2}=1$ and $f''=f_{t}$. So given at most exponential growth, we have uniqueness and so they are equal.
However, as $t\to 0$ we would like to obtain a conformal map with no constraints on $|f'|^{2}$.


text:
Q: Postgres: What is the development process? What is the normal process for working with Postgres in a Node, React, Express application?
In that past, I've used MongoDB Atlas to quickly create and host a database for my development environment. My current project is using Postgres for the database, however, I'm trying to figure out the process/workflow.
For example, trying to find a Postgres as a service equivalent to Atlas, Heroku and Digital Ocean seem to match that bill. However, it looks like Heroku needs a deployed project to work. I don't want to deploy yet and really just want a development database.
Is it normal practice for everyone on the project to spin up a local Postgres database and then deploy/host a single production database at the end? Thanks for the help!

A: I would suggest following workflow that I've recently used on a project.

*

*local instances on docker or something (feature development purposes)

*first staging instance that could be used as stable dev env (can be used for specific feature testing, or as a internal testing environment)

*second staging instance where stable master branch with hashed prod data can be used for external testing

*prod or prod mirror, depends on project requirements

It would be also helpful to have migrations within the code, so that you can keep track of DB development as well. Also look into https://sequelize.org/ as it could be helpful.


text:
Q: NN vs Greedy Search Both NN and Greedy Search algorithms have a Greed nature, and both have tendency towards the lowest cost/distance (my understanding may be incorrect though). But what makes them different in a way that each one can be classified into a distinct algorithm group is somehow unclear to me.
For instance, if I can solve a particular problem using NN, I can surely solve it with Greedy Search algorithm as well specially if minimization is the case. I came to this conclusion because when I start coding them I come across very similar implementations in code although the general concept behind both might be different. Sometimes I can't even tell if the implementation follows NN or Greedy Search.
I have done my homework well and searched enough on Google, but couldn't find a decent explanation on what distinguishes them from one another. Any such explanation is indeed appreciated.

A: Hmm, at a very high level they both driven by heuristics in order to evaluate a given solution against an ideal solution. But, whilst a greedy search algo outputs a solution for a given input, the NN trains a model that will generate solutions for given inputs. So at a very very high level, you can think that the NN generates a solution finder, whereas the greedy search is a harcoded solution finder.
In other words, the NN will generate "code" (i.e. the model (aka the weights)) that finds solutions to the problem when provided to the same network topology. The greedy search is you actually writing the code that finds the solution to the problem. This is quite wishy washy though, I'm sure there is a much more concise, academically sound way of expressing what I've just said
All of what I've just said in based on the assumption that by "Greedy search" you meant the algorithms to solve problems such as travelling sales man.
Another way to think of it is:
In greedy search, you write an algorithm that solves a search problem (find me the graph that best describes the relationship, based on provided heuristic(s), between data point A and data point B).
When you write a neural network, you declare a network topology, provide some initially "random" weights and some heuristics to measure output errors and then train the networks weights via a plethora of different methods (back prop, GAN etc). These weights can then be used as a solver for novel problems.
For what it's worth, I don't think an NN would be a good approach to generate a solver for travelling sales man problem. You would be far better off just using a common graph search algorithm..


text:
Q: three.js - webgl and canvas rendering performance issue I've created a 3d scene with below code.
<!DOCTYPE html>

        <title>3d Model using HTML5 and three.js</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

Now when I change rendering from WebGL to Canvas, the FPS drops down to 1-2 FPS from 56-57 FPS on mobile browser. Native browser does not display anything on page and in Opera page becomes too slow for operations. How do I make page operations fast with Canvas rendering or how do I enable webgl rendering on mobile browsers ?

A: canvas renderer is software mode only, that means no GPU acceleration, the CPU has to do all the hard work that's why your fps drop.
AFAIK not every mobile browser is able to use webgl renderer yet, you could give opera mobile a try it's capable of webgl.

A: One way to speed up canvas rendering is to reduce the number of segments used in TubeGeometry


text:
Q: How can I play Excitebots on a UK Wii? Did Excitebots ever come out in the UK, and if so where can I buy it?
If not, what do I need to do (jailbreaking/modding/etc...) to get my Wii to play a US copy?

A: According to Wikipedia, Excitebots only came out in the US.
If you do wish to play it however, I recommend you get a US copy from a store that ships to the UK (I use VideoGamesPlus to get my US games) and soft-mod your Wii to play games from all regions (you can also get a US Wii, but that'll be quite expensive effort for just one game).
Soft-modding your Wii isn't a very straightforward process and can potentially damage your Wii. There are several guides on the internet for doing so, I used the one here but I'm certain there are many other guides online.


text:
Q: Embed nicely formatted \listfiles into document I am preparing a document for my university and need to insert a list of used packages and their corresponding versions/dates in the appendix of the document.
One possibility is to just copy the output of \listfiles from the logs and format it by hand before actually handing in the final version of the document. But that feels error prone...
So is there a way to include such a list, table or whatever automagically?

A: Another solution
\documentclass{article}
%-- just for the example
\usepackage[a4paper]{geometry}
\usepackage{tikz}
\usepackage{lipsum}
%------------------------
\newlength\mtl
\makeatletter
\newcommand{\mtlistfiles}{%
\par\noindent
%%-- for measuring
\@for\@currname:=\@filelist\do{%
\setbox0=\hbox{\@currname}%
\ifdim\wd0>\mtl\relax\mtl=\wd0\fi}%
%%-- formating list
\@for\@currname:=\@filelist\do{%
\makebox[\mtl][l]{\@currname}
     \expandafter\ifx\csname ver@\@currname\endcsname\relax
     \else\@spaces\csname ver@\@currname\endcsname\fi
     \par\noindent}}
\makeatother
\listfiles
\begin{document}
bla bla
\mtlistfiles
\end{document}

A: The macros I propose just show the information for the document class and the packages, so only those with extension .cls or .sty, discarding the other files.
\documentclass{article}
\usepackage{xparse,l3regex,longtable,array}

\listfiles % initialize
\AtEndDocument{\printfilelist}

\ExplSyntaxOn
\NewDocumentCommand{\printfilelist}{}
 {
  \cleardoublepage
  \section*{Used ~ packages}
  \setlength{\LTleft}{0pt}
  \pagestyle{empty}
  \footnotesize
  \begin{longtable}{@{} >{\ttfamily}l >{\raggedright}p{.6\textwidth} @{}}
  \nobbz_print_filelist:
  \end{longtable}
 }

\tl_new:N \l_nobbz_filelist_body_tl

\cs_new_protected:Npn \nobbz_print_filelist:
 {
  \clist_map_inline:cn { @filelist }
   {
    \nobbz_print_fileinfo:n { ##1 }
   }
  \tl_use:N \l_nobbz_filelist_body_tl
 }

\cs_new_protected:Npn \nobbz_print_fileinfo:n #1
 {
  \regex_match:nnT { \.(sty|cls)\Z } { #1 }
   {
    \nobbz_print_pkginfo:n { #1 }
   }
 }

\cs_new_protected:Npn \nobbz_print_pkginfo:n #1
 {
  \tl_put_right:Nx \l_nobbz_filelist_body_tl
   {
    \exp_not:n { #1 }
    &
    \exp_not:v { ver@#1 }
    \exp_not:N \tabularnewline
   }
 }
\ExplSyntaxOff

\begin{document}

Some text

\end{document}

A variation for separating the file date from the information:
\documentclass{article}
\usepackage{xparse,l3regex,longtable,array,booktabs}

\listfiles % initialize
\AtEndDocument{\printfilelist}

\ExplSyntaxOn
\NewDocumentCommand{\printfilelist}{}
 {
  \cleardoublepage
  \section*{Used ~ packages}
  \setlength{\LTleft}{0pt}
  \footnotesize
  \begin{longtable}{@{} >{\ttfamily}l l >{\raggedright}p{.6\textwidth} @{}}
  \toprule
  \multicolumn{1}{@{}l}{\bfseries File~name} &
    \multicolumn{1}{c}{\bfseries Date} &
    \bfseries File~info
  \tabularnewline
  \midrule
  \endhead
  \bottomrule
  \endfoot
  \nobbz_print_filelist:
  \end{longtable}
 }

\tl_new:N \l_nobbz_filelist_body_tl
\tl_new:N \l_nobbz_fileinfo_tl

\cs_new_protected:Npn \nobbz_print_filelist:
 {
  \clist_map_inline:cn { @filelist }
   {
    \nobbz_print_fileinfo:n { ##1 }
   }
  \tl_use:N \l_nobbz_filelist_body_tl
 }

\cs_new_protected:Npn \nobbz_print_fileinfo:n #1
 {
  \regex_match:nnT { \.(sty|cls)\Z } { #1 }
   {
    \nobbz_print_pkginfo:n { #1 }
   }
 }

\cs_new_protected:Npn \nobbz_print_pkginfo:n #1
 {
  \tl_set_eq:Nc \l_nobbz_fileinfo_tl { ver@#1 }
  \tl_replace_once:Nnn \l_nobbz_fileinfo_tl { ~ } { & }
  \tl_put_right:Nx \l_nobbz_filelist_body_tl
   {
    \exp_not:n { #1 }
    &
    \exp_not:V \l_nobbz_fileinfo_tl
    \exp_not:N \tabularnewline
   }
 }
\ExplSyntaxOff

\begin{document}

Some text

\end{document}


text:
Q: Create shortcut key in firefox to open a URL My system is Xubuntu 16.04 and I would like to create a shortcut key to open a URL. I don't want a desktop entry to open a URL, I know that I can create a desktop shortcut to open a URL. To be precise: Is it possible to set a shortcut key combination to open a URL directly in firefox (not a desktop entry!)?
thanks, Vladi

A: This is not directly in firefox, but isn't using a desktop shortcut either. It won't create a file or link anywhere visibly in your files, so I assume this will fit your needs:

*

*Go to settings and open your Keyboard settings

*Go to the Application Shortcuts tab

*Hit Add and enter the following command: firefox --new-tab "http://example.com" The --new-tab is important if you don't want firefox to open a new window.

*Hit Ok and enter the shortcut you would like to use for this URL.

That's the closest you can get to having a shortcut without a desktop launcher or something like that. There might be an addon for firefox but with bare firefox I don't think it's possible to have an URL shortcut, except for your homepage, of course. (Alt + Home)


text:
Q: PHP Find data in same row as string in SQL Server In my SQL Server, I've got a column called registration. In an HTML page, the user types in a registration. Then, when submit is pressed, I need to run my PHP script and get information in the same row as the registration entered. So, put simply, how do I search the column for a value, and then pull information from the row it is found in? I've got
<?php
$db = mssql_connect("10.1.173.21", "jsonrequsr", "");
mssql_select_db("rygorWestburySite",$db);
$result = mssql_query("SELECT Registration, StageOne, StageTwo, StageThree",$db);
$num = mssql_num_rows($result);
$myrow = /* what goes here */;
$i = 1;
if (/* what to put here */) do {
if ($myrow["StageOne"] == "Completed" and $myrow["StageTwo"] == "Incompleted" and $myrow["StageThree"] == "Incompleted") {
    echo "\"itemId\":\"itemid\", \"itemType\":\"JC_AlertView\", \"loadScreenWithItemId\":\"itemid\"";
} elseif ($myrow["StageOne"] == "Completed" and $myrow["StageTwo"] == "Completed" and $myrow["StageThree"] == "Incompleted") {
    echo "\"itemId\":\"itemid\", \"itemType\":\"JC_AlertView\", \"loadScreenWithItemId\":\"itemid\"";
} elseif ($myrow["StageOne"] == "Completed" and $myrow["StageTwo"] == "Completed" and $myrow["StageThree"] == "Completed") {
    echo "\"itemId\":\"itemid\", \"itemType\":\"JC_AlertView\", \"loadScreenWithItemId\":\"itemid\"";
} if ($num > $i) printf(",");
$i++;
} while ($myrow = mssql_fetch_array($result));
else {
echo "Sorry, nothing there to see!";
}
?>

so far, and it returns blank... and according to PHP Code Checker, the syntax is all correct so far.
Ed

A: Edit:
Okay, I misunderstood your problem. What you could do is with an SQL-query find the row using the registration column. That is, the registration columns value has to be unique, for you only to get one item.
SELECT * FROM table_name where registration = 'user_input';

Pre-edit:
If you're using AUTO_INCREMENT on your ID column for the registration which you should have, then you can just use mysql_insert_id to get the last ID that was inserted and then fetch that row by that ID and show the data that way.
Also you should have an ID (integer) for your table which is the primary key and set to auto increment.


text:
Q: cannot change keyboard layout any longer After a recent Ubuntu update and reboot, my keyboard map -- se -- has disappeared and the layout is frozen to us.
Here is the output from setxkbmap:
~% setxkbmap -v
Trying to build keymap using the following components:
keycodes:   evdev+aliases(qwerty)
types:      complete
compat:     complete
symbols:    pc+se(nodeadkeys)+inet(evdev)
geometry:   pc(pc105)
Error loading new keyboard description

A: Found it--my bad:
I had tried recently to change some definitions in the layout file (/usr/share/X11/xkb/symbols/se) without any effect, so I gave up. Obviously, I made a mistake which somehow disabled the whole chain of setting the layout properly. That was only activated by the reboot. Reverting the changes and rebooting brought the keyboard layout back.
I still do not understand how this all is connected and why it had this effect, but this issue is solved. Nothing to do with the Ubuntu update other than that I rebooted.


text:
Q: Can not write the result in text file - C# I have the following code to extract 2 objects from each html page and save it in array. and finally write it in textfile. But I can not see the result in text file.
Thanks in  advance
for (int y = 0; y < 9; y++)
{
    if (IDs[y] == null)
    break;
    else
    {
        string item = Convert.ToString(IDs[y]);
        string url = "http://mu/tr/";
        string URL = url+item;
        WebClient web = new WebClient();
        String html= web.DownloadString(URL);
        MatchCollection m1 = Regex.Matches(html, @"<strong>\s*(.+?)\s*</strong>");
        MatchCollection m2 = Regex.Matches(html, @"<title>\s*(.+?)\s*</title>");
        foreach(Match m in m1)
        {
           string Gre = m.Groups[1].Value;
           string sic = m.Groups[2].Value;
           ITEM [y][0] = Convert.ToString(item);
           ITEM [y][1] = sic;
           ITEM [y][2] = Gre;
        }
     }
 }
 for (int row = 0; row < 9; row++)
 {
    for (int col = 0; col < 3; col++)
    {
        SIC.Write(ITEM[row][col] + " ");
    }
 SIC.WriteLine();
 }
SIC.WriteLine();

A: I can't comment because i don't have enough points but are you closing the stream writer and file when you are done?
If yeas and still no output debug the program. If all else fails open the stream write one test line and close. If the text is seen in the file then it is a problem in the for loop.

A: Check that your IIS process have enough permission to write in to this particular directory.


text:
Q: How to evaluate the integral $\int e^{2x} \sin^2x\ dx$ How can I evaluate the following integral?
$$\int e^{2x} \sin^2x\ dx$$

A: Note that
$$\int (e^x \sin x)^2\, dx = \int e^{2x}\left[\frac{e^{ix}-e^{-ix}}{2i}\right]^2 \, dx= -\frac1{4}\int [e^{2(1+i)x}-2e^{2x}+e^{2(1-i)x}] \,dx \\= -\frac1{8(1+i)}e^{2(1+i)x}+\frac{2e^{2x}}{8}-\frac1{8(1-i)}e^{2(1-i)x}+C=\\=-\frac1{8}e^{2x}\left[-2+\frac{e^{2ix}}{1+i}+\frac{e^{-2ix}}{1-i}\right]+C\\-\frac1{8}e^{2x}[-2+\cos (2x)+\sin(2x)]+C$$

A: Here are the steps
\[
\int e^{2x}\sin^{2} x\ dx=\frac{1}{2}\int e^{2x}(1-\cos(2x))\ dx
\]
Let $u=2x$
\[
\frac{d}{dx}u=2\Rightarrow du=2\ dx \Rightarrow \frac{1}{2}du=dx
\]
Then
\[
\frac{1}{2}\int e^{2x}(1-\cos(2x))\ dx= \frac{1}{4}\int e^{u}(1-\cos u)\ du = \frac{1}{4}\int e^{u}-e^{u}\cos u\ du
\]
\[
= \frac{1}{4}\int e^{u}\ du- \frac{1}{4}\int e^{u}\cos u\ du= \frac{1}{4}e^{u}- \frac{1}{8}e^{u}(\sin u+\cos u) +C
\]
\[
=\frac{2}{8}e^{u}- \frac{1}{8}e^{u}(\sin u+\cos u) +C=-\frac{1}{8}e^{2x}(\sin(2x)+\cos(2x)-2)+C
\]
Thus
\[
\int e^{2x}\sin^{2} x\ dx =-\frac{1}{8}e^{2x}(\sin(2x)+\cos(2x)-2)+C
\]

A: Using operator D and its properties, we have
$$
\int e^{2x}\sin^2xdx = \dfrac{1}{2D}[e^{2x} - e^{2x}\cos(2x)] = \dfrac{1}{4}e^{2x} - \dfrac{e^{2x}}{2}\dfrac{1}{D+2}\cos(2x)
$$
$$
= \dfrac{1}{4}e^{2x} - \dfrac{e^{2x}}{2}\dfrac{D - 2}{D^2 - 4}\cos(2x) = \dfrac{1}{4}e^{2x} + \dfrac{e^{2x}}{16}[-2\sin(2x) - 2\cos(2x)]
$$
$$
=  \dfrac{1}{4}e^{2x} - \dfrac{e^{2x}}{8}[\sin(2x) + \cos(2x)] + C
$$


text:
Q: $\int_{-\infty}^{\infty}\frac{\mathrm{d}x}{ax^2+bx+c}=\pi$ similar identities I recently found that
$$\int_{-\infty}^{\infty}\frac{\mathrm{d}x}{ax^2+bx+c}=\pi$$
iff
$$b^2-4ac=-4.$$
I found it by integrating
$$I=\int_{-\infty}^{\infty}\frac{\mathrm{d}x}{ax^2+bx+c}.$$
If the reciprocal of the function is to be integrated over the entire real line, then the function must not have any real zeros. This implies that $$b^2-4ac<0$$
With this in mind, we complete the square:
$$I=\int_{-\infty}^{\infty}\frac{\mathrm{d}x}{a(x+\frac{b}{2a})^2+c-\frac{b^2}{4a}}.$$
Then setting $g=c-\frac{b^2}{4a}$, and $x+\frac{b}{2a}=\sqrt{\frac{g}{a}}\tan u$,
$$I=\sqrt{\frac{g}{a}}\int_{-\pi/2}^{\pi/2}\frac{\sec^2u\ \mathrm{d}u}{g\tan^2u+g}=\frac{\pi}{\sqrt{ag}}.$$
So our identity holds for
$$ag=1.$$
And with a little algebra,
$$b^2-4ac=-4.$$
So my question is, are there any other similar identities involving other famous constants? Cheers!

A: First if we consider the integral:
\begin{equation}
 I(a) = \int_{-\infty}^{\infty}\frac{1}{x^2 + a^2}\:dx = \frac{\pi}{a}
\end{equation}
Then we can see:
\begin{equation}
 I(a) + cI(b) = \left[\int_{-\infty}^{\infty}\frac{1}{x^2 + a^2}\:dx + c\int_{-\infty}^{\infty}\frac{1}{x^2 + b^2}\:dx \right] = \frac{\pi}{a} + c\frac{\pi}{b} = \pi\left[\frac{1}{a} + c\frac{1}{b} \right]
\end{equation}
We can see that this can be expanded to any number of $I(a)$ terms and any sequence of $c_i$ values, i.e.
\begin{equation}
 \sum_{i = 1}^{\infty} (-1)^{i + 1} \frac{1}{i + 1}I(i) = \pi \sum_{i = 1}^{\infty} \frac{(-1)^{i + 1}}{i + 1} = \pi\ln(2)
\end{equation}
Thus,
\begin{equation}
 \sum_{i = 1}^{\infty} \int_{-\infty}^{\infty}  \frac{(-1)^{i + 1}}{x^2 + \left(i + 1\right)^2} \:dx = \pi \sum_{i = 1}^{\infty} \frac{(-1)^{i + 1}}{i + 1} = \pi\ln(2)
\end{equation}
Or as another example,
\begin{equation}
 \sum_{i = 1}^{\infty} \int_{-\infty}^{\infty}  \frac{1}{x^2 + i^4} \:dx = \frac{ \pi^3}{6}
\end{equation}
What's even better (IMO) is that we can take each integral spoken to and apply (through Glasser Master Theorem)
$$x = t - \sum_{i = 1}^{n - 1}\frac{\left| d_{i}\right|}{ t - e_{i}}$$
Where $d_i, e_i \in \mathbb{R}$ and $n \in N$ that the value of the integrals remain unchanged!!
As an addendum to the example:
\begin{equation}
 \sum_{i = 1}^{\infty} \int_{-\infty}^{\infty}  \frac{(-1)^{i + 1}}{x^2 + \left(i + 1\right)^2} \:dx = \pi \sum_{i = 1}^{\infty} \frac{(-1)^{i + 1}}{i + 1} = \pi\ln(2)
\end{equation}
If we call on this integral as addressed here we see that
\begin{equation}
 2\int_{0}^{\frac{\pi}{2}} \frac{x}{\tan(x)} \:dx = 2\sum_{i = 1}^{\infty} \int_{-\infty}^{\infty}  \frac{(-1)^{i + 1}}{x^2 + \left(i + 1\right)^2} \:dx =\pi\ln(2)
\end{equation}
Or,
\begin{equation}
 \int_{0}^{\frac{\pi}{2}} \frac{x}{\tan(x)} \:dx = \sum_{i = 1}^{\infty} \int_{-\infty}^{\infty}  \frac{(-1)^{i + 1}}{x^2 + \left(i + 1\right)^2} \:dx = \frac{\pi\ln(2)}{2}
\end{equation}

A: I'm not sure if this example's interesting enough to be an answer, because it can get any result you want with different linearly independent choices of the integrand, so if pressed I'll convert it into a comment.
As has been noted here before, any $f$ analytic on the unit disk in $\Bbb C$ satisfies $$\int_0^{2\pi}\Re f(e^{i\phi})d\phi=2\pi\Re f(0),$$which can be used to get a daunting-looking integral expression for any real value. I've designed some deliberately not-too-complicated examples (so let's hope I made no mistakes in my mental arithmetic).
To ensure that integral is equal to some $k>0$ choose$$f(z):=\exp\frac{\ln\frac{k}{2\pi}}{1+z/2},$$and multiply this choice of $f$ by $z$ or $z-1$ to get $0$ or $-k$ instead. If you try this as an exercise, you'll find for $k\ne 1$ the real integral you obtain is pretty gnarly (though nowhere near as much as it could be with some other choice of $f$), which is deliberate. If you want a far-from-obvious expression for $1$ that follows the same way, try $$f(z)=\exp\frac{z-2\ln 2\pi}{z+2}$$instead.


text:
Q: Plotting similar values on a shared index with Nans I have some data in the format of (x, y, class) like the following:
data = [(1, 2, 'A'), (2, 3, 'A'), (3, 4, 'A'), (4, 5, 'A'), (5, 6, 'A'), (1, 4, 'B'), (2, 5, 'B'), (3, 6, 'B'), (4, 7, 'B'), (5, 8, 'B'), (1, 3, 'C'), (2, 4, 'C'), (3.1, 5, 'C'), (4.1, 6, 'C'), (5.1, 7, 'C')]

And I would like to plot it using pandas. If one uses the commands:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(data, columns = ['x', 'y', 'c'])
df.pivot(index = 'x', columns = 'c', values = 'y').plot()
plt.show()

The output is as follows

If instead we drop class C using:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(data, columns = ['x', 'y', 'c'])
df[df['c'].isin(['A', 'B'])].pivot(index = 'x', columns = 'c', values = 'y').plot()
plt.show()

The output is

This is straightforward: because class C has some different x values, we end up with some nan results in the values columns which means pandas cannot plot the data.
I could use interpolate to fill in the missing values, as my data is not incredibly large, but the scale of my data is sufficiently large that it would make more sense to just plot class 'C' on top of the plot with the other two, meaning it needs to

*

*Be added to the legend

*Appear in its entirety on the plot

How can I do this?

A: Using seaborn is straightforward with lineplot.
import seaborn as sns
sns.lineplot(data=df, x='x', y='y', hue='c')

The other option with pandas is with groupby.
fig, ax = plt.subplots(figsize=(8,6))
for _label, _dfg in df.groupby('c'):
    _dfg.plot(x='x',y='y', ax=ax, label=_label)


text: Q: Compress PDF before upload in angular 7 I have an input button which is used to get the file. How can I compress it before uploading it to the server. Currently, 100mb pdf is taking about 12 mins to get uploaded. How should I reduce this time. Are there any compressing pdf npm libraries present to reduce the pdf size?


text:
Q: How to change VS 2017 RC .csproj project's target framework (from core to classic)? How to change target framework with VS 2017 RC in new core asp "csproj" projects?
I mean to change after project was created. There are no project.json file which was used for that in VS 2015. In project properties in targets "pull down" there are no other options then ".NETCoreApp 1.1" and ".NETCoreApp 1.0".
Details: I have used yoman to generate SPA project: http://blog.stevensanderson.com/2016/05/02/angular2-react-knockout-apps-on-aspnet-core/
so I was unable to select .NET Framework during the csproj creation. What to do now?

A: The safest option, if you have a few files, is to just add a new project with the correct framework. Then copy the files from the old project across. This will stop you having build and other issues.

.NET Core for example has its own class library, console and test types.

A: Edit csproj file this way:
<TargetFramework>netcoreapp1.1</TargetFramework>

replace with:
<TargetFramework>net462</TargetFramework>
<RuntimeIdentifier>win7-x86</RuntimeIdentifier>

and remove:
<PackageReference Include="Microsoft.NETCore.App" Version="1.1.0" />

Then
dotnet restore
dotnet build

Optional:
dotnet run

Do not start dotnet run from Package Manager Console. It starts but it become impossible to stop web app with ctrl c (standard way).
If VS F5 doesn't work, (true for VS 2017 RC, core services generated with yoman templates), then change:
<OutputType>winexe</OutputType>

to
<OutputType>Exe</OutputType>

and restart VS, rebuild is not enough (to enable F5, again true for VS 2017 RC).

A: They've moved the option.  It's now under the "Build" tab, under the "advanced" button.


text:
Q: Cannot create instance of Service Reference I have added a Service Reference to my Windows Phone 8 Project and it is showing in the Service Reference folder.
When I try to create an instance of the service, such as:
var service = new MobileService();

It doesn't recognise what MobileService is. Same goes for when I try doing using MobileService; at the top of the class.
Where am I going horribly wrong?

A: The class is probably called MobileServiceClient. Click the show all files option for your project and you can view the generated code of the service references.


text:
Q: Limiting keyboard inputs to A-Z as opposed to any keyboard input on React component I've just come across a component I'm struggling to get my head around, but basically the value I care about is allowForClassification, which is a boolean value that is passed down into a child component and determines whether or not we display a button. (Basically meaning that only after a user has typed a letter will the "Find" button appear - currently even a spacebar will trigger the button to appear).
However I'm struggling to understand in this component where exactly that check is being made, I understand that at the bottom allowForClassification is set to true if canClassify & !classifyInProgress are returned but I can't find where they are making the check for the keyboard entry, any advice would be really helpful.
const getCcceValues = (object?: FormObjectModel | null) => {
  const ccceInput: $Shape<CcceInput> = {};

  if (!object) {
    return {};
  }

  const ccceValues = object.attributeCollection.questions.reduce(
    (acc, attribute) => {
      const fieldEntry = ccceBeInformedFieldMap.get(attribute.key);

      if (fieldEntry) {
        acc[fieldEntry] = attribute.value;
      }

      return acc;
    },
    ccceInput
  );

  // ready to perfom classification based on user input
  const canClassify = Object.values(ccceValues).every(Boolean);

  return { canClassify, ccceValues };
};

export const useCcceEmbed = (
  ccceResultAttribute: AttributeType,
  onChange: Function
): CcceHook => {
  const { object, form } = useFormObjectContext();
  const [resultCode, setResultCode] = useState<string | null>(null);

  const { canClassify, ccceValues } = getCcceValues(object);

  const { handleSubmit } = useFormSubmit();

  const [showModal, setShowModal] = useState<boolean>(false);

  const handleCloseModal = useCallback(() => setShowModal(false), []);
  const handleShowModal = useCallback(() => setShowModal(true), []);

  // state value to keep track of a current active classification
  const [classifyInProgress, setClassifyInProgress] = useState<boolean>(false);

  const handleResult = useCallback(
    (result) => {
      if (result?.hsCode) {
        onChange(ccceResultAttribute, result.hsCode);

        setResultCode(result.hsCode);
        setClassifyInProgress(false);

        handleSubmit(form);
      }
    },
    [ccceResultAttribute, form, handleSubmit, onChange]
  );

  const handleCancelClassify = useCallback(() => {
    setClassifyInProgress(false);
    handleCloseModal();
  }, [handleCloseModal]);

  const handleClassify = useCallback(
    (event?: SyntheticEvent<any>) => {
      if (event) {
        event.preventDefault();
        console.log("scenario 1");
      }

      if (classifyInProgress || !canClassify) {
        console.log("scenario 2");
        return;
      }

      const ccce = window.ccce;

      if (!ccceValues || !ccce) {
        throw new Error("Unable to classify - no values or not initialised");
        console.log("scenario 3");
      }

      setClassifyInProgress(true);

      const classificationParameters = {
        ...ccceValues,
        ...DEFAULT_EMBED_PROPS,
      };

      ccce.classify(
        classificationParameters,
        handleResult,
        handleCancelClassify
      );
    },
    [
      classifyInProgress,
      canClassify,
      ccceValues,
      handleResult,
      handleCancelClassify,
    ]
  );

  return {
    allowForClassification: canClassify && !classifyInProgress,
    classifyInProgress,
    dataProfileId,
    embedID: EMBED_ID,
    handleCancelClassify,
    handleClassify,
    handleCloseModal,
    handleShowModal,
    isDebugMode,
    resultCode,
    shouldShowModal: showModal,
  };
};

A: Solution
There's a lot that's missing in this code and there may be a better way to do this.  But here's what I came up with.
Instead of evaluating whether or not the input value is empty, we can evaluate whether or not it contains a character.
Replace this line:
const canClassify = Object.values(ccceValues).every(Boolean);

With these two lines:
const regex = new RegExp('\w', 'g');

const canClassify = Object.values(ccceValues).every(value => regex.test(value));

or this one line:
const canClassify = Object.values(ccceValues).every(value => /\w/g.test(value))

Why That Line?
I arrived at that solution by working backwards.  Here's all the steps that I took through the code to arrive at the right place.
allowForClassification: canClassify && !classifyInProgress,

allowForClassification is true if canClassify is true and classifyInProgress is false.  We don't want to classify if we are already performing a classification.  That makes sense.  So it's the canClassify value that we care about.
const { canClassify, ccceValues } = getCcceValues(object);

canClassify comes from the getCcceValues function, and it's value may depend on the value of object.
const { object, form } = useFormObjectContext();

object comes from some external hook which is a dead end for me because I can't see that code.  But note that there might be some alternative solution here.
const canClassify = Object.values(ccceValues).every(Boolean);

.every(Boolean) has the same meaning as writing it out longform .every(value => Boolean(value)).  canClassify is true if every value of ccceValues is true when cast to a Boolean.  Which means that the value is anything other than: false, 0, -0, 0n, "", null, undefined, NaN. (source)
const ccceInput: $Shape<CcceInput> = {};

const ccceValues = object.attributeCollection.questions.reduce(
    (acc, attribute) => {
      const fieldEntry = ccceBeInformedFieldMap.get(attribute.key);

      if (fieldEntry) {
        acc[fieldEntry] = attribute.value;
      }

      return acc;
    },
    ccceInput
);

ccceValues is  bit complex.  It created by an array .reduce() operation. It starts with an initial value of ccceInput which is an empty object {}.  At each step of the iteration, it maybe sets one property on that object.  The final value is the object after a bunch of properties have been set.
The arguments in the callback are acc -- the object that we are building, and attribute -- the current element of the questions array.  The key that we are setting is fieldEntry and the value is attribute.value.
Remember that canClassify checks if all values are "truthy".  So the key doesn't matter.  We only care about the value (attribute.value).

Why That Code?
But working backwards, what we learning is that when canClassify/allowForClassifiation is true in cases where you want it to be false, it's because there are values where Boolean(attribute.value) is true when you want it to be false.  Why is that?
I'm going to make a logical assumption that the attribute.value variable contains the string that the user has typed in the box.
Remember what I said earlier about Boolean casting.  The empty string '' is false and all other strings are true.  So if there is at least one box in object.attributeCollection.questions where the user hasn't entered anything, then allowForClassification will be false because attribute.value will be ''.
As soon as the user hits the spacebar in the last box, the attribute.value becomes ' '. This string has a Boolean value of true, so allowForClassification is now true.
But you want to apply a different ruleset.  You want to consider a value as true if and only if it contains at least one letter.  We can check that using a simple regular expression.  I'm not sure of your exact ruleset (Are numbers ok? What about underscores? What about accented/non-Latin characters?), so you might need to tweak the regex.  But this should get you 99% of the way there.
const regex = new RegExp('\w', 'g');
// can also be written as: const regex = /\w/g;

I am using the \w alphanumeric character class and the g global match flag to match any alphanumeric character anywhere in a string.
To check if a string matches this regex, use the .test() method.
const hasCharacter = regex.test(someString);

We want to use this function in the .every() callback of canClassify instead of the Boolean constructor function.  So we write:
const canClassify = Object.values(ccceValues).every(value => regex.test(value));


text:
Q: Kendo Grid Read data with parameters that comes NULL for a some reasons I'm using the following code:
@(Html.Kendo().Grid(Model.Orders)
  .Name("gridOrders")
  .Columns(columns =>
      {
          columns.Bound(p => p.Date).Title("Date");
          columns.Bound(p => p.Reference).Title("Reference");
          columns.Bound(p => p.Products).Title("Product(s)");
          columns.Bound(p => p.Customer).Title("Customer");
          columns.Bound(p => p.ServiceName).Title("Service");
          columns.Bound(p => p.OrderTotal).Title("Order total");
      })
  .Pageable()
  .Sortable()
  .Scrollable(scr => scr.Height(400))
  .Filterable()
  .Editable(editable => editable.Mode(GridEditMode.InLine))
  .DataSource(dataSource => dataSource
      .Ajax()
      .Model(model => model.Id(p => p.ID))
      .Model(model => model.Field(x => x.Reference).Editable(false))
      .Model(model => model.Field(x => x.OrderTotal).Editable(false))
      .Model(model => model.Field(x => x.Date).Editable(false))
      .Model(model => model.Field(x => x.ServiceName).Editable(false))
      .Model(model => model.Field(x => x.Products).Editable(false))
      .Model(model => model.Field(x => x.Customer).Editable(false))
      .PageSize(10)
      .ServerOperation(true)
      //.Read(read => read.Action("GetOrders", "Dashboard", new { datex = "lalala" } ))
      .Read(read => read.Action("GetOrders", "Dashboard").Type(HttpVerbs.Post).Data("getValues"))
  ))

As you see getValues JavaScript function used. What I have in this function:
<script>
function getValues() {
    return {
        datex: "2012/12/12" // $("#dates").data("kendoDropDownList").value()
    };
}
</script>

In controller code I got datex parameter as NULL:
        [HttpPost]
    public JsonResult GetOrders([DataSourceRequest]DataSourceRequest request, string datex)
    {...}

I have no any ideas why that's happen... Docs told me that all must be ok.

A: What is your Kendo UI version ?
As mentionned on this thread :

There is a known issue regarding the sending of additional data parameters in Q3 SP1 release i.e. version 2013.3.1316.

Maybe you just have to upgrade your version.


text:
Q: Entityframework navigation property insert I have these models that ParentID foreign key for CustomerID
I want to insert an address for customer via navigation property
what should I do?
public partial class Customer
{
    public long CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Cart> Carts { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
}

public partial class Address
{
    public long AddressID { get; set; }
    public long ParentID { get; set; }
    public string State { get; set; }
    public string City { get; set; }
    public string Address1 { get; set; }
    public string PostalCode { get; set; }

    public virtual Customer Customer { get; set; }
    public virtual Supplier Supplier { get; set; }
}


text:
Q: Url.OpenConnection cannot find web address my  Url.OpenConnection cannot find web address in android 4.3 (my client smartphone she is in Spain) and list view doesnot load nothing not even crash, but load xml content on android 2.2 normally (I'm in Argentina) , anybody know what the problem would be please the web page is http://dev.mejorconsalud.com/feed/ from where I'm getting the xml, I don't have any cat log so please any suggestion
URL url = new URL(urlString);
URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());

A: Try to use these two class. It will help you.

**UHttpClient .java**

public class UHttpClient {

    private HttpClient httpClient = null;

    public static final int OK = 200;
    public static final int NO_CONTENT = 204;

    private static final int CONNECTION_TIMEOUT = 5000;

    /* timeout for waiting for data, since once connection is established then waiting for response*/
    private static final int SOCKET_TIMEOUT = 20000;

    public UHttpClient(UAppInstance appInstance, String loginURL, String deviceID)
    throws UBaseException {

        HttpParams httpParameters = new BasicHttpParams();

        // Set the timeout in milliseconds until a connection is established.
        HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);

        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);

        //httpClient = new DefaultHttpClient(httpParameters);
        httpClient = new DefaultHttpClient();

        login(loginURL, deviceID);
    }

    /**
     * Makes the GET call
     * @param urlStr - Url string
     * @param paramNames - parameter names
     * @param paramValues - parameter values
     * @return - response body string
     * @throws UBaseException
     */
    public String executeGet(String urlStr, String[] paramNames, String[] paramValues)
    throws UBaseException {

        HttpGet httpget = null;

        try {
            int length = paramNames != null ? paramNames.length : 0;

            urlStr = length > 0 ? (urlStr + "?") : urlStr;
            for (int k = 0; k < length; k++) {
                urlStr = k > 0 ? (urlStr + "&") : urlStr;
                urlStr = urlStr + paramNames[k] + "=" + paramValues[k];
            }

            httpget = new HttpGet(urlStr);

            // Execute HTTP Get Request
            ResponseHandler<String> respHandler = new BasicResponseHandler();
            String response = httpClient.execute(httpget, respHandler);

            return response;

        } catch (SocketTimeoutException e) {
                throw new UBaseException("Connection Timeout", e);
        } catch (Exception e) {
            if(null == e.getMessage() || "".equals(e.getMessage()))
                throw new UBaseException("Unable to connect to server", e);
            else
                throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Makes the POST call
     * @param urlStr - Url string
     * @param paramNames - parameter names
     * @param paramValues - parameter values
     * @return - response body string
     * @throws UBaseException
     */
    public String executePost(String urlStr, String[] paramNames, String[] paramValues)
    throws UBaseException {

        HttpPost httppost = new HttpPost(urlStr);

        try {
            int length = paramNames != null ? paramNames.length : 0;
            ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();

            for (int k = 0; k < length; k++) {
                paramsList.add(new BasicNameValuePair(paramNames[k], paramValues[k]));
            }

            List<NameValuePair> nameValuePairs = paramsList;
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            ResponseHandler<String> respHandler = new BasicResponseHandler();
            String response = httpClient.execute(httppost, respHandler);

            return response;

        } catch (SocketTimeoutException e) {
                throw new UBaseException("Connection Timeout", e);
        } catch (Exception e) {
            if(null == e.getMessage() || "".equals(e.getMessage()))
                throw new UBaseException("Unable to connect to server", e);
            else
                throw new UBaseException(e.getMessage(), e);
        }
    }

    protected void login(String url, String deviceID)
    throws UBaseException {

        String[] argNames = new String[] {"userDeviceID", "loginMode", "command"};
        String[] argValues = new String[] {deviceID, "handheldLogin", "login"};

        String response = executePost(url, argNames, argValues);

        if(null != response){
            response = response.trim();
        }

        // if response message is not success that means it's a failure so raising exception
        if("success".equals(response) == false) {
            if(!"".equals(response))
                throw new UBaseException(response, null);
            else
                throw new UBaseException("Remote login failed to '" + url + "'", null);
        }
    }
}

**URemoteConnection.java**

public class URemoteConnection {

    private UHttpClient client = null;
    private String remoteHost = null;

    private String appName = null;
    private String servletName = null;
    private String remoteURL = null;
    private String deviceID = null;

    private String httpPortNum = "";
    private String httpsPortNum = "";

    private static final String REMOTE_APP_NAME = "_REMOTE_APP_NAME_";
    private static final String REMOTE_HOST_ADDRESS = "_REMOTE_HOST_ADDR_";
    private static final String REMOTE_HTTP_PORT = "_REMOTE_HTTP_PORT_";
    private static final String REMOTE_HTTPS_PORT = "_REMOTE_HTTPS_PORT_";

    private static final String FEEDBACK_MSG_SEPERATOR = "-stat-";
    private static final String FEEDBACK_MSG_SUCCESS_STR = "200";

    /**
     * URemoteConnection constructor
     *
     * @param appInstance
     *            - UAppInstance object
     * @param app
     *            - remote application name
     * @param servlet
     *            - servlet name
     * @throws UBaseException
     */
    public URemoteConnection(UAppInstance appInstance, String app,
            String servlet) throws UBaseException {

        try {
            appName = app;
            servletName = servlet;
            remoteHost = getServerAddress(appInstance, appName);
            httpPortNum = getServerHttpPort(appInstance, appName);
            httpsPortNum = getServerHttpsPort(appInstance, appName);
            deviceID = CommonUtils.getUserDeviceID(appInstance);

            remoteURL = "http://" + remoteHost + ":" + httpPortNum + "/"
                    + appName + "/" + servletName;

            String loginURL = "http://" + remoteHost + ":" + httpPortNum + "/"
                    + appName + "/Login";

            Log.d("URemoteConnection", "remoteURL : " + remoteURL);

            Log.d("URemoteConnection", "loginURL : " + loginURL);

            client = new UHttpClient(appInstance, loginURL, deviceID);

        } catch (Exception e) {
            throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Call to do any data upload. Makes Http POST call.
     *
     * @param argsNames
     * @param argsValues
     * @return - response text
     * @throws UBaseException
     */
    public String processData(String[] argsNames, String[] argsValues)
            throws UBaseException {
        try {
            String response = client.executePost(remoteURL, argsNames,
                    argsValues);
            response = _filterFeedBackMsg(response);
            return response;

        } catch (Exception e) {
            throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Call to do any data download. Makes Http GET call.
     *
     * @param argsNames
     * @param argsValues
     * @return - response body string
     * @throws UBaseException
     */
    public String requestData(String[] argsNames, String[] argsValues)
            throws UBaseException {
        try {
            String response = client.executeGet(remoteURL, argsNames,
                    argsValues);
            response = _filterFeedBackMsg(response);
            return response;

        } catch (Exception e) {
            throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Loads the remote app details from database and populates the in-memory
     * cache.
     *
     * @param appInstance
     * @throws UDBAccessException
     */
    public static void loadRemoteAppDetails(UAppInstance appInstance)
            throws UDBAccessException {
        Cursor cur = appInstance.getDBHandle().executeQuery(
                "mobi_remote_app",
                new String[] { "remote_app_name", "remote_host_address",
                        "remote_http_port", "remote_https_port" }, null, null,
                null, null, null);

        while (null != cur && cur.moveToNext()) {
            String appName = cur.getString(cur
                    .getColumnIndex("remote_app_name"));

            appInstance.setAttribute(REMOTE_APP_NAME, appName);
            appInstance.setAttribute(REMOTE_HOST_ADDRESS + "~" + appName,
                    cur.getString(cur.getColumnIndex("remote_host_address")));
            appInstance.setAttribute(REMOTE_HTTP_PORT + "~" + appName,
                    cur.getString(cur.getColumnIndex("remote_http_port")));
            appInstance.setAttribute(REMOTE_HTTPS_PORT + "~" + appName,
                    cur.getString(cur.getColumnIndex("remote_https_port")));
        }

        if (null != cur) {
            cur.close();
        }
    }

    public static String getServerAddress(UAppInstance appInstance,
            String appName) {

        return "172.16.0.117";
    }

    public static String getServerHttpPort(UAppInstance appInstance,
            String appName) {

        return "8080";
    }

    public static String getServerHttpsPort(UAppInstance appInstance,
            String appName) {
        return appInstance.getAttribute(REMOTE_HTTPS_PORT + "~" + appName, "");
    }

    /*
     * Checking if from the server side if any error coming then throw the
     * exception else sent the original feedback
     */
    private static String _filterFeedBackMsg(String feedBackMsg)
            throws Exception {
        if (feedBackMsg != null && !"".equals(feedBackMsg)
                && !feedBackMsg.equalsIgnoreCase("null")) {
            if (feedBackMsg.indexOf(FEEDBACK_MSG_SEPERATOR) > -1) {
                String feedBackMsgArr[] = feedBackMsg
                        .split(FEEDBACK_MSG_SEPERATOR);
                if (feedBackMsgArr != null && feedBackMsgArr.length > 1) {
                    if (feedBackMsgArr[0] != null
                            && !FEEDBACK_MSG_SUCCESS_STR
                                    .equals(feedBackMsgArr[0])) {
                        throw new Exception(feedBackMsgArr[1]);
                    }
                }
            }
        }
        return feedBackMsg;
    }
}


text:
Q: Aligning Maths in a Table Column Is there a way to align this column on t_p?
\begin{center}
\begin{tabular}{cl}
 $t_p \le -2\; ^\circ\mathrm{C},$                            & frost is expected \\
 $-2\; ^\circ\mathrm{C} \le\, t_p \le 2\; ^\circ\mathrm{C}$ & frost is possible   \\
 $t_p > 2\; ^\circ\mathrm{C}$                                & frost is not expected
\end{tabular}
\end{center}

Added from wrong answer:
It is also possible to put every part of this as a separate column in a table:
\begin{tabular}{llllll}
                &       & $t_p$ & $\le$ & $\SI{-2}{\celsius}$ & frost is expected     \\
$\SI{-2}{\celsius}$ & $\le$ & $t_p$ & $\le$ & $\SI{2}{\celsius}$  & frost is possible     \\
                &       & $t_p$ & $>$   & $\SI{2}{\celsius}$  & frost is not expected
\end{tabular}

I do not know how to align the 2's in the 4th column, though.

A: You can use alignat, with some trick. I also recommend siunitx.
\documentclass{article}
\usepackage{amsmath,siunitx}

\begin{document}

\begin{alignat*}{4}
                  &      && t_p &&\le \SI{-2}{\celsius}, &\quad& \text{frost is expected} \\
\SI{-2}{\celsius} &\le{} && t_p &&\le \SI{2}{\celsius},  &\quad& \text{frost is possible} \\
                  &      && t_p &&>   \SI{2}{\celsius},  &\quad& \text{frost is not expected}
\end{alignat*}

\end{document}

With other tricks and array:
\documentclass{article}
\usepackage{amsmath,siunitx,array}

\begin{document}

\[
\setlength{\arraycolsep}{0pt}\renewcommand{\arraystretch}{1.2}
\begin{array}{
  r
  >{{}}c<{{}}
  c
  >{{}}c<{{}}
  l
  @{\quad}
  l
}
                  &     & t_p & \le & \SI{-2}{\celsius}, & \text{frost is expected} \\
\SI{-2}{\celsius} & \le & t_p & \le & \SI{2}{\celsius},  & \text{frost is possible} \\
                  &     & t_p & >   & \SI{2}{\celsius},  & \text{frost is not expected}
\end{array}
\]

\end{document}

A: You need to add one more column ... for example -- using array instead of tabular, you can obtain:

Code:
\documentclass{article}
\usepackage{siunitx}
\setlength{\arraycolsep}{1.5pt}

\begin{document}
\[
\begin{array}{rll}
t_p & \le - \SI{2}{\celsius}     & \text{frost is expected}     \\
- \SI{2}{\celsius}\le t_p
    & \le \SI{2}{\celsius}      & \text{frost is possible}     \\
t_p & >     \SI{2}{\celsius}     & \text{frost is not expected}
\end{array}
\]
\end{document}

In above code I use siunitx package for units.

A: A variant with environment tabbing:
\documentclass{article}
\usepackage{siunitx}
\begin{document}
\begin{tabbing}
  $\SI{-2}{\celsius}<{}$\=$t_p\le\SI{-2}{\celsius}$,\quad\=
  \kill
  \>$t_p\le\SI{-2}{\celsius}$,\>frost is expected\\
  $\SI{-2}{\celsius}<{}$\>$t_p\le\SI{2}{\celsius}$,
      \>frost is possible\\
  \>$t_p>\SI{2}{\celsius}$,\>frost is not possible
\end{tabbing}
\end{document}

A: A simpler code with alignat:
\documentclass{article}
\usepackage{amsmath,siunitx}

\begin{document}

\begin{alignat*}{2}
 t_p &\le \SI{-2}{\celsius}, &\quad& \text{frost is expected} \\
\SI{-2}{\celsius}\le t_p &\le \SI{2}{\celsius}, & & \text{frost is possible} \\
                    t_p &> \SI{2}{\celsius}, & & \text{frost is not expected}
\end{alignat*}

\end{document}


text:
Q: Detectar Conexion Buenas amigos necesito ayuda estoy realizando una aplicación en .Net lo que necesito es tener una propiedad o una funcion que automaticamente cuando se conecte a intertnet el equipo donde esta la aplicacion me muestre un mensaje o algo que identifique que estoy conectado.
probe  My.Computer.Network.IsAvailable pero lo necesito siempre que se conecte o desconecte.


text:
Q: How can I remove the 'index out of range' error for a for loop? I'm a fair beginner in Python and I do understand what is wrong in this case, SetVel[i+4] takes it beyond the range. But I can't get my head around rectifying it. Any help would be amazing. Here's my code:
OutSmooth = []
IndexOut = []
IndSmooth = []
length = len(SetVel)
for i in range(2, length-3):
    diffnext = (SetVel[i+4])- (SetVel[i+3])
    diffprev = (SetVel[i+1])-(SetVel[i])
    diff1 = SetVel[i+2]-SetVel[i+1]
    diff2 = SetVel[i+3]-SetVel[i+2]
    if diff1 < 1.5*diffprev or diff2 < 1.5*diffnext:
        IndSmooth.append(SetVel.index(SetVel[i+2]))
    else:
        OutSmooth.append(SetVel[i+2])

PS: for those asking about what this actually is: It is my attempt at non-derivative curve smoothing. In my main program I do have a NumPy based derivative curve smoothing mechanism, but I have done this for my understanding and as a backup. Thanks
EDIT:
break after the condition worked to remove the error, but the code only runs the block once. Only one index is appended

A: You are iterating using i that maxes out just before length-3, at length-4 (which infact is equal to len(SetVel)-4.
Following this logic, if i = len(SetVel)-4 then SetVel[i+4] is equal to SetVel[len(SetVel)-4+4], or SetVel[len(SetVel)].
All that is just to show you the cause of the error - you are seeking an index that's the length itself. That won't be good, since the indexes start at 0 and not 1. The highest index possible is -1 from the length.
In other words, replace
for i in range(2, length-3):

With
for i in range(2, length-4):

Finally, if you break the loop at the end of it, unconditionally, you get only one iteration of it (only one result), so just don't do that

A: highly regular math expressions may be clearer with indexed results rather than named variables
and Python really likes consuming iterators
once you are used to list comprehensions, zip() I think generating a list of diffs may be clearer
SetVel = [math.sin(math.pi*(n % 10 - 5)/5) for n in range(20)]

diffs = [[ e1 - e0, e2 - e1, e3 - e2, e4 - e3 ]
         for e0, e1, e2, e3, e4
             in zip(SetVel,
                    SetVel[1:],
                    SetVel[2:],
                    SetVel[3:],
                    SetVel[4:])]

OutSmooth = []
IndSmooth = []
delta = 1.5    # may want to change the constant, do it one place

for i, d in enumerate(diffs):
if d[1] < delta*d[0] or d[2] < delta*d[3]:
        IndSmooth.append(i+2) # a guess at what you really wanted
    else:
        OutSmooth.append(SetVel[i+2])

IndSmooth
Out[64]: [2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17]

OutSmooth
Out[65]: [0.0, 0.0]

a common programming goal is to parameterize, automate, so here the input is the number of diffs you want, the rest is automatic
n_diff = 4

diffs = [[g - f for f, g in zip(e, e[1:])]
                for e in zip(*[SetVel[n:]
                               for n in range(n_diff+1)])]


text:
Q: SQL Server: is there a way to prevent user from seeing all databases in an instance? Is there a way to prevent that a user sees all databases in an instance? I tried to deny this from user 'mark' by
DENY VIEW ANY DATABASE TO mark

but this prevented him to see (in the SSMS Object Explorer) also the database he is attached to (as a db_reader).

A: In this case you DENY VIEW ANY DATABASE TO public because "mark" is a member of public (as are all logins). Reference
You don't remove rights for logins indivially because then all rights are lost even where expected.
Generally, if a login has permissions on an object (database, table, whatever) they can see that object in Object Explorer in SSMS
Edit: it's not foolproof and the database owner needs changed. Sorry, forgot about that.
Even if the DB is visible, no rights are conferred or implied.


text:
Q: ASP.NET C# retrieve multiple value from database and add in session How to add multiple column values from a SQL Server database and insert in session[]?
Just FirstName is working, when I add LastName, I get an error.
string constr = sql connection here.... ;

using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = @email"), cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = @email"))
    {
        cmd.Parameters.AddWithValue("@email", TextboxUsr.Text);
        cmd.Connection = con;
        cmd2.Parameters.AddWithValue("@email", TextboxUsr.Text);
        cmd2.Connection = con;

        con.Open();

        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            if (sdr.Read())
            {
                string fName = sdr["FirstName"].ToString();
                //string lName = sdr["LastName"].ToString();

                string userFullName = fName;
                Session["New"] = userFullName;
            }
        }

        //con.Close();
    }
}

A: Step 01 : Read more about SQL and C# Basics
you need to read more in

*

*SQL SELECT Statement

*.net - What is the C# Using block and why should I use it? - Stack Overflow

*c# - SqlConnection.Close() inside using statement - Stack Overflow

*c# - var versus concrete type usage - Stack Overflow

*$ - string interpolation - C# Reference | Microsoft Docs
Step 02 : Use Select in a correct way

*

*change
SqlCommand
cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = @email"),
cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = @email"))

*to
SqlCommand
cmd = new SqlCommand("SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = @email")

Step 03 : read the full code
var sql = @"SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = @email";
using (var con = new SqlConnection(constr))
using (var cmd = new SqlCommand(sql, con))
{
    con.Open();
    cmd.Parameters.AddWithValue("@email", TextboxUsr.Text);
    using (var sdr = cmd.ExecuteReader())
    {
        if (sdr.Read())
        {
            var fName = sdr["FirstName"].ToString();
            var lName = sdr["LastName"].ToString();
            var userFullName = fName + " " + lName;
            Session["New"] = userFullName;
        }
    }
}


text:
Q: Bean is expected to be of type 'CourseDAO' but was actually of type 'com.sun.proxy.$Proxy49' In a training Spring MVC + JPA/Hibernate project, I'm getting the error in question, after I've changed my configuration.
Originally the DAO class was like this:
public Course getById(Integer id) throws DAOException {
        Course result = null;
        try {
            EntityManager em = emf.getFactory().createEntityManager();
            result = em.find(Course.class, id);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new DAOException("Could not get Course By Id", e);
        }
        return result;
    }

I was told to spawn EntityManager with @PersistenceContext, and avoid creating new EntityManager every now and then. So I replaced the above EntityManager em = ... line with a @Autowired EntityManager em; field, and changed the JpaConfig class, so it looks like:
@Configuration
@ComponentScan(basePackages = "com.example.school")
@PropertySource("classpath:database.properties")
@EnableTransactionManagement
public class JpaConfig {
    private final Environment environment;

    @Autowired
    public JpaConfig(Environment environment) {
        this.environment = environment;
    }

    @Autowired
    DataSource dataSource;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        em.setPackagesToScan("com.example.school");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        return em;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

While previously the configuration file was that simple:
@Configuration
public class EntityManagerConfig {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU");

    @Bean
    EntityManager em() {
        return emf.createEntityManager();
    }
}

Now I get a stacktrace with the following most important problem in it:
org.springframework.beans.factory.UnsatisfiedDependencyException ...
...
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'courseDAO' is expected to be of type 'com.example.school.dao.CourseDAO' but was actually of type 'com.sun.proxy.$Proxy49'
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1317)
What can be wrong about this configuration?


text:
Q: Dailymotion activities API specification There is no specification available for the possible values of the fields "type", "object_type" and "from_type" in the documentation of the Activity API.
I was hoping to retrieve activities for some events like:

*

*Removing a video from a playlist

*Adding a video to a playlist after having removed it from the same playlist (no activity in that case)

*Adding a playlist

*Editing a video (rename/change description or any other edit)

My question is :
Is there any way to retrieve those events with the Activity API? Is there any full specification for the "type" fields?
API types I know are for example :

*

*user.addVideoToPlaylist

*user.postVideo

*user.startLiveStream

*user.addComment

The documentation URL: http://www.dailymotion.com/doc/api/obj-activity.html

A: You are right by saying that the documentation is lacking on this front. We're going to remedy this situation in the near future. In the meantime, here is the current list of activity types available for you to use.
For users:

*

*user.postVideo

*user.addVideoToPlaylist

*user.rateVideo

*user.bookmarkVideo

*user.addComment

*user.joinGroup

*user.addVideoToGroup

*user.subscribeUser

*user.likeVideo

*user.startLiveStream

*user.subscribeChannel
For groups:

*

*group.memberJoin

*group.videoAdd

*group.noteAdd
For playlists:

*

*playlist.videoAdd
For channels/categories:

*

*channel.featuredVideo