text:
Q: How to stop mac from default booting in deleted windows via boot camp? I bountied this question Boot into Mac from Windows after failed Bootcamp after being trapped in Windows hell on my mac, after the first time using boot camp.
When I got back to my mac I erased windows and reformatted boot camp following the answer to this question How to remove Windows Operating system from Bootcamp?

If you installed Windows on a disk that has a single partition

*

*Start up your Mac in OS X.

*Open Disk Utility, located in the Other folder in Launchpad.

*Select the Windows disk, click Erase, choose the Mac OS Extended (Journaled) >format, then click the Erase button.

Now whenever I restart my mac I have to hold onto the option key to select the mac (and reboot it from there as it defaults to the Windows keyboard and the keys do not match, so I cannot submit my password - don't' ask).
This is what I have when I open boot camp and disk utility:

Erasing the boot camp volume does nothing, as does unmounting. I'm too scared to play around with it beyond this. If I never had to touch Windows OS again I'd be happy, but it's an unfortunate evil. I've gone back to Parallels desktop.
Most of the solutions I've found online have not helped me remedy any of these issues from trying to make it work to wanting to get rid of it - which is why I'm here.
I accept I may have sacrificed the disk space and may never be able to claim it (grrr can't think too hard about it). But I swear to Apple, they'll be taking this machine back if I can't stop it from booting up on Windows.
My machine:
iMac (Retina 5K, 27-inch, Late 2015)
4 GHz Intel Core i7
32 GB 1867 MHz DDR3
How can I stop my mac from defaulting to open Windows?

A: The NVRAM holds the location of the default OS, so resetting that might get you back to the default search order. If you want to set it explicitly, Apple's article linked below as well can help:
From How to select a different startup disk:

Use Startup Disk preferences
When you use Startup Disk preferences to select a startup disk, your
Mac starts up from that disk until you choose a different one.

*

*Choose Apple () menu > System Preferences, then click Startup Disk.

*Click the lock and enter your administrator password.

*Select your startup disk, then restart your Mac.

NOTE: Restart the Mac by clicking the Restart... button. This process checks the system has the correct permissions to start, then writes your choice to NVRAM.


text:
Q: Tortoise and Hare don't have adresses, C++ #include <iostream>

using namespace std;

class Element
{
public:
    Element* next;
    double field;
};

class LinkedList
{
protected:
    Element* begin;
    int num;
public:
    int Number() {return num;}
    LinkedList()
    {
        begin = NULL;
        num = 0;
    }
    LinkedList(LinkedList& L)
    {
        begin = new Element;
        num = L.Number();
        begin = L.begin;
    }

    virtual void push(double a)
    {
        Element* cur = begin;
        if(begin==NULL)
        {
            num = 1;
            begin = new Element;
            begin->field = a;
            begin->next = NULL;
            return;
        }

        while(cur->next!=NULL)
        {
            cur = cur->next;
        }
        num ++ ;

        cur->next = new Element;
        cur->next->field = a;
        cur->next->next = NULL;
    }
    virtual double pop()
    {
        Element* cur = begin;
        Element* prev = NULL;

        if(begin==NULL)
        {
            return -1;
        }
        if(num==1)
        {
            double res = begin->field;
            num--;
            return res;
        }

        while(cur->next!=NULL)
        {
            prev = cur;
            cur = cur->next;
        }
        double res = cur->field;
        prev->next = NULL;
        delete cur;
        num--;
        return res;
    }

    ~LinkedList()
    {
        num = 0;
        Element* cur = begin;
        if(cur!=NULL)
            cur = cur->next;
        while(cur!=NULL)
        {
            Element* prev = cur;
            cur = cur->next;
            delete prev;
        }
        if(begin!=NULL)
            delete begin;
    }
    Element* operator[](int i)
    {
        if(i<0 || i>num) return NULL;
        int k = 0;
        Element* cur = begin;
        for(k=0;k<i;k++)
        {
            cur = cur->next;
        }
        return cur;
    }
};

class R_LinkedList: public LinkedList{
public:

    double pop() {
        double res = begin->field;
        begin = begin->next;
        num--;
        return res;
    }
    bool cycle_search() {
        Element* tortoise = begin, *hare = begin;

        while(tortoise && hare && hare->next) {
            tortoise = tortoise->next;
            hare = hare->next->next;
            if(tortoise == hare) {
                cout << "Got loop" << endl;
                return 1;
            }
        }
        cout << "No loop" << endl; return 0;
    }
};

int main()
{
    R_LinkedList l;
    l.push(2); l.push(3); l.push(6);l.push(3);l.push(6);
    cout  << l[2]->field << endl;
    l[4]->next = l[1];
    l.cycle_search();
    return 0;
}

Scroll down, then up.
So I have this code and trying to implement classic "tortoise and hare" cycle finding algorythm (and also overload virtual function, but that's not the problem [yet]). And it works fine! It prints value, it says happily "Got loop!"
And then it breaks, screaming
HEAP[TestConsole2.exe]: Invalid address specified to RtlValidateHeap( 002E0000, 002EF8F0 )

An adress problem. Favorite. Honestly tried to debug, and he worked it all throught the end and broke again. So it's something with the destructor, but - hell - have no idea what exactly.
Or maybe it's about the algorythm itself. Or I am the problem 'cause don't see something obvious or lack fundamentals.

A: You have an issue in LinkedList destructor.
When you assign the next element of l[4] to be l[1], basically you have cycle (which seems what you wanted).
But the last element (l[4]) points on an existing element.
So in the destructor you are trying to destroy l[1] twice : the first time just after delete l[0], and the second time after deleting l[4].
You should review the design of your list, and in particular the way you destroy it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Life Cylcle of Controller Objects in AngularJS I am working on a Hybrid app written in Ionic-1 that uses Angular-1 javascript library and HTML-5 to create hybrid apps.
In my code I am connecting to Firebase to fetch some data:
MyCtrl:
angular.module('myctrl.controller', [])
  .controller('MyCtrl', function () {
    $ionicPlatform.ready(function () {
      try {
            var userRef = firebase.database().ref().child("users/" + loggedInUser.userName + "/details");
            userRef.on('child_added', function(snapshot, prevChildKey) {
              var newUser = snapshot.val();
              console.log("New user " + JSON.stringify(newUser));
          });
        }
     });
  });

Now as I understand that controllers are re-instantiated every time views they are attached to are re-created. However, in my app even if I am outside the view which is attached to this controller, and add a user in firebase, this code gets executed. It confuses me as this code should have been garbage collected once view is replaced by another one. Does it mean that this on() method somehow getting attached to $rooScope?

A: firebase events won't got deregistered automatically, you have to unregister it manually when leaving controller.
var userRef;
$ionicPlatform.ready(function () {
  try {
    userRef = firebase.database().ref().child("users/" + loggedInUser.userName + "/details");
    userRef.on('child_added', function(snapshot, prevChildKey) {
      var newUser = snapshot.val();
      console.log("New user " + JSON.stringify(newUser));
    });
  }
});

$scope.$on('destroy', function() {
  if (userRef) userRef.off();
})


text:
Q: Which library to add as dependency? Newbie to dialog flow, trying to integrate the java library.
Confused between the two dependencies below:
1) https://cloud.google.com/dialogflow/docs/reference/libraries/java
2) https://developers.google.com/api-client-library/java/apis/dialogflow/v2
The first one says java client library and the second one says api client library for java.
Which is the correct dependency to interact with the dialog flow


text:
Q: Visual Studio performance test - unable to test report (SSRS) I'm trying to create a web performance test in Visual Studio 2010/2012 to test a report based on MS report manager.
The issue comes from a performance test framework - it doesn't execute java script. So, when I open a page with a report I get an error message saying that "This page might not function correctly because either your browser does not support scripts or active scripting is disabled". Because of than the POST request to a page doesn't work as well. Configuring security settings of the Internet Zones doesn't help either.
I profiled web requests with a Fiddler and created a test (Fiddler can export requests to a test) but it didn't work. None of the requests actually triggered report and database procedures were not executed (checked with a profiler). Something is still missing.
I'm wondering if anybody had the same task and faced the similar issue (I'm pretty sure that reports load testing is a common task, but google doesn't help much). Please share your advise/experience.
Thanks.

