text:
Q: Subquery returned more than 1 value. Error when trying to remove entries based on matching colums Good Afternoon,
I am attempting to filter the results from a query I have been running.
Originally I inserted my results into a temptable and assigned rowids then used:
delete from #TEMPtable
       where RowID not in ( select min(RowID)
                         from #TEMPtable
                         group by Customer,Product)

This successfully removed entries so I was left with only 1 row per customer/product. (So if Steve had 5 cars and 2 Bikes the query would return 1 row for Steve, Car, other details and 1 row for Steve, bike, other details)
After this it became apparrent that for a 3 types of products I needed 1 row per customer/product/subproduct.
I attempted to use the below instead and received my error:
delete from #Temptable
      where RowID not in (
      (select min(RowID)  from #Temptable  where ProductID in(19,21,118) group by customer,product,subproduct),
      (select min(RowID) from #Temptable  where ProductID not in(19,21,118) group by customer,product)
      )

so to refer to my steve's car example we want:
1 row for Steve, Car, other details
1 row for Steve, bike, motorbike, other details
1 row forSteve, bike, Pedal Bike, other details
I'm a fairly novice SQLer so any help would be appreciated, I hope what i've posted makes sense.

A: Your idea works, you need union all instead of a comma and change the parentheses:
delete from #Temptable
      where RowID not in (
      (select min(RowID)  from #Temptable  where ProductID in(19, 21, 118) group by customer, product, subproduct union all
       select min(RowID) from #Temptable  where ProductID not in(19, 21, 118) group by customer, product)
      );

However, there are other ways to write this logic.  Here is another way, with just one group by:
delete from #Temptable
      where RowID not in (select min(RowId)
                          from #Temptable
                          group by customer, product,
                                   (case when ProductId in (19, 21, 188) then subproduct end)
                         );

This conditionally aggregates the the data, using subproduct only for the three products that need it.

A: Try like this
Method 1
DELETE FROM #Temptable
WHERE RowID Not In
    (
      (select min(RowID)  from #Temptable  where ProductID in(19,21,118) group by customer,product,subproduct)
      UNION
      (select min(RowID) from #Temptable  where ProductID not in(19,21,118) group by customer,product)
    )

Method 2
DELETE FROM #Temptable
    WHERE RowID Not In
        SELECT ID FROM
        (
          (select min(RowID) AS ID from #Temptable  where ProductID in(19,21,118) group by customer,product,subproduct)
          UNION
          (select min(RowID) AS ID from #Temptable  where ProductID not in(19,21,118) group by customer,product)
        ) AS A


text:
Q: I got "PLS-00103 : Encountered the symbol "CREATE" ..." when I try to declare a directory inside a stored procedure I am trying to create a txt file using "PL/SQL" with "utl_file" but I got some problems. Here is my code
procedure testFile Is
  out_File Utl_File.File_Type;
  CREATE OR REPLACE DIRECTORY tmp AS 'C:\Users\jsnow\Documents';

  GRANT read, write ON DIRECTORY tmp TO jack;
Begin
  out_file:=utl_file.fopen(tmp,'test.txt','W');
  utl_file.put_line(out_file,'Test!');
  utl_file.fclose(out_file);
  Exception when others then
    Dbms_output.put_line(sqlerrm ||'-------'||Sqlcode);
end testfile;

When I try to compile this script I get this error :
PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:

          begin function pragma procedure subtype type <an identifier>
          <a double-quoted delimited-identifier> current cursor delete
          exists prior

Do you know how can I create a text file in a stored procedure?
Thank you in advance.

A: First of all, you shouldn't be doing it in a procedure. Create directory (and grant privileges) out of it, at SQL level (not PL/SQL).
If you insist, then you'll have to use dynamic SQL, i.e. execute immediate:
procedure testFile Is
  out_File Utl_File.File_Type;
Begin
  execute immediate q'[CREATE OR REPLACE DIRECTORY tmp AS 'C:\Users\jsnow\Documents']';
  execute immediate 'GRANT read, write ON DIRECTORY tmp TO jack';

  -- the rest of your code
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run VBA code from external file? I have an excel file with VBA scripts in its background.
I also have an external file generated in a separate process that contains VBA functions i need to integrate into the main Excel.
Today, I copy-n-paste the external functions into the excel editor manually.
I wonder if there is a way to include or import the external functions without me copy-n-paste them.

A: 2017-06-18 was 5 years, 1 month and 16 days ago...
But I sincerely believe that this Q should have a simpler answer than what was provided in the comments (ref: http://www.cpearson.com/excel/vbe.aspx).

To be able to call functions that are resident in another Excel Workbook than the currently active one;

*

*The other_Workbook has to be open in Excel

*e.g. if using a function in a cell, specify the name (of the other workbook) as in =other_Workbook!FunctionName(arguments)

*a similar (workbook name prepended) approach may work for e.g. Sub:s.

Note that your/the VBA-code will run at least once for each reference (call) you have made to the function.
This may become sluggish in case of careless use.


text:
Q: What's an example of good style for an "if/then" statement? I'm not sure what's common for conditional statements, with and without alternative consequent clauses, in speech—even my own—but as a computer programmer, I'm niggled whenever I have to write English instructions that follow the form of a programmatic if (condition) doThis(); else doThat();. I was just wondering what structure seemed clearest and least ambiguous (not necessarily restricted to the following), keeping in mind that the place-holders (condition,alternative,consequent) might include punctuation such as one or more commas, or even a number of sub-clauses:

*

*If <condition>, <consequent>.

*If <condition>, then <consequent>.

With alternative:

*

*<If...>, otherwise <alternative>.

*<If...>; otherwise, <alternative>.

*<If...>. Otherwise, <alternative>.

*If ... is ..., <consequent>. If ... isn't ..., <alternative>.

*<If...>, or else <alternative>.

*

*I've determined "or else"  to be poor style. "Else" on its own would be better but still sounds inferior to otherwise or negating the condition.

A: The basic format is If condition consequence. It's largely a matter of style whether you insert a comma and/or the word "then" between condition and consequence.
If the statement continues with an alternative, it should be preceded by a comma or period (or sometimes a dash). The most common form is otherwise consequence2 (optionally separated by a comma), but the word "otherwise" may be replaced by In all other cases, If not, Failing that, etc.
Variations on the second alternative involving the word "else" are normally either archaic, or you're writing program code.

A: Your first two examples are both sound, though the first sounds more natural (read: casual):

If you heat water to 100 degrees Celsius, it boils.
If you heat water to 100 degrees Celsius, then it boils.

The three otherwise statements are quite similar, though the first is not optimal, since it is harder to parse and understand:

If it rains, we won't be able to attend, otherwise I see nothing against it.
If it rains, we won't be able to attend; otherwise, I see nothing against it.
If it rains, we won't be able to attend. Otherwise, I see nothing against it.

But the third does not fit the pattern:

If it rains, we won't be able to attend, or else I see nothing against it.

This means [If ... then this or that] rather than [If ... then this, otherwise that].

A: It depends on context. If your audience is not trained in logic, then writing a series of syllogisms, while technically more correct, might not be as helpful as something like this:

Whenever you (condition), the program will (consequent).
We will  (consequent) as long as (condition).


text:
Q: Data lost by VirtualBox An Ubuntu LTS 10.04 vdi I was running crashed, and I'm unable to boot from it.  I get stuck in initramfs.
I'm able to mount the image as a secondary device on a working Ubuntu LTS 10.04 image, after first repairing the volume with fsck.
Oddly, the data on the image is out of date!  When I look at the vdi file on the host machine, it has an old modification time.
Strangely, I had rebooted this image in the past, and if changes weren't being written to the vdi file, I would have noticed it on reboot.  I have also checked my other vdis to make sure they didn't contain the data instead, but no luck.
Where could all of that data been written to?  Any place other than the vdi?  I don't understand how it could have just disappeared like that, nor do I understand the modification time on the vdi file, unless VirtualBox was actually writing the data to a location other than the vdi!

A: Did the host crash? It could be that VirtualBox wrote the data and it ended in the disk cache of the host which then crashed and lost it.
Do you have any snapshots? If so, the main disk image won't have been written to, only the snapshot disk files.
You could try SysInternals Processmon or equivalent to see which files it is writing to if you aren't sure.
Lastly, on VMWare ESX, you can set a disk to not keep changes, but they aren't lost if the guest OS does a soft reset, only if the virtual machine is powered off. Perhaps that's similar on VirtualBox?

A: Did you take a snapshot of that VDI? VirtualBox writes data to a separate snapshot file so that it can revert to the previous state (by simply discarding everything in said snapshot file and reading the VDI directly, as you are now). It's kind of like Windows' System Restore, except that it actually works!
I believe the command-line tools will allow you to "discard" that snapshot -- that is, to write the snapshot data to the VDI so that you have an up-to-date VDI that you can use in a different VM, but you would no longer have that snapshot. Unfortunately, I don't know off the top of my head what that command/sequence of commands would be, but hopefully this'll get you pointed in the right direction.


text:
Q: What's the best way of sharing jupyter notebook script with others to be able to run it on their windows computer? I just wrote a script in jupyer notebook and I'm wondering what's the best format I should save this file as if I want to share it with other people so they can run it on their windows computer? I tried to convert my .ipynb to both .py and .exe, but none seem to work... maybe I'm doing something wrong.

A: Converting a Jupyter Notebook to a .py or .exe file would make no sense, as notebooks are used for the purpose to execute certain blocks of code on click. You could convert the notebook and it's output to a .pdf File, as you can read here: How to convert IPython notebooks to PDF and HTML?
If you want to port your Jupyter Notebook to a Python file, you'd have to make sure that you include all the code in the .py file, which is written down in the notebook as well. Keep in mind that, when using a regular Python File, things obviously won't look as great as in Jupyter.
The best way to share your Notebooks, would be to send them the actual file, so they can open the notebook in Jupyter notebook, or - in case they don't want to install Jupyter or Python on their device - they could use an online version of Jupyter Notebook like: https://nbviewer.jupyter.org/ - There are multiple websites available, which offer that kind of service.

A: You can try to use Mercury framework for converting Jupyter Notebook into web application. The Mercury can generate the widgets for your notebook, so don't need to use GUI packages (like tkinter). The widgets are generated by YAML header. Widgets are connected with variables in the notebook code. Your users can change the widgets values and execute the notebook. The final result can be easily exported to PDF. You can read more in the tutorial on how to share Jupyter Notebook with non-technical users.
The example notebook with YAML header

The example notebook converted to web app
Please notice that notebook's code is hidden (show-code: False in the YAML).

The Mercury can be easily deployed to Heroku or any cloud provider (Digital Ocean, GCP, Azure, AWS), please check the docs for details. You just send the server URL to share the app.


text:
Q: In IE8, add a new row before the last row to HTML table using Jquery I need to add a new row before the summary row to a table. I able to add a new row before summary row but the problem is some cells have text field elements and some are non-editable. How to create a row taken this into consideration.
 Please find below the code for adding a new row before the last row.

            Column 1
            Column 2
            Column 3
            Column 4
            Column 5

              <input type="text"/>
              <input type="text"/>
             <input type="text"/>

              <input type="text"/>
              <input type="text"/>
             <input type="text"/>

    <button id="AddBtn" onclick="addTableRow($('#sampTable'));">Add row</button>

The above code adds a text field element for all the columns. I don't need it, as for me some columns contain text fields and some are non-editable.

A: The reason should be that IE8- has a bad syncronization for DOM added as string.
Often you could resolve by adding a jQuery object instead of a string.
So in your case
    var $tds = $('
'); //this create a jQuery object
    /*   other code here   */
    $(this).append(tds); //this add the objet to the DOM

I made a fiddle in order to make it clear.


text:
Q: dynamically input year based on date range I have an application that is good from September 1st of the current year, and ends January 15th of the following year.
What I need to do is enter the current year into the database when they submit their application.
If the user completes the application between Sept 1, 2012 and January 15, 2013 - 2012 will be entered into the table.
Say it is January 2, 2013 - it will enter 2012 into the year column
Say it is November 10, 2012 - it will enter 2012 into the year column
Say it is December 5, 2013 - it will enter 2013 into the year column.
I can't wrap my head around how I will be able to insert the appropriate year (in this situation anyway).
Any help is appreciated.

A: You're giving yourself a grace period of 15 days after the new year. When the user submits the form capture the date and year. If the date is between January 1st and January 15th then substract 1 from your current year, if not use the current year.
Something like:
$date = date('Y-m-d');
$year = date('Y');

if( $date >= date('Y-01-01') && $date <= date('Y-01-15') ) {
  $year--;
}

A: $today = time();
$date1 = strtotime('9/1/2012');
$date2 = strtotime('1/15/2012');
$currentYear = '';
if ($today < $date1) {
    $currentYear = '2011';
}
else if ($today < $date2) {
    $currentYear = '2012';
}
else {
    $currentYear = '2013';
}

That is obviously not dynamic for future years and makes some assumptions about what you want to do when it is less than 9/1/2012, but hopefully this gets you started.


text:
Q: Calculate total number of electrons from density of states? Can someone tell me how to calculate the total number of electrons from partial density of states (projected on each atom)?
Thanks

A: The number of electrons is the integral of the density of states up to the Fermi energy. That is because at $T=0$ all states up to the Fermi energy are filled, all above are empty.
Since the total DoS is just the sum of the partial DoS, you can add up all your partial DoS and integrate from $-\infty$ to the Fermi energy.


text:
Q: logic to select the zip file from source and sending it to another directory I am stuck up in an odd situation that ia I have a folder in C: named sourceconsists of one .dat file and one .zip file
now I want to move only zip file to another diretory in c : named target
1)  Now first I have to write the logic to pick up the .zip file from source folder
what I HAVE TRIED IS ...
private void filemove(String FilePath2, String s2) {  filepath2 contains the location of source c:\\source

String destination ="C:\\target\\"

        try {
            File f = new File(FilePath2);

            if (f.getName().endsWith(".zip")) {

//please advise the logic to copy the file to destination folder

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

please advise the logic to copy the files to destination folder

A: FileUtils#copyFileToDirectory(File srcFile, File destDir) from Commons IO should suit your needs.

A: Create another file object with the current file  path.
And Use the method renameTo() in File class and give the destination path to it.
public boolean renameTo(File dest);

Renames the file denoted by this abstract pathname.

A: The best wayto copy a file in java is using the Apache Commons IO
Look at the class FileUtils it has a lot of methods for copying files.
For example copyFileToDirectory :
File srcFile = new File("c:\test.dat");
File dstDir = new File("c:\targetdir\");
FileUtils.copyFileToDirectory(srcFile, dstDir);


text:
Q: 1.9: programatically switch CMS page template in Observer For a bunch of reasons, I'd like to be able to switch a CMS page's template based on some PHP.
In config.xml:
<frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <Ecomm_Search_set_root_template>
                        <type>singleton</type>
                        <class>Ecomm_Search/observer</class>
                        <method>setRootTemplate</method>
                    </Ecomm_Search_set_root_template>
                </observers>
            </controller_action_layout_load_before>
        </events>
    </frontend>

in local.xml:
<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
    <set_root_template>
        <reference name="root">
             <action method="setTemplate"><template>page/new_template.phtml</template></action>
        </reference>
    </set_root_template>
</layout>

In Observer.php:
public function setRootTemplate(Varien_Event_Observer $observer) {
    //some other logic goes here
    $layout = $observer->getEvent()->getLayout()->getUpdate();
    $layout->addHandle('set_root_template');
    return $this;
}

Everything is running/working as expected, but the template doesn't switch.  what am I missing here? is there some other thing overriding what I do because it runs last?


text:
Q: Unable to print vbscript output on web page and unable to save vbscript output in text file Hi
I want to print vbscript output to a webpage and save it in notepad using vbscript.
This is my html code with vbscript.

Please provide solution for how to display the vbscript output on a webpage and how to save the output to notepad.
Thank you in advance.

A: Good day
Firstly are you testing this in Internet Explorer? You should.
Secondly, you should try something a little more simpler, like opening a text file and just printing out the output.
Here is sample code, I added the TYPE (to the script definition) and it now outputs:

<TITLE>A Simple First Page</TITLE>

A Simple First Page

<FORM><INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here"></FORM>

If you looking for information on how to save output to a textfile, check out the VBScript Guide.
http://msdn.microsoft.com/en-us/library/sx7b3k7y(v=vs.84).aspx
Writing to text file would look something like this, but be advised for what you trying to do you may run into security issues (impersonation may be needed).
Const FOR_READING = 1
Const FOR_WRITING = 2

strFileName = "C:\scripts\test.txt"
strNewContent  = "sample string content"

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile(strFileName,FOR_READING)
strContents = objTS.ReadAll
objTS.Close
Set objTS = objFS.OpenTextFile(strFileName,FOR_WRITING)
objTS.WriteLine strNewContent
objTS.Write strContents


text:
Q: how to get a reference to the function generator that has created an iterator? I would like to get a reference back to the function that created an iterator. In my case I am interested in getting the original docstring.
Example:
def my_generator():
    """this is my generator"""
    for x in (1,2,3):
        yield x

my_iter = my_generator()

# in another part of my code where I Only have access to the iterator
# no access to the generator function "my_generator"
assert my_iter.????.__doc__ == "this is my generator"

A: It feels hacky, but one way would to get at the docstring would be via co_consts:
localhost-2:coding $ cat mod1.py
def my_generator():
    """this is my generator"""
    for x in (1,2,3):
        yield x

it = my_generator()

localhost-2:coding $ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import mod1
>>> mod1.it.__doc__
>>> mod1.it.gi_code.co_consts[0]
'this is my generator'
>>> z = mod1.my_generator()
>>> z.__doc__
>>> z.gi_code.co_consts[0]
'this is my generator'

I'd be more inclined to figure out some decorator to apply to a generator function to make sure the docstring stays.
If you need the function itself, how about:
>>> import mod1
>>> z = mod1.my_generator()
>>> z.__doc__
>>> z.gi_frame.f_globals[z.__name__]
<function my_generator at 0x1004b7cf8>
>>> z.gi_frame.f_globals[z.__name__] is mod1.my_generator
True
>>> z.gi_frame.f_globals[z.__name__].__doc__
'this is my generator'

but I make no promises that this works for every case..

A: What about locals()[my_iter.__name__].__doc__ ?


text:
Q: how to get second last record from driverid Sql server i have following below i have three records in DriverID "134"  i want second last data how do this anyone help me how to get Second last data
AND
can you please help me how to fatch data from my table sort every second last record more then one driverid

A: Use Row_Number() Window function
With cte as
(
select *,Row_Number()over(order by Transdate desc) as Rn from yourtable
Where DriverID = 134
)
Select *
from cte
Where Rn = 2

To handle when there is only one record for the give DriverID then use this
With cte as
(
select *,Row_Number()over(order by Transdate desc) as Rn,
count(1)over() as cnt from yourtable
Where DriverID = 134
)
Select *
from cte
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1)

Note: If there is a tie in last second record and you want both the records then use DENSE_RANK instead of ROW_NUMBER
Update :
To find the second last record for all DriverID's add Partition by in Row_number and remove the DriverID from Where clause
With cte as
(
select *,Row_Number()over(Partition by DriverID order by Transdate desc) as Rn,
count(1)over(Partition by DriverID) as cnt from yourtable
)
Select *
from cte
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1)

A:   SELECT * FROM (
  SELECT
 ROW_NUMBER() OVER (ORDER BY key DEC) AS rownumber,
 columns
 FROM tablename
 ) AS foo
 WHERE rownumber <= 2


text:
Q: Does updating to 17.10 from 17.04 removes all my softwares? I am currently using 17.04 ubuntu now. Update manager is asking me to update to a new 17.10 version of ubuntu. And I really want to update.
My question is on updating will I loose all my softwares in the current version?

A: It would only touch/upgrade packages and dependencies which are part of official 17.10 repositories. Other software should not be removed. However, there may be compatibility issues due to some changes in the latest version, so I suggest you check the Release Notes.


text:
Q: How to convert a hash to a single object in JavaScript? I am having an array of object in the below format:
var log=[
{
  billkey:"Name",
  billvalue:"ABC"
},
{
  billkey:"Department",
  billvalue:"Computer"
}];

which I want to convert in a single object like:
var log={
       "Name":"ABC",
       "Department":"Computer"
     };

I've tried the following approach:
for(var i=0;i<log.length;++i){
   pushToAry(log[i].billkey, log[i].billvalue);
}

function pushToAry(name, val) {
 var obj = {};
 obj[name] = val;
 ary.push(obj);
 }

But it will push a new object every time into the ary array, which results into:
var ary =[
    0:{
      "Name":"ABC"
    },
    1:{
      "Department":"Computer"
    }];

How could I convert this array of object into an object?

A: In ES6 this is quite clean:
let result = {};

for (let {billkey, billvalue} of log)
    result[billkey] = billvalue;

or if you prefer "functional" style:
let result = Object.assign(...log.map(x => (  {[x.billkey]: x.billvalue} )))

A: You can use reduce() to return object.

var log = [{
  billkey: "Name",
  billvalue: "ABC"
}, {
  billkey: "Department",
  billvalue: "Computer"
}];

var result = log.reduce((r, e) => (r[e.billkey] = e.billvalue, r), {});
console.log(result)

A: var obj = {};
for (var i = 0; i < log.length; i++)
    obj[log[i].billkey] = log[i].billvalue;

First, I prepare an empty object to store reult to. Then I go through the log and in every iteration, I extract the log record's key (log[i].billkey) and value (log[i].billvalue) and use it to add the new member to the result: obj[...key...] = ...value...;.

A: You can use Array.prototype.reduce to reduce it to the required object - see demo below:

var log=[{billkey:"Name",billvalue:"ABC"},{ billkey:"Department",billvalue:"Computer"}];

var result = log.reduce(function(p,c){
  p[c.billkey] = c.billvalue;
  return p;
},{})

console.log(result);

A: If you just want to use a loop, you can do it like this :

var log = [
  {
    billkey: "Name",
    billvalue: "ABC"
  },
  {
    billkey: "Department",
    billvalue: "Computer"
  }];
  var result = {};
  log.forEach(x => result[x.billkey] = x.billvalue);
  console.log(result);


text:
Q: How to open a UITextView URL in UI Web View? In my iPhone app an UITextView is containing an URL. I want to open this URL in an UIWebView instead of opening it into safari?
My UITextView contains some data along with an URL. In some cases the no. of URLs can be more than one.
Thanks
Sandy

A: The UITextView has the capability to detect URLs and embed hyperlinks accordingly. You can turn that option on in:
myTextView.dataDetectorTypes = UIDataDetectorTypeLink;

Then you need to configure your app to trap this URL request and let your application handle it. I published a boilerplate class on github that does this, which might be the easiest route: http://github.com/nbuggia/Browser-View-Controller--iPhone-.
The first step is to sub-class UIApplication so you can override who gets to take action on the 'openUrl' request. Here's what that class might look like:
#import <UIKit/UIKit.h>
#import "MyAppDelegate.h"

@interface MyApplication : UIApplication

-(BOOL)openURL:(NSURL *)url;

@end

@implementation MyApplication

-(BOOL)openURL:(NSURL *)url
{
    BOOL couldWeOpenUrl = NO;

    NSString* scheme = [url.scheme lowercaseString];
    if([scheme compare:@"http"] == NSOrderedSame
        || [scheme compare:@"https"] == NSOrderedSame)
    {
        // TODO - Update the cast below with the name of your AppDelegate
        couldWeOpenUrl = [(MyAppDelegate*)self.delegate openURL:url];
    }

    if(!couldWeOpenUrl)
    {
        return [super openURL:url];
    }
    else
    {
        return YES;
    }
}

@end

Next, you need to update main.m to specify MyApplication.h as being the bonified delegate for your UIApplication class. Open main.m and change this line:
int retVal = UIApplicationMain(argc, argv, nil, nil);

to this
int retVal = UIApplicationMain(argc, argv, @"MyApplication", nil);

Finally, you need to implement the [(MyAppDelegate*) openURL:url] method to have it do what ever you would like with the URL. Like maybe open up a new view controller with a UIWebView in it, and show the URL. You could do something like this:
- (BOOL)openURL:(NSURL*)url
{
    BrowserViewController *bvc = [[BrowserViewController alloc] initWithUrls:url];
    [self.navigationController pushViewController:bvc animated:YES];
    [bvc release];

    return YES;
}

Hopefully that should work for you.

A: Assuming you have the following instances, that are also added to your UIView:
UITextView *textView;
UIWebView *webView;

and textView contains the URL string, you can load the contents of the URL into webView, as follows:
NSURL *url = [NSURL URLWithString:textView.text];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:req];

A: You can follow these steps:

*

*Tick on the following properties in UITextView taken from Xib or Storyboard.

OR write these for textview taken dynamically.
textview.delegate=self;
textview.selectable=YES;
textView.dataDetectorTypes = UIDataDetectorTypeLink;

*Now write the below delegate method :

-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
 NSLog(@"URL: %@", URL);
//You can do anything with the URL here (like open in other web view).
    return NO;
}

I think you are searching for that.


text:
Q: How to keep new line when posting data to webapi with angularjs from textarea I have html textarea field. When i have posted data from that field with AngularJS to WebApi I have lost new lines. For example I want to post to WebApi with angularjs string from textarea:
"cm8gQUQgU2tvcGplMQswCQYDVQQLDAJJyDERMA8GA1UEAwwIKi5ta2IubjswggEi
MA0GzSqGSIb3DQE2AQUAA4IBDwAwggEKApIBAQC4VhdOMe7u3tsKykWEOjRG49uD
p39tLAQls2HUnbx4IMmVfsLwE8aEwQ1cVmd80Ms4Et2GEC8WD6q7LRQ1jynqP5m/
l8+pr+RnoqGD6uF4PKf01ZTneO7DMC/yrWk++PvAG/Q7rKPv1mEY+8IGxjRjKX1M
mFh6swc5OzDiD7j4w7I5lp6ouCwAhk1auNn+PQKBSkBl2oGJ"
How to post string to WebApi (with AngularJS) from html textarea untouched?

A: I had a similar problem with saving the line breaks using a WebApi controller.
The $scope.value you are tying to submit needs to be run through the replace method.
 $scope.updateDescription = function() {
    $scope.value.replace(new RegExp('\r?\n', 'g'), "\\n");
}

This will replace all the "\n" with \n in the string.
The database will save these breaks for future use.


text:
Q: $f(n) =$ the sum of digits of $n$ and number of digits in decimal notation. How many solutions does $f(x)=M$ have? For any integer $n$ let us denote $f(n)$ as the sum of digits in decimal notation of $n$ and number of digits in decimal notation. For example, $f(12) = (1+2)+2=5$. Now, consider the equation $f(x) = M$. Can I estimate the number of solutions?

A: I have a proof that it is $2^{M-2}$ for $M>1$ if digits were not capped at 9
First, $M=1$ does not follow this rule, but obviously there is $1$ solution. Now for $M>2$
Each digit except for the leftmost ranges from $0$ to $\infty$ and contributes a value ranging from $1$ to $\infty$, while the leftmost digit contributes a value ranging from $2$ to $\infty$.
Using generating functions, we want the coefficient of $x^{M}$ in the expansion of
$$\left(x^2+x^3+x^4+\ldots\right)\left( 1+\left(x+x^2+x^3+\ldots\right)+\left(x+x^2+x^3+\ldots\right)^2+\left(x+x^2+x^3+\ldots\right)^3+\ldots\right)$$
This simplifies to
$$\left(\frac{x^2}{1-x}\right)\left(1+\left(\frac{x}{1-x}\right)+\left(\frac{x}{1-x}\right)^2+\left(\frac{x}{1-x}\right)^3+\ldots\right)$$
$$\left(\frac{x^2}{1-x}\right)\left(\frac{1}{1-\frac{x}{1-x}}\right)$$
$$\left(\frac{x^2}{1-x}\right)\left(\frac{1}{\frac{1-2x}{1-x}}\right)$$
$$\frac{x^2}{1-2x}$$
$$x^2\left(1+2x+4x^2+8x^3+\ldots\right)$$
$$\sum_{k=2}^\infty 2^{k-2}x^k$$
Hence, the coefficient of $x^M$ is $2^{M-2}$.
When our digits are capped at $9$, we have to also cap most of our infinite geometric series to finite geometric series and this makes the generating function math a lot messier. However, the actual answer should still be somewhat close to $2^{M-2}$ for relatively small values of $M>10$.
The actual generating function would be the coefficient of $x^M$ in
$$\frac{x^2-x^{11}}{1-2x+x^{11}}$$
$$\left(x^2-x^{11}\right)\left(1+(2x-x^{11})+(2x-x^{11})^2+(2x-x^{11})^3+\ldots\right)$$
We can probably use this to estimate some smaller values, but an exact solution is rather complicated.


text:
Q: Maintaining consistency between Datastore and Blobstore If I have the following JPA Entity:
@Entity
public class Image {
   private String name;
   privaet Blobkey blobKey;
   .....
   .....
}

Let's say I then use the blobstore service to persist a blob, and then use the blobkey as the attribute for a new Entity, and then persist the entity.
If I later on decide to delete the blob using the blobstore service, do I have to update the entity manually to make the blobKey attribute null?
I guess my question in general is are the Datastore entries and the blobstore entities 'aware' of each other at all, or is it up to me to keep the consistency/integrity between those datastore entities and the blobstore entries?

A: Blobstore and datastore are completely separate, so if you do delete the blob, you will need to null the blobkey. Of course, if you don't, it won't necessarily be a problem, since the blobkey will point to an non existing object. But the actual entity will keep the blobkey attribute.


text:
Q: Subset a data frame by a function that selects a dataset and a column for subset I have created a function which objective is to select between different data frames and subset the selected data frame from a selected column in that data frame:
#Dataset 1
cases <- c(1:10)
op1 <- c(1,0,1,1,1,1,0,0,0,0)
op2 <-  c(1,0,1,0,0,0,0,0,0,0)
Dataset1 <- data.frame(cases,option1= op1,option2= op2)

#Dataset 2
cases <- c(1:10)
op3 <- c(1,0,1,1,1,1,0,0,0,0)
op4 <-  c(1,0,1,0,0,0,0,0,0,0)
Dataset2 <- data.frame(cases,option1=op3 ,option2= op4)

# The function
Data <- function( selection, dataset){
    Dataset1 <- with( dataset,  dataset [selection == 1,])
    Dataset1
}

# example of intended use
Data(selection= option1, dataset= Dataset2)

This creates an error:
 Error in `[.data.frame`(dataset, selection == "1", ) :
  object 'option1' not found
Called from: (function ()
{
    .rs.breakOnError(TRUE)
})()

But if I use it "manually" it works:
with( Dataset2,  Dataset2 [option1 == 1,])
  cases option1 option2
1     1       1       1
3     3       1       1
4     4       1       0
5     5       1       0
6     6       1       0

Do you know what I am doing wrong when creating the function?
Thank you for your time!

A: When you call a function f with an argument x, R wants to pass an object to the function. Writing f(x) makes R look for an object x in the workspace. In your case, x is not defined. x is hiding in another object called Dataset1. R can't find x there, so it tells you that object option1 not found. The object op1 however is defined in the workspace. Telling R where to look for x is also an option, which is why passing Dataset1$option1 would work. Similarly, you can pass objects directly, as in the case of a character "option1".
To exemplify:
Data <- function( selection, dataset){ # this is your function
  Dataset1 <- with( dataset,  dataset [selection == 1,])
  Dataset1
}

Using the object op1 which is defined in the workspace:
Data(selection= op1, dataset= Dataset2)
  cases option1 option2
1     1       1       1
3     3       1       1
4     4       1       0
5     5       1       0
6     6       1       0

Telling R where to look:
Data(selection= Dataset1$option1, dataset= Dataset2)
  cases option1 option2
1     1       1       1
3     3       1       1
4     4       1       0
5     5       1       0
6     6       1       0

Or passing the name of the selecting column as a character vector to R. This requires some adjustment of the function:
Data <- function(selector, dataset){
  Dataset1 <- dataset[dataset[,selector] == 1,]
  Dataset1
}
Data(selector="option1", dataset= Dataset2)
  cases option1 option2
1     1       1       1
3     3       1       1
4     4       1       0
5     5       1       0
6     6       1       0

The reason why it works "manually" is that you use the with(Dataset, ...) wrapper, so that R looks in the column names of Dataset for a variable named option1.


text:
Q: VS2010 - Add template to New Project window I am trying to add a new project template for an often used pattern.  Starting from the class library template I have done the following (it still does not show up in the new project window):

*

*opened the .vstemplate file

*changed name and description to 'hard coded' values (my template).  The values in there pulled from the csharpui.dll resources.

*changed the TemplateID, DefaultName, and ProjectItems included.

*saved these to the ProjectemplatesCache folder and as a zip in the ProjectTemplates folder.

*restarted VS2010 and checked the new project location which should have shown my new template.

specifically, the folders I saved to were..
C:\program files\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplatesCache\CSharp\Windows\1033\HostComm.zip (the zip is the folder name, not a zip file)
and
C:\program files\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplates\CSharp\Windows\1033 (this folder has a HostComm.zip file in it)
Has anyone else done this? Can it be done?  If it can then what did I miss?

A: Doing this by hand is pretty courageous.  Having a folder name with an extension .zip sounds wrong, I don't see a similar one in the existing templates.  Watch out for the shell's habit of turning .zip archives into folders.
Best thing to do is to use the documented procedure to create a project template and verify what effects it has so you can repro them accurately yourself.  Create a new project, using one of the existing templates as a starter.  You might as well make it look as close as possible to the ultimate template you want to end up with, add project items as desired.
Then use File + Export Template.  Next.  Fill in the text boxes, note the Output location.  Finish.  Have a look-see at the generated .zip file.


text:
Q: R: Categorising Date intervals and adding rows for between data intervals I have a data-set of course enrollments over time, as indicated by a start_date and end_date for ~50,000 ids. I am interested in capturing both periods of enrollment and non-enrollment for this group over a specific time frame, specifically from '2001-06-01' to '2015-01-01' even though the data goes back earlier. I am interested in creating rows for each id that captures the date intervals for these periods of enrollment/non-enrollment, and creating an additional variable that categorizes these periods;  'prior to enrollment', 'enrolled', 'between enrollment', 'never enrolled'.
To clarify;
Some example data

id = c(1,3,3,3,5,5)
entry_date = c(NA, '1996-05-09', '2005-12-12', '2013-12-19', '2011-11-05','2012-12-10')
exit_date = c(NA, '2005-12-10', '2008-12-10', '2016-01-01', '2016-09-01', '2013-02-20')
test

id entry_date  exit_date
 1      NA       NA
 3 1996-05-09 2005-12-10
 3 2005-12-12 2008-12-10
 3 2013-12-19 2016-01-01
 5 2011-11-05 2012-09-01
 5 2012-12-10 2013-02-20

My intended output would be;

id entry_date  exit_date  category
 1 2001-06-01 2016-01-01  Never enrolled
 3 2001-06-01 2005-12-10  Enrolled
 3 2005-12-10 2005-12-12  Between enrollment
 3 2005-12-12 2008-12-10  Enrolled
 3 2008-12-10 2013-12-19  Between enrollment
 3 2013-12-19 2016-01-01  Enrolled
 5 2001-06-01 2011-11-05  Prior to enrollment
 5 2011-11-05 2012-09-01  Enrolled
 5 2012-09-01 2012-12-10  Between enrollment
 5 2012-12-10 2013-02-20  Enrolled
 5 2013-02-20 2016-01-01  Between enrollment

Any help in how to achieve something like this would be really appreciated!


text:
Q: Android google maps inside fragment I know that there are a lot of questions about maps inside a fragment on stackoverflow, but all of them are outdated and are not working for me.. So, I am trying to implement google maps inside a fragment, the map is displayed, but I cannot use setMyLocationEnabler(true), or add markers, or anything.. Here's my code:
public class MapFragment extends Fragment {

private SupportMapFragment mSupportMapFragment;

public MapFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.location_map);
    if (mSupportMapFragment == null) {
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        mSupportMapFragment = SupportMapFragment.newInstance();
        fragmentTransaction.replace(R.id.location_map, mSupportMapFragment).commit();
    }
    if (mSupportMapFragment != null) {
        mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                if (googleMap != null) {
                    googleMap.getUiSettings().setAllGesturesEnabled(true);
                    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    googleMap.setMyLocationEnabled(true);
                    LatLng sydney = new LatLng(-34, 151);
                    googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
                    googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
                }
            }
        });
    }

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_map, container, false);
}

}

My API key is correctly added in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application

    <meta-data android:name="com.google.android.geo.API_KEY" android:value="-----------------------------------"/>

</application>

And here's the fragment layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mk.com.urban.urbanrider.MapFragment">

<!-- TODO: Update blank fragment layout -->
<FrameLayout
    android:id="@+id/location_map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

I have google play services dependencies in by build.gradle:
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile project(':volley')
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.google.android.gms:play-services:8.4.0'
}

I really have no idea what to do next, I've tried everything...

A: I've just tried and I see no problems to use map inside a custom fragment.
Activity class with custom fragment:
public class DemoActivity extends AppCompatActivity {
    public static class WrapFragment extends Fragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.wrap_demo_fragment, container, false);
            return view;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.save_state_demo);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.map_wrap, new WrapFragment(), "qwerty_tag")
                    .commit();
        }
    }
}

