Q: Sorting from multiple loops I have 7 different loops grabbing information from different places in the same format but as they're coming from different areas the data is muddled up.
for event in soup.find('dual').find_all('event'):
 print event

for event in soup.find('int').find_all('event'):
 print event

I want to sort all the information returned from these loops by a specific column number (i.e column seven places along). They are currently in CSV format and I have tried writing them to a CSV file and sorting them from that. Is there a way of sorting from these different loops without having to write to any files.

A: master_list = []

for event in soup.find('dual').find_all('event'):
    master_list.append(event)

for event in soup.find('int').find_all('event'):
    master_list.append(event)

for event in soup.find('whatever').find_all('event'):
    master_list.append(event)

print sorted(event)

You may have to write your own comparison function so that sorted knows how to sort the list.


Q: Debugging PDF for error I'm creating PDF files using PDFClown java library.
Sometimes, when openning these files with Adobe Acrobat Reader I get the famous error message:

"An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem."

The error shows while reading (with Adobe) the attached file only when scrolling down to the 8'th page, then scrolling back up to 3'td page. Alternatively, Zooming out to 33.3% will also produce the message.
Just for the record, Foxit reader reads the file flawlessly, as well as other PDF readers like browsers.
My questions are:

*

*What's wrong with my file?? (file is attached)

*How can I find what's wrong with it? is there a tool which tells you where does the error lie?
Thanks!

A: Ok, this wasn't easy -
Due to a bug in PDFClown the my main stream of information in the PDF page has been corrupted.
After it's end it had a copy of a past instance of it.
This caused a partial text section without the starting command "BT" - which left a single "ET" without a "BT" in the end of the stream.
once I corrected this, it ran great.
Thank you all for your help.
I would have much more difficult time debugging it without the tool RUPS which @Bruno suggested.
edit:
The bug was in the Buffer.java:clone() (line 217)
instead of line:
clone.append(data);
needs to be:
clone.append(data, 0, this.length);
Without this correction it clones the whole data buffer, and set the cloned Buffer's length to the data[].length. This is very problematic if the Buffer.length is smaller than the data[].length.
The result in my case was that in the end of the stream there was garbage.

A:
The error shows while reading (with Adobe) the attached file only when scrolling down to the 8'th page, then scrolling back up to 3'td page. Alternatively, Zooming out to 33.3% will also produce the message.

Well, I get it easier, I merely open the PDF and scroll down using the cursor keys. As soon as the top 2 cm of page 3 appear, the message appears.

What's wrong with my file??

The content of pages 1 and 2 look ok, so let's look at the content of page 3.
My initial attributing the issue to the use of text specific operations (especially Tf and Tw) outside of a text object was wrong as Stefano Chizzolini pointed out: Some text related operations indeed are allowed outside text objects, namely the text state operations, cf. figure 9 from the PDF specification:

So while being less common, text state operations at page description level are completely ok.
After my incorrect attempt to explain the issue, the OP's own answer indicated that the

main stream of information in the PDF page has been corrupted. After it's end it had a copy of a past instance of it. This caused a partial text section without the starting command "BT" - which left a single "ET" without a "BT" in the end of the stream.

An ET without a prior BT indeed would be an error, and quite likely it would be accompanied by operations at the wrong level... Inspecting the stream content of that third page (the focused page of this issue), though, I could not find any unmatched ET. In the course of that inspection, though, I discovered that the content stream contains more than 2000 trailing 0 bytes! Adobe Reader seems not to be able to cope with these 0 bytes.
The bug the OP found, can explain the issue:

in the Buffer.java:clone() (line 217)
instead of line:
clone.append(data);

needs to be:
clone.append(data, 0, this.length);

Without this correction it clones the whole data buffer, and set the cloned Buffer's length to the data[].length. This is very problematic if the Buffer.length``  is smaller than the data[].length.

Trailing 0 bytes can be an effect of such a buffer copying bug.
Furthermore symptoms as found by the OP (After it's end it had a copy of a past instance of it) can also be the effect of such a bug. So I assume the OP found those symptoms on a different page, not page 3, but fixing the bug healed all symptoms.

How can I find what's wrong with it? is there a tool which tells you where does the error lie?

There are PDF syntax checkers, e.g. the Preflight tool included in Adobe Acrobat. but even that fails on your file.
So essentially you have to extract the page content (using a PDF browser, e.g. RUPS) and check manually with the PDF specification on the other screen.

A: the general post about debugging pdf might have been also helpful as rups / pdfstreamdump etc is mentioned there How do you debug PDF files?


Q: Is it possible to use mouse and keyboard through HP USB-C Dock G5 with notebook and another PC I have hp notebook and I use mouse and keyboard through HP USB-C Dock G5 with this notebook. All works fine. Then I have a desktop PC as well, which is separate device. My question is, is it somehow possible to connect the mouse and keyboard I am using with my notebook through the G5 with the PC too? The goal is to have just one mouse and just one keyboard for both, notebook and PC. Both devices use Windows 10. Thanks!

A: That ain't gong to work.
USB uses a single controlling device (the so-called "host") which controls everything  connected to that USB bus. All other devices on the bus can only talk to the host and to nothing else.
A computer is always the host. Connecting a second computer, connects a second host and this is simply not supported in the USB world.
What you need is a so-called KVM (Keyboard, Video, Mouse) switch that supports USB.
A USB capable KVM acts towards BOTH hosts as a set of connected devices. It uses for each host a sperate USB bus to do that, so both hosts don't interfere with each other. But towards the devices themselves it looks as if the KVM itself is a single host (using a 3rd USB bus).


Q: How Can I create an image with python PIL where there are two colors? Here is an example of the output I want to generate. I'm able to create an image with one color, but I don't have idea of how can use two colors, and how to color  only certain parts of the image .

A: I solved in this way. I created two image with two different colors, and then paste them in another one image.
width = 400
height = 300
img = Image.new( mode = "RGB", size = (width, height), color = (209, 123, 193) )
#First IMG

img2 = Image.new( mode = "RGB", size = (width, height + 400), color = (255, 255, 255) )
#Second IMG

img3 = Image.new('RGB', (img.width, img.height + img2.height)) img3.paste(img, (0, 0)) img3.paste(img2, (img.width, 0))
#IMG + IMG2

I got my result.


Q: Interpreting R's ur.df (Dickey-Fuller unit root test) results I am running the following unit root test (Dickey-Fuller) on a time series using the ur.df() function in the urca package.
The command is:
summary(ur.df(d.Aus, type = "drift", 6))

The output is:
###############################################
# Augmented Dickey-Fuller Test Unit Root Test #
###############################################

Test regression drift

Call:
lm(formula = z.diff ~ z.lag.1 + 1 + z.diff.lag)

Residuals:
      Min        1Q    Median        3Q       Max
-0.266372 -0.036882 -0.002716  0.036644  0.230738

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.001114   0.003238   0.344  0.73089
z.lag.1     -0.010656   0.006080  -1.753  0.08031 .
z.diff.lag1  0.071471   0.044908   1.592  0.11214
z.diff.lag2  0.086806   0.044714   1.941  0.05279 .
z.diff.lag3  0.029537   0.044781   0.660  0.50983
z.diff.lag4  0.056348   0.044792   1.258  0.20899
z.diff.lag5  0.119487   0.044949   2.658  0.00811 **
z.diff.lag6 -0.082519   0.045237  -1.824  0.06874 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.06636 on 491 degrees of freedom
Multiple R-squared: 0.04211,    Adjusted R-squared: 0.02845
F-statistic: 3.083 on 7 and 491 DF,  p-value: 0.003445

Value of test-statistic is: -1.7525 1.6091

Critical values for test statistics:
      1pct  5pct 10pct
tau2 -3.43 -2.86 -2.57
phi1  6.43  4.59  3.78

*

*What do the significance codes (Signif. codes) mean? I noticed that some of them where written against: z.lag.1, z.diff.lag.2, z.diff.lag.3 (the "." significance code) and z.diff.lag.5 (the "**" significance code).

*The output gives me two (2) values of test statistic: -1.7525 and 1.6091. I know that the ADF test statistic is the first one (i.e. -1.7525). What is the second one then?

*Finally, in order to test the hypothesis for unit root at the 95% significance level, I need to compare my ADF test statistic (i.e. -1.7525) to a critical value, which I normally get from a table. The output here seems to give me the critical values through. However, the question is: which critical value between "tau2" and "phi1" should I use.
Thank you for your response.

A: As joint-p already pointed out, the significance codes are fairly standard and they correspond to p-values, i.e. the statistical significance of a hypothesis test. a p-value of .01 means that the conclusion is true within 99% confidence.
The Wikipedia article on Dickey-Fuller describes the three versions of the Dickey-Fuller test: the "unit root", "unit root with drift", and "unit root with drift and deterministic time trend", or what is  referred to in the urca documentation as type= "none", "drift", and "trend", respectively.
Each of these tests is a progressively more complex linear regression. In all of them there is the root, but in the drift there is also a drift coefficient, and in the trend there is also a trend coefficient. Each of these coefficients has an associated significance level. While the significance of the root coefficient is the most important and the main focus of the DF test, we might also be interested in knowing whether or not the trend/drift is statistically significant as well. After tinkering around with the different modes and seeing which coefficients appear/disappear in the t-tests, I was able to easily identify which coefficient corresponded to which t-test.
They can be written as follows (from wiki page):

(unit root) $\Delta y_{t} = \delta y_{t-1} + u_{t}$
(with drift) $\Delta y_{t} = \delta y_{t-1} + a_{0} + u_{t}$
(with trend) $\Delta y_{t} = \delta y_{t-1} + a_{0} + a_{1}t + u_{t}$

In your case, "tau2" corresponds to $\delta$, while "phi1" corresponds to $a_{0}$. You will also see a third coefficient appear in the "trend" test, which would correspond to $a_{1}$ in the third equation above. However the names of the variables will change when you switch to "trend", so be careful and make sure you do this tinkering yourself to check. I believe in "trend" mode, "tau3" corresponds to $\delta$, "phi2" corresponds to $a_{0}$, and "phi3" corresponds to $a_{1}$.

A: I found Jeramy's answer pretty easy to follow, but constantly found myself trying to walk through the logic correctly and making mistakes.  I coded up an R function that interprets each of the three types of models, and gives warnings if there are inconsistencies or inconclusive results (I don't think there ever should inconsistencies if I understand the ADF math correctly, but I thought still a good check in case the ur.df function has any defects).
Please take a look.  Happy to take comments/correction/improvements.
https://gist.github.com/hankroark/968fc28b767f1e43b5a33b151b771bf9

A:
More info in Roger Perman's lecture notes on unit root tests
See also table 4.2 in Enders, Applied Econometric Time Series (4e), which summarizes the different hypotheses to which these test statistics refer. Content agrees with the image provided above.