A: Ok, I found a solution. It's pretty simple and obvious, but took time to find it.
There is a blog post (http://technet.microsoft.com/en-us/library/aa964139%28v=sql.90%29.aspx) explaining the idea. Hope it helps and saves time for you.


text:
Q: Excel VBA - Find previous date Hi I'm trying to put in some UserForm validation for date range that is entered by a user.
The date range that needs to be picked is for the previous week from Monday to Sunday eg. 13 Aug 2012 to 19 Aug 2012. So if I was to run the report today (24 Aug 2012) how can I work out that the dates I need to enter in is 13 Aug 2012 to 19 Aug 2012, and what if I ran the report tomorrow.
Can I do it by working out the WeekDayName of the day I'm running the report (eg. Friday) and from that use DateAdd to subtract to the previous Monday (-11) for the first date and subtract to the previous Sunday (-5) for the  second date.
So if the user was to enter the date range of 14 Aug 2012 and 19 Aug 2012, an msgbox will appear telling them that the date range that should be entered is 13 Aug 2012 to 19 Aug 2012 and do they want to continue.
Hope this makes sense.

A: This will work:
Sub testDate()

    Dim myDate As Date
    myDate = "8/14/2012"

    Dim weekStartDate As Integer
    weekStartDate = 2
    'set for the sunday -> sunday for the given date

    Dim startDate, endDate As Date
    startDate = myDate - Weekday(myDate) + weekStartDate   'take current date, find system weekstart (Sunday), adjust accordingly
    endDate = startDate + 6    'you are only adding 6 days to your week it seems?

    MsgBox ("Please select a date between " & startDate & " and " & endDate)

End Sub

When you use Weekday(myDate) it returns an integer which is the number of days which have passed since the system week start, which I believe will normally be Sunday. So Monday = 1 etc.


text:
Q: Dynamic path variable to play audio .mp3 file How to ? d3 javascript coffe script I am trying to play a sound file on "mouseover". It works when I hardcode the path to the .mp3 file, code shown below.
My values, including the paths to multiple .mp3 files, are stored in a .csv file, though.
And I need to find a way to 'feed' the path values to a variable.
Here is my initial element. There are multiple nodes, taking the values from .csv parsing. On mouse over, I can play the - "hardcoded path" - .mp3 file ok:

labelEnter.append("span")
  .attr("class", "bubble-sound")
  .attr("height", 40 )
  .attr("width", 70 )
  .attr("src",(d) -> "sounds/"+fileValue(d))
  .on("mouseover",  (d, i) -> playSound d.file)

playSound = (d) ->
    # hardcoded here in next line
  snd.setAttribute "src", "sounds/Hungarian_FSI_1_0.00.06.059-0.00.07.229.mp3"
  snd.load()
  snd.play()
  return

snd = new Audio()

onPlay = (e) ->
  snd = new Audio()
  snd.addEventListener "play", onPlay

I am trying to get the path-value parsed from the .csv into the snd.setAttribute statement, that is, replace the hard-coded path with a variable, that holds the path value for that node.
The following code shows the correct value of 'file' in the console.log, but it displays undefined for the "setAttribute" path

playSound = (d) ->
  file = fileValue(d)
      # console log shows desired value of 'file'
  console.log("Show me " + file)
      # 'file' undefined
  snd.setAttribute "src", "sounds/"+file
  snd.load()
  snd.play()
   on "mouseoverreturn

My question, beginner, how can I manipulate/set the file variable so that it would correctly append to the source path: "sounds/file-value-as-string-here" in the setAttribute statement ? Thank you very much.

A: Try something like this:
playSound = (d) ->
  file = fileValue(d)
      # console log shows desired value of 'file'
  console.log("Show me " + file)
      # 'file' undefined
  snd.setAttribute("src", "sounds/"+file); //<-- this line changed
  snd.load()
  snd.play()

A: Thank your responding; this is my final solution:
playSound = (d) ->
    file = fileValue(d)
    console.log("Show me " + file)
    snd.setAttribute("src", "#{file}")
    snd.load()
    snd.play()
    return

  snd = new Audio()

  onPlay = (e) ->
    snd = new Audio()
    snd.addEventListener "play", onPlay


text:
Q: Does Hudson have a problem for building a CSPROJ file with MSBUILD? Good morning
I'm running Hudson java -jar hudson.war and I have configured MSBuild as described here. It seems MSBuild is not working.
I think there is something to do with the default value contained in .csproj file:
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

This path is misleading, and takes Hudson to C:\Microsoft.CSharp.targets and not to C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.CSharp.targets as it should be.
I tried to hard code the csproj file, with this full path information, but it throws an exception too telling there is an invalid character.
Maybe I'm using the wrong MSBuild.exe version?
Here is the Hudson message when using default $(MSBuildToolsPath) variable in csproj:

Console Output
Started by user anonymous
Updating http://svn.mycoolserver.org/svn/repository/projects/trunk/MyCoolClassLibrary
U         MyCoolClassLibrary.csproj

At revision 36706
Path To MSBuild.exe: C:\Windows\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe
Executing command: cmd.exe /C C:\Windows\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe /p:Configuration=Release MyCoolClassLibrary.csproj && exit %%ERRORLEVEL%%
[workspace] $ cmd.exe /C C:\Windows\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe /p:Configuration=Release MyCoolClassLibrary.csproj && exit %%ERRORLEVEL%%

Microsoft (R) Build Engine Version 2.0.50727.3053
[Microsoft .NET Framework, Version 2.0.50727.3615]
Copyright (C) Microsoft Corporation 2005. All rights reserved.

C:\Documents and Settings\myUser\.hudson\jobs\MyCoolClassLibrary\workspace\MyCoolClassLibrary.csproj(63,11): error MSB4019: The imported project "C:\Microsoft.CSharp.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
Finished: FAILURE

A: Ok, indeed I just needed to add the right path to
C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe

A: You can also see the answer at the link below for another solution.
The imported project "C:\Microsoft.CSharp.targets" was not found


text:
Q: Can a div using a clip path cut into another div? What I'm trying to create is a div that cuts into two other divs (one above, and one below, see picture below)
First I had no idea how to create a shape like that in css until I discovered clip path: polygon. Now I can sort of get the shape going when using a shape generator, but the problem is I can't get the div to cut into the other places. I tried to use a z-index but that didn't work.
I know I can use a negative margin to move the div more into the hero image but the polygon doesn't come out right.
Here is JSFiddle I tried to add a snippet but was giving me too many issues, figured this would be easier and cleaner to see.
The HTML/CSS in particular is this:

Decide

Pick

Fundraise

We

Celebrate

Give

.ThreeSteps {
  margin-top: -20px;
  background-color: #0066CC;
  -webkit-clip-path: polygon(0px 325px,1689px 491px,1688px -466px,1px 82px);
  clip-path: polygon(0px 325px,1689px 491px,1688px -466px,1px 82px);
  z-index: 1;
}

Anyone have any suggestions on what I should do? Thank you for your time.

A: I've seen that Clip Path just creates a mask on images. I think a better approach should be you create a pseudo-class :before and :after; positioning them absolute to the .ThreeSteps div.
something like this:
.ThreeSteps {
position: relative;
/*Other Stuffs*/
}

.ThreeSteps::before {
content: '';
width: 100%;
height: 100px;
display: block;
position: absolute;
top: -115px;
left: 0;
background: url('my-triangle-image-top.svg') no-repeat;
background-size: contain;
z-index: 2000;
}

.ThreeSteps::after {
content: '';
width: 100%;
height: 100px;
display: block;
position: absolute;
top: 0;
bottom: -115px;
background: url('my-triangle-image-bottom.svg') no-repeat;
background-size: contain;
z-index: 2000;
}

If you can use some Vector Image Editor (Like Adobe Illustrator), you can save a triangle image as 'my-triangle-image.svg', and use as a background image on pseudo-classes :before and :after . If you cant, just use a .png image, but svg is the best for this purpose.


text:
Q: Fuzzy Match between large number of records I have two data frames. One contains 33765 companies. Another contains 358839 companies. I want to find the matching  between the two using fuzzy match. Because the number of records are too high, I am trying to break down the records of both data frames according to 1st letter of the company name.
For example: For all the companies starting with letter "A", 1st data frame has 2600 records, and 2nd has 25000 records. I am implementing full merge between them and then applying fuzzy match to get all the companies with fuzz value more than 95.
This still does not work because number of records are still too high to perform full merge between them and then implement fuzzy. Kernel dies every time I do these operations. The same approach was working fine when the number of records in both frames was 4-digit.
Also, suggest if there is a way to automates this for all letters 'A' to 'Z', instead of manually running the code for each letter (without making kernel die).
Here's my code:
c='A'
df1 = df1[df1.companyName.str[0] == c ].copy()
df2 = df2[df2.companyName.str[0] == c].copy()
df1['Join'] =1
df2['Join'] =1
df3 = pd.merge(df1,df2, left_on='Join',right_on='Join')
df3['Fuzz'] = df3.apply(lambda x: fuzz.ratio(x['companyName_x'], x['companyName_y']) , axis=1)
df3.sort_values(['companyName_x','Fuzz'],ascending=False, inplace=True)
df4 = df3.groupby('companyName_x',as_index=False).first()
df5=df4[df4.Fuzz>=95]

A: You started going down the right path by chunking records based on a shared attributed (the first letter). In the record linkage literature, this concept is called blocking and it's critical to reducing the number of comparisons to something tractable.
The way forward is to find even better blocking rules: maybe first five characters, or a whole word in common.
The dedupe library can help you find good blocking rules. (I'm a core dev for this library)


text:
Q: Construct sum of points on projective line In a course in Geometry we where asked to geometrically construct the sum of two points $x$ and $y$ on a projective line by help of "the theorem on complete quadrilaterals". This theorem (as stated in our lecture notes) says that if $A,B,C,D$ are four points in general position in a real projective plane and if $P=AB\cap CD$ and $Q=AD\cap BC$, $l=PQ$, $X=l\cap BD$, $Y=l\cap AC$. Then the pair of points $\{P,Q\}$ on $l$ separates the pair $\{X,Y\}$ harmonically, meaning that the cross ratio $Cr(P,X,Q,Y)=-1$
Projective planes are assumed to satisfy desargues theorem in my course.
I have the following idea, which I first present and then I will add my concerns.
If $x=y$, then
$Cr(0,x,2x,\infty )=-1$
If $y>x$ then
$Cr(x, \frac{x+y}{2},y, \infty )=-1$
We use this to construct $\frac{x+y}{2}$. Let $P=x$ and $Q=y$, we let $r_1$, $r_2$ be arbitrary lines intersecting in $x$. Furthermore let $A$ and $C$ be the intersection points of $r_1$ and $r_2$ with the line $l_{\infty }$ at infinity respectively. Now draw  the lines $AQ=h_1$, $CQ=h_2$. We let $D=r_2\cap h_1$ and $B=r_1\cap h_2$. Now, we are in the context of the above mentioned theorem. The line $BD$ intersects $l$ in the point $s$ such that $Cr(x, s,y, \infty )=-1$, hence $s=\frac{x+y}{2}$.
My concerns are the following:

*

*I have problems calculating cross ratios, using Berger I would believe $Cr(x, y, \frac{x+y}{2}, \infty )=\frac{\frac{x+y}{2}-x}{\frac{x+y}{2}-y}=-1$, and in the same way I get $Cr(0,2x,x,\infty )=-1$, this seems completely unreasonable however since $2x$ is not between $0$ and $x$ which makes it impossible for these calculations to be correct, please help me clearly write down the standard expression for these crossratios, because I am somehow misunderstanding page 125 in berger $Cr[a,b,c, \infty ]=\frac{\overline{ca } }{\overline{cb}}$.

*Independent on which one of the calculations of crossratio is correct, I run into problems in making the argument when the unknown quantity is on position three, i.e "when I want to construct the point $Q$".
I realized that for constructing 2x, I just map the x-axis or the y-axis to $l$ by the projective transformation taking 0 to 0 and 1 to x and infinity to infinity then the image of 2 is my desired point, hence I think that this together with previous calculations solves the problem, if $Cr(x, \frac{x+y}{2},y, \infty )=-1$ that is.
Any comments, hints or general opinions about crossratios and "geometric construction" are welcome.


text:
Q: DeprecationWarning: Calling an asynchronous function without callback is deprecated. - how to find where the "function:" is? I recently updated my node to 7.2.1 and noticed that there is a warning coming:

(node:4346) DeprecationWarning: Calling an asynchronous function without callback is deprecated.

What is this 4346 for? I only have 2000 lines in the js file, so it can't be a line-number. Where can I find the code?

A: You can use either the --trace-deprecation or --throw-deprecation options.
For example:
node --trace-deprecation app.js

or:
node --throw-deprecation app.js

The first option will log a stack trace and the second will throw an error (which, if not caught, will also log a stack trace).
Also, 4346 is most likely the process ID.

A: You need to include a callback function for the Asynchronous method (writeFile in your case).
For example
var fs = require('fs');
fs.writeFile('writeMe.txt',data,'utf8',(error)=>{
    // your code goes here
});

where
(error) => { });

is the callback function.
From Version: v7.0.0
The callback parameter is no longer optional. Not passing it will emit a deprecation warning.
Please refer: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
for more info.

A: I prefer the following two methods, myself.
1:
fs.writeFile('example.md', data, (error) => { console.log("Error!"); });

2:
fs.writeFile('example.md', data, function (err) {
    if(err){
        throw err;
    }
});

A: this is because you have not catch error by using err callback
use like below in your code
fs.write('./abc.txt',function(err){
    if(err){
        return console.log(err);
    }
    else
    {
        console.log('success.!');
    }
});

A: just mention:
fs.writeFile('<your file name>',<your data>,function(){});

here, you need to mention function(){} as this is a callback() to write text in asynchronous manner.
Using writeFileSync will make an synchronous call

A: I got the same warning
[DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

and had the same problem of not knowing which part of my code was causing it. So I looked at code I had recently modified and saw this statement-suspect:
 Fs . writeFile (path, aString, cb, encoding);

Problem was the cb (= 'callback') and the encoding arguments are in wrong order.
I got rid of the warning simply by changing the above to:
 Fs . writeFile (path, aString, encoding,  cb);

But the problem really is with the ERRONEOUS warning-message.
I WAS  passing in a callback-argument but just one which
was not a Function but a String.  So if the warning had
said
"WWARNING: calling fs.writeFile() with a string-argument
 where a function is expected"

... it would have been obvious what was happening. Of course
a line-number in the warning would be nice as well.
So the point is I was NOT calling writeFile() without
a callback-argument, which is deprecated. I was
calling writeFile() WITH A WRONG TYPE OF ARGUMENT.
That should be an ERROR, not a warning.


text:
Q: MongoEngine - Have a 'virtual' model with complex dependencies? I have an issue where there are two sets of users for one set of MongoEngine documents. One of these uses sets wants complex helper functions to be part of the document definition, the other user set cannot install the dependencies that the those functions require.
I want to achieve something like a clean model and a dirty model where the user can select for themselves, but the actual database document definition is maintained in only one place. E.g.

CleanModel/my_document.py
class MyDocument(Document):
    my_field = StringField()

DirtyModel/my_document.py
from CleanModel import MyDocument as _MyDocument

class MyDocument(_MyDocument):
    def some_function_that_relies_on_compiled_code():
        pass

The use could then do:
from DirtyModel import MyDocument

or
from CleanModel import MyDocument

and work with exactly the same Mongo document. The way I've written it above, DirtyModel.MyDocument.objects() can't get at documents created with the CleanModel.
Any ideas on the best way to solve this? (I don't think that moving the helper methods outside of the document definition is practical in this case)


text:
Q: How does one use both half and full adders together? I am trying to teach myself the concept of (half and full) adders from Wikipedia and am a bit confused.
Do I need to use both half adders and full adders together for performing multi-bit addition? How do I combine them together?

A: Half adders, compared to full adders, don't have the carry input bit; so they're not necessary, but are used to save hardware when only two bits have to be added.
An example is in the sum of two bytes: the least significant bits don't usually need a carry-in, so can be added with a half adder (or a full-adder with Cin=0).
Another example is the multiplier: here you sum the partial products, but the last bit (the most significant) of each one has to be added only to the carry of the previous sum, so this operation can be performed by a half adder.
Note that in several cases, the saving in area is not worth the additional effort of specifically design an half adder; so a full adder with grounded (or tied at 1 if working with inverted logic) carry-in is used instead.

A: A half-adder is used for the first bit since there is no carry-in. For the second and subsequent bits, you need full adders.


text:
Q: zsh script launches Terminal.app instead of iTerm.app I am trying to use the zsh rails workspace launcher for OSX terminal.app written by Jim Fisher. I am on OSX 10.6.8. I want it to launch in iTerm but it continues to launch in Terminal.  Shell is /bin/zsh
Below is the script that I modified slightly.  Any help is always appreciated!
    rails_workspace()

    {
osascript -e 'tell application "iTerm.app"' \
-e 'tell application "System Events" to tell process "iTerm.app" to keystroke "t" using command down' \
-e "do script with command \"cd `pwd`;clear;\" in selected tab of the front window" \
-e "do script with command \"rails server\" in selected tab of the front window" \
-e 'tell application "System Events" to tell process "iTerm.app" to keystroke "t" using command down' \
-e "do script with command \"cd `pwd`;clear;\" in selected tab of the front window" \
-e "do script with command \"rails console\" in selected tab of the front window" \
-e 'tell application "System Events" to tell process "iTerm.app" to keystroke "t" using command down' \
-e "do script with command \"cd `pwd`;clear;\" in selected tab of the front window" \
-e "do script with command \"tail -f log/development.log\" in selected tab of the front window" \
-e 'end tell' &> /dev/null
sleep 2
subl .
open "http://localhost:3000"
    }
    alias rw=rails_workspace

A: I found that the code above was Applescript launched within zsh. So instead I wrote my own Applescript as an Automator task:
 tell application "Finder"
   set project_list to name of folders of folder ("your/projects/folder" as POSIX file)
 end tell

 (choose from list project_list with prompt "What project do you want?")
   set project to result as text

 tell application "iTerm"
   activate
   terminate the first session of the first terminal

   set myterm to (make new terminal)

   tell myterm
     set mysession to launch session "Default Session"
     tell mysession
        write text "website"
        write text project
     end tell

     set mysession2 to launch session "Default Session"
     tell mysession2
        write text "website"
        write text project
        write text "rails console"
     end tell

     set mysession3 to launch session "Default Session"
     tell mysession3
        write text "website"
        write text project
        write text "tail -f log/development.log"
     end tell
   end tell
 end tell


text:
Q: SCP command not working in Crontab I am trying to write a cronjob using scp.But scp is not working correctly.
PATH=/usr/sbin:/usr/bin:/sbin:/bin:/bin/bash:/usr/bin/ssh:/usr/bin/scp
scp -i pi@ipadress:/home/pi/filename /home/flash/mylog.log

scp command works fine when I run it from terminal without password.My log file has nothing in it(it is blank).
How should I fix it?
Thanks in advance.

A: The -i switch has its meaning. It requires the path to your key:
sshpass -p passphrase scp -i ~/.ssh/id_rsa pi@ipadress:/home/pi/filename /home/flash/mylog.log

or leave it out completely, if it is in the default location:
sshpass -p passphrase scp pi@ipadress:/home/pi/filename /home/flash/mylog.log


text:
Q: How to declare and use out parameter in Powerbuilder with ASA database I have a stored procedure named sp_getnextautono(as_sequenceid Char(20), as_sequenceno double output)
In Powerbuilder I have scripted as follows:
//Declaration
Declare proc_autono Procedure for sp_setnextautono
@as_sequenceid = :ls_input,
@as_sequenceno = :ld_sequenceno;

//Execution
Execute proc_autono;

If Sqlca.Sqlcode <> 0 Then
   ls_errormsg = Sqlca.SQLErrText
   Rollback Using Sqlca;
   MessageBox( 'Error', 'Error: ' + Sqlca.SqlErrText , Stopsign! )
   Return FAILURE
End If

// Fetch
Fetch proc_autono Into :ld_sequenceno;

If Sqlca.Sqlcode <> 0 Then
   ls_errormsg = Sqlca.SQLErrText
   Rollback Using Sqlca;
   MessageBox( 'Error', 'Error: ' + Sqlca.SqlErrText , Stopsign! )
   Return FAILURE
End If

There is no error but I am unable to fetch the sequenceno.
The variable ld_sequenceno returns 0.
Can anyone advise me how to solve the above issue?

A: This is your code (wich is almost fine):
//Declaration
Declare proc_autono Procedure for sp_setnextautono
    @as_sequenceid = :ls_input,
    @as_sequenceno = :ld_sequenceno;

You are only missing to indicate that :ld_sequenceno is an OUTPUT variable. Try the next and everything should be ok:
//Declaration
Declare proc_autono Procedure for sp_setnextautono
    @as_sequenceid = :ls_input,
    @as_sequenceno = :ld_sequenceno **OUTPUT**;


text:
Q: Disable a button in WPF before a long operation I want to change the background of a WPF Window from another thread, after a delay (Thread.Sleep() in the code tries to mimic an I/O operation). The action will be invoked when a button is pressed.
More specifically, when the button is clicked I want to

*

*The button to disabled

*The color of the background changed after a
    delay of  seconds

*The button to be enabled again

When I run the application and fire the event I cannot see the button disabled. The background change does happen though, and I'm guessing it has to do with the UI thread and the Dispatcher. But I've also tried to disable it like this
MyButton.Dispatcher.Invoke(() => MyButton.IsEnabled = false)
without any success.
Is anyone able to explain why this is happening and how can I solve it?
XAML
<Window x:Class="ThreadingModel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ThreadingModel"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="450"
        Width="800">
  <StackPanel x:Name='Parent' Background='Green'>
    <TextBlock HorizontalAlignment='Center'
               Margin='10'
               FontSize='32'>Threading and UI</TextBlock>
    <TextBlock Margin='10'
               FontSize='22'
               TextWrapping='Wrap'>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</TextBlock>
    <Button Content='Change Color'
            Width='150'
            Height='50'
            Margin='10'
            FontSize='22'
            Click='Button_Click'
            x:Name='MyButton'/>
  </StackPanel>
</Window>

Code (C#)
public partial class MainWindow : Window
    {
        private delegate void OneArgumentDelegate(int arg);

        private bool isGreen = true;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //MyButton.IsEnabled = false;
            MyButton.Dispatcher.Invoke(() => MyButton.IsEnabled = false);
            /* This starts a background thread from the pool, right?*/
            MyButton.Dispatcher.BeginInvoke(new OneArgumentDelegate(Change_Background_After), DispatcherPriority.Normal, 3000);
        }

        private void Change_Background_After(int delay)
        {
            Thread.Sleep(delay);
            if (isGreen)
            {
                Parent.Background = Brushes.Red;
                isGreen = false;
            }
            else
            {
                Parent.Background = Brushes.Green;
            }
            MyButton.IsEnabled = true;
        }
    }


text:
Q: XCode 7 Compilation Error with Swift Can someone help me fix this issue?  I added another ViewController and modally linked it to the original view controller.  It originally worked, but I ran it again because I made change in text and now it will not compile.  I deleted all constraints and deleted the "button" that it says is not correctly linked.
2015-10-26 00:48:43.611 XXXX[5790:2031206] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x15ce8dac0 V:|-(20)-[UIInputSetContainerView:0x15ce2e050]   (Names: '|':UITextEffectsWindow:0x15ce694a0 )>",
"<NSLayoutConstraint:0x15ce8e630 'UIInputWindowController-top' V:|-(0)-[UIInputSetContainerView:0x15ce2e050]   (Names: '|':UITextEffectsWindow:0x15ce694a0 )>")

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2015-10-26 00:48:44.446 XXXXX[5790:2031206] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<XXXXXX.CreateAnAccountViewController 0x15cd1fd40> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key SignUpLabel.'
*** First throw call stack:
(0x185198f5c 0x19a67ff80 0x185198c1c 0x18600f534 0x18aa4f9b8 0x18ab9b4b8 0x1850c2acc 0x18ab99ea0 0x18aa52cfc 0x18a827ea8 0x18a6ef258 0x18a6ef1b0 0x18af713a4 0x18aa3705c 0x18aa5c508 0x18aa5f294 0x18a7e60c0 0x18adea5d8 0x18adddcf8 0x18adddafc 0x18addddc4 0x18a7263e4 0x18a726360 0x18a70ec88 0x18a725c78 0x18a7258a8 0x18a71eadc 0x18a6efa2c 0x18a6edf18 0x1851505a4 0x185150038 0x18514dd38 0x18507cdc0 0x190518088 0x18a756f60 0x1000d56e4 0x19ae9e8b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

A: You probably have an outlet in your view that is connected to a label (SignUpLabel) in your class that is not found.
Either your File's owner is not set to be your ViewController or you have deleted/renamed the label in your class and need to reset the outlet in your view.
You also have an error with your constraints but that shouldn't contribute to the crash.


text:
Q: Clear Unity Add manifests to package Debug.Log (Google) enter image description here
These logs have occurred since Unity Google Packages were imported
Can you tell me how to turn off these logs?
Clicking log does not link to IDE


text:
Q: How http proxy clients work if an HTTP client reaches a website through a proxy (not reverse proxy) server, what are the actual HTTP request and its parameters that are sent from this client host to the internet?
for example:

Proxy Server: www.proxy.com:80
Target website: www.website.com:8081

Does the HTTP client send the following Get request?

Get http://www.proxy.com:80
Host: www.proxy.com:80

OR

Get http://www.website.com:8081
Host: www.website.com:8081

if the first case is true, How can the proxy know what is the actual destination to forward this request?
otherwise, if the second is true, how can the request actually reach the proxy host machine?

A: When you want to issue a GET request to http://www.example.com:8081/index.html, the browser connects to www.example.com:8081 and sends the following request:
GET /index.html HTTP/1.1
Host: www.example.com:8081

Now when a proxy is configured, say www.proxy.com:80, the browser will connect to www.proxy.com:80 instead, and issue the following request:
GET http://www.example.com:8081/index.html HTTP/1.1
Host: www.example.com:8081

So when a proxy is configured, the HTTP client connects to the proxy instead of to the target server, and sends the request using the absolute URI.

A: The client doesn't have to change the HTTP request for it to be sent to a proxy. It has to change the TCP headers.
The screenshot below shows a HTTP request sent from my browser to a proxy, as you can see nothing in the HTTP request itself specifies the proxy.
How this works is the browser/client will issue a HTTP GET request, which will then be forwarded to the TCP/IP stack and wrapped in a TCP header. The TCP header is where the destination is specified (proxy or otherwise).

A: Http proxy server can read http headers.
Whenever we use http proxy the destination address in the tcp packet(originating from client) has destination address of proxy server..
When the proxy server receives the tcp packet it can read the http headers(which is present in tcp packet payload) the http headers contains the actual destination for the packet.. using this information the http proxy server can forward the packet to actual destination.
Source : https://www.ibm.com/support/knowledgecenter/SSBLQQ_9.1.0/com.ibm.rational.ritpp.install.doc/topics/c_ritpp_advanced_proxy.html


text:
Q: Assumed size arrays in fortran I wrote the following program to mess around with assumed-shape and assumed-size arrays:
program test

implicit none

    integer, dimension(3) :: array

    array(1) = 1
    array(2) = 2
    array(3) = 3

    call mysub(array)

end program test

subroutine mysub(array)

    dimension array(*)

    print *, array(:3)

end subroutine mysub

I'm compiling it with ifort and have 2 questions:

*

*The subroutine outputs random values not equal to the values I assign in the main program. Why is this?

*if I replace line 19 print *, array(:3) by print *, ubound(array) I get an error message

test.f90(19): error #6587: Upper Bound of array is not computable.
  [UBOUND]

I do want to be able to detect the upper bound of my assumed-size array within the subroutine. How can I do this?


text:
Q: How to randomly crop a batch of images I have a batch of 5 images, I want to randomly crop them for w_, h_ size
Example:
import tensorflow as tf
images=tf.reshape(tf.range(100*100*3*5), [100, 100, 3, 5])
batch_crop = tf.random_crop(images, size=(20, 20))
with tf.Session() as sess:
     batch = sess.run([batch_crop])

I get error:
ValueError: Shape must be rank 4 but is rank 3 for 'concat' (op: 'ConcatV2') with input shapes:

A: *Note the extra (3, 5) at the end of size. This effectively tells tensorflow that it should not be cropped along the third and fourth axis
import tensorflow as tf
images=tf.reshape(tf.range(100*100*3*5), [100, 100, 3, 5])
batch_crop = tf.random_crop(images, size=(20, 20, 3, 5))
with tf.Session() as sess:
     batch = sess.run([batch_crop])

Should do the job. From the docs, random_crop  returns

A cropped tensor of the same rank as value and shape size.

The part that you'll want to pay extra attention to is probably:

If a dimension should not be cropped, pass the full size of that dimension. For example, RGB images can be cropped with size = [crop_height, crop_width, 3].

Hope this helps :)


text:
Q: Richfaces datatable - adding a new row without rerendering the whole datatable on the client side The new row can be added to the associated server-side collection on an action event of a command button or a command link, and the newly added row can be displayed on the client if the whole table is re-rendered.
Is it possible to display the newly added row on the client side without needing to refresh the whole datatable, using the partial rendering, with the help of AjaxKeys or something ?
Thanks in advance for any help :)

A: You have to rerender whole datatable if you are adding a new row. AjaxKeys may be useful if you want to rerender existing columns.

A: I am very interested also to know an answer for your question,
I can achieve that using traditional Javascript, but when I use rich:datatable I cant add new rows on client.
But I did that using ajax calls to server functions, this function add new empty row to the dataTable List and render the rich:datatable again.
my xhtml page
<rich:column>
<f:facet name="header"><h:outputLabel value="#{msgs.notes}" style="font-size:15px;"/> </f:facet>
<h:inputText    value="#{line.notes}" >
    <a4j:ajax   event="blur"
    execute="datatable"
    render="datatable"
    immediate="true"
    listener="#{saleBacking.addNewLineInDataTable}"
    oncomplete="document.getElementById('myform:datatable:#{saleBacking.view_no_counter-1}:line').focus();"/>
</h:inputText>
</rich:column>

and in the maneged bean
public void addNewLineInDataTable(AjaxBehaviorEvent event)
    {
        SaleLine saleLine = new SaleLine();
        saleLine.setId(salesLineslist.isEmpty() ? 1 : salesLineslist.get(salesLineslist.size() - 1).getId() + 1);
        salesLineslist.add(saleLine);
        saleLine = new SaleLine();
        saleLine = new SaleLine();
        saleLine.setSaleId(sale);
        saleLine.setViewNo(++view_no_counter);
        saleLine.setDiscount(0d);
        saleLine.setItemPrice(0d);
        salesLines.add(saleLine);
    }


text:
Q: Trying to uncomment unattended-upgrades lines with script, need help I've recently started working as an IT person in a all Linux company, and noticed some of the tasks we do can be 'easily' automated. Today's task to automate is installing software and configuring /etc/apt/apt.config.d/50unattended-upgrades on new computers. I've already written the software-installing script, but now I'm stuck on  uncommenting the desired unattended-upgrades lines.
I'll give you an example, this:
// Automatically upgrade packages from these (origin:archive) pairs
//
// Note that in Ubuntu security updates may pull in new dependencies
// from non-security sources (e.g. chromium). By allowing the release
// pocket these get automatically pulled in.
Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}";
        "${distro_id}:${distro_codename}-security";
        // Extended Security Maintenance; doesn't necessarily exist for
        // every release and this system may not have it installed, but if
        // available, the policy for updates is such that unattended-upgrades
        // should also install from here by default.
        "${distro_id}ESMApps:${distro_codename}-apps-security";
        "${distro_id}ESM:${distro_codename}-infra-security";