activity layout save_state_demo.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="1337" />

    <FrameLayout
        android:id="@+id/map_wrap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

your custom fragment layout wrap_demo_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

</LinearLayout>

That's all you need.


text:
Q: Golang чтение бесконечного цикла горутины в родительском потоке Есть горутина, в которой есть бесконечный цикл for {}, в нем происходит вызов http запроса, при вызове запроса может произойти ошибка, можно ли ее как-то поймать в родительской горутине, передав в канал, не блокируя ее ?
То есть я создал канал errors := make(chan error, 1), передаю errors методу, который вызывается в горутине go someFunc(errors), если делать что-то вроде waitGroup или errorGroup, то основной поток будет заблокирован, пока someFunc не завершит работу, так что не подходит.
В коде это примерно так выглядит
func someMainFunc () error {
    errors := make(chan error, 1)
    go someFunc(errors)
    // тут нужно поймать ошибку из канала и вернуть ее из someMainFunc()
}

func someFunc(errorsChan chan error) {
    for {
        // do http request
        if err != nil {
            errorsChan <- err
            return
        }
    }
}

A: import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    errors := make(chan error, 1)
    go someFunc(errors)

    select {
    // тут пытаемся поймать ошибку. если она произошла, то попадет в канал errors и сработает этот триггер
    case err := <-errors:
        fmt.Printf("here error recieved. %v\n", err)

    // если вдруг ошибку не получили, то не хочется ждать бесконечно,
    // огриничиваем на 10 секунд, то есть эта секуция сработает почсле 10 секунд
    case <-time.After(10 * time.Second):
        fmt.Printf("here error did not recieved after 10 second")
    }

    // one more option
    // тут мы можем без select ждать ошибку пока не поймаем ее.
    err := <- errors
    fmt.Printf(err.Error())

}

