text:
Q: With what should I replace the deprecated sizeWithFont: method? I have a method that gives me the perfect size for a UITextView given a length of string (with the corresponding correct font size) :
- (NSInteger) heightOfLabel:(NSString*) string {
    CGSize maximumLabelSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width - 40, FLT_MAX);
    CGSize expectedLabelSize = [[NSString stringTrimmedForLeadingAndTrailingWhiteSpacesFromString:string]
             sizeWithFont:[UIFont systemFontOfSize:15]
             constrainedToSize:maximumLabelSize
             lineBreakMode:NSLineBreakByWordWrapping];

    return expectedLabelSize.height + 5;
}

In fact, it still gives me a perfect fit, even in iOS7. Although now it comes up with a warning method that says I shouldn't use 'sizeWithFont:contrainedToSize:lineBreakMode'.
It now says I should be using -boundingRectWithSize:options:attributes:context:
This method isn't new to iOS7 and therefore i figure that it is okay to ask it on stack overflow, rather than going across to the official apple developers forum.
I have three questions:
1) Because it is deprecated, does that mean I should definitely replace it, despite it still working?
2) I have tried many different boundingRectWithSize: methods, with various variables but it is never perfect, it always seems to be slightly out (as many stackoverflow questions point out) - is there a perfect replacement with this none-deprecated method that does exactly the same as my previous method with as minimal hassle?
3) why remove this method? Is it because of the overlap with this other method?

A: For linebreak issue:
- (CGFloat)heightNeededForText:(NSString *)text withFont:(UIFont *)font width:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode {
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = lineBreakMode;
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                     options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                  attributes:@{ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle }
                                     context:nil].size;

    return ceilf(size.height);
}

A: After an hour of trial error I managed to make it work:
CGSize maximumLabelSize = CGSizeMake(tableView.width, MAXFLOAT);

NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
                                 NSStringDrawingUsesLineFragmentOrigin;

NSDictionary *attr = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
CGRect labelBounds = [string boundingRectWithSize:maximumLabelSize
                                          options:options
                                       attributes:attr
                                          context:nil];

Update:

As Mr. T mentions in answer below : In iOS 7 and later, this method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function. ceilf function is recommended to use.
CGFloat height = ceilf(labelBounds.size.height);

A: Swift version of the Alexander of Norway's answer...
func heightNeededForText(text: NSString, withFont font: UIFont, width: CGFloat, lineBreakMode:NSLineBreakMode) -> CGFloat {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = lineBreakMode
        let size: CGSize = text.boundingRectWithSize(CGSizeMake(width, CGFloat.max), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle], context: nil).size//text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MA

        return ceil(size.height);
    }

In the code where you want to get the height just call the method like below...
let size = self.heightNeededForText(text as NSString, withFont: UIFont.systemFontOfSize(15.0), width: scrollView.frame.size.width - 20, lineBreakMode: NSLineBreakMode.ByWordWrapping) //Can edit the font size and LinebreakMode

A: I believe the function was deprecated because that series of NSString+UIKit functions were based on the UIStringDrawing library, which wasn't thread safe.  If you tried to run them not on the main thread (like any other UIKit functionality), you'll get unpredictable behaviors.  In particular, if you ran the function on multiple threads simultaneously, it'll probably crash your app.  This is why in iOS 6, they introduced a the boundingRectWithSize:... method for NSAttributedStrings.  This was built on top of the NSStringDrawing libraries and is thread safe.
If you look at the new NSString boundingRectWithSize:... function, it asks for an attributes array in the same manner as a NSAttributeString.  If I had to guess, this new NSString function in iOS 7 is merely a wrapper for the NSAttributeString function from iOS 6.
On that note, if you were only supporting iOS 6 and iOS 7, then I would definitely change all of your NSString's sizeWithFont:... to the NSAttributeString's boundingRectWithSize.  It'll save you a lot of headache if you happen to have a weird multi-threading corner case!  Here's how I converted NSString's sizeWithFont:constrainedToSize::
What used to be:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
CGSize size = [text sizeWithFont:font
               constrainedToSize:CGSizeMake(width, CGFLOAT_MAX)];

Can be replaced with:
NSString *text = ...;
CGFloat width = ...;
UIFont *font = ...;
NSAttributedString *attributedText =
    [[NSAttributedString alloc]
        initWithString:text
        attributes:@
        {
            NSFontAttributeName: font
        }];
CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];
CGSize size = rect.size;

Please note the documentation mentions:

In iOS 7 and later, this method returns fractional sizes (in the size
  component of the returned CGRect); to use a returned size to size
  views, you must use raise its value to the nearest higher integer
  using the ceil function.

So to pull out the calculated height or width to be used for sizing views, I would use:
CGFloat height = ceilf(size.height);
CGFloat width  = ceilf(size.width);