//      "${distro_id}:${distro_codename}-updates";
//      "${distro_id}:${distro_codename}-proposed";
//      "${distro_id}:${distro_codename}-backports";
};

should look like this:
// Automatically upgrade packages from these (origin:archive) pairs
//
// Note that in Ubuntu security updates may pull in new dependencies
// from non-security sources (e.g. chromium). By allowing the release
// pocket these get automatically pulled in.
Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}";
        "${distro_id}:${distro_codename}-security";
        // Extended Security Maintenance; doesn't necessarily exist for
        // every release and this system may not have it installed, but if
        // available, the policy for updates is such that unattended-upgrades
        // should also install from here by default.
        "${distro_id}ESMApps:${distro_codename}-apps-security";
        "${distro_id}ESM:${distro_codename}-infra-security";
        "${distro_id}:${distro_codename}-updates";
//      "${distro_id}:${distro_codename}-proposed";
//      "${distro_id}:${distro_codename}-backports";
};

(the updates line should be uncommented)
I've tried to do it with sed, but it just isn't working, probably because I'm a total n00b. Here is my clumsy sed line so someone can, hopefully, explain to me what I am doing wrong!
#!/bin/bash

    sudo sed -i 's@//      "${distro_id}:${distro_codename}-updates"@        "${distro_id}:${distro_codename}-updates"@' /etc/apt/apt.conf.d/50unattended-upgrades