func someFunc(errorsChan chan error) {
    for {
        err := doSomething()
        if err != nil {
            errorsChan <- err
            errorsChan <- fmt.Errorf("my custom error")
            return
        }
    }
}

func doSomething() error {
    time.Sleep(time.Second)
    if rand.Int()%5 == 0 {
        return fmt.Errorf("test error")
    }
    return nil
}

output:
here error recieved. test error
my custom error

https://play.golang.org/p/-OP82HJrwXe
я показал 2 способа поймать ошибку, в любом случае алгоритм простой.  если есть канал и мы хотим вытянуть из него информацию, то это делается через <-, например, err := <- errors. Если в канал попадает несколько ошибок, то нужно несколько раз запрашивать ошибку.
выбор с Select предпочтителен, так как можем обработать ситуацию, когда в канали ничего не пришло.


text:
Q: This expression was expected to have type string -> int but here has type int Sorry if this question is really silly, just started to get my feet wet with F# (Coming from C#).
Suppose I have following:
1: let Foo (names : string[]) =
2:    let favNames : string[] =
3:        Array.filter(fun name -> name.StartsWith("M")) names
4:    let sortByLengthOfName (x : string) : int = x.Length
5:    let sortedNamesByLegth : string[] =
6:        Array.sortWith(fun name -> fun n -> n.Length) favNames
7:    Array.iter(fun name -> printfn "%s" name) sortedNamesByLegth