text:
Q: Tcl split regex over multiple lines I have a long RE to match dates in multiple files and I would like to split it out over multiple lines so it is easier to read and update. I am setting it as a variable and then calling that variable in the regex statement.
set ::eval::regexdate { \d[\/\.-]\d{2}[\/\.-]\d{4}|\d{2}[\/\.-]\d{2}[\/\.-]\d{4}|\d{4}[\/\.-]\d{2}[\/\.-]\d{2}|(([12]\d|3[01])|([12]\d|3[01])(th|nd|rd|st))\s(January|February|March|April|May|June|July|August|September|October|November|December)\s\d{4}|(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[\/\.-]\d{2}[\/\.-]\d{4} }

I am then calling it with the following regexp line...
if {[regexp "($::eval::regexdate)" $linefromfile all date]} {
    Do something...
 }

This all works fine if the RE is set as one long string, but if I try to break it out over multiple lines using (?x) as outlined in this post.
regexp pattern across multiple lines
set ::eval::regexdate {(?x)
    \d[\/\.-]\d{2}[\/\.-]\d{4}|
    \d{2}[\/\.-]\d{2}[\/\.-]\d{4}|
    \d{4}[\/\.-]\d{2}[\/\.-]\d{2}|
    (([12]\d|3[01])|([12]\d|3[01])(th|nd|rd|st))\s(January|February|March|April|May|June|July|August|September|October|November|December)\s\d{4}|
    (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[\/\.-]\d{2}[\/\.-]\d{4}
}

I get the following error...
 `couldn't compile regular expression pattern: quantifier operand invalid.`

I am not sure why this is happening, my understanding is that using (?x) ignores all white space and comments so it should just stitch the lines back together to create the one long RE, no? Are the "|" operands causing an issue in the way that I have split the RE up?
Any help would be greatly appreciated in figuring out why it won't work when using (?x).
Thanks

A: The problem is the way you use the regexdate variable in your regxep command. As the post you reference indicates, (?x) should be at the start of the regular expression. However, by using "($::eval::regexdate)" you put parentheses around it, effectively making the expression ((?x)…). Putting parentheses around the complete regular expression is not very useful, as the regexp command will already put the full match in the first variable handed to it.
So, either omit the parentheses and use the complete match as the date:
regexp $::eval::regexdate $linefromfile date

Or move the (?x) to the call:
set ::eval::regexdate {
    \d[\/\.-]\d{2}[\/\.-]\d{4}|
    \d{2}[\/\.-]\d{2}[\/\.-]\d{4}|
    \d{4}[\/\.-]\d{2}[\/\.-]\d{2}|
    (([12]\d|3[01])|([12]\d|3[01])(th|nd|rd|st))\s(January|February|March|April|May|June|July|August|September|October|November|December)\s\d{4}|
    (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[\/\.-]\d{2}[\/\.-]\d{4}
}

if {[regexp "(?x)($::eval::regexdate)" $linefromfile all date]} {
    Do something...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError with scipy.optimize when minimizing Cost func I want to optimize 9 variables in W((1×9)matrix) by using scipy.optimize.
from scipy.optimize import minimize

def func(W):
    W = W.reshape(1,9) #(1,9)
    Y = df0.values.reshape(49,1) #(49,1)
    X = df1.values.reshape(49,1) #(49,9)
    Z = np.dot(X, W.T) #(49, 1)
    Z = np.abs(Z - Y) #(49, 1)
    Cost = np.sum(Z ,axis=0, keepdims=True)
    return Cost[0][0]  #float

W = np.array([2,3,4,5,6,7,8,9,10])
cons = ({'type': 'ineq', 'fun': W[1]-W[0]})

result = minimize(func, x0=W0, constraints=cons, method="SLSQP")

But I get a TypeError like this
'numpy.int32' object is not callable

I changed the 'cons' to
def cons(W):
    return W

cons = (
    {'type': 'ineq', 'fun': cons}
)

Then it worked fine and I got a result
     fun: 125.4977648197736
     jac: array([26.3666687 , 39.73333454, 46.56666756, 32.76666737, 38.23333454,
       25.20000076,  9.        ,  5.        ,  5.76666737])
 message: 'Optimization terminated successfully.'
    nfev: 332
     nit: 24
    njev: 24
  status: 0
 success: True
       x: array([7.36486798e-03, 8.29918593e-03, 9.61602518e-02, 9.17950729e-03,
       2.98795999e-12, 3.73831662e-12, 3.59100171e-12, 4.73656828e-01,
       1.77345002e+00])

I can't reach out to a good solution.

A: It is due to the fact, that scipy's minimize needs an actual function (not output of it) to minimize properly. See this question. Your above code works, because you pass function  reference to the callable one (cons, not cons(W)). You can try creating a lambda function for it, for example:
cons = ({'type': 'ineq', 'fun': lambda *args: W[1]-W[0]})


text:
Q: I want to output a list of every Case_Number with Code 1 that has a higher UniqueID value than its Code 2 counterpart's UniqueID value I have a table which looks something like this:
    Case_Number  |  Code  |  UniqueID
        a             1       1372
        a             2       1352
        a             3       1325
        b             1       1642
        b             2       1651
        b             3       1623
        c             1       1743
        c             2       1739
        c             3       1720
       ...           ...        ...

From this database I want to output a list of every Case_Number where the UniqueID value of Code 1 is higher than the UniqueID value of Code 2 (But ignoring the UniqueID value of Code 2, or any other Code x that might be in the table). Meaning that if the UniqueID value of Code 2 is higher than Code 1, which is the case with Case_Number b in the example above, it should not show up in the list.
So, querying the above table would result in this:
    Case_Number  |  Code  |  UniqueID
        a             1       1372
        c             1       1743

A: Hmmm . . . You seem to want:
select t.*
from t
where t.code = 1 and
      t.uniqueid > (select max(t2.uniqueid)
                    from t t2
                    where t2.case_number = t.case_number and t2.code = 2
                   );

The max() in the subquery is simply to handle the case where there is more than one matching value.

A: The query below gives you the expected result
CREATE TABLE CaseTab
(Case_Number VARCHAR(10),
 Code        INT,
 UniqueID    INT);

INSERT INTO CaseTab VALUES ('a',             1,       1372);
INSERT INTO CaseTab VALUES ('a',             2,       1352);
INSERT INTO CaseTab VALUES ('a',             3,       1325);
INSERT INTO CaseTab VALUES ('b',             1,       1642);
INSERT INTO CaseTab VALUES ('b',             2,       1651);
INSERT INTO CaseTab VALUES ('b',             3,       1623);
INSERT INTO CaseTab VALUES ('c',             1,       1743);
INSERT INTO CaseTab VALUES ('c',             2,       1739);
INSERT INTO CaseTab VALUES ('c',             3,       1720);

WITH v_code_gt_1 AS
(SELECT Case_Number, MAX(UniqueID) AS UniqueID
   FROM CaseTab
  WHERE Code > 1
  GROUP BY Case_Number)
SELECT c1.Case_Number, c1.UniqueID
  FROM CaseTab c1 JOIN
       v_code_gt_1 c2
       ON (c1.Case_Number = c2.Case_Number)
 WHERE c1.UniqueID > c2.UniqueID
   AND c1.Code = 1;

Basically the query gets the max UniqueID for all cases where code is greater than 1 and compares against the Unique ID for Code 1.
You haven't stated whether there can be cases with code = 1, but no other codes. If so, use LEFT JOIN as below.
WITH v_code_gt_1 AS
(SELECT Case_Number, MAX(UniqueID) AS UniqueID
   FROM CaseTab
  WHERE Code > 1
  GROUP BY Case_Number)
SELECT c1.Case_Number, c1.UniqueID
  FROM CaseTab c1 LEFT JOIN
       v_code_gt_1 c2
       ON (c1.Case_Number = c2.Case_Number)
 WHERE c1.UniqueID > ISNULL(c2.UniqueID, 0)
   AND c1.Code = 1;


text:
Q: fetching and viewing data from database in ci I have  subjects table like this
id  parent_id subject_title
1   0         maths
2   1         algebra
3   0         English
4   3         essay

how to show those subjects having id=0 as heading and other subjects below heading subjects like
heading       maths
sub-heading   algebra

A: its up to you how you get the record . if its a array you should use an if array index  . something like that `
for($i=0;$i<$count;$i++ ) {
 if($data[$i][0] ){
 echo "heading : {$data[$i][0]}";
 }else{
 echo "sub-heading   {$data[$i]}"
 }
}

this is just an idea and may not work with your code so please modify before using but main idea here that if it match the certain criteria it will display differently
hope this will help you . thanks

A: Here is sample code based on your table and problem
<?php
// Connecting to and selecting a MySQL database
$mysqli = new mysqli('host_name', 'your_user', 'your_pass', 'db_name');

// A connect_errno exists so the connection attempt failed!
if ($mysqli->connect_errno) {
    echo "Sorry, this website is experiencing problems.";
    exit;
}

// Perform an SQL query
$sql = "SELECT * FROM subjects";

if (!$result = $mysqli->query($sql)) {
    // The query failed.
    echo "Sorry, the website is experiencing problems.";
    exit;
}

// Fetch result
while ($subjects = $result->fetch_assoc()) {
    if($subjects['parent_id '] == 0){
        echo "Heading: ".$subjects['subject_title ']."
";
    }
    else{
        echo "Sub-heading: ".$subjects['subject_title ']."
";
    }
}
?>


text:
Q: Trim or remove leading/trialing spaces inside the element I converting the html to xml. I am struggle in removing the spaces. As I used normalize() function, the spaces are removed, but the single space between text and element e.g. ofAgriculturalstudies, limitedaccording standard commercialpractices also removed. Below i defined my input

The need of               Agricultural              studies

               (a) term for leases

               (b) be limited                  according standard commercial                practices with maximum

                  (1) General Lease

                  49 years

                  General Permit

                  Forest      1       Management Agreement

                  (2) Agricultural Lease

I tried by using this xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
    <xsl:output indent="no" omit-xml-declaration="yes" method="html"/>
       <xsl:strip-space elements="*"/>

    <xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

   <xsl:template match="/">
       <xsl:apply-templates/>
   </xsl:template>

     <xsl:template match="text()">
         <xsl:value-of select="normalize-space()"/>
     </xsl:template>

</xsl:stylesheet>

and the output I got is

The need ofAgriculturalstudies

(a) term for leases

(b) be limitedaccording standard commercialpractices with maximum

(1) General Lease

49 years

General Permit

Forest1Management Agreement

(2) Agricultural Lease

I found it removes the spaces near to the text also, that is around  element and  element
ofAgriculturalstudies, limitedaccording standard commercialpractices

I need to retain the space as
of Agricultural studies, limited according standard commercial practices

My expected output is

The need of Agricultural studies

(a) term for leases

(b) be limited according standard commercial practices with maximum

(1) General Lease

49 years

General Permit

Forest1 Management Agreement

(2) Agricultural Lease

Please someone help for removing the space generically

A: This seems to work reasonably well:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
    <xsl:output indent="yes" omit-xml-declaration="yes" method="html"/>

    <xsl:strip-space elements="*"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
     </xsl:template>

    <xsl:template match="text()[preceding-sibling::* and following-sibling::*]">
        <xsl:text> </xsl:text>
        <xsl:value-of select="normalize-space()" />
        <xsl:text> </xsl:text>
    </xsl:template>

    <xsl:template match="text()[preceding-sibling::*]">
        <xsl:text> </xsl:text>
        <xsl:value-of select="normalize-space()" />
    </xsl:template>

    <xsl:template match="text()[following-sibling::*]">
        <xsl:value-of select="normalize-space()" />
        <xsl:text> </xsl:text>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:value-of select="normalize-space()" />
    </xsl:template>
</xsl:stylesheet>

Output (wrapped as you did in your question, not as the XSLT processor created it):

The need of Agricultural studies

(a) term for leases

(b) be limited according standard commercial practices with maximum

(1) General Lease

49 years

General Permit

Forest 1 Management Agreement

(2) Agricultural Lease


text:
Q: Configuring Windows Server Backup Destination Drive Sets Is it possible to set up the standard backup system in SBS 2011 (or Server 2008 R2) to use an internal drive as a destination as well as external drives?
Before you say yes, from my tests and from what I've read on the web, backups with internal drives included as a destination always seems to prefer the internal drive over connected external ones. (Regardless of what drive might be marked as 'active'). So no data ever gets written to a plugged in external drive.
In my opinion external drives should always have priority over internal drives or including them is pointless.

A: Create a new share on the SBS server you want to backup.
Assign the correct permissions.
Configure Windows Server Backup to point to the UNC path of the share on the server you have created, thus pointing it at itselfs using a UNC path.
So on the C:\ of SBS create a new directory 'SBS Backups', share it, assign NTFS permissions and then point Windows Server Backup to \SERVERNAME\SBS Backups.
Just tried it on SBS 11 it works!


text:
Q: Two UIScrollView's on top of each other? I'm working on a iphone game, and part of it includes a section where you scroll horizontally through a list of images (which have transparent backgrounds).
but I also want to be able to vertically scroll and change the background image, without the image in the horizontal scroll view changing.
I have the horizontal scrollview working now, and I've placed a second scrollview behind it for the vertical scrollview, but obviously the vertical scrollview doesn't catch the up/down swipes.
Is there some way to push vertical swipes through to the second scrollview, but catch the horizontal swipes on the first?
Mike

A: IF you implement the scrollViewDidScroll Delegate for the first scroll view and catch the scroll offset, you can pass the same to the second scroll and control how the offset moves on the second scroll.


text:
Q: How do I pull a certain table from Internet Explorer in Excel VBA Hello I've scoured the internet trying to find a solution to this problem.

*

*I'm trying to pull a certain table from this a private website using excel-vba.

*I came across this code that allows me to pull all the tables but I only need one table - is there any way I can edit this to pull just one specific table?

code
Sub GetAllTables(doc As Object)

' get all the tables from a webpage document, doc, and put them in a new worksheet

Dim IE As Object
Dim ws As Worksheet
Dim rng As Range
Dim tbl As Object
Dim rw As Object
Dim cl As Object
Dim tabno As Long
Dim nextrow As Long
Dim I As Long
Dim oXL As Excel.Application

Set ws = Sheet1

For Each tbl In doc.getElementsByTagName("TABLE")
tabno = tabno + 1
nextrow = nextrow + 1
Set rng = ws.Range("C" & nextrow)
rng.Offset(, -1) = "Table " & tabno
For Each rw In tbl.Rows
For Each cl In rw.Cells
rng.Value = cl.outerText
Set rng = rng.Offset(, 1)
I = I + 1
Next cl
nextrow = nextrow + 1
Set rng = rng.Offset(1, -I)
I = 0
Next rw
Next tbl

ws.Range("C:N").ClearFormats

A: Sure there is. Which table do you need to pull? Either you can identify it by index position:
Dim t as Integer    'represents the index position of the table you want to obtain.
t = 0
Set tbl = doc.getElementsByTagName("TABLE")(t)

Or, if the index position is not known, you would need to develop some other logical tests within a For/Each loop. Note: this is a very simplistic example with pseudo-code. You may require more complex logic/conditions to determine which table is the correct table in the collection:
For each tbl in doc.getElementsByTagName("TABLE")
    If tbl.__some_property__ = "something" Then
        Exit For
    End If
Next


text:
Q: Write text over picture taken from SD card Can anyone please refer any tutorial for writing text over images taken from SD card in android

A: You can put an EditText and Write into it and after writting you first convert it to Bitmap like
Bitmap bmp = Bitmap.createBitmap(mEditText.getDrawingCache());
Now you can add created image bmp to your original image like this
call like this : Bitmap combined = combineImages(bgBitmap,bmp);
public Bitmap combineImages(Bitmap background, Bitmap foreground) {

    int width = 0, height = 0;
    Bitmap cs;

    width = getWindowManager().getDefaultDisplay().getWidth();
    height = getWindowManager().getDefaultDisplay().getHeight();

    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas comboImage = new Canvas(cs);
    background = Bitmap.createScaledBitmap(background, width, height, true);
    comboImage.drawBitmap(background, 0, 0, null);
    comboImage.drawBitmap(foreground, matrix, null);

    return cs;
}

A: Surround the image with layout..then add the text view to the same layout


text:
Q: Fortran module segmentation fault- GNUFOR I need a special library for Fortran so that I can code and visualize on the fly, instead of writing to a text file then use either Python or Matlab to plot. I followed this:
https://people.sc.fsu.edu/~jburkardt/f_src/gnufor/gnufor.html
The instructions are not cleared so I did not use their examples, so I wrote my own code. There are 2 files: gnu.f90 from website, and myplot.f90, which I wrote like this:
program myplot

    !Declare data types
    implicit none
    integer, parameter :: N1 = 50
    real(kind=8)       :: x1(N1),x2(N1)
    real(kind=8)       :: y1(N1)
    real(kind=8)       :: y2(N1)
    integer            :: i

    !Generate 2D plot

    do i = 1,N1
        x1(i) = i
        x2(i) = i
    end do

    y1 = x1**2
    y2 = x2**3

    !print *, 'Plotting'
    !call plot(x1,y1,x2,y2)

    call write_xy_data(x1,y1)

end program myplot

Apparently, from their gnufor.f90 file, I only need to do:
write_xy_data(X,Y) and it should work.  In their example code, they did not use gnufor.f90 as a module so I didnt put:  use gnufor at the beginning. Although, I tried that and it didn't work as well. So in my current directory, I have:
gnufor.90
myplot.f90
And to compile it, I am on Linux: gfortran myplot.f90 -o test
The error was:
 Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

    Backtrace for this error:
    #0  0x7FB0B051DE08
    #1  0x7FB0B051CF90
    #2  0x7FB0AFF574AF
    #3  0x40302F in write_xy_data_
    #4  0x400D7E in MAIN__ at myplot.f90:?
    Segmentation fault (core dumped)

Any help is greatly appreciated. I expected the problem to be in my own code, although all array sizes are declared.

A: The subroutine write_xy_data in gnufor.f90 from the website you linked has a signature
subroutine write_xy_data(data_filename, n, x, y, ierror)
    implicit none
    character ( len = * ) data_filename
    integer ( kind = 4 ) n
    real ( kind = 8 ) x(n)
    real ( kind = 8 ) y(n)
    integer(kind = 4) ierror

Which means instead of passing only x,y, you have to call it as
call write_xy_data('myfile',N1,x1,y1,ierr)

passing as arguments the name of the file to write to ('myfile' in the example), the number of points to write (N1), the data (x1,y1) and an integer that carries information on the success of the write (ierror, this one has to be declared, too)
Also, there is no module gnufor, so no use clause is required, all functions in gnufor.F90 are global, which is also the reason why you need to pass the number of points as an extra argument, as assumed shape would require an explicit interface.


text:
Q: Freedonia Rainy and Sunshine In Freedonia, every day is either cloudy or sunny (not both). If it's sunny on any given day, then the probability that the next day will be sunny is $\frac 34$. If it's cloudy on any given day, then the probability that the next day will be cloudy is $\frac 23$. Given that a consecutive Saturday and Sunday had the same weather in Freedonia, what is the probability that that weather was sunny?
So far, I have tried to do (Sunny)/(Sunny + Cloudy) which ended up giving me $9/17$. This though is wrong.
I know this question has been asked before but none of them gave me a complete answer.

A: Let $p=$ the probability that Freedonia is sunny on a day and $q=$ the probability that Freedonia is cloudy on a day. Then the given condition implies the following equilibrium condition holds:
$$\begin{eqnarray}
p&=&\frac{3}{4}p+\frac{1}{3}q,\\
q&=&\frac{1}{4}p+\frac{2}{3}q.
\end{eqnarray}$$ Using $p+q=1$, we can solve $p=\frac{4}{7}$ and $q=\frac{3}{7}$. Now, the probability that consecutive days are sunny days is $p\cdot \frac{3}{4}=\frac{3}{7}$, and probability that consecutive days are cloudy is $q\cdot\frac{2}{3}=\frac{2}{7}$. By the definition of conditional probability, this gives
$$\begin{eqnarray}
&&P(\text{consecutive days are sunny}\;|\;\text{consecutive days have the same weather})&\\&&=\frac{P(\text{consecutive days are sunny})}{P(\text{consecutive days are sunny})+P(\text{consecutive days are cloudy})}\\&&=\frac{\frac{3}{7}}{\frac{3}{7}+\frac{2}{7}}=\frac{3}{5}.
\end{eqnarray}$$


text:
Q: SQL Select syntax I've came cross a SQL SELECT statement which is different than what I normally see:
Select Distinct [Employee: Department_key_historic],[Employee: Department_key_current]
From [shared].[vw_Table]

What does the colon do in the above code? I am used to see format like Select table.columnName but never a :

A: This appears to be a SQL Server query.  If that is the case, [] are used to surround object names.  Therefore the : that you see are simply part of the name of the column itself.


text:
Q: Dimension reduction Can i apply dimension reduction method such as random forest, lasso, factor anaysis or principle compoenet analysis on data which was extracted from two stage stratfied survey

A: Welcome to CV.
The simple answer to this question is "maybe".
Presumably, you want to know how to do this and when it can be done. For that, your question is much too broad.  First, you list four different methods that have different purposes and apply in different cases. This should be four different questions. (I would really only think of PCA as a pure 'data reduction' technique. Random forest is a prediction method, lasso is a variable selection method and factor analysis is a way of finding latent variables).
In addition, you'll have to tell us a lot more about the study design.


text:
Q: koa - Wrong http status message when piping response from remote server I have server A and server B. The client requests a file from server A, and server A gets the file from server B.
This works fine when the client requests a file that exists, but the client receives the wrong http status message when requesting a file that doesn't exist.
Problem:
The client receives "404 OK" in the status line when it should be "404 Not Found".  No matter what status code I send, the status message is always 'OK', but the client does always receive the status code I set (301, 402, etc).
Also, Server A does receive the correct status message, and for whatever reason, server A seems to propagate the status code, but not the message.
Server A code:
import request from 'request'

context.response.body = request( my_url );

//request( my_url, (error, response, body) =>
//{
//   console.log( "message: " + response.statusMessage );  //prints 'Not Found'
//});

Server B code:
context.response.status = 404;
context.response.message = 'Not Found';
context.response.body = 'Page not found';

What am I doing wrong?
Edit:
I found a "solution", but I'm hoping there's a better one.
In server A, I changed the code to:
let stream = request( my_url );

stream.on( 'response', function( response )
{
    context.response.message = response.statusMessage;
});

contest.response.body = stream;

I can't say I'm happy with this though because it seems silly that the status code gets propogated but not the message.


text:
Q: Boolean does not set back to true I have a boolean variable in my game that I use to control how many times a NPC can move each turn. It's a tactical RPG. The NPC can move just once per turn. The boolean is called canMoveNPC and it's initialized as true. Then, when the NPC reaches his destination, I set it to false.
However, when I pass the turn to the human player, I want this variable to be true again, because in this way, the NPC is able to move again when it's his turn. But it doesn't set back to true, it stays as false. I don't know what I'm doing wrong.
This code I use to move the NPC and set the variable to false:
ublic void Move()
     {
         for (int i = 0; i < mov.NPCS.Length; i++)
         {
             if (!Physics.Raycast(Sherrif.transform.position, Sherrif.Left_Right, out Sherrif.hitRight) || Sherrif.hitLeft.transform.tag != "Human")
             {
                 if (mov.gameManager.NPCTurn && canMoveNPC )
                 {
                     mov.NPCPlayer = mov.NPCS[2];
                     mov.NPCS[2].GetComponent<NPC>().isNPC = true;
                     IsMoving = true;

                     this.transform.position = Vector3.MoveTowards(this.transform.position, targetPosition, velocity * Time.deltaTime);
                 }

                 if(this.transform.position == targetPosition)
                 {
                     mov.NPCS[2].GetComponent<NPC>().isNPC = false;
                     IsMoving = false;
                     canMoveNPC = false;
                 }
             }
         }
     }

And here, I have a game manager that I use to control the turns and set the variable to true again. I use the code bellow when the NPC passes his turn:
else if (mov.gameManager.playerTurn == 2)
         {
             mov.gameManager.playerTurn = 1;
             mov.gameManager.NPCTurn = false;
             mov.gameManager.HumanTurn = true;
             mov.TurnEnd();
             mov.interfaceManager.ChangeTurn();

             for (int i = 0; i < mov.NPCS.Length; i++)
             {
                 mov.NPCS[i].GetComponent<NPC>().canMoveNPC = true;

             }
         }

How could I solve it?

A: I've found out what was happening. The target position wasn't being updated, so it would always be false that variable.
The problem is solved.


text:
Q: Can't make a multi-variable linear regression converge The following is a simple linear regression/ML code that I have modified. For all initial weight and bias (i.e. weight = np.array([0.03, 0.04, 0.02]), bias = 0.01), the training will blow up (It just won't converge).
Wonder if there is a bug in the code or how to choose good initial values (weight and bias) so it will converge.
#Adopted from http://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html
import numpy as np
from numpy import genfromtxt

def predict(X, weight, bias):
    return np.dot(X, weight) + bias

def cost_function(X, Y, weight, bias):
    companies = X.shape[0]
    return np.sum((predict(X, weight, bias) - Y) **2) / companies

def update_weights(X, Y, weight, bias, learning_rate):
    companies = X.shape[0]

    dW = 2 * np.dot(X.T,  predict(X, weight, bias) - Y)
    db = 2 * np.sum(predict(X, weight, bias) - Y)
    """
    for i in range(companies):
        # Calculate partial derivatives
        # -2x(y - (mx + b))
        dw += -2*X[i] * (sales[i] - (weight*X[i] + bias))

        # -2(y - (mx + b))
        db += -2*(sales[i] - (weight*X[i] + bias))
    """
    #print(dW, db)
    # We subtract because the derivatives point in direction of steepest ascent
    #weight -= (dW / companies) * learning_rate
    #bias -= (db / companies) * learning_rate

    return weight - (dW / companies) * learning_rate, bias - (db / companies) * learning_rate

def train(X, Y, weight, bias, learning_rate, iters):
    cost_history = []

    for i in range(iters):
        weight,bias = update_weights(X, Y, weight, bias, learning_rate)

        #Calculate cost for auditing purposes
        cost = cost_function(X, Y, weight, bias)
        cost_history.append(cost)

        # Log Progress
        if i % 100 == 0:
            print ("iter: "+str(i) + " cost: "+str(cost) + "\n")

    return weight, bias, cost_history

#the Advertising.csv is from http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv
if __name__ == "__main__":
    my_data = genfromtxt('Advertising.csv', delimiter=',')
    X = my_data[1:, 1:4:1]
    Y = my_data[1:, 4];  #the sales
    a,b, _ = train(X, Y, np.array([0.03, 0.04, 0.02]), 0.01, 0.001, 1000)

The problem is, whatever value I use as initial weight and bias (i.e. weight = np.array([0.03, 0.04, 0.02]), bias = 0.01) will cause the value to blow up.
It just won't converge.
train(X, Y, weight, bias, 0.001, 1000)
UPDATE1
When I ran the above code snippet, I got
$ python linearRegression_multi.py
iter: 0 cost: 212337.75728564826

/Users/joe/anaconda3/lib/python3.6/site-packages/numpy/core/_methods.py:32: RuntimeWarning: overflow encountered in reduce
  return umr_sum(a, axis, dtype, out, keepdims)
linearRegression_multi.py:11: RuntimeWarning: overflow encountered in square
  return np.sum((predict(X, weight, bias) - Y) **2) / companies
iter: 100 cost: inf

linearRegression_multi.py:34: RuntimeWarning: invalid value encountered in subtract
  return weight - dW * learning_rate / companies , bias - db * learning_rate / companies
iter: 200 cost: nan

iter: 300 cost: nan

iter: 400 cost: nan

iter: 500 cost: nan

iter: 600 cost: nan

iter: 700 cost: nan

iter: 800 cost: nan

iter: 900 cost: nan

A: Figured out the cause of the problem! The learning rate in this case 0.001 is too high.
Change it to be 0.00001 works.  i,e, change the last line in original snippet to be the following makes it work.
a,b, _ = train(X, Y, np.array([0.03, 0.04, 0.02]), 0.01, 0.00001, 1000)

Here is the output:
python te.py
iter: 0 cost: 23.07411798374272

iter: 100 cost: 6.479930413738248

iter: 200 cost: 5.097751463999494

iter: 300 cost: 4.528064099014893

iter: 400 cost: 4.263917598438141

iter: 500 cost: 4.1398851132621655

iter: 600 cost: 4.081383875535448

iter: 700 cost: 4.053584811192947

iter: 800 cost: 4.040172367398533

iter: 900 cost: 4.033501506011401


text:
Q: Errors from `ObjectSpace._id2ref` What is the difference between the following two kinds of errors that ObjectSpace._id2ref returns?
0x... is recycled object (RangeError)

0x... is not id value (RangeError)

A: not id value means that there never was an object with that id.
recycled object means that there once was an object with that id, but it has been garbage collected.
Demo on Ruby 1.9.3/Ubuntu:
x = Object.new
id = x.object_id

puts "0x%x" % id
# => 0x4aef5e8

puts ObjectSpace._id2ref id
# => #<Object:0x95debd0>

x = nil

puts ObjectSpace._id2ref id
# => #<Object:0x95debd0>

GC.start

puts ObjectSpace._id2ref id
# => 0x4aef5e8 is recycled object (RangeError)

Note that the number in Object#to_s is not the object_id - according to the docs it is "an encoding of the object id".


text:
Q: Not able to shutdown Oracle Database ORA-01031 I am having trouble shutting down a local oracle database. I've googled the problem, and the SYSTEM user I am using is in the ora_dba domain, and I also noticed that I need the sqlnet.ora in my ORACLE_HOME/network/admin folder, but I do not have a network/admin folder in my oracle home. All I have is a middleware folder. I am installing all of this to be able to publish a BPEL process to a local weblogic instance, and this has taken me a little over two days just trying to get this all set up. I am starting to get a bit frustrated lol. Here's the error I am getting below:

A: In order to startup/shutdown the oracle instance you need extended privileges - Oracle database SYS privileges.
As soon as your Windows user DOMAIN\user has been granted group 'ora_dba', you are authorized on the OS-level to log into the database as user SYS.
C:\>sqlplus / as sysdba
SQL>show user
SQL>USER is "SYS"
SQL>shutdown immediate


text:
Q: Parse JS ACL - getPublicReadAccess for Parse.User.current() always returning false? I'm attempting to do the following in my view:
<option data-ng-selected="userACL.getPublicReadAccess()">Public</option>

and I can't seem to get the full ACL list for the Parse.User.current() - it always returns an ACL with read/write only for the current user. Here's the code from the controller (the project is in angularjs)
$scope.userACL = new Parse.ACL(Parse.User.current());
console.log($scope.userACL.toJSON());

the output of that toJSON returns an object with the current user id, and the properties of read: true, and write: true

but what I can't seem to get is the publicReadAccess for the user... which, I can see through the Parse dashboard to be public

I feel like I'm either going about this wrong, or misconstruing how the ACL should be used (in my mind, _User contains data that can be either public or private to the single user) Any help is much appreciated!

A: Of course, writing out the question helped me solve it!
The answer is by creating a new ACL object, it was assigned a new list (of just the _User object) in the constructor for that _User object as the documentation says it will
The simple solution is to use Parse.Object .getACL() to retrieve the existing ACL for the _User object facepalm


text:
Q: Static Qt program build in VS2013 - a lot of unresolved externals After nights trying to build Qt properly at last I made it with:
configure -static -debug-and-release -developer-build -mp -opengl desktop -platform win32-msvc2013 -no-webkit -qt-zlib
and
/MT, MTd flags in mkspecs\win32-msvc2013\qmake.conf
but it did not help me much.
I am using VS2013 Pro, with QT Add-in 1.2.3, and when I tried to compile add-in template I received 55 unresolved external errors, most of them was from OpenGL, so I added opengl32.lib to linker, and error number reduced to 42, but still most of them are from OpenGL. Libs like GLU32 or Qt5OpenGL did not helped me at all.
Here are few unresolved external symbols errors from linker:
_WSAAsyncSelect@16 referenced in function "private: void __thiscall QEventDispatcherWin32::createInternalHwnd(void)" (?createInternalHwnd@QEventDispatcherWin32@@AAEXXZ)
_glBindBuffer@8 referenced in function "public: bool __thiscall QOpenGLBuffer::bind(void)" (?bind@QOpenGLBuffer@@QAE_NXZ)
_glCompileShader@4 referenced in function "public: bool __thiscall QOpenGLShaderPrivate::compile(class QOpenGLShader *)" (?compile@QOpenGLShaderPrivate@@QAE_NPAVQOpenGLShader@@@Z)
_glUniform4fv@12 referenced in function "public: void __thiscall QOpenGLFunctions::glUniform4fv(int,int,float const *)" (?glUniform4fv@QOpenGLFunctions@@QAEXHHPBM@Z)

And for me its quite strange, cos those errors are from core gl lib, which is linked :
qtmain.lib
Qt5Core.lib
Qt5Gui.lib
Qt5Widgets.lib
opengl32.lib

Does anyone know how to fix it?

A: Can you please tell us which Qt version have you downloaded from the Qt website?
Also, you have to be careful because Qt is not bundle with openGL by default, you have to download the proper version (the one with openGL in the name obviously)
Hope it helps!

A: You could try out the following libraries:
imm32.lib
winmm.lib
Ws2_32.lib
qtharfbuzzng.lib
This worked for me: https://stackoverflow.com/a/27807379/4415923


text:
Q: R ggplot unresponsive dataset I need particular values to change with selection.
#server.R
bio <- read.csv('bio.csv')

bioSlice <- subset(bio, "Athlete" == "AA" & "Biomarker" == "B1")
h<-bio[,1]
i<-bio[,2]

shinyServer(function(input, output) {

 formulaText <- reactive({
  paste(input$Athlete, "~", input$Biomarker)
 })

 output$caption <- renderText({
   formulaText()
 })

output$bioPlot <- renderPlot({
d=data.frame(x1=c(1, h),x2=c(h, i))
print(ggplot() +
})

})

#ui.R
shinyUI(pageWithSidebar(

  # Application title
   headerPanel("Results"),

  sidebarPanel(
    selectInput("Athlete", "Athlete:",
                list("1" = "1",
                     "2" = "2")),

    selectInput("Biomarker", "Biomarker:",
                list("B1" = "B1",
                     "B2" = "B2"))
  ),

  mainPanel(
    h3(textOutput("caption")),
    plotOutput("bioPlot")

  )
))

My data.frame doesn't seem to like the way I've set the variables. Maybe I need to get it to start automatically at say h=bio[1,1], i=bio[1,2], etc. But how do I set this while making the code responsive to the users input?
I don't want to give away too much of my code, but if anyone has any ideas as to how to make the values react to the input, I'd be very grateful.

A: To get the plot to be reactive as you intend, you have to make the subsetting part to be reactive. It has to take the user input values (Athlete and Biomarker in your case) and use those values to subset the data before you plot it. Notice that your d=data.frame(...) statement is not reactive at all.
In your server.R, you have to add a reactive function:
  biomarkerSlice <- reactive({
    subset(biomarker.df, Athlete==input$Athlete & Biomarker==input$Biomarker)
  })

and call this reactive function using biomarkerSlice() when plotting. That way, the resulting plot will change with user input.
Your UI.R is fine. (I just added a tableOutput line to illustrate.) All the reactive elements above go into Server.R.
Here's a fully working version that I tested with some data dummy data.
UI.R
    #ui.R
    # Define UI for Blood Results application
    shinyUI(pageWithSidebar(

     headerPanel("Results"),

  sidebarPanel(
    selectInput("Athlete", "Athlete:",
                list("AA" = "AA",
                     "BB" = "BB",
                     "CC" = "CC",
                     "DD" = "DD",
                     "EE" = "EE")),

    selectInput("Biomarker", "Bio marker:",
                list("Creatinine" = "Creatinine",
                     "B2" = "B2",
                     "B3" = "B3",
                     "B4" = "B4"))
  ),

  mainPanel(
    h3(textOutput("caption")),
    tableOutput("biomarkerDataTable"),
    plotOutput("biomarkerPlot")

  )
))

Server.R
library(shiny)
library(ggplot2)
library(reshape2)

# dummy data
biomarker.df <- data.frame(Athlete=rep(c("AA","BB","CC","DD","EE"), 4),
                           Biomarker=rep(c("Creatinine","B2","B3","B4"), 5),
                           Outside = sample(50:70,20, replace=T),
                           Lower = sample(40:80,20, replace=T),
                           Value = sample(42:90,20, replace=T),
                           Higher = sample(60:110,20, replace=T))

shinyServer(function(input, output) {

  biomarkerSlice <- reactive({
    subset(biomarker.df, Athlete==input$Athlete & Biomarker==input$Biomarker)
  })

  # Compute the formula text in a reactive expression since it is
  # shared by the output$caption and output$Plot expressions
  formulaText <- reactive({
    paste(input$Athlete, "~", input$Biomarker)
  })

  # Return the formula text for printing as a caption
  output$caption <- renderText({
    formulaText()
  })

  #subset to the Ath and the BioMarker of interest
  output$biomarkerDataTable <- renderTable({
    biomarkerSlice()
  })

  # Generate a plot of the requested Athlete against requested Biomarker
  output$biomarkerPlot <- renderPlot({
    melted_df <- melt(biomarkerSlice())
    print(ggplot(melted_df, aes(x=variable, y=value, fill=variable))+
            geom_bar(stat="identity") +
            theme(axis.text.x  = element_text(vjust=0.5, size=20))
          )
  })

})

And that produces a reactive plot as you desire (Shown below). As you change the inputs, the plot changes.

Hope that helps you move forward.


text:
Q: Running Opengl program with CLion IDE I know this question has been asked already but the solutions provided really hasn't worked for me.
I want to run my OpenGL program via CLion IDE. I am able to run the same program via the terminal in Ubuntu using
$gcc progname.c -lglut -lGL -lGLU

but am unable to run the same in CLion
This is my CMakeLists.txt file

PS: I am using CLion in Ubuntu. Also there is no error in the program.

A: Clion uses CMake for project files, and CMake makes it easy to link libraries that are in the system paths using target_link_libraries, which you can use in your case as shown below, which can come after the add_executable line:
target_link_libraries(jarvis -lglut -lGL -lGLU)
The documentation for target_link_libraries is here:
https://cmake.org/cmake/help/v3.3/command/target_link_libraries.html

A: I have made it work in both Windows 10 and Linux (Ubuntu 16.04) after a lot of searching on Google. Apparently it's not so easy to find after all. So, I am gonna put an end to this problem now and here.
Here, I am going to show you how to configure the CMakeLists.txt file to compile a OpenGL program which is the main challenge here. I am assuming that you can write basic OpenGL programs and you have written a file named
'demoMain.cpp'.
For Windows
I am assuming you can setup OpenGL on windows. If you can't, there are plenty of tutorials on youtube and StackOverflow. After that, continue.
cmake_minimum_required(VERSION 3.10)
project(Graphics_Offline_1) # Your Project Name

set(CMAKE_CXX_STANDARD 11)

include_directories(OpenGL)
include_directories(OpenGL/include) # OpenGL/include has to contain the required OpenGL's .h files
include_directories(OpenGL/lib) # OpenGL/lib has to contain the required OpenGL's .lib files

# glut32.dll must be present in "project-directory/OpenGL/dll/"

add_custom_target(glutdlllib
    COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/OpenGL/dll/glut32.dll ${CMAKE_BINARY_DIR}
    )

# required .lib files to be copied into compiler's proper directory
set(OpenGlLibs glaux glu32 glui32 glut32 opengl32)

#These 3 lines are just linking and making executables

add_executable(demo demoMain.cpp)

target_link_libraries(demo ${OpenGlLibs})

add_dependencies(demo glutdlllib)

For Linux (Ubuntu 16.04)
It should work for other Ubuntu versions too. Linux has made it easier to use OpenGL than Windows.
cmake_minimum_required(VERSION 3.10) # common to every CLion project
project(OpenGLLinuxTest) # project name

set(OpenGlLinkers -lglut -lGLU -lGL) # setting all the Glut libraries as one variable.

################################################

add_executable(OpenGLLinuxTest1 main.cpp ) #common to all clion project
target_link_libraries(OpenGLLinuxTest1 ${OpenGlLinkers}) # linking opengl libraries to the project

#################################################

I am assuming that you can install OpenGL on Ubuntu. If you are facing problem with that,

follow this link -
  http://www.codebind.com/linux-tutorials/install-opengl-ubuntu-linux/ .
  If this is not working, follow this one -
  https://gist.github.com/shamiul94/a632f7ab94cf389e08efd7174335df1c


text:
Q: How's using FileAttributeKey.posixPermissions different from using stat -f %A? I'm trying to get the posix permissions of a file, but when I use the key FileAttributeKey.posixPermissions (originally NSFilePosixPermissions) to retrieve the numerical posix permissions value, it returned 511 (-r-x--x--x), but when I use stat -f %A /path/to/file in Terminal, it returned 777 (-rwxrwxrwx) which is the correct one (I used chmod 777 /path/to/file, so it should be 777 (-rwxrwxrwx)).
This is my code using FileAttributeKey.posixPermissions (Swift 4):
var numericalValue = "000"
if let attributes = try? FileManager.default.attributesOfItem(atPath: "/path/to/file") {
    if let posixPermissions = attributes[.posixPermissions] as? NSNumber {
        numericalValue = posixPermissions.stringValue
    }
}

I don't know what is going on, I'm wondering how is the value returned from FileAttributeKey.posixPermissions different from the output of stat -f %A /path/to/file or stat -x /path/to/file, can anyone please help me to figure out?

A: You need to display the result in octal:
if let attributes = try? FileManager.default.attributesOfItem(atPath: "/path/to/file") {
    if let posixPermissions = attributes[.posixPermissions] as? NSNumber {
        let octal = String(posixPermissions.intValue, radix: 8, uppercase: false)
        print(octal)
    }
}


text:
Q: Capture the eventId of a link in spring web flow Suppose I have link in the a page.For example hello.Once i click on hello it has to take to me a page.Before it take to new page I am trying to set some values using on-entry in main_flow.xml.
I do no how to how to capture the event when the link is get clicked.If it is get clicked the clicked event should be passed to flow handling file.
I know for a button i can capture the event using the action keyword.The same action value whatever i mentioned in the jsp file can be used in flow handler file.
So for a link how can I capture the event same as the button.


text:
Q: When is a good time to start thinking about scaling? I've been designing a site over the past couple days, and been doing some research into different aspects of scaling a site horizontally.  If things go as planned, in a few months (years?) I know I'd need to worry about scaling the site up and out, since the resources it would end up consuming would be huge.
So, this got me to thinking, when is the best time to start thinking about, and designing for, scalability?  If you start too early on, you could easily over complicate your design, and make it impossible to actually build. You could also get too caught up in the details, the architecture, whatever, and wind up getting nothing done.  Also, if you do get it working, but the site never takes off, you may have wasted a good chunk of extra effort.
On the other hand, you could be saving yourself a ton of effort down the road.  Designing it from the ground up to be big would make it much easier later on to let it grow big, with very little rewriting going on.
I know for what I'm working on, I've decided to make at least a few choices now on the side of scaling, but I'm not going to do a complete change of thinking to get it to scale completely.  Notably, I've redesigned my database from a conventional relational design to one similar to what was suggested on the Reddit site linked below, and I'm going to give memcache a try.
So, the basic question, when is a good time to start thinking or worrying about scaling, and what are some good designs, tips, etc. for when doing so?
A couple of things I've been reading, for those who are interested:
http://www.codinghorror.com/blog/2009/06/scaling-up-vs-scaling-out-hidden-costs.html
http://highscalability.com/blog/2010/5/17/7-lessons-learned-while-building-reddit-to-270-million-page.html
http://developer.yahoo.com/performance/rules.html

A: Under a certain point of view, scaling techniques are quite accepted and consolidated. So instead on relying on web links/articles, I'd read books on the topic before starting the probject.
I suggest:

*

*"Scalable Internet Architectures" - http://www.amazon.com/Scalable-Internet-Architectures-Theo-Schlossnagle/dp/067232699X/ref=sr_1_1?ie=UTF8&s=books&qid=1274462743&sr=8-1

*"The Art of Scalability" - http://www.amazon.com/Art-Scalability-Architecture-Organizations-Enterprise/dp/0137030428/ref=sr_1_3?ie=UTF8&s=books&qid=1274462743&sr=8-3

*"Art of capacity Planning" - http://www.amazon.com/Art-Capacity-Planning-Scaling-Resources/dp/0596518579/ref=pd_bxgy_b_text_b

A: A well-though out, sensible architecture should allow you to scale up later without requiring excessive resources to implement.  This should be thought about from the very beginning of the project.
Nowadays there are very good architectures and enterprise design patterns you can draw from (Rails, MVC, Spring, etc.) that allow you to develop software on a well-established and well-understood foundation that provides the necessary mechanisms for scaling up.


text:
Q: What has to be done to resolve 80040154 Class not registered execption I am facing the following error only when i try to run the project on a target machine

[ERROR] ExecuteTestScriptsOnSAP_GUI: Retrieving the COM class factory
  for compo   nent with CLSID {B90F32AD-859E-4EDD-BFAE-C9216849520C}
  failed due to the foll   owing error: 80040154 Class not registered
  (Exception from HRESULT: 0x8004015   4 (REGDB_E_CLASSNOTREG)).

It seems to work fine on my development machine.
I am trying to launch SAP gui 7.40 from my project and it has a reference to Interop.SAPFEWSELib.dll
The above .dll file was built when sapfewse.ocx was first added as a dependency to the project.
Can anyone please guide me as to what can be done to resolve this issue?

A: I can't comment yet and so can only respond in an answer.
It could be that that the control sapfewse.ocx that you are consuming via Interop.SAPFEWSELib.dll is not registered on your target machine.
Check the registry HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID  and locate the class for B90F32AD-859E-4EDD-BFAE-C9216849520C on your dev machine. The InProcServer32 key should tell you the path of the registered component. Ensure that this component is deployed and registered on your target machine.
Hope that points you in the right direction.

A: If you're on a 32bit OS machine then
"C:\Windows\System32\regsvr32.exe" /i "Path to OCX"
Or 64 bit then "C:\Windows\SysWOW64\regsvr32.exe"
If you double click the .ocx on the target machine, it should prompt you to select a program to complete the action with. Browse to the relevant regsvr32.exe and it will then register it for you.
But it looks as if your ocx comes from a third party SDK? as it resides in c:\program files (x86)\sap\frontend\sapgui\ on your dev machine. Have you installed this SDK on your target machine? If not.. do so and this will install and register the component for you.


text:
Q: ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=2 I have an input data(X_train) with data shape (180,11,161)
180-> no. of subjects   11->no. of electrodes   161->no. of samples
I used the following code for the input layer:
model.add(Conv2D(64,(3,3),input shape=(180,11,161)))

But I am getting the following error:
ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=2

What's the mistake? If Conv2D shouldn't be used, what else should I use?Any help is appreciated


text:
Q: python import error: partially initialized module 'aiohttp' has no attribute I have gotten a error on one of my python scripts and I have no idea what it is and google has been no help. what is this error and how could I fix it?
code snippet:
import discord
import os
import asyncio
from discord.ext import commands
from discord.ext.commands import Bot
from discord.utils import get
import requests, random, replit
import json

intents = discord.Intents(members=True, messages = True, guilds=True,)
BOT_PREFIX = ("!")
client = commands.Bot(command_prefix=BOT_PREFIX, intents = intents)
bot = commands.Bot(command_prefix=BOT_PREFIX, intents = intents)

error:
Traceback (most recent call last):
  File "C:/Users/Parents/Desktop/Documents/python/json.py", line 3, in <module>
    import discord
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\__init__.py", line 25, in <module>
    from .client import Client
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 33, in <module>
    import aiohttp
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\__init__.py", line 6, in <module>
    from .client import (
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 6, in <module>
    import json
  File "C:/Users/Parents/Desktop/Documents/python\json.py", line 10, in <module>
    from discord.ext import commands
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\__init__.py", line 13, in <module>
    from .bot import Bot, AutoShardedBot, when_mentioned, when_mentioned_or
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 37, in <module>
    from .core import GroupMixin
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 36, in <module>
    from .cooldowns import Cooldown, BucketType, CooldownMapping, MaxConcurrency
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\cooldowns.py", line 32, in <module>
    from ...abc import PrivateChannel
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 40, in <module>
    from .voice_client import VoiceClient, VoiceProtocol
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\voice_client.py", line 50, in <module>
    from .gateway import *
  File "C:\Users\Parents\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\gateway.py", line 214, in <module>
    class DiscordClientWebSocketResponse(aiohttp.ClientWebSocketResponse):
AttributeError: partially initialized module 'aiohttp' has no attribute 'ClientWebSocketResponse' (most likely due to a circular import)


text:
Q: How to update with strong parameter? What I want to do
My application has Order model and List model.
List model is Order's child.
Order has total column.
List has price and quantity columns.
I want to update the total of the Order by adding the subtotals of each lists line together.
What I did
Here is my orders_controller.
def update
    @order = Order.find(params[:id])
    @order.total = @order.total_price
    if @order.update(order_params)
      redirect_to orders_path, notice: 'The order has been updated.'
    else
      render :edit
    end
  end

Here is my order.rb(model)
  def total_price
    lists.to_a.sum { |list| list.subtotal }
  end

To update total price, I set @order.total_price to @order.total.
But as you see, it updated with strong parameter(order_params).
I couldn't resolve how to update with total price.
What should I do?
Environments

*

*ruby2.7.2

*rails6

A: There are many ways to do it.
# One is just to do it on separate lines.
@order.update(total: @order.total_price)
@order.update(order_params)

# Merge with order_params
@order.update(order_params.merge(total: @order.total_price))

Finally the most Rails way is probably to use a before_save on the model
# Order.rb
before_save do
  total = lists.to_a.sum { |list| list.subtotal }
end

# orders_controller.rb
# just to
@order.update(order_params)


text:
Q: Getting ERROR [[/Allies]] Exception starting filter struts2 Unable to load configuration I am running an application developed using Struts2,Hibernate in myeclipse. when i am deploying the application in liferay-portal on JBoss server, it is giving following exception:-
ERROR [[/allies]] Exception starting filter struts2
Unable to load configuration. - bean - vfszip:/K:/Sam/liferay-portal-6.0-ee-sp2/jboss-5.1.0/server/default/deploy/allies.war/WEB-INF/lib/struts2-core-2.1.6.jar/struts-default.xml:46:178
    at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:58)
    at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:360)
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:403)
    at org.apache.struts2.dispatcher.FilterDispatcher.init(FilterDispatcher.java:190)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:234)
    at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:332)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:90)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3783)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4413)
    at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)
    at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
    at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
    at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
    at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
    at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
    at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
    at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
    at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
    at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
    at $Proxy38.start(Unknown Source)
    at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
    at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
    at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
    at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
    at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
    at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
    at org.jboss.system.ServiceController.doChange(ServiceController.java:688)
    at org.jboss.system.ServiceController.start(ServiceController.java:460)
    at org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
    at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
    at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
    at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
    at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
    at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
    at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
    at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
    at org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)
    at org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)
    at org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:361)
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
    at org.jboss.system.server.profileservice.repository.AbstractProfileService.activateProfile(AbstractProfileService.java:306)
    at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:271)
    at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)
    at org.jboss.Main.boot(Main.java:221)
    at org.jboss.Main$1.run(Main.java:556)
    at java.lang.Thread.run(Unknown Source)
Caused by: Unable to load bean: type:org.apache.struts2.dispatcher.multipart.MultiPartRequest class:org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - bean - vfszip:/K:/sam/liferay-portal-6.0-ee-sp2/jboss-5.1.0/server/default/deploy/allies.war/WEB-INF/lib/struts2-core-2.1.6.jar/struts-default.xml:46:178
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.register(XmlConfigurationProvider.java:222)
    at org.apache.struts2.config.StrutsXmlConfigurationProvider.register(StrutsXmlConfigurationProvider.java:101)
    at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:165)
    at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:55)
    ... 75 more

i have added following jars in WEB-INF\lib path:-
struts2-core-2.1.6.jar,xwork-2.1.2.jar,xwork-core-2.1.6.jar.
Please help me to solve this issue.
thanks


text:
Q: Android ExpandableListView notifyDataSetChanged I have got problem with my code in Android application.
I have expandable list view with some data.
Periodically after 2 seconds, I use command NotifyDataSetChanged to update my all data.
The problem is that I have a seekbar and if I change progress then after this 2 seconds, the data was updated and the progress stops changing.
I don't know what I can do to update only row in expandable list view some row but not all.
    final Handler handler = new Handler();
    timer3 = new Timer();
    czyUruchomionoTimer=true;
    TimerTask doAsynchronousTask = new TimerTask() {

        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {

    exAdpt.notifyDataSetChanged();

                }
            });
        }
    };
    timer3.schedule(doAsynchronousTask, 100, 2000);

  }

Here is code of my Adapter:
   package akme.akmewiz_new;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ListAdapter_Exp extends BaseExpandableListAdapter {

    private List<List_KategoriaObiekty> catList;
    private Context ctx;
    private LayoutInflater inflater;
    private ExpandableListView list;
    private String numerIP;
    int tempMax = 35;
    int tempMin = 10;
    private String numerID;
    Boolean wejscie = false;
    int max = (tempMax-tempMin)*2 ;
    final private static int DIALOG_LOGIN = 1;

    public ListAdapter_Exp(List<List_KategoriaObiekty> catList, Context ctx, String ip, String ID, Boolean wejscie) {

        this.catList = catList;
        this.ctx = ctx;
        this.inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.numerIP= ip;
        this.numerID = ID;
        this.wejscie=wejscie;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return catList.get(groupPosition).getItemList();
    }
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        Object obj =  catList.get(Integer.valueOf(numerID)).getItemList().get(groupPosition+2);
        Lista_menu menus = (Lista_menu) obj;
        return menus.getTabelaNazwaItem(childPosition).hashCode();
    }
    @Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {

        ViewHolder holder;
        final int tempgroupPos = groupPosition;
        View v = convertView;
        Object obj =  catList.get(Integer.valueOf(numerID)).getItemList().get(groupPosition+2);
        Lista_menu menus = (Lista_menu) obj;

        if(true){
            holder = new ViewHolder();
            v = inflater.inflate(getLayoutId(ctx,"list_exp_"+menus.getTabelaSposobPrezentacji(childPosition)),null);
            Log.d("TAGS","list_exp_"+menus.getTabelaSposobPrezentacji(childPosition));

            list = (ExpandableListView) parent.findViewById(R.id.listExp);
            if(menus.getTabelaSposobPrezentacji(childPosition).equals("0")) {
                holder.item_nazwa = (TextView) v.findViewById(R.id.item_0_nazwa);
                holder.item_wartosc = (TextView) v.findViewById(R.id.item_0_wartosc);
                Log.d("TAGS","tworze0 "+menus.getTabelaSposobPrezentacji(childPosition));
            }
            if(menus.getTabelaSposobPrezentacji(childPosition).equals("1")) {
                holder.item_nazwa = (TextView) v.findViewById(R.id.item_0_nazwa);
                holder.Seek = (SeekBar) v.findViewById(R.id.seekTemp);
                holder.Lab1 = (TextView) v.findViewById(R.id.tvLabel1);
                holder.Lab3 = (TextView) v.findViewById(R.id.tvLabel3);
                holder.Seek.setTag(childPosition + 1);
                Log.d("TAGS","tworze1 "+menus.getTabelaSposobPrezentacji(childPosition));
            }

            v.setTag(holder);
        }else{
            holder = (ViewHolder) v.getTag();
        }

        if(menus.getTabelaSposobPrezentacji(childPosition).equals("0")){
            holder.item_nazwa.setText(menus.getTabelaNazwaItem(childPosition));
            holder.item_wartosc.setText(menus.getTabelaWartoscItem(childPosition));
            Log.d("TAGS","wpisuje "+menus.getTabelaSposobPrezentacji(childPosition));
        }
        if(menus.getTabelaSposobPrezentacji(childPosition).equals("1")){
            holder.item_nazwa.setText(menus.getTabelaNazwaItem(childPosition));
            holder.Lab1.setText("10.0" + " \u2103");
            holder.Lab3.setText("35.0" + " \u2103");
            holder.Seek.setMax(max);
            Log.d("TAGS","wpisuje "+menus.getTabelaSposobPrezentacji(childPosition));

            holder.Seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    notifyDataSetChanged();
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress,
                                              boolean fromUser) {

                    float przelicznik = (float) ((progress / 2.0) + 10.0);
                    View view = (View) seekBar.getParent();
                    if (view != null) {
                        TextView tvProgress2 = (TextView) view.findViewById(R.id.tvLabel2);
                        TextView tvProgress1 = (TextView) view.findViewById(R.id.tvLabel1);
                        TextView tvProgress3 = (TextView) view.findViewById(R.id.tvLabel3);

                        tvProgress1.setText(Float.toString(tempMin) + " \u2103");
                        tvProgress2.setText(Float.toString(przelicznik) + " \u2103");
                        tvProgress3.setText(Float.toString(tempMax) + " \u2103");
                    }

                    Object obj =  catList.get(Integer.valueOf(numerID)).getItemList().get(tempgroupPos+2);
                    Lista_menu menus = (Lista_menu) obj;

                    String ustaw = Float.valueOf(przelicznik).toString();
                    menus.setTabelaWartoscItem2(ustaw,childPosition);

                }
            });

            String str1 = menus.getTabelaWartoscItem2(childPosition);

            if(wejscie){
                str1 = menus.getTabelaWartoscItem(childPosition);
                wejscie=false;
            }

            int ustaw1 =(int)(( ( ( (Float.parseFloat(str1.replaceAll("\\D+","")))/10)*2)-20));
            holder.Seek.setProgress(ustaw1);

        }

        return v;

        }
    @Override
    public int getChildrenCount(int groupPosition) {
        Object obj =  catList.get(Integer.valueOf(numerID)).getItemList().get(groupPosition+2);
        Lista_menu menus = (Lista_menu) obj;
        return menus.ilosc();
    }
    @Override
    public Object getGroup(int groupPosition) {

        return catList.get(groupPosition+2);
    }
    @Override

    public int getGroupCount() {
        int ilosc = catList.get(Integer.valueOf(numerID)).getItemList().size();
        return ilosc-2;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return catList.get(Integer.valueOf(numerID)).hashCode();
    }
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        GroupViewHolder holder;
        View v = convertView;

        if(v==null || !isExpanded || isExpanded){
            holder = new GroupViewHolder();

            v = inflater.inflate(R.layout.list_group_item_exp,null);
            list = (ExpandableListView) parent.findViewById(R.id.listExp);

            holder.groupName = (TextView) v.findViewById(R.id.groupName);
            holder.groupImage = (ImageView) v.findViewById(R.id.groupImage);
            holder.groupIndicator = (ImageView) v.findViewById(R.id.imageView5);
            holder.groupImage.setTag(groupPosition + 11);
            list.setDividerHeight(8);

        v.setTag(holder);
        }else{
            holder = (GroupViewHolder) v.getTag();

        }

        if(isExpanded){
            holder.groupIndicator.setImageResource(R.mipmap.arrow_g);

        }else{
            holder.groupIndicator.setImageResource(R.mipmap.arrow_d);
        }

        holder.groupName.setTextColor(Color.parseColor("#e3e9e4"));

        list.setDividerHeight(8);

        List<Object> lista = catList.get(Integer.valueOf(numerID)).getItemList();
        Object obj = lista.get(groupPosition + 2);

        v.setBackgroundResource(R.drawable.lista_obiekty_niebieski);

        Lista_menu menu = (Lista_menu) obj;
        String obraz = menu.getObrazek();

        holder.groupImage.setImageResource(getImageId(ctx,"ico_" + obraz));
        holder.groupName.setText(menu.getNazwaGrupy());

        return v;

    }

    @Override
    public boolean hasStableIds() {
        return true;
    }
    public static int getImageId(Context context, String imageName) {
        return context.getResources().getIdentifier("mipmap/" + imageName, null, context.getPackageName());
    }
    public static int getLayoutId(Context context, String name) {
        return context.getResources().getIdentifier("layout/" + name, null, context.getPackageName());
    }
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    class ViewHolder {
        TextView item_nazwa, item_wartosc, Lab1, Lab3, Lab2;
        SeekBar Seek;
    }

    class GroupViewHolder {

        TextView groupName;
        ImageView groupImage, groupIndicator;
    }

}


text:
Q: NSTableHeaderView Resizing Makes Table Rows Move Down I've created a subclass of NSScrollView which is set as the class of a scroll view with table view in IB.  I increased the height of the table's header view and added a label to act as the title for the table view.  The problem is that the table rows start below the column headers by an amount that is equal to the amount that I made the header view taller (so the column titles appear in the middle of the new taller header view).

I've tried changing the origin or size of the table, the table's clip view, the header view, and its clip view -- none of this changes anything except for the size of the header view.  This is the code I used to make the custom header view:
-(void)awakeFromNib {
    //self is a subclass of NSScrollView enclosing an NSTableView
    NSClipView *tableClip = [self.subviews objectAtIndex:0];
    NSClipView *headerClip = [self.subviews objectAtIndex:3];
    NSTableHeaderView *header = [[[self.subviews objectAtIndex:3] subviews]lastObject];
    NSTableView *table = [[[self.subviews objectAtIndex:0] subviews]lastObject];
    NSLog(@"%@  %@  %@  %@",tableClip,headerClip,header,table);

    [header setFrameSize:NSMakeSize(header.frame.size.width, header.frame.size.height+60)];//HeaderView Frame
    NSTextField *titleLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 5, header.frame.size.width,22)];
    titleLabel.selectable = NO;
    titleLabel.font = [NSFont systemFontOfSize:16];
    titleLabel.alignment = NSCenterTextAlignment;
    titleLabel.bordered = NO;
    titleLabel.stringValue = @"This is my title";
    [header addSubview:titleLabel];
}


text:
Q: onDeviceReady never gets called in Cordova app I am just trying to run a simple page within the inappbrowser plugin. I am running Cordova 5.0, and the plugin is version 1.0. I run the app with the splashscreen plugin and it seems to work fin. The default splashscreen runs when the app start but the in app browser plugin does not seem to work. Here is my code below:
<!DOCTYPE html>

<html>
    <head>

        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>

    <script type="text/javascript" src="../platforms/android/assets/www/cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

// Wait for Cordova to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}

// Cordova is ready
//
function onDeviceReady() {
alert("dfs");

var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
ref.addEventListener('exit', function(event) { alert(event.type); });

}
</script>

</head>

    <body onload="onLoad()">
    </body>
</html>

The cordova.js file is properly linked I assume since that is the correct path. I have also uninstalled and installed the plugin back, created a new project and none of them seem to solve my problem. I am testing it on my Android 5.0 smartphone and Android 4.1 emulator. Any ideas?

A: Just include corodova.js as follows
<script type="text/javascript" src="cordova.js"></script>

And use ripple emulator [which is a google plugin] and you will see onDeviceReady() is fired. Acutually this works well for me. Please try it


text:
Q: Need clarification on delegates in iOS As per Apple documentation:

Delegation is a simple and powerful pattern in which one object in a
  program acts on behalf of, or in coordination with, another object.
  The delegating object keeps a reference to the other object—the
  delegate—and at the appropriate time sends a message to it.

Please clarify.  In the case of UIAlertView, is UIAlertView is delegating object?

A: In the case of UIAlertView, yes, UIAlertView is a delegating object and whatever its delegate property points to is its delegate.
For everything in Apple's built-in frameworks, the delegating object will typically have a property called delegate.  The delegating object is the one which has this property (which is where it holds the reference to its delegate).  The delegate is the object to which the delegate property points.
In addition to this, some of Apple's classes, such as UITableView (there are plenty of others too), will additionally have a datasource property.  UITableView holds the same sort of relationship with its datasource as it does with its delegate.
Technically speaking, in both cases, UITableView is the delegating object, and both the delegate and the datasource (which can point to different objects) point to the "delegate" objects.
Realistically speaking, we would never refer to UITableView's datasource object as being its "delegate"--we'd call it its datasource.  This prevents confusion between which object is the datasource and which object is the delegate.
Also, keep in mind that just because something is a delegating object doesn't mean it can't also be something else's delegate.


text:
Q: How can I convert a multi-line batch file statement into Powershell? I'm in the process of converting an old batch file to Powershell.  In the batch file, the SET command is used to declare and set multiple variables, and then an executable is called that uses those variables, along with additional flags.  How would I do this in Powershell?
Batch File code excerpt:
SET VAR1=VAL1
SET VAR2=VAL2
SET VAR3=VAL3
SET VAR4=VAL4
%DIRECTORY%\%SUBDIR%\EXECUTABLE.EXE -FLAG1 -FLAG2 -FLAG3

I first attempted to declare the Powershell variables and call the exe using Start-Process, but the executable is looking for specific variable names. I'm not sure if those variables can be seen by the exe in this scenario, but it doesn't work.
  $VAR1 = VAL1
  $VAR2 = VAL2
  $VAR3 = VAL3
Start-Process "$DRIVE\DIR\EXECUTABLE.exe -FLAG1 -FLAG2 -FLAG3"

I've also unsuccessfully attempted passing the multiple line command to the command shell:
$Command =  "CMD.exe /C
             SET VAR1=VAL1
             SET VAR2=VAL2
             SET VAR3=VAL3
             SET VAR4=VAL4
             $DRIVE\$DIR\EXECUTABLE.exe -FLAG1 -FLAG2 -FLAG3
Invoke-Expression $Command

Note** The variables have to be set on multiple lines, even when I run the exe from a DOS prompt.  Using the "&" (Batch) or ";" (Powershell) and passing all variables on one line doesn't work.

A: *

*For external programs (child processes) to see variables, they must be environment variables: use $env:VAR1 = 'VAL1' rather than $VAR1 = 'VAL1' - also note how the values must be quoted.

*

*In cmd.exe (batch files), all variables are invariably also environment variables; in PowerShell, regular variables such as $VAR1 are visible only to the PowerShell session itself.

*Do not use Start-Process to invoke external console applications, invoke them directly (synchronously, with standard streams connected to PowerShell's streams), using &, if the executable name/path is quoted and/or contains variable references; do not quote the command line as a whole; specify and - if necessary - quote the executable name/path and arguments individually.
Similarly, Invoke-Expression should generally be avoided.
Therefore:
  $env:VAR1 = 'VAL1'
  $env:VAR2 = 'VAL2'
  $env:VAR3 = 'VAL3'
  & "$DRIVE\DIR\EXECUTABLE.exe" -FLAG1 -FLAG2 -FLAG3


text:
Q: minus query in sql developer I have two database connections in sql developer active lets say DB1 and DB2. I am working on ETL validation. So I want to check if data from Table1 of DB1 is populated correctly in Table2 of DB2.
To access tables from this two connections how can I write a query?
Any help on this will be helpful

A: There are common ways to validate if the ETL is correct:

*

*You can run 2 queries to calculate the line counts separately against to Table1@DB1 and Table2@DB2, and compare the line counts between them.

*Or perform some aggregate functions, such as sum(), avg()...etc on tables in DB1/DB2.


text:
Q: Drawing with request animation framemaximum callstack exceeded? I am making my own little canvas library because I have time to kill and am trying to animate my canvas objects, the method currently looks like so;
proto.update = function () {

    for (var i = 0; i < this.objects.length; ++i) {

        this.objects[i].draw(this.context);
    }

    var self = this;

    requestAnimationFrame(self.update());
};

I have not use requestAnimationFrame before and I get an error saying maximum callstack exceeded.
I followed this tutorial http://creativejs.com/resources/requestanimationframe/ and am quite sure I have made no mistakes.
What did I do wrong?

A: The callback parameter passed to requestAnimationFrame should be a reference to a function to call when it's time for the next repaint (see documentation here). Your error is that you have included parenthesis after the function name which means it executes immediately causing a recursive loop.
Try updating your code as follows:
proto.update = function () {

    for (var i = 0; i < this.objects.length; ++i) {

        this.objects[i].draw(this.context);
    }

    var self = this;

    // Pass the function reference don't call it
    requestAnimationFrame(self.update);
};


text:
Q: How do I avoid using !important? I am trying to make my website responsive. However, when I use another media query, a lot of things won't work. For example:
(Normal CSS)
div#divName
{
    font-size:1em;
}

(Media query code)
@media screen and (max-width: 320px)
{
    div#divName
    {
        font-size:.5em;
    }
}

This doesn't work. It only works when I use "!important" behind it. But I don't know if that is correct or "wrong". Could anyone tell me how I can fix this?

A: All !important does is increase specificity. To avoid using !important, all you need to do is increase specificity.
In your case, both of your selectors have identical specificity. The issue is most likely caused by your media query being placed before your "Normal CSS", and thus getting overridden.

*

*If they're in the same CSS file, ensure your "Normal CSS" is placed before your media query.

*If they're in different CSS files, ensure the file containing your media query is included in your HTML document after your "Normal CSS".

A: make sure your CSS rules that you want to override loads after.
in your case
div#divName
{
    font-size:1em;
}

should be loaded first and after that:
@media screen and (max-width: 320px)
{
    div#divName
    {
        font-size:.5em;
    }
}

you want to have two separated files style.css and responsive.css and include them in following order:
<link href="style.css" rel="stylesheet" />
<link href="responsive.css" rel="stylesheet" />


text:
Q: How to get most repeate item on Multidimensional Array Good day, Im trying to Get the most repeated inside a foreach loop on php. Each array is a cycle of the loop. I need to get the id and name of the most repeated item, in this example is jake.
This is the loop:
    foreach ($json[$key]['data'] as $user){
      var_dump($user);
    }

and the output is:
    array(2) {
      ["id"]=>
      string(4) "7032"
      ["name"]=>
      string(4) "Jake"
    }
    array(2) {
      ["id"]=>
      string(4) "1021"
      ["name"]=>
      string(3) "Ana"
    }
    array(2) {
      ["id"]=>
      string(4) "2058"
      ["name"]=>
      string(4) "John"
    }
    array(2) {
      ["id"]=>
      string(4) "7032"
      ["name"]=>
      string(4) "Jake"
    }

I need the output to be:
    $repeated = array(2) {
      ["id"]=>
      string(4) "7032"
      ["name"]=>
      string(4) "Jake"
    }

Thanks in advance for all your answers.

A: You don't have to use an explicit loop here:
$counts = array_count_values(array_map(function ($user) {
    ksort($user);
    return json_encode($user);
}, $users));

arsort($counts);

$result = json_decode(key($counts), true);

Basically, we map array elements to JSON representations. This is done with array_map. And it is done because array_count_values can count only strings or integers. Pay attention that before using json_encode we use ksort. This is needed in case user data is the same but have a different order.
Then we sort descending preserving array keys with arsort.
Finally, we get the first key with key and decode it get the original array element with json_decode.
Here is working demo.

A: try this step to remove the duplicates from your array,
$repeated  = array_map("unserialize", array_unique(array_map("serialize", $repeated)));


text:
Q: Unit test Angular directive within directive I'm having a real hard time running a karma unit test over an angularjs directive. Here's my setup:
var scope, ele;
    var template = '

';

    beforeEach(function () {
        // Load directive's module
        module('dashboard');
        module('templates-dev');

        // Load mock services/data (overriding real implementation)
        module(function($provide) {
            $provide.value("MockWidgetData", new MockWidgetData());
        });

        // Construct services/data to be available
        // inside each testing block.
        inject(function($rootScope, $compile, MockWidgetData) {
            // Create a fresh scope
            scope = $rootScope.$new();
            ele = angular.element(template);

            // Fill that scope with mock data
            scope.config = MockWidgetData.config;
            scope.data = MockWidgetData.data;

            // Compile the element and attach our scope
            $compile(ele)(scope);

            // Digest the scope to trigger a scope update
            // and attach our directive's link function
            scope.$digest();
        });
    });

My directive passes 'data' and 'config' objects to its children, which happen to be other directives. The directive itself uses a templateUrl, which is why I provide the module(templates-dev): an html2js pre-compiled, angular-modularized, $templateCache'd version of my templates. Here's a sample of my directive's templateUrl:

        <button id="my-btn" ng-click="doSomething('parameter')"></button>

Here's a sample of my directive:
angular.module('dashboard').directive('myDirective', function() {
    return {
        restrict: 'A',
        templateUrl: 'my-dir-template.html',
        scope: { //
            data: '=',
            config: '='
        },
        replace: true,
        link: function(scope, element, attrs) {

            scope.someFunc() = { ... },
            scope.someFunc1() = { ... },

        });

Problem:

*

*After $compile(ele)(scope), a .log() of the element shows the entire
    DOM, including all sorts of angular.js directives and other strange
    information. I would expect to see my directive's test template
    mashed together with the above templateUrl.

*A .log() of the scope shows the complete data and config objects, with their expected values. It also shows the functions available inside of my directive's link function, as one would expect. However, inside my test blocks, it's as if the scope object is emptied... I cannot access any of my directive's functions (they all return undefined).

*I am able to capture some elements of my directive's html via ele.find("#my-btn").eq(0), but none of the normal functions work (.click(), etc.).

What am I doing wrong? Is there something wrong with the compile process? Am I structuring the test wrong? Should I try to remove the link function and replace it with a Controller? My scopes just aren't lining up, and I've been failing at this for two days now... kind of annoying.

After closer inspection... It looks like I can scope.$digest() before $compile(ele)(scope), which will correctly propagate "data" and "config" objects to the child scope. However, my scope then loses access to the functions defined in my directive's link.

A: You should call scope.$digest() after $compile(ele)(scope). Digest is necessary to proceed compilation of directive. Your directive has an isolated scope, that's why you can't access it functions. To get them you should try this:
var elScope = element.isolateScope();
here you'l got your elScope.someFunc();
Check this example of unit testing directives:
http://best-web-creation.com/articles/view/id/angular-js-unit-test-directive?lang=en


text:
Q: Not able to test route with prefixes with Laravel 4 I am trying to test the routing mechanism of my app (which is a Laravel PHP App) that was based on the documentation (http://laravel.com/docs/routing#route-prefixing). The case is: We are trying to handle the app localisation based on the route, for example:
www.example.com/en/something -> Should use EN as language,
www.example.com/es/something -> Should use ES as language,
www.example.com/de/something -> Should use DE as language.

We accomplished the behaviour described before by using prefixes and it works perfect. The thing is that I am not able to write tests to test this behaviour. I did a little bit of research, and I found this third party library (https://github.com/mcamara/laravel-localization/blob/master/tests/LocalizerTests.php), that uses a similar approach, and I think it might help you understand which is the situation.
If you take a look in there, he is not testing the scenario that I want to test (I mean, with the locale code on the path).Btw: I've already turned on the filters with Route::enableFilters() and it does not work :(
Thanks a lot

A: If you use route inside the group.
Route::group(array('domain' => {account}.'.$domain), function()
{
    Route::get('myproduct/en/list', 'HomeController@showWelcome');
});

then try this.
  public function testBasicExample() {
    $crawler = $this->client->request('GET', 'http://subdomain.domain.local/myproduct/en/list');
$this->assertTrue($this->client->getResponse()->isOk());
    }