Any help would be greatly apreciated! Have a nice day!

A: Why not just create another file /etc/apt/apt.config.d/51my-unattended-upgrades with the content:
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-updates";
};

The options are merged together. Check it with apt-config dump.
Additionally it is easier to remove your changes by just removing the single file. And any upgrade changing /etc/apt/apt.conf.d/50unattended-upgrades will not break your changes.
Better never change config files of others if not needed.
Try of an explanation:
From the python source of unattended-upgrade you can see, that it does not parse the config files in /etc/apt/.... Instead it uses the python-apt-api. It is similar to use apt-config in the shell (which you should always do instead of reading the config files).
In this special case, the python-apt-api does the merging of all the files and returns a list of Origins-Pattern and the unattended-upgrade script loops over all of them.
I don't know of any good docu about this. Best you can do is looking into the source.

A: Please see Marco's answer, that's The Right Way To Do It®, I am focusing only on the sed and regular expression issues here.

The first rule of working with regular expressions is "less is more". Don't try to match the entire line, instead use the smallest possible regex that catches what you need to catch. Here, for instance, you don't care about the empty spaces at the beginning of the line, so don't bother trying to match them. Plus, the number of spaces is very likely to change and you don't want that to break your script, so ignore them!
As far as I can tell, all you really ant here is to remove a leading // from any lines that contain the string -updates. If so, all you need is:
sed '/-updates/{s@^\s*//@@}' /etc/apt/apt.conf.d/50unattended-upgrades