Here I'm trying to define/(declare?) a function Foo which will accept array of strings (names) and perform the following:

*

*Filter array by returning only names that start with M

*Sort by length of the name

*Print out the results

Now this almost works (except of sorting part, it doesn't sort at all, which is fine for now) but I'm confused with following - if I replace lines #5, 6 with following:
let sortedNamesByLegth : string[] =
    Array.sortWith(fun name -> sortByLengthOfName name) favNames

Compiler starts to complain with This expression was expected to have type string -> int but here has type int. Now this is confusing for me because sortByLegnthOfName to me is string -> int. I tried something along these lines
let sortedNamesByLegth : string[] =
    Array.sortWith(fun name -> (sortByLengthOfName name)) favNames

But I'm still getting the same message.
Can anyone please explain what is wrong here? What's the difference between compiling one and non-compiling? And more importantly, where can I read more about this behavior?

A: The function for sortwith this signature
Array.sortWith : ('T -> 'T -> int) -> 'T [] -> 'T []

Your lambda then needs to have a signature of
('T -> 'T -> int)

but yours is just
'T -> int

You probably want sortBy instead as sortwith needs a comparer function


text:
Q: html2canvas producing blurry image I'm using html2canvas and jspdf to create pdfs from a html page. But they produce a blurry image.
I already tried increasing scale and dpi, this didn't change much.
Here is the code for converting the html to a picture:
   html2canvas(document.body, {
        // Scale image for better quality
        scale: 5,
        dpi: 300,
        onrendered: function (canvas) {
            // Convert image to dataURL
            const image = canvas.toDataURL("image/png");
            // Save dataURL in session storage
            try {
                window.sessionStorage.setObject(new Date().getTime(), image);
                document.getElementById('status').innerHTML = "Aktuelle Kennzahl erfolgreich hinzugefügt!"
            } catch (error) {
                console.log(error);
                document.getElementById('status').innerHTML = "Fehler beim Hinzufügen der Kennzahl!"
            }
        }
    });

And for creating the pdf:
    let doc = new jsPDF('p', 'mm', 'a4');

    // Set image width to a4
    const width = doc.internal.pageSize.getWidth();
    const height = doc.internal.pageSize.getHeight();

    doc.addImage(image, 'PNG', 0, 0, width, height * 0.65, '', 'SLOW');
    doc.addPage();

A: I use 1.0.0-alpha.12 version. I use html2canvas download image, but this picture has a white transparent mask. Finally, I found if I set {backgroundColor: null} or other color,  this problem disappear and picture is clear.
html2canvas(element, {
    backgroundColor: '#1b2b4e'
    }).then(canvas => {

})


text:
Q: Why does the -O4 compiler directive give unexpected results? I'm supposed to use the compiler directives gcc -pedantic -Wall -ansi -O4. But the -O4 flag is giving me some problems. It works without the O4 flag but with it I get unexpected results:
$ gcc -pedantic -Wall -ansi openshell.c
$ ./a.out
'PATH' is set to /home/dac/proj/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games.
miniShell>> ls | wc -l
82
6318: child 6319 status 0x0000
Execution time 1.197 ms
miniShell>> exit
$ gcc -pedantic -Wall -ansi -O4 openshell.c
$ ./a.out
'PATH' is set to /home/dac/proj/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games.
miniShell>> ls | wc -l
./a.out:6332: Syntax error: pipe with no command following (10: No child processes)

What can I do about it? The relevant code is:
static void exec_arguments(int argc, char **argv)
{
    /* Split the command line into sequences of arguments */
    /* Break at pipe symbols as arguments on their own */

    int i = 1;

    char ***cmdv = malloc(sizeof *cmdv * (argc/2));
    char **args = malloc(sizeof *args * (argc+1));
    int cmdn = 0;
    int argn = 0;

    cmdv[cmdn++] = &args[argn];

    for (i=1; i < argc; i++)
    {
        char *arg = argv[i];
        if (strcmp(arg, "|") == 0)
        {
            if (i == 1)
                err_sysexit("Syntax error: pipe before any command");
            if (args[argn-1] == 0)
                err_sysexit("Syntax error: two pipes with no command between");
            arg = 0;
        }
        args[argn++] = arg;
        if (arg == 0)
            cmdv[cmdn++] = &args[argn];
    }
    if (args[argn-1] == 0)
        err_sysexit("Syntax error: pipe with no command following");
    args[argn] = 0;

    exec_pipeline(cmdn, cmdv);
    free(cmdv);
    free(args);
}

It happens if I compile with O3 and O4 but not with O2. The call to the above function is this code:
 argv2[1] = line;
 i = 1;
 p = strtok (line, " ");

 while (p != NULL)
 {
   array[i++] = p;
   p = strtok (NULL, " ");
 }
 exec_arguments(i, array);
 corpse_collector();

This is the profiling with valgrind:
$ valgrind --leak-check=full -v ./a.out
==9145== Memcheck, a memory error detector
==9145== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==9145== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==9145== Command: ./a.out
==9145==
--9145-- Valgrind options:
--9145--    --leak-check=full
--9145--    -v
--9145-- Contents of /proc/version:
--9145--   Linux version 3.16.0-48-generic (buildd@lcy01-10) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #64~14.04.1-Ubuntu SMP Thu Aug 20 23:03:57 UTC 2015
--9145--
--9145-- Arch and hwcaps: AMD64, LittleEndian, amd64-cx16-lzcnt-rdtscp-sse3-avx-avx2-bmi
--9145-- Page sizes: currently 4096, max supported 4096
--9145-- Valgrind library directory: /usr/lib/valgrind
--9145-- Reading syms from /home/dac/ClionProjects/openshell/a.out
--9145-- Reading syms from /lib/x86_64-linux-gnu/ld-2.21.so
--9145--   Considering /lib/x86_64-linux-gnu/ld-2.21.so ..
--9145--   .. CRC mismatch (computed c1319e6e wanted c87fa39c)
--9145--   Considering /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.21.so ..
--9145--   .. CRC is valid
--9145-- Reading syms from /usr/lib/valgrind/memcheck-amd64-linux
--9145--   Considering /usr/lib/valgrind/memcheck-amd64-linux ..
--9145--   .. CRC mismatch (computed cd34a87b wanted 936d30dc)
--9145--    object doesn't have a symbol table
--9145--    object doesn't have a dynamic symbol table
--9145-- Scheduler: using generic scheduler lock implementation.
--9145-- Reading suppressions file: /usr/lib/valgrind/default.supp
==9145== embedded gdbserver: reading from /tmp/vgdb-pipe-from-vgdb-to-9145-by-dac-on-???
==9145== embedded gdbserver: writing to   /tmp/vgdb-pipe-to-vgdb-from-9145-by-dac-on-???
==9145== embedded gdbserver: shared mem   /tmp/vgdb-pipe-shared-mem-vgdb-9145-by-dac-on-???
==9145==
==9145== TO CONTROL THIS PROCESS USING vgdb (which you probably
==9145== don't want to do, unless you know exactly what you're doing,
==9145== or are doing some strange experiment):
==9145==   /usr/lib/valgrind/../../bin/vgdb --pid=9145 ...command...
==9145==
==9145== TO DEBUG THIS PROCESS USING GDB: start GDB like this
==9145==   /path/to/gdb ./a.out
==9145== and then give GDB the following command
==9145==   target remote | /usr/lib/valgrind/../../bin/vgdb --pid=9145
==9145== --pid is optional if only one valgrind process is running
==9145==
--9145-- REDIR: 0x401add0 (ld-linux-x86-64.so.2:strlen) redirected to 0x3809e1b1 (???)
--9145-- Reading syms from /usr/lib/valgrind/vgpreload_core-amd64-linux.so
--9145--   Considering /usr/lib/valgrind/vgpreload_core-amd64-linux.so ..
--9145--   .. CRC mismatch (computed 1c3ef3cc wanted d1ae2653)
--9145--    object doesn't have a symbol table
--9145-- Reading syms from /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
--9145--   Considering /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so ..
--9145--   .. CRC mismatch (computed 6e6e6f70 wanted ea7b69f1)
--9145--    object doesn't have a symbol table
==9145== WARNING: new redirection conflicts with existing -- ignoring it
--9145--     old: 0x0401add0 (strlen              ) R-> (0000.0) 0x3809e1b1 ???
--9145--     new: 0x0401add0 (strlen              ) R-> (2007.0) 0x04c2f060 strlen
--9145-- REDIR: 0x401ab30 (ld-linux-x86-64.so.2:index) redirected to 0x4c2ec00 (index)
--9145-- REDIR: 0x401ad50 (ld-linux-x86-64.so.2:strcmp) redirected to 0x4c30110 (strcmp)
--9145-- REDIR: 0x401bac0 (ld-linux-x86-64.so.2:mempcpy) redirected to 0x4c33330 (mempcpy)
--9145-- Reading syms from /lib/x86_64-linux-gnu/libc-2.21.so
--9145--   Considering /lib/x86_64-linux-gnu/libc-2.21.so ..
--9145--   .. CRC mismatch (computed 871d6e12 wanted 63ccc9d2)
--9145--   Considering /usr/lib/debug/lib/x86_64-linux-gnu/libc-2.21.so ..
--9145--   .. CRC is valid
--9145-- REDIR: 0x4ec7950 (libc.so.6:strcasecmp) redirected to 0x4a26730 (_vgnU_ifunc_wrapper)
--9145-- REDIR: 0x4ec9c40 (libc.so.6:strncasecmp) redirected to 0x4a26730 (_vgnU_ifunc_wrapper)
--9145-- REDIR: 0x4ec70d0 (libc.so.6:memcpy@GLIBC_2.2.5) redirected to 0x4a26730 (_vgnU_ifunc_wrapper)
--9145-- REDIR: 0x4ec5370 (libc.so.6:rindex) redirected to 0x4c2e8e0 (rindex)
==9145== Syscall param rt_sigaction(act->sa_mask) points to uninitialised byte(s)
==9145==    at 0x4E6D3F1: __libc_sigaction (sigaction.c:62)
==9145==    by 0x401061: main (in /home/dac/ClionProjects/openshell/a.out)
==9145==  Address 0xffeffefc8 is on thread 1's stack
==9145==
--9145-- REDIR: 0x4ec3670 (libc.so.6:strlen) redirected to 0x4c2efa0 (strlen)
--9145-- REDIR: 0x4ec3ae0 (libc.so.6:__GI_strncmp) redirected to 0x4c2f750 (__GI_strncmp)
--9145-- REDIR: 0x4ece6b0 (libc.so.6:strchrnul) redirected to 0x4c32e60 (strchrnul)
--9145-- REDIR: 0x4ec7300 (libc.so.6:__GI_mempcpy) redirected to 0x4c33060 (__GI_mempcpy)
'PATH' is set to /home/dac/proj/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games.
--9145-- REDIR: 0x4ebc440 (libc.so.6:malloc) redirected to 0x4c2bb60 (malloc)
--9145-- REDIR: 0x4ecc390 (libc.so.6:__GI_memcpy) redirected to 0x4c30b60 (__GI_memcpy)
--9145-- REDIR: 0x4ec30a0 (libc.so.6:strcpy) redirected to 0x4a26730 (_vgnU_ifunc_wrapper)
--9145-- REDIR: 0x4edcab0 (libc.so.6:__strcpy_sse2_unaligned) redirected to 0x4c2f080 (strcpy)
--9145-- REDIR: 0x4ebc7f0 (libc.so.6:free) redirected to 0x4c2cdc0 (free)
miniShell>> ls | wc -l
--9145-- REDIR: 0x4ec67c0 (libc.so.6:memchr) redirected to 0x4c301b0 (memchr)
--9145-- REDIR: 0x4ec5330 (libc.so.6:strncpy) redirected to 0x4a26730 (_vgnU_ifunc_wrapper)
--9145-- REDIR: 0x4edd0e0 (libc.so.6:__strncpy_sse2_unaligned) redirected to 0x4c2f5b0 (__strncpy_sse2_unaligned)
--9145-- REDIR: 0xffffffffff600000 (???:???) redirected to 0x3809e193 (???)
./a.out:9145: Syntax error: pipe with no command following--9145-- REDIR: 0x4ec77e0 (libc.so.6:__GI_stpcpy) redirected to 0x4c31fe0 (__GI_stpcpy)
 (10: No child processes)
==9145==
==9145== HEAP SUMMARY:
==9145==     in use at exit: 64 bytes in 2 blocks
==9145==   total heap usage: 8 allocs, 6 frees, 300 bytes allocated
==9145==
==9145== Searching for pointers to 2 not-freed blocks
==9145== Checked 73,312 bytes
==9145==
==9145== LEAK SUMMARY:
==9145==    definitely lost: 0 bytes in 0 blocks
==9145==    indirectly lost: 0 bytes in 0 blocks
==9145==      possibly lost: 0 bytes in 0 blocks
==9145==    still reachable: 64 bytes in 2 blocks
==9145==         suppressed: 0 bytes in 0 blocks
==9145== Reachable blocks (those to which a pointer was found) are not shown.
==9145== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==9145==
==9145== Use --track-origins=yes to see where uninitialised values come from
==9145== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==9145==
==9145== 1 errors in context 1 of 1:
==9145== Syscall param rt_sigaction(act->sa_mask) points to uninitialised byte(s)
==9145==    at 0x4E6D3F1: __libc_sigaction (sigaction.c:62)
==9145==    by 0x401061: main (in /home/dac/ClionProjects/openshell/a.out)
==9145==  Address 0xffeffefc8 is on thread 1's stack
==9145==
==9145== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
$

The thing does compile and run cleanly with the clang compiler. I suppose I'm left to making a minimal example and compare the generated assembly if I want to proceed solving this problem. The entire code is available here.
Oddly, if we insert a print statement in the loop, then the code works:
miniShell>> ls | wc -l
Processing 1 [ls]
Processing 2 [|]
Processing 3 [wc]
Processing 4 [-l]
84
27892: child 27900 status 0x0000
Execution time 1.358 ms

static void exec_arguments(int argc, char **argv)
{
    /* Split the command line into sequences of arguments */
    /* Break at pipe symbols as arguments on their own */

    int i = 1;
    char ***cmdv = malloc(sizeof *cmdv * (argc/2));
    char **args = malloc(sizeof *args * (argc+1));
    int cmdn = 0;
    int argn = 0;
    char *arg;
    cmdv[cmdn++] = &args[argn];

    for (i=1; i < argc; i++)
    {
        arg = argv[i];
        printf("Processing %d [%s]\n", i, arg);
        if (strcmp(arg, "|") == 0)
        {
            if (i == 1)
                err_sysexit("Syntax error: pipe before any command");
            if (args[argn-1] == 0)
                err_sysexit("Syntax error: two pipes with no command between");
            arg = 0;
        }
        args[argn] = arg;
        argn++;
        /*printf("argn %d", argn);*/
        if (arg == 0)
            cmdv[cmdn++] = &args[argn];
    }
    if (args[argn-1] == 0)
        err_sysexit("Syntax error: pipe with no command following");
    args[argn] = 0;

    exec_pipeline(cmdn, cmdv);
    free(cmdv);
    free(args);
}

Knowing the above, I could put in a debug statement that doesn't write any output and makes the loop work (but we don't know why) that will allow my code to compile with the highest optimization level. We still suspect some pointer handling that we might investigate by making stand-alone minimal example of the bug. For now, this will make me proceed:
static void exec_arguments(int argc, char **argv)
{
    /* Split the command line into sequences of arguments */
    /* Break at pipe symbols as arguments on their own */

    int i = 1;
    char ***cmdv = malloc(sizeof *cmdv * (argc/2));
    char **args = malloc(sizeof *args * (argc+1));
    int cmdn = 0;
    int argn = 0;
    char *arg;
    FILE* debug;

    cmdv[cmdn++] = &args[argn];

    for (i=1; i < argc; i++)
    {
        arg = argv[i];
        debug = fopen("/dev/null", "w");
        fprintf(debug, "Debug Information");

        if (strcmp(arg, "|") == 0)
        {
            if (i == 1)
                err_sysexit("Syntax error: pipe before any command");
            if (args[argn-1] == 0)
                err_sysexit("Syntax error: two pipes with no command between");
            arg = 0;
        }
        args[argn] = arg;
        argn++;
        /*printf("argn %d", argn);*/
        if (arg == 0)
            cmdv[cmdn++] = &args[argn];
    }
    if (args[argn-1] == 0)
        err_sysexit("Syntax error: pipe with no command following");
    args[argn] = 0;

    exec_pipeline(cmdn, cmdv);
    free(cmdv);
    free(args);
}