A: It seems the creators of this particular R command presume one is familiar with the original Dickey-Fuller formulae, so did not provide the relevant documentation for how to interpret the values.  I found that Enders was an incredibly helpful resource (Applied Econometric Time Series 3e, 2010, p. 206-209--I imagine other editions would also be fine).  Below I'll use data from the URCA package, real income in Denmark as an example.
> income <- ts(denmark$LRY)

It might be useful to first describe the 3 different formulae Dickey-Fuller used to get different hypotheses, since these match the ur.df "type" options.  Enders specifies that in all of these 3 cases, the consistent term used is gamma, the coefficient for the previous value of y, the lag term.  If gamma=0, then there is a unit root (random walk, nonstationary).  Where the null hypothesis is gamma=0, if p<0.05, then we reject the null (at the 95% level), and presume there is no unit root.  If we fail to reject the null (p>0.05) then we presume a unit root exists.  From here, we can proceed to interpreting the tau's and phi's.

*

*type="none": $\Delta y_t = \gamma \, y_{t-1} + e_t$ (formula from Enders p. 208)

(where $e_t$ is the error term, presumed to be white noise; $\gamma = a-1$ from $y_t = a \,y_{t-1} + e_t$; $y_{t-1}$ refers to the previous value of $y$, so is the lag term)
For type= "none," tau (or tau1 in R output) is the null hypothesis for gamma = 0.  Using the Denmark income example, I get "Value of test-statistic is 0.7944" and the "Critical values for test statistics are: tau1 -2.6  -1.95  -1.61.  Given that the test statistic is within the all 3 regions (1%, 5%, 10%) where we fail to reject the null, we should presume the data is a random walk, ie that a unit root is present.  In this case, the tau1 refers to the gamma = 0 hypothesis.  The "z.lag1" is the gamma term, the coefficient for the lag term (y(t-1)), which is p=0.431, which we fail to reject as significant, simply implying that gamma isn't statistically significant to this model. Here is the output from R
> summary(ur.df(y=income, type = "none",lags=1))
>
> ###############################################
> # Augmented Dickey-Fuller Test Unit Root Test #
> ###############################################
>
> Test regression none
>
>
> Call:
> lm(formula = z.diff ~ z.lag.1 - 1 + z.diff.lag)
>
> Residuals:
>       Min        1Q    Median        3Q       Max
> -0.044067 -0.016747 -0.006596  0.010305  0.085688
>
> Coefficients:
>             Estimate Std. Error t value Pr(>|t|)
> z.lag.1    0.0004636  0.0005836   0.794    0.431
> z.diff.lag 0.1724315  0.1362615   1.265    0.211
>
> Residual standard error: 0.0251 on 51 degrees of freedom
> Multiple R-squared:  0.04696,   Adjusted R-squared:  0.009589
> F-statistic: 1.257 on 2 and 51 DF,  p-value: 0.2933
>
>
> Value of test-statistic is: 0.7944
>
> Critical values for test statistics:
>      1pct  5pct 10pct
> tau1 -2.6 -1.95 -1.61

*type = "drift" (your specific question above): : $\Delta y_t = a_0 + \gamma \, y_{t-1} + e_t$ (formula from Enders p. 208)

(where $a_0$ is "a sub-zero" and refers to the constant, or drift term)
Here is where the output interpretation gets trickier.  "tau2" is still the $\gamma=0$ null hypothesis.  In this case, where the first test statistic = -1.4462 is within the region of failing to reject the null, we should again presume a unit root, that $\gamma=0$.
The phi1 term refers to the second hypothesis, which is a combined null hypothesis of $a_0 = \gamma = 0$.  This means that BOTH of the values are tested to be 0 at the same time.  If p<0.05, we reject the null, and presume that AT LEAST one of these is false--i.e. one or both of the terms $a_0$ or $\gamma$ are not 0.  Failing to reject this null implies that BOTH $a_0$ AND $\gamma = 0$, implying 1) that $\gamma=0$ therefore a unit root is present, AND 2) $a_0=0$, so there is no drift term.  Here is the R output
> summary(ur.df(y=income, type = "drift",lags=1))
>
> ###############################################
> # Augmented Dickey-Fuller Test Unit Root Test #
> ###############################################
>
> Test regression drift
>
>
> Call:
> lm(formula = z.diff ~ z.lag.1 + 1 + z.diff.lag)
>
> Residuals:
>       Min        1Q    Median        3Q       Max
> -0.041910 -0.016484 -0.006994  0.013651  0.074920
>
> Coefficients:
>             Estimate Std. Error t value Pr(>|t|)
> (Intercept)  0.43453    0.28995   1.499    0.140
> z.lag.1     -0.07256    0.04873  -1.489    0.143
> z.diff.lag   0.22028    0.13836   1.592    0.118
>
> Residual standard error: 0.0248 on 50 degrees of freedom
> Multiple R-squared:  0.07166,   Adjusted R-squared:  0.03452
> F-statistic:  1.93 on 2 and 50 DF,  p-value: 0.1559
>
>
> Value of test-statistic is: -1.4891 1.4462
>
> Critical values for test statistics:
>       1pct  5pct 10pct
> tau2 -3.51 -2.89 -2.58
> phi1  6.70  4.71  3.86

*Finally, for the type="trend": $\Delta y_t = a_0 + \gamma * y_{t-1} + a_{2}t + e_t$ (formula from Enders p. 208)

(where $a_{2}t$ is a time trend term)
The hypotheses (from Enders p. 208) are as follows:
tau: $\gamma=0$
phi3: $\gamma = a_2 = 0$
phi2: $a_0 = \gamma = a_2 = 0$
This is similar to the R output.  In this case, the test statistics are -2.4216  2.1927 2.9343
In all of these cases, these fall within the "fail to reject the null" zones (see critical values below).  What tau3 implies, as above, is that we fail to reject the null of unit root, implying a unit root is present.
Failing to reject phi3 implies two things: 1) $\gamma = 0$ (unit root) AND 2) there is no time trend term, i.e., $a_2=0$.  If we rejected this null, it would imply that one or both of these terms was not 0.
Failing to reject phi2 implies 3 things: 1) $\gamma = 0$ AND 2) no time trend term AND 3) no drift term, i.e. that $\gamma =0$, that $a_0 = 0$, and that $a_2 = 0$.  Rejecting this null implies that one, two, OR all three of these terms was NOT zero.
Here is the R output
> summary(ur.df(y=income, type = "trend",lags=1))
>
> ###############################################
> # Augmented Dickey-Fuller Test Unit Root Test #
> ###############################################
>
> Test regression trend
>
>
> Call:
> lm(formula = z.diff ~ z.lag.1 + 1 + tt + z.diff.lag)
>
> Residuals:
>       Min        1Q    Median        3Q       Max
> -0.036693 -0.016457 -0.000435  0.014344  0.074299
>
> Coefficients:
>               Estimate Std. Error t value Pr(>|t|)
> (Intercept)  1.0369478  0.4272693   2.427   0.0190 *
> z.lag.1     -0.1767666  0.0729961  -2.422   0.0192 *
> tt           0.0006299  0.0003348   1.881   0.0659 .
> z.diff.lag   0.2557788  0.1362896   1.877   0.0665 .
> ---
> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>
> Residual standard error: 0.02419 on 49 degrees of freedom
> Multiple R-squared:  0.1342,    Adjusted R-squared:  0.08117
> F-statistic: 2.531 on 3 and 49 DF,  p-value: 0.06785
>
>
> Value of test-statistic is: -2.4216 2.1927 2.9343
>
> Critical values for test statistics:
>       1pct  5pct 10pct
> tau3 -4.04 -3.45 -3.15
> phi2  6.50  4.88  4.16
> phi3  8.73  6.49  5.47

In your specific example above, for the d.Aus data, since both of the test statistics are inside of the "fail to reject" zone, it implies that $\gamma=0$ AND $a_0 = 0$, meaning that there is a unit root, but no drift term.

A: phi1 phi2 phi3 are equivalent to F-tests in ADF framework


Q: openVAS - Microsoft RDP Server Private Key Information Disclosure Vulnerability - false Alarm? I performed a openVAS scan on a Windows Server 2008 R2 and got a report for a high threat level vulnerability called Microsoft RDP Server Private Key Information Disclosure Vulnerability. An remote attacker could perform a man-in-the-middle attack to gain access to a RDP session.
Affected Software is Microsoft RDP 5.2 and below.
My server uses RDP 7.1, is this alarm a false alarm?
Security Advisor Pages say: Solution Status Unpatched, No remedy...
References
http://secunia.com/advisories/15605/
http://xforce.iss.net/xforce/xfdb/21954/
http://www.oxid.it/downloads/rdp-gbu.pdf
CVE: CVE-2005-1794
BID:13818