This means "if this line matches -updates, then replace 0 or more leading whitespace characters (the comment doesn't have to be the first character of the line) followed by // with nothing". So this will remove the leading // from lines matching -updates.
As you can see, this is much easier to write and to understand. That said, your original command works as expected with your example file, it is just unnecessarily complicated and fragile (it breaks if whitespace is added):
$ sed 's@//      "${distro_id}:${distro_codename}-updates"@        "${distro_id}:${distro_codename}-updates"@' file
/ Automatically upgrade packages from these (origin:archive) pairs
//
// Note that in Ubuntu security updates may pull in new dependencies
// from non-security sources (e.g. chromium). By allowing the release
// pocket these get automatically pulled in.
Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}";
        "${distro_id}:${distro_codename}-security";
        // Extended Security Maintenance; doesn't necessarily exist for
        // every release and this system may not have it installed, but if
        // available, the policy for updates is such that unattended-upgrades
        // should also install from here by default.
        "${distro_id}ESMApps:${distro_codename}-apps-security";
        "${distro_id}ESM:${distro_codename}-infra-security";
        "${distro_id}:${distro_codename}-updates";
//      "${distro_id}:${distro_codename}-proposed";
//      "${distro_id}:${distro_codename}-backports";
};

Finally, a couple of general observations:

*

*never use sed -i on importan files without taking a backup. The -i option allows you to specify a backup suffix, so if you run sed -i.bak 's/a/b/' file, that will copy the original as file.bak. So you should do something like sudo sed -i.bak ... in your case, so you can always undo things.

*It is very rarely a good idea to have sudo inside your script. Instead, write the script without sudo and then call it with sudo with sudo script.sh.


text:
Q: Probable reasons why autoloading wont work in Zend Framework 1.10.2? Iam writing an application using Zend Framework 1.10.2.
I  created few model classes and a controller to process them.
When Iam executing my application and accessing the admin controller. Iam seeing this error.
Fatal error: Class 'Application_Model_DbTable_Users' not found in C:\xampp\htdocs\bidpopo\application\controllers\AdminController.php on line 16
The error clearly shows its an autoloading error.
Hence I wrote this code in the bootstrap file.
    protected function initAutoload()
{
    $modeLoader = new Zend_Application_Module_AutoLoader(array
        ('namespace'=>'','basePath'=>APPLICATION_PATH ));
    //echo(APPLICATION_PATH);
    return $modeLoader;
}

Still the error remains :( . Can anyone suggest me what Iam missing out here?
This is the location of the Model Users class.
C:\xampp\htdocs\bidpopo\application\models\DbTable\Users.php
This is its code.
    class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    //put your code here
protected $_name='users';

public function getUser($id)
{
    $id = (int)$id;
    $row = $this->fetchrow('id='.$id);
    if(!$row)
    {throw new Exception("Could not find row id - $id");}
    return $row->toArray();
}

public function addUser($userDetailArray)
{
    $this->insert($userDetailsArray);
}

public function updateUser($id,$userDetailArray)
{
    $this->update($userDetailArray,'id='.(int)$id);
}

public function deleteUser($id)
{
    $this->delete('id='. (int)$id);
}

}

This is the Admin Controller's code
class AdminController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $this->view->title= "All Users";
        $this->view->headTitle($this->view->title);

        $users = new Application_Model_DbTable_Users();
        $this->view->users = $users->fetchAll();
    }

    public function addUserAction()
    {
        // action body
    }

    public function editUserAction()
    {
        // action body
    }

    public function deleteUserAction()
    {
        // action body
    }

A: You application classes don't follow the proper naming convention for the namespace you've set. The Zend_Application_Module_AutoLoader is a little different than the normal autoloader in that it doesn't simply change the '_' in the class name with '/'. It looks at the second part of the class name and then checks a folder for the existence of the class based on that.
You need to change the line:
$modeLoader = new   Zend_Application_Module_AutoLoader(array(
    'namespace'=>'Application',
    'basePath'=>APPLICATION_PATH
));

This means it will autoload all module classes prefixed with 'Application_'. When it the second part of the class is 'Model_' it will look in "{$basePath}/models" for the class. The '_' in the rest of the class name will be replaced with '/'. So the file path of the file will be "{$basePath}/models/DbTable/Users.php".
Read more here.


text:
Q: MongoDB Cloud Deployment - High TTFB I am building a mobile only application in Node.js + MongoDB. I have deployed my server in the AWS AP-Southeast-1 Region.
Since I am new to MongoDB, I am leveraging cloud hosting services like MongoLabs, Compose.IO, MongoDirector (testing a few out). Now, these cloud hosting platforms are deploying my database in either of the AWS AP-Southeast-2 OR US-East-1 Region due to unavailability of Shared hosting in the Southeast-1 Region.
While testing my APIs, I saw a alarmingly high latency in the form of TTFB (Time to First Byte) of ~ 1-1.5seconds. Is this because of the server & database hosted in different regions? Apart from this, my queries are relatively taking less time.
Awaiting a reply as we're soon to goto Production.

A: You really don't want to do this. As I am sure you are aware ap-southeast-2 (Sydney) is a very long way from us-east-1 (East Coast of the U.S.) and a long way from ap-southeast-1 (Singapore) - probably ping times of 100ms+, whereas within an aws region ping times should be <2ms.
In addition you will be charged  more for data transfer to and from your database. EC2 data transfer within a region is $0.01/GB (free if same AZ), data between regions is $0.09/GB


text:
Q: Dplyr group_modify and anonymous functions Please have a look at the code below, where I have a data frame which I group and I then add a couple of summary statistics (I modified some examples I found online).
It works and it relies on the formula interface to specify the anonymous function, but whenever I tried to rewrite it as
function(x) bind_rows(x, ...)
I get an error because I do not specify at least two arguments. I simply want to make sure I can write this both ways (with and without the "~" notation).
Can anyone help me out and calculate df_out with an anonymous function without the formula interface?
Thanks!
 library(tidyverse)

##Have a look at

## https://stackoverflow.com/questions/54831166/how-would-i-add-a-total-row-for-each-value-in-a-specific-column-that-does-calcu

## https://community.rstudio.com/t/add-specific-rows-to-create-new-row-using-r-dplyr/13137/2

df1 <- structure(list(month = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), person = c("John",
   "Jane", "Tim", "Cindy", "John", "Jane", "Tim", "Cindy"), total = c(7L,
 18L, 20L, 11L, 18L, 13L, 15L, 9L), days_in_month = c(31L, 31L,
  31L, 31L, 28L, 28L, 28L, 28L)), class = "data.frame", row.names = c(NA,
                                                                      -8L)) %>%
    as_tibble

df1
#> # A tibble: 8 x 4
#>   month person total days_in_month
#>   <int> <chr>  <int>         <int>
#> 1     1 John       7            31
#> 2     1 Jane      18            31
#> 3     1 Tim       20            31
#> 4     1 Cindy     11            31
#> 5     2 John      18            28
#> 6     2 Jane      13            28
#> 7     2 Tim       15            28
#> 8     2 Cindy      9            28

df_out <- df1 %>%
  group_by(month, days_in_month) %>%
    group_modify(~ bind_rows(.x, tibble(person = "Mean", total = mean(.x$total)),  tibble(person = "Mean2",
                                        total = mean(.x$total[.x$total>10])))   ) %>%
    ungroup

df_out
#> # A tibble: 12 x 4
#>    month days_in_month person total
#>    <int>         <int> <chr>  <dbl>
#>  1     1            31 John     7
#>  2     1            31 Jane    18
#>  3     1            31 Tim     20
#>  4     1            31 Cindy   11
#>  5     1            31 Mean    14
#>  6     1            31 Mean2   16.3
#>  7     2            28 John    18
#>  8     2            28 Jane    13
#>  9     2            28 Tim     15
#> 10     2            28 Cindy    9
#> 11     2            28 Mean    13.8
#> 12     2            28 Mean2   15.3

Created on 2020-04-12 by the reprex package (v0.3.0)

A: If we need the regular function(x, y) as the .f in group_modify specifies

.f - If a function, it is used as is. It should have at least 2 formal arguments.

library(dplyr)
df1 %>%
  group_by(month, days_in_month) %>%
  group_modify(function(x, y) bind_rows(x,
        tibble(person = "Mean", total = mean(x$total)),
        tibble(person = "Mean2",
               total = mean(x$total[x$total>10])))   ) %>%
   ungroup


text:
Q: Why is Physics so hard? I'm in a classical mechanics class now. On our exams, most questions are quantitative. And in general, besides the theory part, all physics problems just require you to gather formulas, manipulate them a little bit by using other formulas, and come up with an appropriate value. In the question, you are given all the information you need. For our exams, they even give us a formula sheet, with every formula and equation we can possibly need. But even after all this, physics remains to be one of the most challenging subject for many students, including myself. I just don't get it. It seems like it should be so easy. Grab a formula or two, and manipulate it until all the given quantities can fit into these formulas. But yet, even after all this, its not easy to do, but it should be. Sorry if I'm not making any sense. I'm a student, and most of you already know this stuff, so try thinking as a newbie to physics.
Edit: Although this seems like a general study question, its actually a very specific question. I'm a really good student, but I think I've met my match with physics. It seems you just cant 'memorize' things in this class, like you can with any other class. You really just have to understand it. And lately, I've just been so discouraged to study since no matter how hard I study, I do really bad on the tricky exams. My study routine goes a little something like this:

*

*Watch pre-lecture video that explains the current chapter, and take notes on that.

*Do the weekly homework, which itself is pretty challenging.

*To study for the exams, I do a BUNCH of practice problems from previous semester exams that they supply us with. I literally go over and do 5 old exams, one question at a time, and I understand everything perfectly-at least I think I do, until the REAL exam comes around, and I do absolutely terrible.

I don't know what else to do at this point.