A: After taking a pruning hook to the code, I've discovered the cause of trouble.
As I first suggested, the trouble is "most likely, there's some undefined behaviour in your code, and using optimization is revealing it".
The problem is the array in main() defined as char *array[4];.  The code overflows that array, leading to undefined behaviour.  Changing the size to 40 means the program works reliably.
Although I hacked out large quantities of the code, there are still well over 400 lines of code in the file.  I'm sure a more thorough reduction job could be done, but I'm confident that this is the primary cause of the trouble.
Here's the simplified main() function with the too-small setting of char *array[4]l, and two new auxilliary functions, dump_argv() and AllWhiteSpace().  A number of other functions have been removed.  The foreground/background stuff has gone; the built-in commands (like cd and exit and unixinfo was removed.  The corpse_collector() already collected corpses; the Janitor() function was also trying to collect them, and seldom (okay, I mean never!) found anything because the corpse collector had already done the dirty work.  I removed the signal handling as not immediately relevant.
#include <ctype.h>
#include <stdbool.h>

static void dump_argv(const char *tag, int argc, char **argv)
{
    assert(argv != 0 && tag != 0);
    printf("%s: (%d)", tag, argc);
    for (int i = 0; i < argc; i++)
        printf(" {%s}", (argv[i] == NULL) ? "(null)" : argv[i]);
    putchar('\n');
    fflush(stdout);
    assert(argv[argc] == 0);
}