A: It was fixed in 5.3, (actually 6.0 since there wasn't a 5.3, but the vulnerability tests look for 5.3) so if you have 7.1 then it does not apply to your system.
Unfortunately it doesn't appear to be possible to detect the exact RDP version remotely, as the RDP server returns the same version number for anything 5.0 and higher. This vulnerability, then, would always be reported if an RDP server is present on the target host.

A: You are still potentially vulnerable unless you have configured the server to only use the newer protocol.
You can do this as follows:

*

*Open the System control panel.

*Click on "Remote settings" on the left-hand side.

*Make sure that the "Allow connections only from computers running Remote Desktop with Network Level Authentication (more secure)" option is selected.

Once this is done, OpenVAS should no longer report the vulnerability.  (At least, it worked for me.)


Q: MVC 3 DropDownList displays multiple values on Edit page I'm using an enum to populate my DropDownList that works fine with a List and Create views but my Edit view loads duplicate values in the DropDownList. The duplicate values are only the selected value for the property meaning, if Rented was the value saved in the DB the DropDownList would show Rented selected, Available, and another Rented in the list. What I need to know is how to load a DropDownList that selects the value previously stored in the DB for the PropertyStatus enum without any duplicates?
Controler:
        public ActionResult Edit(int id)
    {
        Property property = db.Properties.Find(id);

        ViewBag.PropertyStatus = SetViewBagPropertyStatus();
        return View(property);
    }

    private IEnumerable<SelectListItem> SetViewBagPropertyStatus()
    {
        IEnumerable<ePropStatus> values =
            Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>();

            IEnumerable<SelectListItem> items =
             from value in values
             select new SelectListItem
             {
                 Text = value.ToString(),
                 Value = value.ToString()
             };
            return items;
    }

Model:
    public enum ePropStatus
    {
        Available ,
        Rented
    }

    public partial class Property
    {
         public int PropertyId { get; set; }
         public string PropName { get; set; }
         public string Address { get; set; }
         public string City { get; set; }
         public string State { get; set; }
         public string ZipCode { get; set; }
         public int SqFeet { get; set; }
         public int Bedrooms { get; set; }
         public int Bathrooms { get; set; }
         public int Garage { get; set; }
         public string Notes { get; set; }
         public ePropStatus PropertyStatus { get; set; }
    }

Edit View:
@Html.DropDownList("PropertyStatus", Model.PropertyStatus.ToString())

A: Try this instead :
@Html.DropDownListFor(model => model.PropertyStatus, ViewBag.PropertyStatus)

Edit ::: Alternately try this
Controler:
public ActionResult Edit(int id)
{
    Property property = db.Properties.Find(id);

    ViewBag.PropertyStatusList = SetViewBagPropertyStatus(property.PropertyStatus);
    return View(property);
}

private IEnumerable<SelectListItem> SetViewBagPropertyStatus(string selectedValue = "")
{
    IEnumerable<ePropStatus> values =
        Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>();

        IEnumerable<SelectListItem> items =
         from value in values
         select new SelectListItem
         {
             Text = value.ToString(),
             Value = value.ToString(),
             Selected = (selectedValue == value.ToString())
         };
        return items;
}

View:
@Html.DropDownList("PropertyStatus", ViewBag.PropertyStatusList)


Q: find out windows in side-by-side mode The "View Side By Side" and "Synchronous Scrolling" made the comparison of 2 spreadsheets easier than ever. However, there isn't a "Synchronous Switching tab" feature, so if I switch to a different tab in one of the workbooks and continue scrolling, the sync'ed scrolling become quite funny.
Well, I shouldn't complain, because it's all done manually, and I should use this feature wisely.
As a lazy developer, I would like to write some code to dig myself out: Can I write a macro to automate the worksheet switching on the peer window in side-by-side mode?
It breaks down to 2 steps:

*

*how do I know if a window, most likely the ActiveWindow, is in side-by-side mode?

*if it is, how do I tell which window is its peer?

I did my homework. It seems Excel is not very programming friendly on this feature. There are 3 methods

*

*BreakSideBySide()

*CompareSideBySideWith(WindowName)

*ResetPositionsSideBySide()
and 1 Boolean property

*

*SyncScrollingSideBySide
on the Windows collection related to this feature, but are insufficient to solve my questions.
Does anyone have any idea how to achieve this? Or, is it indeed impossible? Thank you in advance.

A: You can achieve this using the Workbook_SheetActivate event:
http://msdn.microsoft.com/en-us/library/office/ff195710.aspx
if you put this code in your ThisWorkbook Object, then each time you change the active worksheet, it will...

*

*Cycle through all open workbooks with a different name

*Look for a worksheet with the same name as the sheet you just clicked on

*Activate the worksheet in the other Workbook
Private Sub Workbook_SheetActivate(ByVal Sh As Object)

    For i = 1 To Application.Workbooks.Count
        If Application.Workbooks(i).Name <> ThisWorkbook.Name Then

            Dim otherWB As Workbook
            Set otherWB = Application.Workbooks(i)
            otherWB.Sheets(Sh.Name).Activate

        End If
    Next

End Sub

Note that this requires the worksheet to exist in all open workbooks.  An error will result if it does not.  However, you could easily add error handling to ignore workbooks with unfound corresponding worksheets.
Also note that it's probably best to use this when only two workbooks are open.  I have not looked into the other methods you mentioned, but there may exist a way to identify the two workbooks that are currently in side-by-side mode, at which point the code could shed its for loop and become more concise.


Q: Android Datepicker Single Cell Color Hi I'd like to be able to choose a few dates in the month and change the color of it. Say in my application I want the dates 3, 4, 8  of September to be red so that the user would be able to know that at those specific dates there is already a submission. Is this possible, if so how? Thanks in advance!
edit. Ive tried searching the forums, searching other places, and have not been able to get an answer.
To make things clear, Im not just looking to change the color theme, Im looking to change the color of specific dates. Say the user has submitted something for the 8th of September. I want my application date picker to show that by changing the color of the number 8 in the datepicker window.

A: check the library to show date with the different colour themes:
Add to your styles.xml
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
    <item name="android:colorAccent">@color/beautiful_color</item>
</style>

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/beautiful_color</item>
    <item name="android:datePickerMode">calendar</item>
</style>

Moreover, if you want to change the entire theme of the date picker, use the following dependency
dependencies {
    compile 'com.wdullaer:materialdatetimepicker:3.6.3'
}

You can use app:mcv_dateTextAppearance (or the Java setter) to do this. I don't have the full explanation, but for now, you can copy the default implementation and modify as you need. Essentially you need to supply a android:textColor that is a color state list with your desired colors.
Add a style:
<style name="TextAppearance.MyCustomDay" parent="android:TextAppearance.DeviceDefault.Small">
    <item name="android:textSize">12sp</item>
    <item name="android:textColor">@color/my_custom_day_color</item>
</style>

and create color/my_custom_day_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="@android:integer/config_shortAnimTime"
    android:exitFadeDuration="@android:integer/config_shortAnimTime">

    <item android:state_checked="true" android:color="SELECTION_COLOR" />
    <item android:state_pressed="true" android:color="SELECTION_COLOR" />
    <item android:state_enabled="false"  android:color="#808080" />
    <item android:color="@android:color/black" />
</selector>

then set app:mcv_dateTextAppearance="@style/TextAppearance.MyCustomDay"


Q: MySQL Actibity without any active visitors via Google Analytics I am hosting a WP website on a VPS (Debian) and I noticed that my MySQL service is constantly being processed, even without any active live visitors that I can see on Google Analytics.
I am aware that there are crawlers from search engines that try to get the content.
Is there a valid way to prevent overloading my MySQL service by ghost visitors (force visitors to be processed via the Google Analytics? Enable Java?)? Or prevent unwanted bots and crawlers?


Q: Google Cloud App Deploy and Cloud SQL Schema migrations I wonder if I should handle schema updates when deploying new code with gcloud app deploy. Should I just go in manually and update the tables in the database, and then run a deploy? Or is there some way I can have SQL files that need to be applied on a deploy?


Q: Can I change JVM parameters during execution I am writing a Java program and at some point during execution I want to change the JVM settings (decrease the heap) and after a while increase it again. Is it possible with Java?

A: Long story short: you can't. Heap size is fixed once you are running it, and there's no way to modify it from the code.

A: I do not think this is possible, but you could of course control the heap with -Xmx or -Xms.
You can also play with : -XX:MaxHeapFreeRatio : this is the maximum percentage (70 by default if I am no mistaken) of the heap that is free before GC will shrink it.
Giving a small -Xms will make the heap grow (if needed and will involve a full GC) and shrink back is possible also.
Generally people try to avoid as much as possible this shrinking and growing because it involves a gull GC aka stop-the-world events that will slow you down.


Q: Analog phase shifting circuit I have a high voltage(let's say +-100Vpp) sine signal of 500khz and i want this signal to be phase shifted(+ve) by 0, 90, 180 and 270 degrees.
That is a circuit which has 500khz input signal and 4 outputs with 0, 90, 180 and 270 degrees phase shifted.
I do not want any attenuation in the circuit. I have looked into op-amp/transistor circuits with RC Components. But have not come very far with that yet.
Sugestions?


Q: Why does node.js don't find the function if the files requires each other Here is my situation:

*

*file a.js require file b.js

*file b.js require file a.js

When I try to call a function which is in file b.js from file a.js then I get the exception that b.xy() is not a function.
If I remove the require in file b.js then node.js can find the function.
Why does node.js don't find the function if the files requires
each other?


Q: How to get relative path for logging.ini and log file in python over multiple OS I have created one wrapper logger class which actually wraps the functionality of logging module. I have created it so that every class in my application using logging doesn't need to add logging.config.fileConfig() and logging.getLogger() at the top every-time.
My wrapper class looks like this -
class MyFileLogger():
    # The config file for logging formatter.
    logging.config.fileConfig('logging.ini', disable_existing_loggers=False)

    def __init__(self, name):
        self.logger=logging.getLogger(name)

    def log_debug(self, message):
        self.logger.debug(message)

logging.ini file -
[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=myFormatter

[logger_root]
level=NOTSET
handlers=fileHandler

[handler_fileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=myFormatter
args=('testlog.log','midnight',)

[formatter_myFormatter]
format=%(asctime)s |%(name)-12s |%(levelname)-8s |%(message)s
datefmt=
class=logging.Formatter

MyFileLogger.py and logging.ini file resides on the same path. My intention to create testlog.log is also in same path as logging.ini file.
Implementation of the MyFileLogger.py would be like -
imp.py -
fileLogger = MyFileLogger(__name__)
message = "hey!"
fileLogger.log_debug(message)

Now this imp.py doesn't reside on the same path as MyFileLogger.py and logging.ini. That's why when I run it, this gives me below error cause the python is running at imp.py path.
  File "C:\Python34\lib\logging\config.py", line 76, in fileConfig
    formatters = _create_formatters(cp)
  File "C:\Python34\lib\logging\config.py", line 109, in _create_formatters
    flist = cp["formatters"]["keys"]
  File "C:\Python34\lib\configparser.py", line 937, in __getitem__
    raise KeyError(key)
KeyError: 'formatters'

I know if I just give an absolute path to logging.ini and testlog.log it will work. But I don't want to go there, since this application can be ran in Windows or in Linux. So there would be path problem.
Now even if I don't care about the Windows-Linux thing and only concentrate on the Linux. There is another problem. So if we assume the current directory structure as this ("ProjectDir/src" is added in PYTHONPATH and assuming there is __init__.py in every module folders)-
ProjectDir
├── src
│   └── sales
│       ├── common
│       │   ├── logger
│       │   │   ├── logging.ini
│       │   │   ├── MyFileLogger.py
│       │   │   └── testlog.log
│       │   └── implmnts
│       │       └── imp.py
│       └── unitTest
│           └── test_MyFileLogger.py
└── bar.txt

Let's assume:
imp.py -
fileLogger = MyFileLogger(__name__)
message = "From imp.py"
fileLogger.log_debug(message)

test_MyFileLogger.py -
fileLogger = MyFileLogger(__name__)
message = "from test_MyFileLogger.py"
fileLogger.log_debug(message)

Then if I run imp.py I need to change the logging.config.fileConfig('logging.ini', disable_existing_loggers=False) to logging.config.fileConfig('../logger/logging.ini', disable_existing_loggers=False)
After that it will run but when I try to run test_MyFileLogger.py I need to change again to logging.config.fileConfig('../common/logger/logging.ini', disable_existing_loggers=False)
So my code is dependent upon which file I am running which I want to get rid of. Is there any way I can dynamically get the path of logging.ini and testlog.log independent of which file(from other path) is invoking this? I don't want to hardcore the absolute path, since this needs to run in both Windows and Linux, any solution?


Q: How do I approach a question with multiple variables and no set equations? I am very confused when it comes to related rates. I am not comprehending how I need to go about solve these questions.
An example problem is ...
The radius of a circular oil slick expands at a rate of 6 m/min.
(a) How fast is the area of the oil slick increasing when the radius is 20 m?
(b) If the radius is 0 at time t=0, how fast is the area increasing after 3 mins?
I know that I would need to use the area of a circle formula and then differentiate implicitly but everything is still very confusing. Any guidance is appreciated.

A: Let's look at part $(a)$:
First, write what you want as an expression:

*

*We want to know the rate at which the area is increasing, that is, ${dA\over dt}$ where $A$ represents area (measured in meters$^2$).

Second, write what you know with equations.

*

*The radius expands at a rate of $6$ m/min - that is, the ${dR\over dt}=6$, where $R$ represents the radius (measured in meters) and $t$ represents time (measured in seconds).

*The radius is $20$ meters - that is, $R=20$.

*Finally, the area and the radius of the slick are related: $A=\pi R^2$.
So to recap, we know ${dR\over dt}=6$, $R=20$, and $A=\pi R^2$; and we want to know ${dA\over dt}$. The problem is basically how to get from $A$ to $R$.
This is where the expression $A=\pi R^2$ comes in: we have ${dA\over dR}=2\pi R$. Do you see how to combine this fact with something we already know to figure out a general expression for ${dA\over dt}$? (Hint: chain rule . . .)

A: The radius of a circular oil slick expands at a rate of 6 m/min.
$$  \frac{dr}{dt} =6$$
(a) How fast is the area of the oil slick increasing when the radius is 20 m? (b) If the radius is 0 at time t=0, how fast is the area increasing after 3 mins?
$$ A = \pi r^2  $$
a) find $\frac{dA}{dt}$ when $r=20$
b) find $\frac{dA}{dt}$ when $r=6(3)=18$


Q: String diff to show positions of changed characters? I'm looking for a way to diff two strings and return the index value of where the changes start and finish.
I'm already using diff-lcs to find out which lines have changed, but I need to figure out the positions of which characters have changed. I need the positions of the new characters so I can handle them with JavaScript, not the actual text, which is what most diff tools seem to give.
So, for example if I have this string:
The brown fox jumps over the lazy dog

and compare to this string:
The red fox jumps over the crazy dog

I would like to see something like:
[[5,8],[28,33]]

Those numbers being the position where the new characters are found.
Does anyone have any idea how I might get this done?

A: How about the Google diff-match-patch code? https://github.com/elliotlaster/Ruby-Diff-Match-Patch
I've used it in the past and been happy with the results.
Taken from the documentation linked above:
# Diff-ing
dmp.diff_main("Apples are a fruit.", "Bananas are also fruit.", false)
=> [[-1, "Apple"], [1, "Banana"], [0, "s are a"], [1, "lso"], [0, " fruit."]]

You would just need to iterate through the non-matches and find the character position in the appropriate string.
pos_ary = s.enum_for(:scan, /search_string/).map { regexp.last_match.begin(0) }


Q: Android studio/libGDX/admob cannot find dependecies() So I've been searching around for days trying to figure out why I can't implement admob into my Android Studio project.
Things I've tried:
I have the google play services installed and latest Android SDKs
File->Project Structure->ads->ticking admob
--this will try to load in the dependencies, and always fails with
(Error:Could not find method dependencies() for arguments [build_23ysmkvnpvbphbg3g4deijgq4$_run_closure6@4afc19b] on org.gradle.plugins.ide.idea.model.IdeaModel_Decorated@18b40be.)
I've tried deleting the .gradle folder, restarting AS and rebuilding with the same Error.
I've tried creating a new blank LibGDX project and importing that and directly getting the admob dependencies and still the same error message.
I'm honestly not sure what I'm overlooking here.
If there's any info you feel I've left out, please let me know.

A: So, I'm coming from the Eclipse environment, and whenever I built a libgdx project, I've never had to go into the "advanced" settings. so messing around some more I went into the advanced settings and saw a checkbox for IDEA(generates intellij IDEA project files) which has seemed to work in getting rid of that error.


Q: Scraping data from HTML to return to cells in Excel I am very new to coding. I know the basics, but I don't need that advanced of knowledge for my field--aside from this project.
I am attempting to search a license number on the AZ Medical Board website, click the search result to pull up a profile, and transfer the information on a profile to cells in Excel.
So far my code looks like this and it works perfectly (aside from the data scraping part)
Sub AZMDSearch()

Dim lastrow As Long
Dim Name2 As Object

lastrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row

For i = 1 To lastrow
Application.ScreenUpdating = False

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "https://gls.azmd.gov/glsuiteweb/clients/azbom/public/WebVerificationSearch.aspx"

Application.StatusBar = "Submitting"
While IE.Busy
    DoEvents
    Cells(i, 1).Select
    Selection.Copy
Wend
'**********************************************************************
With IE.document
delay 1
.getelementbyid("tbFileNumber").Value = Cells(i, 1).Value
delay 1
.getelementbyid("btnLicense").Click
delay 2
.getelementsbytagname("a")(0).Click
End With
'**********************************************************************

The code does exactly what I want it to do up until this point.
Now, here's what the HTML looks like for the data I want to transfer over:
Gabby Laub
MD

1234 S Pine
Scottsdale AZ 85258
Phone: (123) 456-7891

I need to be able to pull the Name (Gabby Laub) into Cell(i,2), the address part 1 (1234 s Pine) into Cell(i,3), address part 2 (Scottsdale, AZ) into Cell(i,4), and phone number into Cell(i,5).
I was working on something like this:
Set Name = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").innerHTML

But it doesn't work at all. I have been working on this project for weeks, and I would really appreciate some help. Obviously I'm aware that I am missing Next i and End sub.
Again, the ONLY part I need help on is how to actually get the data into Excel.
Thanks!

A: You could try something like:
Cells(i, 2).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText

Cells(i, 3).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText

Since address1, address2 and phone would all be in Cells(i, 3) you might want to use to use text to column to split them into their appropriate columns.
Additionally you could create an array to store these data in if you're doing a bigger search. Then you could paste the array values into their cells after you've finished scraping, like:
searchInfo(i, 1) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText
searchInfo(i, 2) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText

Then after looping:
 For i = 1 to last row
       Cells(i,2).Value = searchInfo(i, 1)
       Cells(i,3).Value = searchInfo(i, 2)
 Next i

You'd still have the text to column issue but that can be solved pretty easily with some code in the loop. Specifics just depend on how the third column's values come out.
EDIT: Based on your comments below, this worked for me. It might take a little customizing, but this is the idea.
    ' remove .getelementsbytagname("a")(0).Click and replace with this
.location = .getElementsByTagName("a").getAttributes("href")


Q: Arduino IDE on Android tablet Hi am wondering if anyone knows of a IDE for my Android tablet that I can edit compile and upload sketches to my Arduino board via USB?

A: Really slow response, I know but once this gets out of beta phase it could work http://codebender.cc/

A: You can have Arduino IDE on android, but have some problem with the usb port
http://arduino.cc/forum/index.php/topic,114141.0.html
veckoff

A: Not that I know of, but maybe you could build something like it with this?
http://www.amarino-toolkit.net/

A: You can upload sketch, no root required:
http://arduinocommander.blogspot.com/2013/03/upload-sketch.html

A: Check out ArduinoDroid - full-featured Arduino IDE on android:
https://play.google.com/store/apps/details?id=name.antonsmirnov.android.arduinodroid


Q: Error in declaring data in rstan for graded response model I am trying to use Stan, specifically through rstan, to fit a graded response model. Luo and Jiao (2018), available here, provide Stan code for doing so. Here is their code, edited only to include more white space:
data{
    int<lower=2, upper=4> K; //number of categories
    int <lower=0> n_student;
    int <lower=0> n_item;
    int<lower=1,upper=K> Y[n_student,n_item];
}

parameters {
    vector[n_student] theta;
    real<lower=0> alpha [n_item];
    ordered[K-1] kappa[n_item]; //category difficulty
    real mu_kappa; //mean of the prior distribution of category difficulty
    real<lower=0> sigma_kappa; //sd of the prior distribution of category difficulty
}

model{
    alpha ~ cauchy(0,5);
    theta ~ normal(0,1);
    for (i in 1: n_item){
        for (k in 1:(K-1)){
            kappa[i,k] ~ normal(mu_kappa,sigma_kappa);
    }}
    mu_kappa ~ normal(0,5);
    sigma_kappa ~ cauchy(0,5);
    for (i in 1:n_student){
        for (j in 1:n_item){
            Y[i,j] ~ ordered_logistic(theta[i]*alpha[j],kappa[j]);
    }}
}

generated quantities {
    vector[n_item] log_lik[n_student];
    for (i in 1: n_student){
        for (j in 1: n_item){
            log_lik[i, j] = ordered_logistic_log (Y[i, j],theta[i]*alpha[j],kappa[j]);
    }}
}

However, when I try to use this code, the parser throws an error. Here is the R code to reproduce the error:
library("rstan")

n <- 100
m <- 10
K <- 4
example_responses <- sample(x = 1:4, size = n * m, replace = TRUE)
example_responses <- matrix(example_responses, nrow = n, ncol = m)

example_dat <- list(K = K,
                    n_student = n,
                    n_item = m,
                    Y = example_responses)

fit <- stan(file = "~/grm.stan", data = example_dat)

Here is the error I receive:
SYNTAX ERROR, MESSAGE(S) FROM PARSER:
 error in 'modelf6471b3f018_grm' at line 2, column 21
  -------------------------------------------------
     2:
     3: data {
     4:     int<lower=2, upper=4> K; // number of categories
                            ^
     5:     int<lower=0> n_student;
  -------------------------------------------------

PARSER EXPECTED: <one of the following:
  a variable declaration, beginning with type,
      (int, real, vector, row_vector, matrix, unit_vector,
       simplex, ordered, positive_ordered,
       corr_matrix, cov_matrix,
       cholesky_corr, cholesky_cov
  or '}' to close variable declarations>
Error in stanc(file = file, model_code = model_code, model_name = model_name,  :
  failed to parse Stan model 'grm' due to the above error.

I've tried going through the code and the Stan manual to see what the issue is with the data declaration, but I can't find a problem with it. The declaration appears to be very similar to a declaration example in the Stan Language Reference:
int<lower = 1> N;

Can anyone tell me what I'm missing?

A: Your code has non-standard characters in some of the white space, including right after K;


Q: how to take more than one photo in QML? I have to take 4 continues pictures using the webcamera in QML i can take only one picture after that
I get an error from the QML debugger which states "Camera not ready for capture" how do i get the camera to be in ready state after the first capture this is the code i have tried
even if i set the ready state to true: it does not seem to be working? is there an easy way to get my way around this?
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Rectangle{
        width: parent.width
        height: parent.height
        ColumnLayout{
            width: parent.width;height: parent.height
            spacing: 15;
            Camera{
                id:cam
                captureMode: Camera.CaptureStillImage
                imageCapture {
                    onImageCaptured: {
                         ready:true
                        console.log(ready)
                    }

            }
            }
            VideoOutput{
                id:vid1
                source: cam
                height:parent.height
                width: 800
                Layout.fillWidth: true
                Layout.fillHeight: true

            }
            Rectangle{
                id:rect1
                width: 100
                height: 30
                Layout.fillWidth: true
                Layout.alignment:bottom
                color: "#365688"
                Text {
                    id: text1
                    anchors.centerIn: parent
                    text:"capture"
                    font.pointSize: 10
                }
                MouseArea{
                    anchors.fill:parent
                    onClicked: {
                        console.log("clicked");
                     for(var i=0;i<=3;i++){
                        cam.start()
                        cam.imageCapture.captureToLocation("C:/Users/vinay/Documents")
                        console.log(cam.cameraStatus)
                        }
                    }
                }
            }

        }
    }
}


Q: History.js bookmark support for HTML5 (pushState) and HTML4 (#) I've have the back and foward buttons working via History.js in both HTML5 and HTML4 browsers.
I'm now attempting to add bookmark support by parsing the url, and loading the content in the querystring.  The code I normally use to do this is:
var urlParams = {};
            (function () {
            var match,
                pl     = /\+/g,
                search = /([^&=]+)=?([^&]*)/g,
                decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
                query  = window.location.search.substring(1);

            while (match = search.exec(query))
            urlParams[decode(match[1])] = decode(match[2]);
            })();

This works great for the HTML5, but obviously does not work for the HTML4.   Whats a good way to parse the hash in HTML4, and the substring in HTML5?

A: found a solution on this page: https://getsatisfaction.com/balupton/topics/history_js_and_retrieving_state_from_a_url
"You can use this function however from one of my utility projects called jQuery Sparkle to do what you need: https://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/core.string.js#L164
So you would do this:
var State = History.getState(), dataQuery = State.url. queryStringToJSON();"


Q: How can I search, display, and retrieve file using C manually by inputing the value first? #include <stdio.h>
#include <stdbool.h>

#define HASH_SIZE 10

int hash(int value);
void dfs(FILE *file, int value);

int main()
{
    FILE *file = fopen("DATA_FILE.csv", "r");

    if (file == NULL)
    {
        perror("Error while opening the file");
        return 1;
    }

    int value = -685434;

    dfs(file, value);

    fclose(file);

    return 0;
}

void dfs(FILE *file, int value)
{

    bool visited[HASH_SIZE] = { false };

    // Read the first value from the file
    int currentValue;
    fscanf(file, "%d", &currentValue);

    while (currentValue != value && !feof(file))
    {

        int key = hash(currentValue);
        visited[key] = true;

        fscanf(file, "%d", &currentValue);

        if (visited[hash(currentValue)])
        {
            fscanf(file, "%d", &currentValue);
        }
    }

    if (currentValue == value)
    {

        printf("Value found in file: %d\n", currentValue);
    }
}

int hash(int value)
{
    return value % HASH_SIZE;
}

While the instruction says,
"The data file has two pairs of columns, the first of which has the number you're seeking for and the second of which contains the paired numbers you need to retrieve and show.
In this instance, you need to use data scanning for the file by reading row by row to find the data
Here is what is expected to work from the code:
Your code receives input from command line arguments.
The format in command line as follow
find [-s | -t] number
description:
number : is the number that you must find inside the data file
[ … | …. ] : is the searching techniqye option that you need to choose one of the
parameters.
-s : you will search inside data file using file scanning row by row.
-t : you will search using your solution
Here is the input and output:

*

*find -s 12345
Found 12345 with data on second column is 987234
Time elapsed 200 ms
or

*find -t 12345
Found 12345 with data on second column is 987234
Time elapsed 1 ms

if an error occurs, it will say:
No method defined
Proper Syntax is
find [ -s | -t ] number

A: From my top comments ...

*

*From the problem description, the input [.csv] file is a series of lines of the form: key,value.

*Your code should be doing (e.g.): fscanf(file,"%d,%d",&curkey,&currentValue), so you are reading the file incorrectly.

*What you call value, I would call desired_key as it needs to match the key [and not the value] and if a match is found on the key, you want to print the value.

*You have to do this line-by-line if given -s as a command line arg.

*If given -t, you have to reading the file and store the key/value pairs in an array. You need a struct such as: struct row { int key; int value; };

*The problem statement doesn't mention a hash.

*I don't see a need for visited at all. To me, that's some extraneous code from a shortest path algorithm (e.g. Dijkstra's or A*).

*Your code doesn't look at argc/argv at all. So, you can't select the method from -s or -t and get the desired key value to search for.

Here is the corrected code. It is annotated:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int opt_s;
int opt_t;

// key/value item
struct keyval {
    int key;
    int val;
};

struct keyval *csvdata;                 // array of all pairs in file
int csvcount;                           // number of pairs in array

// method_s -- match on a line-by-line basis
int
method_s(FILE *file,int desired_key,int *retval)
{
    int curkey;
    int curval;
    int found = 0;

    // read all lines of the form:
    //   key,val
    while (fscanf(file,"%d,%d",&curkey,&curval) == 2) {
        found = (curkey == desired_key);
        if (found)
            break;
    }

    // return the value if a match
    if (found)
        *retval = curval;

    return found;
}

// load_t -- load up CSV array
int
load_t(FILE *file)
{
    int cap = 0;
    int curkey;
    int curval;
    struct keyval *pair;

    csvdata = NULL;
    csvcount = 0;

    while (fscanf(file,"%d,%d",&curkey,&curval) == 2) {
        if (csvcount >= cap) {
            cap += 10;
            csvdata = realloc(csvdata,sizeof(*csvdata) * cap);
            if (csvdata == NULL) {
                perror("realloc");
                exit(1);
            }
        }

        pair = &csvdata[csvcount++];
        pair->key = curkey;
        pair->val = curval;
    }

    // trim array to actual size used
    csvdata = realloc(csvdata,sizeof(*csvdata) * csvcount);
    if (csvdata == NULL) {
        perror("realloc");
        exit(1);
    }
}

// method_t -- match on a stored array basis
int
method_t(FILE *file,int desired_key,int *retval)
{
    struct keyval *pair;
    int found = 0;

    // load up the array
    load_t(file);

    // loop through the stored array, looking for a match
    for (int idx = 0;  idx < csvcount;  ++idx) {
        pair = &csvdata[idx];
        found = (pair->key == desired_key);
        if (found)
            break;
    }

    // return the value if a match
    if (found)
        *retval = pair->val;

    return found;
}

int
timems(void)
{
    struct timespec ts;
    long long nsec;
    static long long timebase = 0;

    clock_gettime(CLOCK_MONOTONIC,&ts);

    nsec = ts.tv_sec;
    nsec *= 1000000000;
    nsec += ts.tv_nsec;

    if (timebase == 0)
        timebase = nsec;
    nsec -= timebase;

    nsec /= 1000000;

    return nsec;
}

int
main(int argc,char **argv)
{
    int err = 0;

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        char *cp = *argv;

        if (cp[0] != '-')
            break;

        if ((cp[1] == '-') && (cp[2] == 0))
            break;

        cp += 2;
        switch (cp[-1]) {
        case 's':
            opt_s = 1;
            break;
        case 't':
            opt_t = 1;
            break;
        default:
            err = 1;
            break;
        }
    }

    if (opt_s && opt_t)
        err = 1;

    if (! (opt_s || opt_t))
        err = 1;

    int desired_key = -1;
    if (argc != 1)
        err = 1;
    else
        desired_key = atoi(*argv);

    if (err) {
        printf("No method defined Proper Syntax is find [ -s | -t ] number\n");
        exit(1);
    }

    FILE *file = fopen("DATA_FILE.csv", "r");
    if (file == NULL) {
        perror("Error while opening the file");
        return 1;
    }

    int found = 0;
    int retval = 0;

    int msbeg = timems();

    do {
        if (opt_s) {
            found = method_s(file,desired_key,&retval);
            break;
        }
        if (opt_t) {
            found = method_t(file,desired_key,&retval);
            break;
        }
    } while (0);

    int msend = timems();

    fclose(file);

    if (found)
        printf("Found %d with data on second column is %d Time elapsed %d ms\n",
            desired_key,retval,msend - msbeg);

    return 0;
}

Here is the sample input (DATA_FILE.csv) file I used:
46079,96649
71463,62685
81995,47037
50876,79762
95492,88344
45272,72553
41950,80235
81543,99066
67329,78252
79563,36472
63549,83972
94173,58525
81532,25036
39514,94603
90454,25278
33306,95455
85052,5202
49451,58592
69333,80996
94039,34855

Here is the output for ./find -s 67329:
Found 67329 with data on second column is 78252 Time elapsed 0 ms

Here is the output for ./find -t 67329:
Found 67329 with data on second column is 78252 Time elapsed 0 ms

A: /* find_value.c */
#include <stdio.h>

int main()
{
    FILE *file;
    file = fopen("DATA_FILE.csv", "r");

    if (!file)
        {
            perror("DATA_FILE.csv");
            return 1;
        }

    int n;
    int find_value = 32;
        while(fscanf(file, "%d", &n) == 1) {
        if(n == find_value) {
            printf("%d\n", n);
        }
    }

        fclose(file);
        return 0;
}


Q: Add Google login to OpenIddict Authorization Server - who provides the client_id and how? Starting with the Zirku Sample of OpenIddict, I wanted to add Google Accounts as login provider (nuget: Microsoft.AspNetCore.Authentication.Google).
My changes include adding the google auth provider after AddOpenIddict(...):
services.AddAuthentication()
        .AddGoogle("Google", options =>
        {
            options.CallbackPath = "/signin-google";
            options.ClientId = "0000000000000-redacted.apps.googleusercontent.com";
            options.ClientSecret = "redacted";
            options.SignInScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
        });

Adding /signin-google as valid authorization endpoint to allow calling SignIn:
options.SetAuthorizationEndpointUris("/connect/authorize", "/signin-google")
       .SetLogoutEndpointUris("/connect/logout")
       .SetIntrospectionEndpointUris("/connect/introspect")
       .SetUserinfoEndpointUris("/connect/userinfo");

However, when coming back from google, the OpenIddict Server always complans, that the client_id is missing:
fail: OpenIddict.Server.OpenIddictServerDispatcher[0] The authorization request was rejected because the mandatory 'client_id' parameter was missing.
Tried these config options already without any change:
options.AcceptAnonymousClients();
options.Configure(op => op.AcceptAnonymousClients = true);

What am I doing wrong?
complete log can be found here.
(and yes, I changed the port to 6001 to reuse an existing redirect-url registered at google)

A: options.AcceptAnonymousClients() has no effect on the code flow as client_id is a mandatory parameter in this case (it only affects the token, introspection and revocation endpoints).
options.SignInScheme cannot be set to a scheme belonging to OpenIddict. In most cases, it must correspond to a cookie handler (typically the one registered by Identity).
You will also want to remove /signin-google from the endpoints managed by OpenIddict, as it will prevent the Google authentication handler from working properly.


Q: Core animation (size change) with autolayout challenge I have a piece of core animation by use of 2 methods in order to give appearance that the object is growing in size from the centre-outwards from the existing location...
(1) viewDidLayoutSubviews()

self.imageView.frame = CGRectMake(187, 249, 0, 0)

which is in the centre of the screen for this imageView object
(2) viewDidAppear()
 - with animation block of duration 1 second. e.g.
UIView.animateWithDuration(1.0, delay: 1.5, options: [], animations: {

        self.imageView.frame = CGRectMake(16, 70, 343, 358)

        }, completion: nil)

which puts object where I want it to show in full size, for the specific screen size.
When I use the x and y coordinates for CGRectMake(...) on the iPhone size I'm looking for they work fine, But when I try on simulator with different screen sizes, it doesn't work in conjunction with the Autolayout constraints, but overrides the existing Constraints.
Question(s)...
Is there a way of making this animation work by centering it proportional to the screen size somehow, rather than explicit coordinates and sizes? via CGRectMake...? (...which seems to show a clash between use of Autolayout and Animation)
Ideally I'm looking for an elegant simple solution? or am I at the limits of the tech?
Many thanks in advance!

A: You can set imageView location using autolayout constraints & give it a size constraint and by taking an outlet from it you can animate height to increase leaving all other constraints working

@IBOutlet var myViewHeight: NSLayoutConstraint!
UIView.animateWithDuration(0.3, delay: 0.0, options: [], animations:
  {
      () -> Void in
        self.myViewHeight.constant = 300

        self.view.layoutIfNeeded()
        }, completion:nil)

You should take the outlet from the constraint itself like control+drag on Label.top = topMargin


Q: Integrating Lucene Index and Amazon AWS I have a an existing index of lucene index files and the java code to perform search functions on it.
What I would like to do is perform the same thing on a server so users of an app could simply pass a query that will be taken as an input parameter by the java program and run it against the existing index to return the document in which it occurs.
All the implementation has been tested on my local pc,but what I need to do is implement it in an Android app.
So far I have read around and concluded that porting the code in AWS lambda and using S3 to store the files and calling the s3 objects from lambda.
Is this the right approach?Any resources that point to the this approach or alternative suggestions are also appreciated.
Thanks in advance.

A: Every time your Android app sends a request to AWS Lambda (via AWS API Gateway I assume) the Lambda function will have to download the entire index file from S3 to the Lambda /tmp directory (where Lambda has a 512MB limit) and then perform a search against that index file. This seems extremely inefficient, and depending on how large your index file is, it might perform terribly or it might not even fit into the space you have available on Lambda.
I would suggest looking into the AWS Elasticsearch Service. This is a fully managed search engine service, based on Lucene, that you should be able to query directly from your Android application.

A: As you already have your index files in S3, you can direct your Lucene Index reader to point to a Location on S3.
String index = "/<BUCKET_NAME>/<INDEX_LOCATION>/";
String endpoint = "s3://s3.amazonaws.com/";
Path path = new com.upplication.s3fs.S3FileSystemProvider().newFileSystem(URI.create(endpoint), env).getPath(index);
IndexReader reader = DirectoryReader.open(FSDirectory.open(path))

You can either pass in client credentials in env or you can assign role to your Lambda function.
Ref:
https://github.com/prathameshjagtap/aws-lambda-s3-index-search/blob/master/lucene-s3-searcher/src/com/printlele/SearchFiles.java

A: For Lucene indices less than 512MB you can experiment with lucene-s3directory.
As Mark said, on AWS Lambda you are limited to 512MB on /tmp. I think having a completely serverless search service is very desirable but until that limit is gone, we're stuck with EC2 for production deployments. Once you go with running Lucene on EC2, storing the index on S3 becomes pointless as you have access to EBS or ephemeral storage.
In case you want to try out S3Directory, here's how to get started:
S3Directory dir = new S3Directory("my-lucene-index");
dir.create();
// use it in your code in place of FSDirectory, for example
dir.close();
dir.delete();


Q: Sequelize validation throwing error I'm trying to check that a username is unique, and I gather that I'd need a custom validation for that. I've written the following code, but instead of returning the error in the array returned by .validate(), it just throws the error, which isn't the behaviour described in the docs and isn't what I want.
var User = sequelize.define('User', {
    username: {
        type: DataTypes.STRING,
        validate: {
            isUnique: function (username) {
                User.find({ where: { username: username }})
                    .done(function (err, user) {
                        if (err) {
                            throw err;
                        }

                        if (user) {
                            throw new Error('Username already in use');
                        }
                    });
            }
        }
    },

A: The validation you are doing is asynchronous. You call the User.find method, and after that the validation method returns. Sequelize has no way of knowing that you are doing something async in your validation, unless you tell it so. Once your find call is done you throw the error, but the validation has completed, so there is no code to catch that error, which means the error is thrown and crashes the app
The way to tell sequelize that you are doing something async is to take a second argument  to your function, which is a callback. If you call the callback without any arguments, the validation succeeded, if you give it an argument, the validation failed.
var User = sequelize.define('User', {
username: {
    type: DataTypes.STRING,
    validate: {
        isUnique: function (username, done) {
            User.find({ where: { username: username }})
                .done(function (err, user) {
                    if (err) {
                        done(err);
                    }

                    if (user) {
                        done(new Error('Username already in use'));
                    }

                    done();
                });
        }
    }
},

Could you point me to the part of the documentation that mislead you, then we can hopefully correct it :)

A: Sequelize supports Promise style async operations. Specifically the Bluebird.js lib. Just change your function to specifically use the Promise -> next() pattern.
var User = sequelize.define('User', {
   username: {
    type: DataTypes.STRING,
    validate: {
        isUnique: function (username) {
            User.find({ where: { username: username }})
                .then(function (user) {
                    if (user) {
                        throw new Error('Username already in use');
                    }
                });
        }
    }
},

This will also handle any errors on User.find() for you.
See this example in their codebase
Of course the easiest way to handle unique constraints is by setting unique: true on the field definition itself:
var User = sequelize.define('User', {
  username: {
    type: DataTypes.STRING,
    unique: true
  },

But this requires that you are either creating the table using Sequelize or already have a table with the unique constraint set.

A: This question got a valid answer which explains how the validation option works. But in this situation you don't have to check if a user exists on your own.
Sequelizejs has a findOrCreate() method, that checks if somethings exists before doing anything.
Very useful method :)


Q: matplotlib says libpng16.so.16: cannot open shared object file: No such file or directory I am trying to install matplotlib version 2.0.0. I don't have root access, hence can't use sudo/apt-get When I tried installing matplotlib, it showed dependencies on freetype and libpng. So, I executed the following steps:
wget http://prdownloads.sourceforge.net/libpng/libpng-1.6.34.tar.gz
tar -xzf libpng-1.6.34.tar.gz
cd libpng-1.6.34/
./configure --prefix=/home/$username$/
make
make check
make install

cd ..
wget http://download.savannah.gnu.org/releases/freetype/freetype-2.5.3.tar.gz
tar xzf freetype-2.5.3.tar.gz
cd freetype-2.5.3
./configure --prefix=/home/$username$ --without-png
make && make install
export PKG_CONFIG_PATH=/home/$username$/lib/pkgconfig

pip install matplotlib==2.0.0

Which worked perfectly fine. But when I do import matplotlib.pyplot as plt it throws the following error:
ImportError: libpng16.so.16: cannot open shared object file: No such file or directory


Q: How do I recover files from a RAW-formatted external HDD?
Possible Duplicate:
RAW to NTFS (Data already recovered so not important)

My external HDD suddenly changed to RAW format so i can't access it anymore. Is formatting the disk to NTFS and recovering the data with a recovery tool the only way to get my data back?

A: Do not Format! This will make recovery significantly more difficult. Take a look at easeus's article on drive recovery.
If software does not work, you may consider professional recovery.

A: In far too many cases, simply mounting the drive on a linux system (a live usb or livecd works great here) will probably allow you to grab your files for transfer elsewhere easily - you'll want one with ntfs-3g support, which most common distros have. For some reason, i've been able to read disks that won't mount on a windows system with linux without any issues. After that reformat and move the data back in
If that fails give testdisk a run following their handy step by step guide - it searches drives for data and often can undo a basic format, or other drive issues.
You wouldn't want to format it, and you'd want to consider doing a full backup if you want to run any potentially destrictive recovery methods.

A: I had the exact same issue with a Seagate external usb drive a couple years back, I put the enclosure into a large baggie and set it in a cooler then filled the cooler with ice, let the drive cool down, this allowed me to copy my files off of the failing device, then sent it in for a warranty replacement.
If this does not work, remove the hard drive from the enclosure and connect it to your PC using another usb to hard drive converter cable. Sometimes the hard drive is ok, its just a bad enclosure/usb board
.


Q: How to ensure that UINavigationController has finished animating before poping up another one? I make a program that push uinavigationcontroller. Once done it pop things back and then do something.
One of the thing it wanna do is wait until it finishes poping up before doing that something.
That's because one of the thing that it may do is to push another viewcontroller.
How should I do so?
I already create a category

-(void)SafelyPushController:(UIViewController *) pushee
{
    AssertMainThread;
    if([self.viewControllers lastObject]!=pushee){
        [self pushViewController:pushee animated:YES];
        while (false);
    }
    else{
        //DLog(@"Dont need to pushview");
    }

    while (false);
    //[self pushViewController:pushee animated:YES];
}

To prevent some of the cases.
I need more general solution.
Something like:
If navigationController is still animating, wait till it finish in background and do this block at current thread.
That kind of thing.

A: You need to use UINavigationController's delegate:
@property(nonatomic, assign) id<UINavigationControllerDelegate> delegate;

Set it to an object of a class that conforms to this protocol, which implements this method:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

In this method you'll know when you have finished showing a view controller, thus if it was animated the animation has ended. Notice that if you push multiple view controllers you have to keep track of them.
Documentation:
UINavigationController
UINavigationControllerDelegate


Q: http_negotiate_language issue Perhaps I missed something but when I call
$result='';
      $langs = array(
          'en-US',
          'fr',
       );
var_dump(http_negotiate_language($langs,$result));

I have an 500 error message. Should I add some extensions, should I parametrize something on my php.ini ?

A: It is require PECL pecl_http >= 0.1.0


Q: xcode How to show $ value in a Label and a Text Box. Example 125000 as 125,000.00 I need to show $value on a Label.
currently it appears as 125000 but i need it to be 125,000.00
thanks in advance to all supporters.

A: Drag the Number Formatter (found in the object library) object onto the field/label.  Change the behavior (be sure your in the attributes inspector for the number formatter) to 'OS X 10.4+ Custom' (that's what it was in Xcode 4.5.2).
In the 'Integer Digits' field, change the minimum to 1 and leave the maximum whatever you need.  For the 'Fraction Digits' fields set the minimum and maximum to 2.
Near the top of the field, stick a dollar sign in front of the 'Format (+)' and '(-)' fields.
Check the group separator box then change the primary and secondary grouping fields to 3.

A: The solution of your problem is NSNumberFormatter
Some code to get you started:
    NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSLog(@"%@", [currencyFormatter stringFromNumber:[NSNumber numberWithInt:10395209]]);
[currencyFormatter release];


Q: Sending mail with embedded image in Ruby I want to send a mail with an attached image and embed this image in html. As a source for  tag , What should I write and is there any missing header parts such a content_type ?
When I am doing real test, I send to a mail to my gmail account. I can see there is an attachment with name "unnamed" and I could not display image even when I download.
Gem: Pony
require 'pony'
Pony.override_options = { :via => :test }
Pony.mail(
    :to => 'foo@bar',
    :from => 'abc@abc.com',
    :subject => 'test123',
    :body =>   "
Dear X, check the newsletter ,

 ",
    :attachments => {"happy_image.jpg" => File.read("happy_image.jpg")}
)
puts Mail::TestMailer.deliveries

output:
Date: Tue, 06 Dec 2016 17:23:05 +0300

From: abc@abc.com

To: foo@bar

Message-ID: <5846c9ca183d6_5983c9fd899060@MW7BIQ12TKYHQC.mail>

Subject: test123

Mime-Version: 1.0

Content-Type: multipart/mixed;

boundary="--==_mimepart_5846c9caf15a_5983c9fd8989e5";

charset=UTF-8

Content-Transfer-Encoding: 7bit

----==_mimepart_5846c9caf15a_5983c9fd8989e5

Content-Type: text/plain;

charset=UTF-8

Content-Transfer-Encoding: 7bit

Dear X, check the newsletter ,

----==_mimepart_5846c9caf15a_5983c9fd8989e5

Content-Type: image/jpeg;

 filename=happy_image.jpg

Content-Transfer-Encoding: base64

Content-Disposition: attachment;

filename=happy_image.jpg

Content-ID: <happy_image.jpg@MW7BIQ12TKYHQC>

/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQE

BQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/

2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU

FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAHiAuMDASIAAhEBAxEB/8QA

HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF

BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK

FhcYGQ==

----==_mimepart_5846c9caf15a_5983c9fd8989e5--

A: You should be able to BASE64 encode the image, and use the resulting string as the src of the img tag.
For example:

Also make sure that your content type is set as text/html instead of text/plain. Looking at the mail, it seems that it's set to the latter, hence why images don't render and tags render as text. Add the following to your arguments to use text/html content type:
:headers => { 'Content-Type' => 'text/html' }


Q: Finding distribution of r.v. by using the Laplace transform In the book An Intermediate Course in Probability by Allan Gut there is this exercise

For a positive, (absolutely) continous random variable $X$ we define the Laplace transform as,.
  $$L_{X}(s)=E\,e^{-sX}=\int_{0}^{\infty}e^{-sx}f_{X}(x)\,dx, \quad s>0.$$
  Suppose that $X$ is positive and stable with index $\alpha \in (0,1)$, which means that
  $$L_{X}(s)=e^{-s^{\alpha}},\quad s>0.$$
  Further, let $Y\in \text{Exp}(1)$ be independent of $X$. Show that
  $$(\frac{Y}{X})^{\alpha}\in \text{Exp}(1)\qquad (\text{which means that}\quad (\frac{Y}{X})^{\alpha})\stackrel d= Y.$$

I am thinking that I should solve this by using

$$ X^{-\alpha}=\frac{1}{\Gamma(\alpha)}\int_{0}^{\infty}\lambda^{\alpha-1}e^{-\lambda X}\, \mathrm{d}\lambda,\quad x>0,\quad \text{and}\\
Y^{\alpha}=\frac{1}{\Gamma(\alpha)}\int_{0}^{\infty}\lambda^{\alpha -1}e^{-\frac{\lambda}{Y}}\, \mathrm{d}\lambda,\quad y>0.\\
(\frac{Y}{X})^{\alpha}=(\frac{1}{\Gamma(\alpha)}\int_{0}^{\infty}\lambda^{\alpha-1}e^{-\lambda X}\, \mathrm{d}\lambda)\times(\frac{1}{\Gamma(\alpha)}\int_{0}^{\infty}\lambda^{\alpha -1}e^{-\frac{\lambda}{Y}}\, \mathrm{d}\lambda),\quad X,Y\text{ independent.}\\
f_{(\frac{Y}{X})^{\alpha}}(x,y)= (\frac{1}{\Gamma(\alpha)}\int_{0}^{\infty}\lambda^{\alpha-1}e^{-\lambda f_{X}(x)}\, \mathrm{d}\lambda)\times (\frac{1}{\Gamma(\alpha)}\int_{0}^{\infty}\lambda^{\alpha -1}e^{-\frac{\lambda}{e^{-y}}}\, \mathrm{d}\lambda)$$

But here I am stuck. I do not know how to go from here. How to evaluate this Intergal? Anyone who can leave a hint? I would be very thankful.

A: Write out the cdf for $(Y/X)^\alpha$, then find the pdf by applying the Leibniz rule and use the formula for the Laplace transform of $t f(t)$:
$$F_{(Y/X)^\alpha}(x) =
\operatorname P(Y < x^{1/\alpha} X) =
\int_0^\infty d\tau_1 f_X(\tau_1)
 \int_0^{x^{1/\alpha} \hspace{2px} \tau_1} d\tau_2 f_Y(\tau_2), \\
f_{(Y/X)^\alpha}(x) =
\frac d {dx} F_{(Y/X)^\alpha}(x) =
\int_0^\infty d\tau_1 f_X(\tau_1)
 \frac d {dx} (x^{1/\alpha} \tau_1) f_Y(x^{1/\alpha} \tau_1) = \\
\frac {x^{1/\alpha - 1}} \alpha \int_0^\infty
 \tau_1 f_X(\tau_1) e^{-x^{1/\alpha} \hspace{2px} \tau_1} d\tau_1 =
-\frac {x^{1/\alpha - 1}} \alpha \frac d {ds} \int_0^\infty
 f_X(\tau_1) e^{-s \tau_1} d\tau_1 \bigg\rvert_{s = x^{1/\alpha}} = \\
-\frac {x^{1/\alpha - 1}} \alpha
 \frac d {ds} e^{-s^\alpha} \bigg\rvert_{s = x^{1/\alpha}} =
e^{-x}.$$


Q: Centroid of wedge I am going crazy trying to figure out what I am doing wrong on this basic problem. I need to find the $y$ coordinate of the center of mass of a pan of water that is sloshing back and forth. Let the equilibrium height be $h$, the length of the pan be $L$, and the height at $x=L$ be $y=h+b$. The coordinate of the center of mass should be
$$
y_{CM}= \frac{1}{M} \iint y \rho dA
$$
Here, we have $y = (h-b) + \frac{2b}{L} x$. We also have $dA = y dx$. Thus, the coordinate is
$$
y_{CM}= \frac{\rho}{M} \int_0^L \left( (h-b) + \frac{2b}{L} x  \right)^2 dx = \frac{b^2}{3h} + h
$$
where we have used the fact that $M = \rho h L$. But this result is incorrect because when $b = 0$ we should have $y_{CM} = \frac{h}{2}$ not $h$. The result should be (I think) $y_{CM} = \frac{h-b}{2} + \frac{2b}{3}$ obtained by simply adding the positions of the center of masses of the two regions. However, I am more interested in what about this method is incorrect.
Here is a diagram to make the shape more explicit.

A: Looks like you might’ve been a bit hasty in converting the double integral into iterated definite integrals. Factoring out the constant density $\rho$, you’ve got $$y_{CM}=\frac1{Lh}\iint y\,dA = \frac1{Lh}\int_0^L\int_0^{y(x)}y\,dy\,dx=\frac1{Lh}\int_0^L\frac12y^2\,dx.$$ Comparing this to your integral, there’s a factor of $\frac12$ that you missed by not also integrating in the $y$-direction.

A: There is the factor $\frac{1}{2}$ missing due to not doing the integration over $y$. Due to insight in physics you already noticed that there was a mistake, which is always good. (Correct result should be $y_c=\frac{b}{6 h} + \frac{h^2}{2}$.)
You also came up with a second option to get the result, via the addition of centres of mass of the rectangular and triangular areas. This is a nice alternative approach, but you can not simply add the positions of the centres of mass go both of them. You need to take an average of them. Moreover, you need to weight them because a large mass is far more important for the combined centre of mass than a much lighter one. You would need to use:
$$
y_{tot} = \frac{m_1 y_1 + m_2 y_2}{m_1+m_2}
$$
where $m_i$ are the masses and $y_i$ the locations of them to get the combined centre of mass.
The centre of mass of the rectangular mass is indeed $y_1 = \frac{h-b}{2}$, but the one for the triangle $y_2 = \frac{2 b}{3}$ is wrong. Should that depend on $h$ or not?
As another remark on physics, you could use either method also to locate the $x$-position of the centre of mass. Unless $b=0$, it will not be at $x=\frac{L}{2}$ but will swing about that. This explains why a pan with a sufficient amount of sloshing water will tend to move.


Q: delete a DataTable row bound to a datagridview I have a DataTable bound to a dataGridView using the following code :
            dataGridView1.DataSource = ReducedColTable;

At some point i would like to move the selected rows into another Table.
So here is the loop :
   List<DataGridViewRow> rows = (from DataGridViewRow row in dataGridView1.SelectedRows
                                      where !row.IsNewRow
                                      orderby row.Index
                                      select row).ToList<DataGridViewRow>();
        foreach (DataGridViewRow item in rows)
        {
            DataRow newRow = dtarget.Rows.Add();
            newRow.SetField("artiste", item.Cells[0].Value);
            newRow.SetField("album", item.Cells[1].Value);
            newRow.SetField("song", item.Cells[2].Value);
            newRow.SetField("year", item.Cells[3].Value);
            newRow.SetField("file_path", item.Cells[4].Value);
            newRow.SetField("file_size", item.Cells[5].Value);
            dataGridView1.Rows.RemoveAt(item.Index);
        }

Ps : I didnt find a way to copy the row into the new table (dtarget) which is declared globally hence the approach col by col.
DataTable dtarget = new DataTable();

My issue is that the last line is removing the row from the DataGridView but not from the original table (ReducedColTable)
Any hint how to achieve this ?

A: I found that the DataTable’s ImportRow works well for this. If you set the grids SelectionMode to FullRowSelect then you should be able to loop through the grids SelectedRows collection and “import” the selected row(s) into the other DataTable. Below is a simple example.
dt and dt2 are two DataTables with similar schemas. dt is a data source for datagridview1 and dt2 is a data source to datagridview2. Initially, dt is filled with some data and dt2 is empty. Once the user selects one or more rows, a button's click event initiates moving the selected rows from dt to dt2.
To start, a simple loop through the selected rows. A check if the “new row” is selected which we do not want to copy, therefore we ignore it. Next, get the “data bound” row from the data table in the form of a DataRowView object. Then we “import” that row into dt2, and finally removing the copied row from dt. I did not do a lot of testing on this however it appears to work as expected.
private void button1_Click(object sender, EventArgs e) {
  DataRowView drv;
  foreach (DataGridViewRow row in dataGridView1.SelectedRows) {
    if (!row.IsNewRow) {
      drv = (DataRowView)row.DataBoundItem;
      dt2.ImportRow(drv.Row);
      dt.Rows.Remove(drv.Row);
    }
  }
}

To make the example complete, drop two grids and button onto a form.
DataTable dt;
DataTable dt2;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  dt = GetTable();
  dt2 = GetTable();
  FillTable(dt);
  dataGridView1.DataSource = dt;
  dataGridView2.DataSource = dt2;
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Col1", typeof(string));
  dt.Columns.Add("Col2", typeof(string));
  dt.Columns.Add("Col3", typeof(string));
  return dt;
}

private void FillTable(DataTable dt) {
  for (int i = 0; i < 10; i++) {
    dt.Rows.Add("C0R" + i, "C1R" + i, "C2R" + i);
  }
}

Hope this helps.


Q: Chrome on Windows triggers d3.zoom behavior on click I'm creating an interactive map using dc.js and d3.js. The map should support zooming and panning, so I'm using the d3.zoom behavior. I also want a function to run when I click areas on the map. The code works as expected in Firefox (Linux and Windows), IE, and Chrome (Linux), but Chrome version 47 on Windows interprets the clicks as attempts to zoom, which suppresses the click events. Is there any way to avoid this?
I created a simplified jsfiddle to demonstrate the issue. The code is below:
HTML

JS
var container = d3.select('#container');
var fmt = d3.format('.2f');

var svg = container.append('svg')
    .attr('width', 400)
    .attr('height', 400)
    .append('g');

var colors = ['#444488', '#448844', '#884444'];

svg.selectAll('circle')
    .data(colors)
    .enter()
    .append('circle')
    .attr('cx', function(d, i) { return 50 + 100*i; })
    .attr('cy', function(d, i) { return 50 + 100*i; })
    .attr('r', function(d, i) { return 10 + 10*i; })
    .style('fill', function(d) { return d; })
    .on('click', function(d, i) {
        // Skip the click handler if preventDefault was called. This prevents the click
        // handler from running at the end of a drag.
        if (!d3.event.defaultPrevented) {
            console.log('clicked circle #' + i);
        }
    });

var zoomBehavior = d3.behavior.zoom()
    .scale(1)
    .scaleExtent([1, 15])
    .translate([0, 0])
    .on('zoom', function() {
        console.log('got zoom: scale = ' + fmt(d3.event.scale) + ', translate = [' + fmt(d3.event.translate[0]) + ',' + fmt(d3.event.translate[1]) + ']');
        svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
    });

container.call(zoomBehavior);

The demo adds three circles to the SVG and gives each one a click handler. It also adds the d3.zoom behavior to the container element. I want it to do the following:

*

*Clicking a circle runs the cirlce's click handler.

*Using the mousewheel zooms in and out, whether the mouse is over a circle or the background.

*Clicking and dragging pans the area, whether the click/drag starts over a circle or over the background. If it starts over a circle, the circle's click handler shouldn't be run.

All these requirements are met by the demo in Firefox and IE. In Chrome, when I click a circle, the zoom handler runs instead of the click handler. Does anyone have suggestions for how to deal with this?
As another approach, I tried putting a rectangle either above or below the rest of the SVG elements and attaching the zoom behavior to the rectangle instead of the container, but I ran into various issues with events not reaching the correct element. I'm willing to explore that further if people think that's the way to go.

A: I experienced the same problem with an old version of d3 (3.3.3). I'm not sure if it's been fixed since. The problem, as you said, is that Chrome gets in a weird state where a mouse click triggers a mousemove event. Completely closing Chrome and reopening it seems to get it out of this state.
I was able to resolve the issue by checking in d3's mousemove function for actual movement. I added two lines to the moved() function within mousedowned() in d3:
function moved() {
    if(d3.event.movementX === 0 && d3.event.movementY === 0) // new
        return false; // new
    dragged = 1;
    translateTo(d3.mouse(target), l);
    zoomed(event_);
}

That seems to resolve the problem without having to restart Chrome.

A: My Chrome instance must have gotten into some strange state while I was developing and debugging. I restarted Chrome and tried again, and now it's working fine.


Q: Why is get_current_user_id() returning 0 when used in woocommerce_login_redirect hook I was searching now for a while to find a solution for my problem, where the function get_current_user_id() returns 0 when hooked to woocommerce_login_redirect.
Right after the login-redirect there should always be an user-id, or am I getting s.th wrong here?
In my function.php file I have follwoing code:
add_action( 'woocommerce_login_redirect', 'ffaces_register_customer' );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer' );

function ffaces_register_customer( $user ) {

  $customerid = get_current_user_id();

  if ( $customerid == 0 ) {
    $redirection_url = get_permalink( wc_get_page_id( 'myaccount' ) );
    return $redirection_url;
    exit();
  }

  // more code working with $customerid

  return home_url("my-account/my-projects");
  exit();
}

A: There are some mistakes in your code (the first function argument is not the user, but the url redirection to be filtered). Try the following instead:
add_filter('woocommerce_login_redirect', 'ffaces_register_customer', 10, 2 );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer', 10, 2 );
function ffaces_register_customer( $redirect, $user = '' ) {

    if( isset($user) && is_a( $user, 'WP_User' ) && $user->ID > 0 ) {
        return home_url("my-account/my-projects");
    } else {
        return get_permalink( wc_get_page_id( 'myaccount' ) );
    }

}

Code goes in functions.php file of your active child theme (or active theme). It should work.

A: I don't think its set yet when this fires.
The hook passes the user object of the user that logged in try to change
$customerid = get_current_user_id();
to
$customerid = $user->ID;


Q: Use ajax without a plugin? What I'm trying to do:
Make an ajax-powered search button that gets the text from an input and give a list of post id's that match that search.
Note: I must probably sound very stupid to 90% of you, but I'm rather new to ajax and wordpress, so if I'm doing it all wrong, it would be great if someone could point me out what I'm doing wrong or if he knows a better guide than the ones I used. (The problems I think I'm having with the script are written all the way down below.)
To start I thought of just making a button that uses ajax to get the title of a post-id.
I read these pages:

*

*https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/

*https://developer.wordpress.org/plugins/javascript/summary/
I've tried out all this code on both these pages, however, I'm always stuck because I need to create a plugin. I'm not trying to create a plugin so I was wondering if I could just write all the code on my search page.
I'm sad however that it doesn't work, and I cannot find out why... (i get redirected to the homepage)
I'm just curious if I have to research how to create plugins etc. or is there a much simpler way that just allows me to get e.g. the post title of a certain ID through an AJAX call without using a plugin?
This is the code I tried:
The Ajax call:

The search form:
$the_title = '';
 $s_str = 18694;
 $nonce = wp_create_nonce("get_title_nonce");
  $link = admin_url('http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?action=get_title&post_id='.$s_str.'&nonce='.$nonce);
        echo ''.$s_str.' Title: '.$the_title."";

The rest of the code I added as written in the guides:
<?php

add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
    wp_register_script('ajax_search',TEMPLATEPATH.'/new/js/ajax_search.js', array('jquery'));
    wp_localize_script('ajax_search', 'admin_ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'ajax_search' );
}

add_action("wp_ajax_get_title", "get_title");
add_action("wp_ajax_nopriv_get_title", "get_title_must_login");

function get_title() {
   if ( !wp_verify_nonce( $_REQUEST['nonce'], "get_title")) {
      exit("No naughty business please");
   }
   $the_title = get_the_title($_REQUEST["post_id"]);

   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      $result = json_encode($result);
      echo $result;
   }
   else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }

   die();
}
function get_title_must_login() {
   echo "You must log in to get title";
   die();
}
?>

Probably the problems lie here:
I'm not sure about these add_action parts... I don't think I need it if I add the link to admin-ajax.php directly like I did just here above:
http://jtc.ae/pre/wp/wp-admin/admin-ajax.php? So could I just scrap this first add_action?
Also I think that the bottom add_actions are probably not properly excecuted on my search_page.php. But this is just the thing: I'm not planning on creating any plugins, so I don't know where to put them...

A: Plugin code is just... code, it can go in a themes functions.php, or a plugin file, there's no magical or special difference other than the order they're loaded in, and the API calls are identical, work the same way etc because they're the same. It's just how the code is packaged
For example, if you ever want to do something without using a plugin, take a plugin, remove the comment at the top of the main file, and hey presto you've got your answer.
The problem you're facing is that you've tried to put your logic inside the search page. But that's not how the AJAX API works. When the browser makes a request to the AJAX endpoint, no templates are loaded, so your search template is never loaded, and your code to handle the request is never loaded.
Instead, the code needs to be in functions.php which is always loaded.
You can see this here:
add_action( 'init', 'my_script_enqueuer' );

Here, you're saying "When the init event happens, run this function", but if you're in the search page template, then that event has already happened. Remember, templates are loaded after everything else, not before

A: After a lot of tinkering I finally got the answer:
First of all you don't need this: Delete it
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
    wp_register_script('ajax_search',TEMPLATEPATH.'/new/js/ajax_search.js', array('jquery'));
    wp_localize_script('ajax_search', 'admin_ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'ajax_search' );
}

Second, I was messing up GET and POST data.
Use this to create an ajax search form:
<form method="post" id="searchbox">
    <input value="18694" name="post_id" class="ajax">
    <input type="button" class="ajaxgo" value="Submmmittt" name="submit">
</form>
Title:  //to test the output

And make the ajax call with a script below this like this:

Finally use this code in your template's functions.php file:
function get_title() {

   if ( !wp_verify_nonce( $_POST['nonce'], "get_title_nonce")) {
      exit("No naughty business please");
   }
   $result = get_the_title($_POST["post_id"]);

   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      //$result = json_encode($result);
      echo $result;
   } else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }

   die();
}
function get_title_must_login() {
   echo "You must log in to get title";
   die();
}

A: You may not want to post the ID via ajax for security reasons becuase your users can manipulate the ajax request.  Here is a server side way to get the post id:

And
function get_title() {

  if ( !wp_verify_nonce( $_POST['nonce'], "get_title_nonce" ) ) {
    exit( "No naughty business please" );
  }

  $url      = wp_get_referer();
  $post_id  = url_to_postid( $url )
  $result   = get_the_title( $post_id );

  if ( !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) {
    //$result = json_encode( $result );
    echo $result;
  } else {
    header( "Location: ".$_SERVER["HTTP_REFERER"] );
  }

  die();
}

function get_title_must_login() {
  echo "You must log in to get title";
  die();
}


Q: Google Calendar API Sharing Example I am looking for examples of share calendar and share event using google calendar API in any programming language java, .net, java script.
Thanks,
Aqeel

A: I'm not sure how much this will help, but I have an example here using scala with the ical4j library to read a shared/public google calendar:
http://github.com/kevinwright/lsug-website/tree/master/src/main/scala/org/lsug/ical4scala/