A:
I dont know what else to do at this point :(

Party less? Just kidding. Well @fprime, the first thing to realize is that physics is really friggin' hard and it seems to me that once you're over that hump you might actually end up enjoying it. However, loving the subject does not imply that you will never have night terrors where you wake up screaming "Its a real job I tell you, its a real job".
So if you think you have what it takes then hold your nose and dive in. Six months and no social life later you might start finding physics a lot easier and also a lot more different than what you expect.
One good place for beginners seeking inspiration is the set of lectures by Feynman. Good luck !

A: This is perhaps a bit besides the point and not really answering your question, but I'll mention it anyway. For me at least, the difference between "how can I possibly memorize all of this?" and true understanding often boils down to an interest and curiosity. I realize classes have a tendency to kill these things (even when done right, because you're now doing something because you have to), but I think it's worth the effort to try and rekindle your true interest.
Now, being told to "be more interested" is hardly help, and I'm sorry for that. I just know it tends to make the difference between being miserable cramming things into my head and working hard learning to understand something. When you learn something that explains a thing you've been wondering about, you no longer have to memorize. You feel in some sense immersed in your newfound knowledge, and you know it instead of just remembering it. I think this applies to most sciences (I've definitely experienced it in both physics, mathematics, computer science and electronics).
So my real advice is this: There will always be courses that don't interest you. For those you'll just have to cram it in. But at least the majority of courses can hopefully be viewed with from a different angle where they seem more like a way of answering a question or curiosity you have than a list of things you must know for the exam.

A: You can't just memorize it, you have to understand it
Suppose I tell you that an electron has been fired through an electric field towards an oscillating platform, and I want to know the time after which it will hit the platform, and what minimum initial energy I need. To answer that, you need to have a clear model in your head of what an electron is, how it interacts with electric fields, the idea that a particle follows a path defined by an equation of motion, the thought that the oscillation of the platform will change both the time taken and the minimum initial energy needed to reach the platform.
So:

*

*Learn the appropriate theory

*Form a mental model of that theory

*Using your mental model see, in your mind, what you think might happen in this specific circumstance

*Use the equations to construct some equations that reflect your intuition about what will happen.

You see the process of starting from the general (e.g. electromagnetism theory) to the specific (e.g. motion of an electron through an electric field). When doing research in Physics, you tend to do this to get an intuitive expectation, or prediction, of what will happen, and then you do an experiment to test it. Experimental Physics often works in the opposite direction, starting from some specific experimental results, and coming up with a general theory to tie them together.
If you haven't got the understanding, the intuitive mental model that captures all the rules (theory) that you know, then you will struggle to see your way to the solution.
So, you were right when you said "You really just have to understand it.".

A: Formulas are (merely) a means of describing relations between physical quantities. You should understand what a formula expresses, the physical concept (e.g. energy conservation) behind it. It's often useful if you can find an everyday analogy for it (e.g. 'money conservation': income equals expenses plus savings). Also, before applying a given formula you must check whether the assumptions made when deriving it are fulfilled in a given problem.
Unfortunately it's not clear why despite the learning effort you seem not to perform so well at the exams. Try studying together with other students (from whom you can learn). Or try asking questions here. And try to find out where your exam answers differ from the correct answers.

A: The problem is: There are so many formulas which you can combine, rearrange and manipulate in oh so many ways that just knowing the formulas doesn't get you that far. What you need is intuition and understanding as to which formulas relate to your problem and how you should relate them to get what you want. This intuition can only be built through experience, i.e. numerous hours of problem solving.
That's why it's so important you do all the problem sets you can find, because only then will you become really familiar with the formulas.
Think of it like learning to play chess: You can learn the rules in an afternoon, they aren't that hard. But this teaches you nothing about how to be a good chess player. That takes years of practice.

A: I don't know how helpful this group will be, we are probably a selfselected subgroup whose natural intuitions were such that physics was easy (at least up until some advanced level, when the math got challenging). A lot has to do with
understanding the material, and being very good at problem solving. And I've always felt the statement about the worst teachers being those who didn't have to struggle to learn the material, has a lot of truth to it. I think being good at undrgrad level physics has a very high correlation with being good at math word problems, so if you don't get a satisfactory answer here (on how to make it much easier), I'd ask the math group the same question about word problems.
The best learning technique for me when I was learning it was to speedread the chapter in the text book, then take out lots of paper and derive all the formulas just taught -the speedreading was to get the gist of where you are trying to go to and a feeling for how to get there. Also you should have mentally noted any nonobvious tricks needed to get the math to work out. Once you can do that, your understanding should be high enough to enable you to work through problems that need the understanding of the theory, but for which a cookbook like approach (simply plug in equation XXX for problems of type YYY, almost never works). If
you have a really good understanding of equation XXX, how it was arrived at etc., you have a good chance of being able to use it when it is appropriate, (at least if you are creative about problem solving).
I think the biggest thing about physics, is its mostly about a mode of thinking, and secondarily about the detailed material. Watch how those who are good at it descibe how they solve problems, hopefully some of their thinking style can be learned.

A: There is an answer to your question in the form of a physics paper : Determining dynamical equations is hard by Toby Cubitt, Jens Eisert and Michael Wolf. Basically, of you define physics as determining dynamical equations —the laws of physics— from some observations —the experiments—, they prove that this problem is NP-complete.
In other words, physics is not only hard, it is NP-hard !

A: Physics is about the ability to predict the outcome of scenarios. Either with formulas, simulation, or good old curve fitting. The underlying principles a few basic ones, but to use them you required to understand higher lever math, so to make it "easy", basic physics classes boil it down to a cookbook method. Add one of this, two of this, mix and voila here is the result. That is not how physics supposed to be, and it is a pitty you are stuck in such a situation. My suggestion is to bear with it, until you discover some of the commonalities by yourself and find your own way of making sense of the world.
Hang in there, it gets only beter from here!

A: The relevant concepts involved may not have been properly explained to you in sufficient detail for you to manipulate them easily.
Have you considered using a book with very clear definitions and many worked examples, like Schaum's outline series?   See http://www.amazon.com/s/ref=nb_sb_ss_i_6_15?url=search-alias%3Dstripbooks&field-keywords=schaums+physics&sprefix=schaums+physics.   They get surprisingly good reviews.
Can anyone recommend very good online lectures, preferably videos?

A: The way I see it, there are two aspects to the practice of science, there is a constructive one and a destructive one. Let me try to expand on that.
The destructive one is the easiest to explain and usually the one on which a fair amount of time is spent. It is basically the skeptical part of science, the one where you test one idea against another. There are various tools at your disposition to do this: experiment, checking for mathematical/logical coherence of the ideas.
The constructive or creative aspect is the hardest part. We don't have a systematic approach to it, basically, all we do is just try. The reason some people are more successful than others at doing this is experience, they can immediately select the potentially successful ideas from a larger set of ideas, without going through all the steps of the destructive part. Or they just are willing to spend so much more time on working on the subject, giving up on many other activities, which of course forges experience.
To summarize: critique is always relatively easy, coming up with good ideas is the hard part.
Now, one might say that these two aspects are not necessarily exclusive to physics, which is true. An artist has to go through the same motions, but the criteria are different. Nature is a harsh mistress, and that's why physics is so difficult. We can come up with lots of ideas, but nature doesn't care about how creative we are, if the idea doesn't work it doesn't work.
I'd say sciences in general are difficult because of this. If you didn't encounter the problem in other sciences yet, it's because you are still at a more elementary study level in them as compared to physics.


text:
Q: How can I get a textarea from model+ModelForm? models.py=>
from django.db import models
from django.forms import ModelForm
from datetime import date
import datetime
from django import forms
from django.forms import Textarea

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created = models.DateField(auto_now_add=True)
    modified = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return self.title

class PostModelForm(ModelForm):
    class Meta:
        model = Post

But I get a text input not textarea for models.TextField(). Is that a reason of css?

A: I think this section in the documentation should be useful to solve the problem.
from django.forms import ModelForm, Textarea

class PostModelForm(ModelForm):
    class Meta:
        model = Post
        widgets = {
            'content': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

A: Alternative to jcollardo's solution (same result, different syntax):
from django import forms

class PostModelForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Post

A: You are using models not forms, which means you can't use textarea properly. Instead you can try TextField:
field_name = models.TextField( **options)


text:
Q: System.exit(0) vs JFrame.EXIT_ON_CLOSE Is there any difference between the two. I was reading an article ( http://www.javalobby.org/java/forums/t17933 ) about that you should always use
System.exit(0);

Currently I use
JFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

The article says that even for a Java Swing Application you should add a listener WindowAdapter and and call System.exit() inside its method windowClosing(WindowEvent e).
Is there any difference? Is one method better then the other?

A: If you look at the JFrame code, it does:
 protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);

        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            switch(defaultCloseOperation) {
              ...
          case EXIT_ON_CLOSE:
                  // This needs to match the checkExit call in
                  // setDefaultCloseOperation
        System.exit(0);
        break;
            }
        }
    }

So, it's exactly the same thing. I would just set EXIT_ON_CLOSE if that's what you want it to do.

A: Well, considering System.exit(0) is in the JFrame coding, either would work.


text:
Q: Is libspotify available as a plugin for any mobile cross-platform SDK? Is libspotify available as a plugin for any cross-platform SDK? I'm talking about a native plugin for mobile SDKs like Phonegap, Gideros Mobile, Corona, Intel XDK, Marmalade or similar.

A: libspotify is a C library compiled for various targets (Mac, Windows, iOS, Android and various Linux variants), so there's no single cross-platform build.
However, it should be possible to create a wrapper around libspotify in these SDKs and deploy them along with the pre-built binaries to the platforms libspotify supports. There's nothing official like this, though.