static bool AllWhiteSpace(char *source)
{
    unsigned char c;
    while (isspace(c = *source))
        source++;
    return(c == '\0');
}

int main(int argc, char *argv[])
{
    err_setarg0(argv[argc-argc]);

    while (1)
    {
        char *p;
        char *array[40];
        char line[BUFFER_LEN];
        size_t length;
        long time;
        struct timeval time_start;
        struct timeval time_end;

        printf("miniShell>> ");
        fflush(stdout);
        if (!fgets(line, BUFFER_LEN, stdin))
        {
            putchar('\n');
            break;
        }

        if (AllWhiteSpace(line))
            continue;

        length = strlen(line);
        if (line[length - 1] == '\n')
            line[length - 1] = '\0';

        gettimeofday(&time_start, NULL);

        printf("Command line: %s\n", line);
        int i = 1;
        p = strtok(line, " ");

        array[0] = NULL;
        while (p != NULL)
        {
            array[i++] = p;
            p = strtok(NULL, " ");
        }
        array[i] = NULL;
        dump_argv("Before exec_arguments", i, array);
        exec_arguments(i, array);
        corpse_collector();

        gettimeofday(&time_end, NULL);
        time = (time_end.tv_sec  - time_start.tv_sec) * 1000000 +
                time_end.tv_usec - time_start.tv_usec;
        printf("Execution time %ld.%03ld ms\n", time / 1000, time % 1000);
    }

    return(0);
}

The symptoms of trouble now are somewhat different — the strings to be executed are not meaningful, and therefore things fail to execute, but increase the space large enough (40 is overkill for the command line in use; 6 is sufficient) and it works fine.

A: There is a bug in your program. The -O4 option doesn't do anything different from -O3. A quick look at man gcc would've enumerated the list of options that do anything, and a sanity check:
diff <(gcc -Q --help=optimizers -O4) <(gcc -Q --help=optimizers -O3)

shows no difference.
Typically changing optimization levels is a good way to find bugs in your program as it may behave perfectly fine in one optimization level or break in another. This is indicative of undefined behavior, etc. I'm not going to waste my time debugging your program for you but at least you know that the problem is not directly caused by -O4.
Sidenote: I'm assuming that -ansi is a requirement that you can't change, however that compiles in C90 mode, aka ancient C mode. I would recommend C99 or C11 to avoid surprises.


text:
Q: Propagator with derivative interaction I work with this interaction Lagrangian density
$$\mathcal{L}_{int} = \mathcal{L}_{int}^{(1)} + \mathcal{L}_{int}^{(2)} + {\mathcal{L}_{int}^{(2)}}^\dagger = ia\bar{\Psi}\gamma^\mu\Psi Z_\mu +ib(\phi^\dagger\partial_\mu \phi - \partial_\mu\phi^\dagger \phi)Z^\mu,$$
with
$$
\mathcal{L}_{int}^{(2)} = +ib(\phi^\dagger\partial_\mu \phi)Z^\mu,$$
where $Z^\mu$ is an hermitian vector field, $\phi$ is a complex scalar field and $\Psi$ is the field of the electron.
I must work with Hamiltonian formalism.
I know that in this case I can work with $\mathcal{H}_{int} = - \mathcal{L}_{int}$ because the non-convariant term of the propagator of the vector field is cancelled by the non-covariant term of the interaction Hamiltonian (this is the case of quantizing a vector field with an interaction $J^\mu Z_\mu$ ).
My teacher told me the easiest way to derive feynman rules for the vertex $+ib(\phi^\dagger\partial_\mu \phi - \partial_\mu\phi^\dagger \phi)Z^\mu$ is to "attach" the incoming/outgoing particle momenta to the vertex. So, I get the following Feynman rules:
$\mathcal{H}_{int}^{(1)} = -ia\bar{\Psi}\gamma^\mu\Psi Z_\mu$
vertex: $-ia\gamma^\mu$ (the others feynman rules are obvious in this case)
$ \mathcal{H}_{int}^{(2)} + {\mathcal{H}_{int}^{(2)}}^\dagger = -ib(\phi^\dagger\partial_\mu \phi - \partial_\mu\phi^\dagger \phi)Z^\mu$  vertex: $\pm bp^\mu$ where $\pm$ if the sign of momenta $\vec{p}$ and the arrow of the charge are concordant.
Ok, the Feynman rules for the vertices are very simple.
Let's go to the computation of feynman rules for the propagator, like that
$$
\int d^4x d^4y <0|T(\phi^\dagger(x)\partial_\mu\phi(y))|0>
$$
if $\mu = 1,2,3$, then it's true that I have just to "attach" the momenta of incoming/outgoing particle to the vertex; but there is an extra term if $\mu= 0$ that yields a non-covariant term after have substituted the integral representation of theta-function
$$
\int d^4x d^4y <0|T(\phi^\dagger(x)\partial_\mu\phi(y))|0> = \delta_\mu^j\int d^4x d^4y \frac{d^4p ip_j}{(2\pi)^4}e^{ipx}\Delta_F(p) + \delta_\mu^0\int d^4x d^4y d^3p d^3q \left[ ip_0\theta(x^0-y^0)[\phi^+_c(x,p),\phi^-_c(y,q)]- iq_0\theta(y^0-x^0)[\phi^+(y,p),\phi^-(x,q)]\right].
$$
How to handle it? How to find the feynman rule for the propagator??
p.s. I write the scalar field as $\phi(x) = \int d^3p \phi^+(x,p)+\phi^-_c(x,p)$