text:
Q: Add array with unknown size into database I need to build a page where the user can enter the name of the categories of products of an webstore. I created a page with dynamic input fields so the user will be able to add all the categories (which i don't know the ammount). I have to get the name of those categories and put into a database. I got a script online and made a few changes but i dont know how to proceed further on. I need help with the php script, how to get the array and insert into the database.
This is my form script:
<form method="post" action="setup3.php">

        <button class="add_field_button">Add More Fields</button>

            <input type="text" name="mytext[]">

        <input type="submit" value="Next" />

</form>

A: I think this would point you in the right direction:
<?php
if (! empty($_POST['mytext'])) {
    foreach ($_POST['mytext'] as $entry) {
        // perform your insert here.
    }
}

I would strongly recommend using an ORM like Doctrine (http://www.doctrine-project.org/) since it already tackles a lot of security issues for you.
If you wish to stay pretty close to low-level database interactions, writing plain SQL queries, I'd recommend using PDO (http://php.net/manual/en/book.pdo.php)


text:
Q: Locked LVM logical volume in VG with missing PV So, I had disk failure and was moving LVs from the failing disk, to the new PVs. Some LVs were moved successfully, some not.
Afterwards I ended up with following state:
- two locked LVs
- volume group with missing PV
When I try to remove PV, I get:
vgreduce --removemissing --force vg3
  Couldn't find device with uuid RQr0HS-17ts-1k6Y-Xnex-IZwi-Y2kM-vCc5mP.
  Removing partial LV var.
  Can't remove locked LV var

lvremove -fff vg3/var
  Couldn't find device with uuid RQr0HS-17ts-1k6Y-Xnex-IZwi-Y2kM-vCc5mP.
  Can't remove locked LV var

pvmove --abort
  Couldn't find device with uuid RQr0HS-17ts-1k6Y-Xnex-IZwi-Y2kM-vCc5mP.
  Cannot change VG vg3 while PVs are missing.
  Consider vgreduce --removemissing.
  Skipping volume group vg3

I also tried executing vcfgbackup and then restore after editing the locks out, but to no avail:
vgcfgrestore --force vg3
  Couldn't find device with uuid RQr0HS-17ts-1k6Y-Xnex-IZwi-Y2kM-vCc5mP.
  Cannot restore Volume Group vg3 with 1 PVs marked as missing.
  Restore failed.

So I went even further, and inserted the disk back - its failed, but it is detectabled for a bit.
vgreduce --removemissing vg3
  /dev/vg3/var: read failed after 0 of 4096 at 9638445056: Input/output error
  /dev/vg3/var: read failed after 0 of 4096 at 9638502400: Input/output error
  WARNING: Partial LV var needs to be repaired or removed.
  WARNING: Partial LV pvmove1 needs to be repaired or removed.
  There are still partial LVs in VG vg3.
  To remove them unconditionally use: vgreduce --removemissing --force.
  Proceeding to remove empty missing PVs.

lvremove -fff vg3/var
  /dev/vg3/var: read failed after 0 of 4096 at 9638445056: Input/output error
  /dev/vg3/var: read failed after 0 of 4096 at 9638502400: Input/output error
  Can't remove locked LV var

pvmove --abort
  /dev/vg3/var: read failed after 0 of 4096 at 9638445056: Input/output error
  /dev/vg3/var: read failed after 0 of 4096 at 9638502400: Input/output error
  Cannot change VG vg3 while PVs are missing.
  Consider vgreduce --removemissing.
  Skipping volume group vg3

And this is the moment, at which I am out of ideas.

A: Similar to Can't remove volume group, solved this problem by creating a temporary pv with the same uuid:
UUID="RQr0HS-17ts-1k6Y-Xnex-IZwi-Y2kM-vCc5mP"  # from question
dd if=/dev/zero of=/tmp/tmp.raw bs=1M count=100
losetup -f
losetup /dev/loop0 /tmp/tmp.raw
pvcreate --norestorefile -u $UUID /dev/loop0   # it has arisen!
killall lvmetad      # so it stops complaining about duplicate uuids
pvremove /dev/loop0  # a clean removal
losetup -D
pvscan --cache       # to restart lvmetad

Season with vgreduce etc. if needed.


text:
Q: sass child elements order? I just want to add styles for child divs. I did this way and it's working.
.summary_boxes {
  .header {
    text-align: center;
  }
  .description {
    text-align: center;
  }
}

But my header class and description class is in inside of the other div called content.
Should I mention that class also? Like this way
.summary_boxes > content {
  .header {
    text-align: center;
  }
  .description {
    text-align: center;
  }
}

Which is the correct format?

A: The answer is not simple. It depends on how you would like to scale your CSS. First thing's first. CSS is parsed right to left, not left to right. Many people think that something like this:
.container > .left-col .column-heading > div > .final_thing_to_style {
  // styles
}

is faster than this:
.final_thing_to_style {
 // styles
}

The second version is more efficient because CSS is parsed from right to left. The class final_thing_to_style is immediately found, and the parser is done.
Let's look at your CSS.
.summary_boxes > content {
  .header {
    text-align: center;
  }
  .description {
    text-align: center;
  }
}

While adding the immediate child makes your CSS more specific, it's not necessary, and should be omitted. But ask yourself how you'll be using .header and .description. If this is the only place you'll use these classes, consider something like this instead:
.summary_box_header,
.summary_box_description {
  text-align: center;
}

If you'll need different flavors of .header and .description in different areas of your web page, this suggestion will make your styles too tightly coupled. You'll end up with a lot of duplication.
To loosen the coupling a bit, you could try something like this:
.header {
  .summary_boxes & {
    text-align: center;
  }

  .another_context & {
    text-align: left;
  }

  .yet_another_context & {
    text-align: right;
  }
}

This will create the following CSS:
.summary_boxes .header {
  text-align: center;
}

.another_context .header {
  text-align: left;
}

.yet_another_context .header {
  text-align: right;
}

Using the parent selector &, we can create very readable contexts for our .header class. We do add some specificity, but gain readability and flexibility.
With some experimentation, you'll be able to create an appropriate, flexible pattern for your styles.

A: It all comes down to specificity (https://css-tricks.com/specifics-on-css-specificity/).
The rule is to try to keep the specificity level as low as possible, without having your css rules bleed outside of it's intended use area.
Low specificity adds a lot of benefits, one being reusability, simplicity and lighter files. However if your specificity is too low your rules will start to bleed and interfere with each other.
There's no right or wrong here, it all comes down to the intended use case and future proofing your code. Without the HTML code and some background info on how these classes could be used in the future there is no way of saying what you should or shouldn't do in terms of specificity.
Andy's answer has a few examples but there's of course no limits to all the different ways your code could be structured (or restructured in the future).


text:
Q: Is there any way to read both .xls and .xlsx files using Apache POI? I need to create a method that can read both xls and xlsx files. According to my research, HSSF is used to read xls and XSSF to read xlsx. Is there a part of the Apache POI I can use to read both files? I also came across the ss.usermodel but found no sufficient codes that will entertain both xls and xlsx....

A: Thanks to Tom's answer just to add, use foll. code to get inputstream else we may face Exception in thread "main" java.io.IOException: mark/reset not supported
     InputStream inputStream = new FileInputStream(new File("C:\\myFile.xls"));

     if(! inputStream.markSupported()) {
                inputStream = new PushbackInputStream(fileStream, 8);
     }

A: You can use
Workbook wb = WorkBookFactory().create(inputStream);

A: Yes, there's a new set of interfaces provided by POI that work with both types.
Use the WorkbookFactory.create() method to get a Workbook:  http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/WorkbookFactory.html
You can check for excel files without relying on file extensions (which are unreliable - many csv files have xls extensions for example but cannot be parsed by POI) using the following:
//simple way to check for both types of excel files
public boolean isExcel(InputStream i) throws IOException{
    return (POIFSFileSystem.hasPOIFSHeader(i) || POIXMLDocument.hasOOXMLHeader(i));
}

A: I haven't had much exp with Apache POI, but as far as i know if you refer to a workbook by class "Workbook" then you can read and write both xls & xlsx.
All you have to do is when creating object write
for .xls-
Workbook wb = new HSSFWorkbook();

for .xlsx-
Workbook wb = new XSSFWorkbook();

you can pass a parameter for file type and create the WorkBook object accordingly using If statement.

A: you can read using poi-ooxml and poi-ooxml-schema jars provided by apache.
and use below code:--
Workbook wb = null;
excelFileToRead = new FileInputStream(fileName);
wb = WorkbookFactory.create(excelFileToRead);
Sheet sheet = wb.getSheet(sheetName);

the above code will read both xls and xlsx files

A: one option would be to check the file name with lastIndexOf for . and see if it is .xls or xlsx and then use an if condition to switch accordingly.
been a long time since i worked on poi but i think it the attributes are like  HSSF for .xls and XSSF for .xlsx
refer http://poi.apache.org/ site, last line under the topic
Why should I use Apache POI?

A: It appears you are looking for a way to abstract the read process, you are saying it doesn't matter if its XLS or XLSX, you want your code to work without modification.
I'd recommend you to look at Apache Tika, its an awesome library that abstracts file reading and content parsing, it uses POI and many other libraries and has a nice abstraction to all of them.
reading a PDF/XLS/XLSX is similar to reading a text file, all the work is done behind the scene.
read this for more. http://www.searchworkings.org/blog/-/blogs/introduction-to-apache-tika


text:
Q: URL Regex For HTTP/HTTPS is optional Hi I am using Following URL regex for finding web site urls.
 NSString *urlRegEx =@"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";

But I need to find following URL's too.
Examples:

www.gmail.com
gmail.com
https://stackoverflow.com/questions/ask

Like this.

A: Maybe try using another "or" | after (http|https)://:
(http|https)://|((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+

That should find all of the examples you've shown.

A: You can just make your first part optional:
((http|https)://)?

However you've also got a few errors in your expression, so it matches more than it should. You've used | and escaped . inside [ ], all that does is add | and \ to the set. Fixing that and simplifying gives:
(https?://)?(\w|[-_0-9])+([./](\w|[-_0-9])+)+

HTH


text:
Q: Get selected value from drop down inside GridView on Update So I have some GridView. When you edit a row, a particular column changes from a label to a DropDownList. The content of this drop down is populated via some SQL data source.
The user may make a selection choice and click "Update".
How can I actually get at the SelectedValue property of the drop down?
I thought this would work:
    <asp:GridView ... >
        <Columns>
            ...
                <EditItemTemplate>
                    <asp:DropDownList ID="ServiceCategoriesGvDropDown" AutoPostBack="True" .../>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ... />
                </ItemTemplate>
            </asp:TemplateField>
            ...
        </Columns>
    </asp:GridView>

And then wire it up with a ControlParameter in my SqlDataSource:
    <UpdateParameters>
        ...
        <asp:ControlParameter ControlID="ServiceCategoriesGvDropDown" PropertyName="SelectedValue" ... />
    </UpdateParameters>

However, I get the following exception:
System.InvalidOperationException: Could not find control 'ServiceCategoriesGvDropDown' in ControlParameter 'ServiceCategoriesID'.
So clearly my drop down doesn't get found. Perhaps it's been destroyed by this point?

A: try this in the updating event of the grid.
 protected void YourGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {
  DropDownList ddl= (DropDownList )YourGrid.Rows[e.RowIndex].FindControl("ddlId");
  string selectedvalue=ddl.selectedvalue;
  //Your update code goes here
 }

A: What I think you need to do is:

*

*Attach a SelectedIndexChange event to the DropDownlist on your Gridview

*Grab the SelectedValue on that event.

*Grab a reference to your DataSource's UpdateParameters and populate the respective parameter programmatically with the SelectedValue.

*Call your DataSource's Update method.

A: You can try doing this:
assuming the ID of the gridview is gridview1
<asp:ControlParameter ControlID="gridview1$ServiceCategoriesGvDropDown" PropertyName="SelectedValue" />


text:
Q: Why does this polynomial only generate primes? I recently saw this polynomial...
$f(x) = x^2+x+27941$
What i found amazing about it that it generates only prime numbers. Here are some first values generated by this polynomial for negative numbers even
I cannot understand why this is happening? Also, i do not think it specifically generates all numbers $\equiv 1,-1 \pmod 6$. Can you please help me? Also, is there any proof of this, that it generates so many primes?
EDIT: As pointed out in the comments, i see that this polynomial does not generate a prime for $x=1000000$. Her is the factprization:-

A: The statement is false. You can check this without a computer by observing that for $x = 27\,941$ we have $$f(27\,941) = 27\,941^2 + 27\,941 + 27\,941 = 27\,941 (27\,941 + 2) = 27\,941 \cdot 27\,943 ,$$ which is not prime.
Edit In fact, consulting a computer shows that the claim fails already for $x = 5$: $$f(5) = 83 \cdot 337 .$$

A: plenty of composites
====================
here are some that are not squarefree
346    148003  =   47^2 67
364    160801  =   401^2
547    327697  =   67^2 73
658    461563  =   67 83^2
995    1018961  =   89 107^2

===================
-21    28361  =   79 359
-20    28321  =   127 223
-18    28247  =   47 601
-17    28213  =   89 317
-12    28073  =   67 419
-9    28013  =   109 257
-6    27971  =   83 337
5    27971  =   83 337
8    28013  =   109 257
11    28073  =   67 419
16    28213  =   89 317
17    28247  =   47 601
19    28321  =   127 223
20    28361  =   79 359
29    28811  =   47 613
32    28997  =   107 271
36    29273  =   73 401
42    29747  =   151 197
55    31021  =   67 463
56    31133  =   163 191
58    31363  =   79 397
64    32101  =   47 683
65    32231  =   167 193
72    33197  =   89 373
74    33491  =   107 313
76    33793  =   47 719
77    33947  =   83 409
78    34103  =   67 509
88    35773  =   83 431
99    37841  =   79 479
100    38041  =   109 349
101    38243  =   167 229
105    39071  =   89 439
106    39283  =   163 241
107    39497  =   127 311
108    39713  =   151 263
109    39931  =   73 547
111    40373  =   47 859
117    41747  =   109 383
122    42947  =   67 641
123    43193  =   47 919
127    44197  =   193 229
134    46031  =   191 241
137    46847  =   79 593
139    47401  =   107 443
145    49111  =   67 733
146    49403  =   127 389
154    51811  =   197 263
158    53063  =   47 1129
160    53701  =   83 647
161    54023  =   89 607
170    57011  =   47 1213
171    57353  =   83 691
178    59803  =   79 757
181    60883  =   107 569
182    61247  =   73 839
189    63851  =   67 953
193    65383  =   151 433
194    65771  =   89 739
203    69353  =   223 311
205    70171  =   47 1493
209    71831  =   109 659
212    73097  =   67 1091
216    74813  =   79 947
217    75247  =   47 1601
219    76121  =   163 467
226    79243  =   109 727
232    81997  =   167 491
234    82931  =   127 653
238    84823  =   271 313
239    85301  =   197 433
242    86747  =   223 389
243    87233  =   83 1051
246    88703  =   107 829
247    89197  =   191 467
248    89693  =   257 349
250    90691  =   89 1019
252    91697  =   47 1951
254    92711  =   83 1117
255    93221  =   73 1277
256    93733  =   67 1399
257    94247  =   79 1193
258    94763  =   193 491
259    95281  =   151 631
264    97901  =   47 2083
265    98431  =   257 383
268    100033  =   167 599
269    100571  =   163 617
273    102743  =   127 809
279    106061  =   67 1583
283    108313  =   89 1217
288    111173  =   107 1039
295    115261  =   79 1459
299    117641  =   47 2503
300    118241  =   317 373
303    120053  =   271 443
311    124973  =   47 2659
318    129383  =   109 1187
320    130661  =   193 677
323    132593  =   67 1979
325    133891  =   191 701
326    134543  =   83 1621
328    135853  =   73 1861
330    137171  =   229 599


text:
Q: Limit User Uploads PHP I have a script that allows anyone to upload a file under 200 MB and after the file is downloaded once it will delete it, and after 24 hours all files are deleted from the server. My question is how can I limit the number of times someone can upload a file for example. If someone were to upload 3 files in one hour, if they were to upload a 4th file, they would need to put in a captcha code to ensure they are not a robot. But how would I go about doing this?
Code for uploading:
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

    <script>
    function _(el){
    return document.getElementById(el);
    }

    function uploadFile(){
    var file = _("file1").files[0];
    //alert(file.name+" | "+file.size+" | "+file.type);
    var formdata = new FormData();
    formdata.append("file1", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "upload.php");
    ajax.send(formdata);
    }

    function progressHandler(event){
    //_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+'%';
    }

    function completeHandler(event){
    _("completed").innerHTML = event.target.responseText;
    _("progressBar").value = 100;
    }

    function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
    }

    function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";
    }
    </script>

    <body>

    <input type="button" value="Upload File" onclick="uploadFile()" class="UploadButton">
    <progress id="progressBar" value="0" max="100">
    </progress>
    </body>

php upload script:

    <?php

    include('connect.php');
    $file = $_FILES["file1"]["name"];

    if ($file == "") {
    // if file not chosen
    exit();
    }

    $ogname = $_FILES["file1"]["name"];
    // The file name

    $length = 20;
    $randomString =     substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0,     $length);

    $num = rand () ;
    $key = md5($num);

    $info = pathinfo( $ogname );
    $ext  = $info['extension'];

    $fileName = $randomString . "." .$ext;

    //gets ip address of client
    //Test if it is a shared client
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip=$_SERVER['HTTP_CLIENT_IP'];
    //Is it a proxy address
    }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
    $ip=$_SERVER['REMOTE_ADDR'];
    }

    //returns ip to be stored later
    $downloads = 0;
    $time = 0;
    $fileTmpLoc = $_FILES["file1"]["tmp_name"];

    // File in the PHP tmp folder
    $fileType = $_FILES["file1"]["type"];
    // The type of file it is
    $fileSize = $_FILES["file1"]["size"];

    if($fileSize > 209715201){
    // if too large
    exit();
    }

    // File size in bytes
    $fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
    if (!$fileTmpLoc) {
    // if file not chosen
    exit();
    }
    if(move_uploaded_file($fileTmpLoc, "files/$fileName"))
    {

    //success

                mysql_query("INSERT INTO file(name, ogname, type, size,     tmp_name, keyID, ip, time, downloads)
                VALUES('$fileName', '$ogname', '$fileType',     '$fileSize',     '$fileTmpLoc', '$key', '$ip', '$downloads', '$time')");

    }else {
     //not uploaded
    }
    ?>

A: First of all, you need a way to tell one user from another.
If users have to log in to your site before they can upload these files, then this part is easy: you know which user is uploading each file because they're logged in.
If not - and if you're not willing to add a login requirement - you'll have to take a different approach. There are two possible approaches, both imperfect:
a. Assume that every unique IP address, as found in $_SERVER['REMOTE_ADDR'], is a distinct user.
This is imperfect because different users sometimes have the same IP address (for example, if they're visiting your site from within the same corporate network), so this approach could mistakenly conclude that a user has exceeded their quota (even though they haven't).
or,
b. Use PHP sessions; it's specifically designed to uniquely identify visitors.
This one is imperfect because it's easily circumvented - the user can clear their cookies, or use a different browser, and the site will think they're a different user.
If you need a hard limit that can't be circumvented, then you need to require a login. If the upload limit is more of a courtesy, and it's not the end of the world if someone happens to circumvent it, then you need to choose which is more important to you: slightly better (but still pretty weak) security, at the cost of some false positives (choose option a), or slightly better user-friendliness, at the cost of worse security (choose option b).

A: You need a way of identifying a user and keeping track as to how many files they have uploaded so far.
I would probably use a database where I store a combination of identification values (e.g. IP, host, browser) and keep a counter with a timestamp.


text:
Q: Mongoose query blocks Node.js Mongoose blocks Node.js when it is getting data. I thought that it is supposed to be absolutely no blocking and when callback appears then it should  just get back there.
The problem is with:
Container.find({}, function (err, documents) {
        res.status(200).send(documents);
});

When I will run this route in ExpressJS it will just freeze NodeJS for around 10sec, and no one else can reach connection then.
I'm having a open connection to MongoDB at the start using Mongoose and not doing anything with it later on. What's the problem? It is supposed to work like that?
UPDATE:
So this is how I init mongoose
function initialDb() {
seed();
seedStructure();
startApplication();
}

database.connect();
database.loadModels(initialDb);

and this is the place where i connect and init models
import mongoose from 'mongoose';
import chalk from 'chalk';
import config from '../config';

export default {
    loadModels(callback){
        require('../../models/site');
        require('../../models/page');
        require('../../models/container');
        require('../../models/template');
        require('../../models/theme');

        if (typeof callback === 'function') {
            return callback();
        }
    },

    connect () {
        mongoose.connect(config.db.uri, function (err) {
            if (err) {
                console.error(chalk.red('Could not connect to MongoDB!'));
                console.log(err);
            }
        });
    },

    disconnect(callback) {
        mongoose.disconnect(function (err) {
            console.info(chalk.yellow('Disconnected from MongoDB.'));
            callback(err);
        });
    }
};

and the model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var container = new Schema({

});

let model = mongoose.model('container', container);

module.exports = model;

It returns around 26k documents.

A: Ok so basically I found out, that if I will stream that instead of getting it with one callback it will work way better (I will be able to get into some other actions)
like this
var stream = Container.find({}).stream();

var array = [];
stream.on('data', (doc) => {
    array.push(doc);
}).on('error', (err) => {

}).on('close', () => {
    res.send(array);
});

It will solve the problem. So this is how I would get big data from mongodb, though why it is slowing so much if I will get it in one callback? Due to 12MB data? Big json that needs to be parsed or what?
Cause this is a quite mysterious for me (the reason for slow down)


text:
Q: Asp.net https allow only payment page I know some asp.net http block techniques. I have payment page Payment.aspx. I want to apply https only this page other pages will use http but Payment.aspx will use https.
    pageName = Request.Url.AbsoluteUri;
    if (pageName == "http://?????.com/Payment.aspx")
    {
        Response.Redirect("https://?.com/Payment.aspx");
    }

This tehniques do not work because of my server provider. Waiting your suggestions. Thank you.

A: if(!Request.IsSecureConnection)
{
    //perform your redirect here.
}

Use the Request.IsSecureConnection to detect if HTTPS is being used. Don't try to recognize magic strings.

A: You have to do some SSL change for it you can use the mentioned link for it
Click here