text:
Q: Which statistical analyses should I use? I want to compare data from a treatment group vs a control group over time (baseline, 1 yr, 2 yr).
The measurements are repeated for all subjects across all time points (i.e., all participants complete the same set of questionnaires at all time points).
Some participants have missing data (some did not complete questionnaires at certain time points).
Control group has more subjects than treatment group (unequal sample sizes).
I am not sure whether I should use mixed models analyses to handle missing data because I am not sure whether mixed models can be used for unequal sample sizes. Or should I use Scheffe's method (non-parametric variant of anova) to handle the unequal sample sizes.

I am interested to investigate whether scores on a questionnaire (that measures severity of symptoms) differ between the treatment group (given medication) and the control group (not on medication) across the different time points.
I was thinking of using repeated measures mixed model analysis (specified as 'Linear Mixed Models analysis' in SPSS which involves selecting the appropriate covariance structure [e.g.compound symmetry and 1st order auto regressive]) because all subjects undergo the same questionnaire across all time points and also due to incomplete data from some participants.
The only issue is that I have 300+ participants in the control group and 30+ participants in the treatment group. (very unequal group sizes).
In this case, will the repeated measures mixed model analysis still be appropriate?
I agree with Peter that performing multiple t-tests will not be advisable in this case as it also increases family-wise error (hence increases tendency of committing a type 1 error).
Please kindly clarify. Thanks!

A: If by "mixed model" you mean a multilevel model (which is known by a variety of terms) that is, a model of the form
$Y = X\beta + Z\gamma + \epsilon$
then, yes, they can deal with unequal sample sizes.
Given that the same set of subjects took tests multiple times, you violate the assumption of independent data and so the simpler models will not be appropriate.
These methods also deal well with missing data, provided it is missing at random. There are no really good methods for dealing with data that is missing not at random.

A: A little more context about your data and missing info would be nice, but here goes nothing:
First, check out the Two Sample t-test for equal means. The two data sets can either have a one-to-one map or not. This tests if the means are equal or not. With unequal sample sizes and (possibly) unequal variances, you can use a more specific model known as Welch's t test. You can do this at each point in time, and then test the three models to see if there are significant model differences.
These models are easy to understand and helpful when you are just looking for mean and variance comparisons. Are there other stats you are trying to compare?
Also, there are various options for dealing with mssing data. Either ignore them, or fill them in using various methods. Here is a short list of popular methods in R.


text:
Q: Javascript: Callback function called from inside object method producing unexpected results I have a simple object called RouteLeg that contains a set of Lat/Lng values and has the ability to render a driving route between the two lat/lng points using the google maps api.
In the renderRoad method I call the google maps api DirectionsService.route method, using closure on the callback function so that it has access to the RouteLeg object (self is an object member defined as self = this):

directionsService.route(request, (function(obj) {
    return function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            obj.getDisplay().setDirections(result);
        }
    };
})(self));

The code only works if the display member variable of RouteLeg (a DirectionsRenderer object) is declared as private (var display) instead of public (this.display).  When display is declared as public it always has a value of null in the callback function.
I'm relatively new to JS and do not understand this behavior.  What am I missing?
(P.S. When I change the scope of the display variable I also change the this.getDisplay function to match.  directionsService and map are global variables).

function RouteLeg(aStart, aEnd) {
  var start = aStart; //an object that contains lat/lng values
  var end = aEnd; //lat/lng object
  this.display = null;  //does not work, only works as when declared as a var
  var self = this;

  this.getDisplay = function() {
    return this.display;
  }

  this.render = function() {
    renderRoad();
  }

  var renderRoad = function() {
    if (this.display == null) {
      this.display = new google.maps.DirectionsRenderer({
        suppressMarkers: true
      });
    }
    this.display.setMap(map);

    var request = {
      origin: new google.maps.LatLng(start.getLat(), start.getLng()),
      destination: new google.maps.LatLng(end.getLat(), end.getLng()),
      travelMode: google.maps.TravelMode.DRIVING
    };

    //directionsService is a global variable for now
    directionsService.route(request, (function(obj) {
      return function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          obj.getDisplay().setDirections(result);
        }

      };
    })(self));

  }
}

A: the renderRoad function is being called without the context, ergo the code that sets this.display is setting it on another object then the one passed by self.
renderRoad.apply(this)

A: This is happening because renderRoad does not have an execution context of RouteLeg. Meaning when you are executing renderRoad, this refers to the global object and not an instance of RouteLeg.
In order to make it work either define renderRoad on the RouteLeg instance:
this.render = function() {
  this.renderRoad();
}

this.renderRoad = function() {

Or use call/bind/apply to set the execution context of renderRoad to the RouteLeg instance
this.render = function() {
  renderRoad.call(this);
}

var renderRoad = function() {


text:
Q: Argument data type text is invalid for argument 1 of lower function In my application's search function, I have implemented a search function which executes the following statement against the database.
resultsquery = db.DBMovies.Where(m => (m.Actors.ToLower()).Contains(q.ToLower()))

In the part q.ToLower() I read the url parameter q and converts into lowercase and find it in the relevant database column. In my database, the column 'Actors' is of type 'text' rather than varchar. When I run my application, I get an exception called Argument data type text is invalid for argument 1 of lower function. Is there any way that I can avoid this exception? I prefer a way that I can solve it in a single line.
Thank you.

A: Just change the datatype of your column in database to NVARCHAR(MAX) and your code will work like a charm. It's a known issue, if you do some googling. For instance please have a look here.

A: You can simply convert the column to a VARCHAR - Something like this:
ALTER TABLE DBMovies
ALTER COLUMN Actors VARCHAR(MAX)


text:
Q: How to disable xamdatagrid cell editing in wpf I used xamdatagrid cellupdated event,inside that event i have to disable the specific cell in editing and want to enable it after getting the response of an API call,the problem is when i enable the cell after disabling it,the cursor wont set in the correct position.
private async void RenewDataGrid_OnCellUpdated(object sender, CellUpdatedEventArgs e)
{
    row.Cells[4].IsEnabled = false;
    await datacontext.CalculateFdtotalAmount();
    row.Cells[4].IsEnabled = true;
}

A: I have had similar types of issues with XamDataGrid within a function call. I solved it by processing the statements like the old windows PeekMessage. To do that, try something like:
private async void RenewDataGrid_OnCellUpdated(object sender, CellUpdatedEventArgs e)
{
    row.Cells[4].IsEnabled = false;
    DoEvents();
    await datacontext.CalculateFdtotalAmount();
    DoEvents();
    row.Cells[4].IsEnabled = true;
}

    public object ExitFrame(object f)
    {
        ((DispatcherFrame)f).Continue = false;
        return null;
    }
    public void DoEvents()
    {
        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
            new DispatcherOperationCallback(ExitFrame), frame);
        Dispatcher.PushFrame(frame);
    }


text:
Q: Not able to create a Zip archive in Gradle I'm trying to create a simple Zip archive that contains all the javascript files in my resources directory
Here's the code:
  task zip(type:Zip){
    from ('resources/'){
        include '*.js'
    }
    into 'resources'
}

This does not seem to work for some reason. I've heard many people saying that all you need is a from and into to create an archive. Can someone help me here ? I'm using Gradle v1.0. Thanks in advance.

A: Try something like this (docs):
task zip(type:Zip) {
 from ('resources/')
 include '*.js'
 into 'resources' // note that this specifies path *in* the archive
 destinationDir file('dir') // directory that you want your archive to be placed in
}

A: task someTask << {

    // other code...

    task(zipResources, type: Zip) {
        destinationDir new File(projectDir, 'resources')
        archiveName 'resources.zip'
        from 'src/main/webapp'
        include '*.js'
    }.execute()

    task(zipSomethingElse, type: Zip) {
        destinationDir buildDir
        archiveName 'source-code.zip'
        from 'src/main/java'
        include '**/*.java'
    }.execute()

    // some other code...

}


text:
Q: for loop in coffeescript promise I've a coffeescript where I wish to add 100 legal holds to an object.
To add one I do the following:
  .then (data) =>
      s3.addLegalHold({
        Bucket: bucketName,
        Key: 'foo',
        RetentionLegalHoldId: 'holdid'
      }).promise()

To add 100 I tried this but it doesn't work:
  .then (data) =>
    for i in [0 .. 99]
      console.log('count: ' + i)
      s3.addLegalHold({
        Bucket: bucketName,
        Key: 'foo',
        RetentionLegalHoldId: 'holdid' + i
      }).promise()

My console.log('count: ' + i) goes up to 99 but I can only ever see one legal hold when the test is complete. I giess it's something to do with the promise but I'm not sure. Ho do I do this?

A: You will want to use Promise.all on the array of promises that your loop evaluates to:
  .then (data) =>
    Promise.all( for i in [0 ... 100]
      console.log ('count: ' + i)
      s3.addLegalHold {
        Bucket: bucketName,
        Key: 'foo',
        RetentionLegalHoldId: 'holdid' + i
      }
      .promise() )

This will get you a promise for an array of the results.

A: Try this:
.then (data) =>
  promises = []
  for i in [0 .. 99]
    promises.push(s3.addLegalHold({
      Bucket: bucketName,
      Key: 'foo',
      RetentionLegalHoldId: 'holdid' + i
    }).promise())
  return Promise.all(promises)

The crucial difference is Promise.all (MDN). It takes an array of promises (in your case, 100 promises), waits for all of them to resolve, then resolves itself.


text:
Q: C++ versus Java performance Say theoretically you just generate random numbers [using standard libraries] in as many threads as you can [bound by hardware].  How fast would C++ over Java?
no disk i/o, memory or gc.  Just pure Math.random() calls across threads.

A: Depends on hardware, OS and many other factors...  I think this a very hard question to answer, cause there is too many variables involved.  Why don't you test it?

A: Test it.
And Pay attention to the fact, that Java performance is not static above runtime. Because it can use a hot spot compiler, that compiles the hot spots after it detects them.

A: test both in the environment you will be deploying at.


text:
Q: mysql - right joining two tables as one to many relation I know that this question already asked many times here but after all I could't found my answer that what I want.
My Question is:
I have two tables and the structure of these tables is as:
table1:
item_id, store,title,available,shipping
table2:
item_id, review_rate,user_id,review_title
These tables should be join as one to many relation.
For example if the data in these tables is as:
table1:

item_id      store      title    available    shipping
-------------------------------------------------------
11           glasses    ..........................
12           dresses    ..........................
.
.
.

table2:

item_id     review_rate    user_id    review_title
--------------------------------------------------
11           3              10023      good item
11           5              10024      nice item
12           1              10024      nice one
.
.
.

then the result should be as after joining:
afterJoin:

item_id   store   title   available   shipping   rate   people_reviewed
-----------------------------------------------------------------------
11        ....................................   4      2
12        ....................................   1      1

The query I tried to join is as:
CREATE OR REPLACE VIEW afterJoin AS
SELECT i.*,round(AVG(r.review_rate)) as rate,count(r.user_id) as people_reviewed
   FROM table1 i
   RIGHT JOIN  table2 r ON i.item_id = r.item_id

but this return only one row.

A: Your query is missing a GROUP BY clause.  Without it your database is aggregating all of the records together.
SELECT i.*, round(AVG(r.review_rate)) as rate, count(r.user_id) as people_reviewed
FROM table1 i
    RIGHT JOIN  table2 r ON i.item_id = r.item_id
GROUP BY i.item_id

The GROUP BY instructs the db to aggregate for each item_id.


text:
Q: How can I let one element do two events at the same time so, I'm having a game, and I want the user to reset the score when he clicks the button, and reset boundaries when he hovers over it.
How can I do it so that he can both, hover and click
function reset_bounderies() {

    let start = document.getElementById("start")
    start.addEventListener("mouseover", function (event) {
        game = true;
        document.querySelectorAll(".boundary:not(.example)").forEach(item => {
            item.classList.remove("youlose")
            document.getElementById("status").innerHTML = `Begin by moving your mouse over the "S".`
        })
    })
    start();

}

and the second function
function reset_game() {

    let start = document.getElementById("start")
    start.addEventListener("click", function (event) {
        game = true;
        score = 0;
        print_score()

    })
    start();
}

P.S: I can't edit html or css file

A: You can add two differents EventListener to your button

function functionOne(){
  console.log("functionOne")
}

function functionTwo(){
  console.log("functionTwo")
}

const myButton = document.getElementById("myButton")

myButton.addEventListener('click', functionOne)
myButton.addEventListener('mouseover', functionTwo)
<button id="myButton">Click me !</button>


text:
Q: how to define rewriterules in cloud9 web-ide I'm playing arround with cloud9 and I would like to define rewrite rules for my apache based web application in c9 web-ide.
I created a .htaccess file (not sure if is located correctly). I guess I need to configure httpd.conf file but can't find such.
how should it be done?
Thanks.

A: I had this issue. Turned out it was all down to typos in the .htaccess file. No further configuration was required.
I saved the .htaccess file in a folder I created called 'site' which I am using as the root for my web app (so the same folder which contains index.php), i.e. like this: myWorkspaceName/site/.htaccess
The full contents of my .htaccess file is:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

You might copy and paste that to use as a test of the configuration (remembering to save and restart Apache of course).
In case you do need to configure something like httpd.conf it appears that you would want to take a look at the following files as a starting point:
/etc/apache2/apache2.conf

and
/etc/apache2/sites-available/001-cloud9.conf

Access to these files is via the command line, so you would type:
sudo nano /etc/apache2/sites-available/001-cloud9.conf

for example.
It may be worth mentioning that for my specific rewrites, the address I would use has to include my sub folder 'site', i.e,
https://myWorkspaceName-wkille.c9.io/site/anything

whereas
https://myWorkspaceName-wkille.c9.io/anything

throws a Not Found error.


text:
Q: How do I effectively create controls dynamically in Excel's VBA or How do I use Application.OnTime()? I am working on a very large VBA project in Excel at my job.  We are about 1500 lines of code for just one feature and have about a dozen more features to add.  Because of this, I've been trying to break everything down so that I can keep code for each feature in separate places.  OOP sucks in VBA... The problem being that these controls MUST have events fired.  Of course, some events (like the TextBox_AfterUpdate event) are not available when you dynamically create controls.  It's a bit convoluted because of everything that is going on, so I'll break it down the best I can:
I have a class module that represents a tab for a multipage control.  When a user clicks on a tab, the Userform calls this class module and THERE I have the controls created dynamically.  This way I can keep the code in that class module.  I have a sub that I deemed as the "AfterUpdate" sub and put code that I needed to run there.  Now the problem is to get that sub to be called at the appropriate time.
So what I did is to set up a Timer of sorts to check and see if the "ActiveControl" is said textbox.  If it is not, we can assume that focus has left and we can raise that event.  Here's the code I'm using:
An abbreviated version of the tab creation...
Private WithEvents cmbMarketplace As MSForms.ComboBox

Public Sub LoadTab(ByVal oPageTab As Object)
    If TabLoaded Then Exit Sub

    Set PageTab = oPageTab

    Dim tmp As Object

    Set tmp = PageTab.Add("Forms.Label.1")
    tmp.Top = 6: tmp.Left = 6: tmp.Width = 48
    tmp.Caption = "Marketplace:"

    Set cmbMarketplace = PageTab.Add("Forms.ComboBox.1", "cmbMarketplace")

    ' LOAD OTHER CONTROLS '

    TabLoaded = True
    Start_Timer
End Sub

Then Start_Timer:
Public Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:00:01"), "Timer"
End Sub

And the sub that is to be fired:
Public Sub Timer()
    If TimerActive Then
        ' DO SOME RANDOM THINGS '
        Application.OnTime Now() + TimeValue("00:00:01"), "Timer"
    End If
End Sub

Does this seem like a reasonable approach to solving the problem I'm facing?  I'm open to suggestions...
That's the first problem.  This seems like a lot of work to accomplish this.  (I'm working on getting visual studio, but I don't know if that's going to happen)
The above code will work but the "Timer" sub will not get raised at all.  I get no errors if I just run the code.  Everything is created, everything works as I would hope.  However, if I step through the code, I eventually will get the following error:
Cannot run the macro "...xlsm!Timer".  The macro may not be available in this workbook or all macros may be disabled.

Obviously neither of those suggestions are valid.  Macros ARE enabled and the sub is in the same darn class module.  I tried making it public, same problem.  Tried "ClassModule1!Timer" to no avail.  I'm at my wits end trying to figure this out.  Thinking of having people write ALL this in the Userform or just giving up.
Does anybody have any suggestions on how to effectively break up large chunks of code?  And does anybody have a clue why this sub will not run and seemingly cannot be found?
I understand that this is a confusing situation, so if you need more info or code examples or want to know why I have something set up the way I do, let me know.
Thanks!

A:
Obviously neither of those suggestions are valid. Macros ARE enabled and the sub is in the same darn class module.

There's the problem: a macro cannot be in a class module. The message is entirely correct: VBA cannot see the Timer procedure, because it's not accessible.
A class module is a blueprint for an object, VBA (or any OOP language for that matter) can't do anything with a class module, without an instance of that class - i.e. an object.
Your timer callback needs to be a Public Sub in a standard module, so that it can be called directly as a macro. Public procedures of a class modules are methods, not macros.
Depending on what ' DO SOME RANDOM THINGS ' actually stands for, this may or may not require some restructuring.
1500-liner spaghetti code can be written in any language BTW.


text:
Q: How to send message to a specific user from discord bot using discord.js I want to send a message from my discord bot to a specific user like myself using my discord id.
I have tried the following code where my client object is named as bot:
bot.users.get("My Id copied from discord").send("Message to Send");
but it gives the following error in the terminal:
bot.users.get is not a function
Please help me in resolving this error.
Thank you

A: Since discord.js v12 you need to use cache to access the users collection
bot.users.cache.get('ID').send('hello')

You need to use users.fetch() instead since the user might not be cached
const user = await bot.users.fetch('ID')
user.send('hello')


text:
Q: Why and how does this piece of Javascript Code print 6 five times on execution? This is the piece of code,which on execution gives 6,five times in one second intervals. Can someone please explain this to me in detail?
for (var i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
        }, i*1000 );
}

A: The variable i is part of the closure of the timer function.
When the timer function is executed,
it will print the value of i at that time.
By the time that happens, the loop has already completed,
and so the value of i is 6.
For all 5 executions of timer,
so you see 6 printed 5 times.
What else would you expect?
If you want to print a count from 1, 2, ..., 5 with timeouts in between,
then pass the current concrete value of i into the closure,
using an immediately evaluated function expression:
for (var i = 1; i <= 5; i++) {
  setTimeout(function (value) {
    return function timer() {
      console.log(value);
    }
  }(i), i*1000);
}

Another equivalent variation:
for (var i = 1; i <= 5; i++) {
  (function () {
    var value = i;
    setTimeout(function timer() {
      console.log(value);
    }, i*1000);
  })()
}

Notice in both examples that the variable value is defined in the closure of the inner function, and a different instance of value is created in every iteration of the for loop,
with the value of i at the time of the iteration.
This is the crucial difference from the code in the question.


text:
Q: How to push notify consumers from kafka message bus I am writing microservice application using C# asp.net core 2.0, Kafka, CQRS and Confluent Kafka .net library.
Just wonder if kafka can notify the consumers rather than the consumers poll/consume message?
Thanks

A: Kafka can not push notifications to consumers.
Consumers have to keep polling/consuming messages in order to receive them. This is the only way messages stored in Kafka can flow to consumers.
The Consumer Design section in the Apache Kafka documentation explains why "consumer pulling" was choosed over "broker pushing".

A: Kafka is pull only, that's by design. But you could use an higher level abstraction. I've built a library called Silverback (https://github.com/BEagle1984/silverback) that implements all that for you, so that you can focus on the logic. The consume loop is implemented in Silverback, that then "pushes" the messages to your subscribers.
See a sample here: https://silverback-messaging.net/samples/kafka/basic.html#consumer.


text:
Q: Another way to load remote data in Select2 I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]

and the script is like this:
$(document).ready(function() {
    $('#test').select2({
        minimumInputLength: 1,
        placeholder: 'Search',
        ajax: {
        dataType: "json",
        url: "subject/data_json.php",
        data: function (term, page) {// page is the one-based page number tracked by Select2
            return {
                college: "ABC", //search term
                term: term
            };
        },
        type: 'GET',
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: function(data) {
            return "
" + data.name + "
";
        },
        formatSelection: function(data) {
            return data.name;
        },
        initSelection : function (element, callback) {
            var elementText = $(element).attr('data-init-text');
            callback({"name":elementText});
        }
    });
});

It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
    $("#test").select2({
        createSearchChoice:function(term, data) {
        if ($(data).filter(function() {
        return this.text.localeCompare(term)===0; }).length===0) {
        return {id:term, text:term};}
    },
    multiple: false,
    data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
    });
});

But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
            url: "subject/data_json.php",
            data: function (term, page) {// page is the one-based page number tracked by Select2
                return {
                    college: "ABC", //search term
                };
            }
            dataType: "json",
            success: function(data){
                return data
            }
        }

But its not working, can anyone help?
Thanks

A: Why did you move away from your original code?
minimumInputLength: 1

Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.

A: if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:

Javascript:
$(document).ready(function () {
  $.ajax('/path/to/data_json.php', {
    error: function (xhr, status, error) {
      console.log(error);
    },
    success: function (response, status, xhr) {
      $("#mySelect").select2({
        data: response
      });
    }
  });
});

I've found that the above does not work if you create a <select> element instead of a .