text:
Q: Setting state causes a UI lag in React I have a react app that renders a list of cards in a container widget. The container widget has a useEffect where we subscribe to an observable and update the array that is then used to render the cards inside the component. Each time any of the cards change, the observable emits new values resulting in creating of the array all over again and thus all the cards are re-rendered. However this re-render causes a noticeable UI lag.
Here is the stripped down version of code from the container component.
const obsRef = useRef<Subscription>(null);
const [apiResArray, setApiResArray] = useState([]);

useEffect(() => {

    if(obsRef.current) obsRef.current.unsubscribe();

    const mySubscription = myObservable$(changingValue)
    .subscribe((val) => {
        setApiResArray(val.apiArray);
    });

    obsRef.current = mySubscription;

    return () => {
      obsRef.current && obsRef.current.unsubscribe();
    };

}, [changingValue])

return (
    <CardWrapper $showMenu={showMenu}>
        { apiResArray.map((res, resIndex) => {
            return (
                <Card
                    data={{
                        // a json object with props
                    }}
                    key={res?.hKey}
                />
            );
        })}
    </CardWrapper>
);

The Card component here simply renders the content based on props passed to it. I know that since data is an Object, referential equality may fail and I have tried memoizing the component but even that does not help.
There is a lot more to these components but posting all the code won't make sense. I wish to understand what possibly might be causing the list re-render to be such a heavy operation that the whole UI gets stuck for a second or two. The array contains around only 100 objects or so. It happens whenever changingValue changes. I can share more information as required.
Any suggestions on improving the performance are highly appreciated.

A: React will mount and unmount the component in DEV mode to validate effect cleaner and any side effect.
I'm concerned about that subscribe and unsubscribe in your effect.
If you want changingValue to be defined why not just wrap it inside an if statement ?
if (changingValue) {
    const mySubscription = myObservable$(changingValue)
    .subscribe((val) => {
        setApiResArray(val.apiArray);
    });

    obsRef.current = mySubscription;
}

Another observation is at render of items
<Card
  data={
    {
      // a json object with props
    }
  }
  key={res?.hKey} // Why is this a falsy value ?
/>

Falsy value can make key prop change those re-rendering the component, one with React internal key value and another with your implementation value


text:
Q: Why is a PHP script waiting "to finish script" before any echo/output? Considering a simple script
<?php
echo "hi";
foreach ($_GET['arr'] as $a)
{
 echo $a ."
";
}
echo "
Masel tov
";
foreach ($_GET['arr2'] as $a)
{
 echo $a ."
";
}

i expect the script to echo continuously. Instead the script does echo all-at-once when finished. Even the first "hi" gets echoed after 1 minute when the script finishes.
Is there a setting to prevent this from happen or why is that so?

A: Depending on your config, output is cached until completion. You can force a flush with either ob_flush() or flush(). Sadly many modern browser also dont update until page load is complete, no matter how often you flush.

*

*flush http://php.net/manual/en/function.flush.php

*ob_flush http://php.net/manual/en/function.ob-flush.php
Configuration Settings for PHP's output buffering.
http://www.php.net/manual/en/outcontrol.configuration.php

A: There is a function ob_implicit_flush that can be used to enable/disable automatic flushing after each output call. But have a look at the comments on the PHP manual before using it.

A: Check with this
if (ob_get_level() == 0)
{
    ob_start();
}
for ($i = 1; $i<=10; $i++){
        echo "
 Task {$i} processing ";
        ob_flush();
        flush();
        sleep(1);
}
echo "
 All tasks finished";
ob_end_flush();

A: If you want displaying the items one by one and keep clean code that works with every server setup,  you might consider using ajax. I don't like flushing the buffer unless there are no other options to accomplish the task.
If your project isn't a webproject you might consider running your code in the php console (command line) to receive immediate output.

A: PHP sends, as you noticed, all data at once (the moment the script has finished) - you search for something like this http://de1.php.net/manual/de/function.ob-get-contents.php :
<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert NSURL to String in Swift How do you convert an NSURL to a String in Swift?
The following:
var directoryURL: NSURL
var urlString: String = nsurlObject as String

Throws the error:

Cannot convert value of type 'NSURL' to type 'String' in coercion

A: It turns out there are properties of NSURL you can access (see Swift Reference):
var directoryURL: NSURL
var urlString: String = directoryURL.absoluteString
// OR
var urlString: String = directoryURL.relativeString
// OR
var urlString: String = directoryURL.relativePath
// OR
var urlString: String = directoryURL.path
// etc.


text:
Q: Improve update performance in oracle I've generated two temporary tables, also assigned a primary key to the generated tables - to get an index on them.
Like this on both:
ALTER TABLE TEMP_MEASURINGS ADD PRIMARY KEY (MEASURINGID)
ALTER TABLE TEMP_VALUES ADD PRIMARY KEY (<some_other_col>)
The two temp-tables are related by a date and another id as you can see by the query. Now I need to update the "measuringid" in TEMP_VALUES based on the other table.
Can I make this query go faster in any way?
UPDATE TEMP_VALUES v
SET v.MEASURINGID =
(
    SELECT MEASURINGID
    FROM TEMP_MEASURINGS m
    WHERE m.MEASURDATE = v.MEASUREDATE
    AND m.ORDERID = v.ORDERID
)

The tables needs to be generated first, so I can't do an insert directly.
SELECT COUNT(*) FROM TEMP_VALUES ~6M
SELECT COUNT(*) FROM TEMP_MEASURINGS ~1.5M

A: Your query is going to be slow, because so many rows are being updated.
You can speed it with an index on TEMP_MEASURINGS(MEASUREDATE, ORDERID, MEASURINGID).  This is a covering index for the subquery.  The lookups should be fast.
You might find it faster just to create a new table:
create new_temp_values as
    select v.*, m.measuringid
    from temp_values v left join
         temp_measurings m
         on v.measuredate = m.measuredate and v.orderid = m.orderid;

The same index will work here (you can adjust the select columns to be what you really need).
Typically, creating a new table is much, much faster than updating all or even a significant number of rows in a given table.

A: Try with below merge for peformance:
MERGE TEMP_VALUES v
USING (SELECT MEASURINGID,
              MEASURDATE,
              ORDERID
       FROM TEMP_MEASURINGS) m
ON
   m.MEASURDATE = v.MEASUREDATE
   AND m.ORDERID = v.ORDERID
WHEN MATCHED THEN
       UPDATE
       SET v.MEASURINGID = m.MEASURINGID;

A: Instead of updating all records you can update records that exists in temp table:
UPDATE TEMP_VALUES v
    SET v.MEASURINGID =
    (
        SELECT MEASURINGID
        FROM TEMP_MEASURINGS m
        WHERE m.MEASURDATE = v.MEASUREDATE
        AND m.ORDERID = v.ORDERID
    )
    where
    exists (select 1 from TEMP_VALUES ttt, TEMP_MEASURINGS ttm WHERE ttm.MEASURDATE = ttt.MEASUREDATE
        AND ttm.ORDERID = ttt.ORDERID and ttt.ID = v.ID)


text:
Q: missing permissions to create folder from java application I am setting up a spring boot application and when running it, it should generate a folder in the source directory (see step 3: https://www.baeldung.com/spring-boot-h2-database)
But when running the application I receive the following error:
org.h2.message.DbException: Log file error: "/data/sample.trace.db", cause: "org.h2.message.DbException: Error while creating file ""/data"" [90062-200]" [90034-200]
    at org.h2.message.DbException.get(DbException.java:194)
    at org.h2.message.TraceSystem.logWritingError(TraceSystem.java:294)
    at org.h2.message.TraceSystem.openWriter(TraceSystem.java:315)
    at org.h2.message.TraceSystem.writeFile(TraceSystem.java:263)
    at org.h2.message.TraceSystem.write(TraceSystem.java:247)
    at org.h2.message.Trace.error(Trace.java:194)

it seems to be a permission problem but I do not understand why. My current user, has admin permissons. What am I missing here?

A: When I encounter this problem on my machine I proceed through following steps:

*

*If I don't know what user & group I am right now: $whoami && groups

*What user is the program executed with (I'm not into Java so eg. PHP "echo exec('whoami');")

*Who has access to the directory: $ls -la

*

*3.1 If only owner has access and you are not the owner: $chown user:group file

*3.2 If group and owner should have access consider: $chmod 770 file


text:
Q: Android Opencv calculate size of rotated image inside rectangle I want to calculate  rotated image size, Image is inside rectangle. I have rectangle width, height and angle of rotated image. Any one tell me
how to calculate rotated image size?

A: So you have width, height and angle means you already got RotatedRect.
Now using the method
Rect RotatedRect::boundingRect();

you can easly calculate the bounding box for rotated rect.
for more info see  RotatedRect.
Edit:
As per your comment below  is the way how to find the width and height of rotated rect.
So you know the four corners of rectangle, lets say (x1,y1),(x2,y2),(x3,y3),(x4,y4), now you need to find the transformed point after rotation by the given angle, let it be (xT1,yT1),(xT2,yT2),etc...
where
xT = x0+(x-x0)*cos(theta)+(y-y0)*sin(theta)
yT = y0-(x-x0)*sin(theta)+(y-y0)*cos(theta)

here (x0,y0) is the center around which you are rotating. and theta = angle * CV_PI / 180.0
Using above calculate four transformed points,  finally  calculate the height and width by finding the distance between transformed points.


text:
Q: How to add multiple styles of Google Maps using StyledMapType? I have added one additional style to a Google Map, following Google's instructions.
However I have had no sucess adding more than one style. Can this be achieved? If so, how?
Here is an example: http://jsfiddle.net/mikegoodstadt/A9zwa/3/
Many thanks for any suggestions,
Mike
  var geocoder;
  var map;
  var MAPTYPE_1;
  var MAPTYPE_2;

  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlngLondon = new google.maps.LatLng(51.507335, -0.127683);
    var latlngMarrakech = new google.maps.LatLng(34.02590, -6.83640);

    var style1 = [
     {
       "stylers": [
         { "visibility": "on" },
         { "weight": 0.9 },
         { "gamma": 0.99 },
         { "lightness": -4 },
         { "hue": "#ffc300" },
         { "saturation": -14 }
       ]
     }
    ];
    var style2 = [
     {
       "stylers": [
         { "visibility": "on" },
         { "weight": 0.9 },
         { "gamma": 0.99 },
         { "lightness": -4 },
         { "hue": "#ff6e00" },
         { "saturation": -14 }
       ]
     }
    ];

    var mapOptions = {
      zoom: 12,
      center: latlngLondon,
      mapTypeControl: 1,
      panControl: 0,
      streetViewControl: 0,
      zoomControl: 0,
      mapTypeControlOptions: {
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, MAPTYPE_1, MAPTYPE_2]
      },
    };

    map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);

    var mapType1 = new google.maps.StyledMapType(style1, {name: 'London'});
    var mapType2 = new google.maps.StyledMapType(style2, {name: 'Marrakech'});

    map.mapTypes.set(MAPTYPE_1, mapType1);
    map.mapTypes.set(MAPTYPE_2, mapType2);

  }

  function codeAddress() {
    var address = document.getElementById("search-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert("Buscedad sin exito: " + status);
      }
    });
  }

A: You need to declare/set the setMapTypeIDs
 map.mapTypes.set('MAPTYPE_1', mapType1);
 map.setMapTypeId('MAPTYPE_1');

 map.mapTypes.set('MAPTYPE_2', mapType2);
 map.setMapTypeId('MAPTYPE_2');


text:
Q: How to calculate the volume of revolution around $x=3$ for the region bounded by x, y axis and $\sqrt{x}+\sqrt{y}=1$? So I intend to do it in both shell and disk ways.
Let's first use shell method (formula: $\int 2\pi x(f(x)-g(x))dx$):
Since $x=3$ is the major axis, and $y=(1-\sqrt{x})^2$, we have $V=\int_0^1 2\pi (3-x)((1-\sqrt{x})^2)dx$
Next, disk method (formula: $\int \pi (f^2(x)-g^2(x))dx)$:  we have $x=(1-\sqrt{y})^2$$V=\int_0^1 \pi ((3-0)^2-(3-(1-\sqrt{y})^2))dy$
Did I write my equations wrong?


text:
Q: Pyspark aggregation - each field aggregated in a different way I have some data that has four basic fields:

*

*Field 1 is a key for the data

*Field 2 should be a set of all unique values for this field

*Field 3 is a minimum value (timestamp)

*Field 4 is a maximum value (timestamp)

Original Code looks like this:
data = (
    dataframe
    .rdd
    # flatten rows
    .flatMap(lambda x: x)
    # Parse JSON
    .flatMap(lambda x: encode_json(x))
    # Capture values
    .map(lambda x: [
        # Merge 'field1', 'field2' --> 'field1, field2'
        ','.join(_ for _ in [x.get('metadata_value'), x.get('field2')]),
        # Create pairing of low and high timestamps
        [x.get('low'), x.get('high')]
    ])
    # Aggregate into a list of low/high timestamps per 'field1, field2'
    .aggregateByKey(list(), lambda u, v: u + [v], lambda u1, u2: u1 + u2)
    # Flatten keys 'ip,guid' --> 'ip', 'guid'
    .map(lambda x: (x[0].split(',')[0], x[0].split(',')[1], x[1], sum(1 for _ in x[1])))
    # Reduce timestamps to single values:  [s1, e1], [s2, e2], ... --> s_min, e_max
    .map(lambda x: (x[0], x[1], min(_[0] for _ in x[2]), max(_[1] for _ in x[2]), x[3]))
)

Original output looks like this:
a | x012345 | 20160103 | 20160107
a | x013579 | 20160101 | 20160106

New output should look like this:
a | {x012345,x013579} | 20160101 | 20160107

A: Add this 2 transforms to your current output, to map to a pair RDD, and reduce each field by it's corresponding operation (dictionary, min,max).
data.map(lambda reg: (reg[0],[reg[1],reg[2],reg[3]]))
      .reduceByKey(lambda v1,v2: ({v1[0],v2[0]},min(v1[1],v2[1]), max(v1[2],v2[2])))


text:
Q: android ediitext ontouchlistener second tourch I have one EdiiText and I wrote setOnTouchListener method and I wont to check any touch without first touch(second touch ,3th touch and etc)
   AgroJaninputcount.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {

                        iCount++;
                        System.out.println(iCount + "  iCount");
                        if(iCount >1)
                        {

                            Toast.makeText(getApplicationContext(), "Second Click", Toast.LENGTH_SHORT).show();

                        }

                        return false;
                    }
                });

My Toast message has seen in first time also. If anyone knows solution please help me.
thanks everyone

A: Try this, Im pretty sure will solve your problem. If it does please mark my answer as correct.The problem is that  you are incrementing the value before the if.
 AgroJaninputcount.setOnTouchListener(new OnTouchListener() {

                            @Override
                            public boolean onTouch(View v, MotionEvent event) {

                                System.out.println(iCount + "  iCount");
                                if(iCount >1)
                                {

                                    Toast.makeText(getApplicationContext(), "Second Click", Toast.LENGTH_SHORT).show();

                                }

 iCount++;
                                return false;
                            }
                        });

A: try motionEvent.getPointerCount()
maybe you should check, if the onTouchEvent is a ACTION_DOWN event ->
if (action == MotionEvent.ACTION_DOWN) {}

A: Change your condition
if(iCount >1)

To
if(iCount >2)


text:
Q: Visualforce in Cloud Console showing Alerts only when a case is created I have a Service Cloud Console sidebar that I have a visualforce page embedded that runs 2 queries, and based on the results presents Alerts.  One for cases, and one for account issues.  My problem is that I can't get them to show independently.  I have to have an open case for the Account alert to show. Also when the Alert query returns null I still see a blank red box.  Any help would be appreciated.
Visualforce Page

<apex:includeScript value="/support/console/33.0/integration.js"/>

    <apex:pageMessage id="EMFmessage" summary="{!ShowMessage.Message__c}" severity="error" strength="1"/>

    <apex:pageMessages escape="false"/>

</apex:page>

Controller
public class AccountCaseExtension {

    private final Account acct;
    public Case alertCase {get;set;}
    boolean showCaseAlert = false;
    boolean showAccountAlert = false;
    String severity;
    public Account alertAccount {get; set;}
    public Account EMFStatusAccount {get;set;}
    //public Boolean EMFIssue = false;
    public Alert__c ShowMessage {get; set;}
    public String message = '';
    public String EMFStatus = '';

    public String getSeverity() {
        return severity;
    }

    public AccountCaseExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();

        String alertString;

        try {
            alertCase = [Select Id, AccountId, Subject, Origin, CreatedDate, CaseNumber, IsClosed, LastViewedDate, Priority from Case where AccountId = :acct.Id and CreatedDate = LAST_N_DAYS:7  and IsClosed = False /*and Origin = 'Compass'*/ order by CreatedDate ASC LIMIT 1];
                        showCaseAlert = true;
            alertString = 'A case was generated by ' + alertCase.Origin+' with the following subject: '+alertCase.Subject+'';
            System.Debug('Alert String: ' + alertString);
            if(alertCase.Priority == 'Low') {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,alertString));
            }
            else if(alertCase.Priority == 'Medium') {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING,alertString));
            }
            else if(alertCase.Priority == 'High') {
                System.Debug('high');
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,alertString));
            }
            } catch(Exception e) {
                System.debug('Thrown Exception: '+ e);
        }
        try{
            EMFStatusAccount = [SELECT Id, Name, EMF_Status__c, EMF_Issue__c FROM Account WHERE id = :acct.Id LIMIT 1];
            EMFStatus = EMFStatusAccount.EMF_Status__c;//This gets a Yes/No from the above query.
            ShowMessage = [SELECT Id, Name, Message__c FROM Alert__c WHERE Alert_Start__c = TODAY ORDER BY Alert_Start__c DESC LIMIT 1];
            message = ShowMessage.Message__c;//Figure out how to handle the null pointer in the above query.
            showAccountAlert = true;
        }catch(QueryException qe) {
            showAccountAlert = false;
            System.debug('EMF Alert Query returned no rows' + qe);
        }
    }

    public String getGreeting() {
        return 'Hello ' + acct.name + ' (' + acct.id + ')';
    }
    public boolean getShowCaseAlert() {
        return showCaseAlert;
    }
    public boolean getShowAccountAlert() {
        return showAccountAlert;
    }

    public String getEMFStatus () {
        return EMFStatus;
    }
    public String getShowMessage () {
        return message;
    }
}

A: After painstakingly going over the code I finally have this figured out.  So I figured I would share this for anyone else who might want to show alerts in the Service Cloud Console.  As I found no information about creating this functionality.
I inherited this code from the implementors so I assumed it was all necessary.  I found out that I didn't need anything in the visualforce page except the  tags and the  tag.  This was put into a Custom Console Component left sidebar.  Here is the code:
Visualforce Page
<apex:page standardController="Account" extensions="AccountCaseExtension" showHeader="false" sidebar="false" rendered = "{!showAlert}">
    <apex:pageMessages escape="false"/>
</apex:page>

Controller
public class AccountCaseExtension {

    private final Account acct;
    public Case alertCase {get;set;}
    boolean showAlert = false;
    String severity;
    public Account alertAccount {get; set;}
    public Account EMFStatusAccount {get;set;}
    public Alert__c ShowMessage {get; set;}
    public String EMFStatus = '';

    public String getSeverity() {
        return severity;
    }

    public AccountCaseExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();

        String alertString;
        // This is where the case alerts are generated.
        try {
            alertCase = [Select Id, AccountId, Subject, Origin, CreatedDate, CaseNumber, IsClosed, LastViewedDate, Priority from Case where AccountId = :acct.Id and CreatedDate = LAST_N_DAYS:7  and IsClosed = False /*and Origin = 'Compass'*/ order by CreatedDate ASC LIMIT 1];
            showAlert = true;
            alertString = 'A case was generated by ' + alertCase.Origin+' with the following subject: '+alertCase.Subject+'';
            System.Debug('Alert String: ' + alertString);
            if(alertCase.Priority == 'Low') {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,alertString));
            }
            else if(alertCase.Priority == 'Medium') {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING,alertString));
            }
            else if(alertCase.Priority == 'High') {
                System.Debug('high');
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,alertString));
            }
        } catch(Exception e) {
                System.debug('Thrown Exception: '+ e);
        }
        // This is where the EMF Alerts are generated.
        try{
            EMFStatusAccount = [SELECT Id, Name, EMF_Status__c, EMF_Issue__c FROM Account WHERE id = :acct.Id LIMIT 1];
            EMFStatus = EMFStatusAccount.EMF_Status__c;//This gets a Yes/No from the above query.
            System.debug('Emf Status: ' + EMFStatus);
            // Next line throws exception if query returns Null
            ShowMessage = [SELECT Id, Name, Message__c FROM Alert__c /*WHERE Alert_Start__c = TODAY*/ ORDER BY Alert_Start__c DESC LIMIT 1];
            if(ShowMessage.Message__c != null && EMFStatus == 'Yes') {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,ShowMessage.Message__c));
            }

            showAlert = true;
        }catch(QueryException qe) {
            showAlert = false;
            EMFStatus = 'No';
            System.debug('EMF Alert Query returned no rows' + qe);
        }
    }
    public boolean getShowAlert() {
        return showAlert;
    }
    public String getEMFStatus () {
        return EMFStatus;
    }
}

I hope this helps someone in the future. Happy coding.


text:
Q: How do you use a variable argument on base64.b64encode but when i am not using the prompt window? This question is similar to this one here but if I put this into this code like so:
import base64
theone = input('Enter your plaintext: ')
encoded = str(base64.b64encode(theone))
encoded = base64.b64encode(encoded.encode('ascii'))
encoded = encoded[2:]
o = len(encoded)
o = o-1
encoded = encoded[:o]
print(encoded)

it raises this problem:
line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

And then if I remove this line of code:
encoded = base64.b64encode(encoded.encode('ascii'))

then it raises the same error. I'm not sure what to do from here and I would be grateful for any help.

A: You seem to be having problems with bytes and strings.  The value returned by input is a string (str), but base64.b64encode expects bytes (bytes).
If you print a bytes instance you see something like
b'spam'

To remove the leading 'b' you need to decode back to a str.
To make your code work, pass bytes to base64.b64encode, and decode the result to print it.
>>> theone = input('Enter your plaintext: ')
Enter your plaintext: Hello World!
>>> encoded = base64.b64encode(theone.encode())
>>> encoded
b'SGVsbG8gV29ybGQh'
>>> print(encoded.decode())
SGVsbG8gV29ybGQh


text:
Q: Set View Script in Plugin - Check if Exist? I'm developing a multi-lingual site.
Some languages uses right-to-left layouts and some left-to-right.
So some of my view scripts have another RTL view script that I want to load automatically.
I wrote a plugin that checks if the user is RTL and if yes it adds '.rtl' to the suffix of the file:
                Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')-  >setViewSuffix('rtl.phtml');
the problem is that not all of my view scripts have an rtl view script, so I want to check if the file exist....
the problem with that if I do in my controller $this->render('someScript') then I've got no way to check if the .rtl script exist.. as far as I know.
In short: is there some way (event) to hook up after the action finishes but before it renders?
Maybe I should write a custom view renderer?
Thanks.

A: If the RTL check can only happen after an action has been executed, you could create an action helper, which uses the postDispatch hook to set the viewSuffix via the ViewRenderer and retrieve the path to the view script. Using the view scriptPath and the viewRenderer getViewScript(), you can create the absolute path to the file.
It is not a particularly pretty way to accomplish your goals, though.
It might be an idea to create two scriptPaths, one for the LTR and another for the RTL. When the user uses a RTL language, you can add the RTL scriptPath to the view scriptPath stack. That way, Zend_View will first check the RTL directory and use the LTR directory as a fallback.


text:
Q: How to get output of the nested loop in a data frame using r? And how to put a time loop? I am new to r and work on boolean modelling - my nested loop gives output of 50 values of rtk in terms of 0 and 1, how to store this output in a dataframe , cbind is not working . Please help.
2. Also I would like to introduce a time loop ie if j = is 5 seconds I want rtk to change accoding to nwki value in i0 for j =1to 3 and for time j = 4,5 seconds i want rtk to change accoding to nwk value in i0
CODE IS AS FOLLOWS
library (BoolNet)#make sure lib is installed
library(igraph)
setwd("C:/Users/neha gopal/Desktop/IISC-mkj/r for boolean")#"

nwki<- loadNetwork("rtkufi.txt",bodySeparator =",",lowercaseGenes = FALSE)#"
nwk<- loadNetwork("rtkuf.txt",bodySeparator =",",lowercaseGenes = FALSE)#"
inc<-c(1,0,0,0,0,0,0,0,0,0)#vector
stF<- stateTransition(network=nwki,state= inc,type = "asynchronous")
stF
#loops working
rtk_values <-rep(0,50)# empty vector for total no of rtk  output values
rtk_values
ts<- 10
for (i in 1:ts)# trajectories i=10
{
  i0 <- inc
  rtk_values <-rep(0,50)
  rtk <- i0[2]

tr<-5 #time j=5

for (j in 1:tr)
{

  i0 <- stateTransition(network=nwki,state= i0,type = "asynchronous")
  rtk <- i0[2]
  print (paste0( ",Im in J and my j is ", j, " and my i is", i,"rtk is" , rtk ))

}

}

#table  NOT working

rtk_values[j]= rtk
rtk_table <- cbind.data.frame( rtk_values, rtk)

A: The best way to ask a question is to provide a reproducible example. If your question is how to store variables from a for loop, this would be a way of doing it:
result <- list() # initalize an empty list

for (i in 1:10){
  result[[i]] <- i # populate list with every loop
}

The same system can be used for nested loops:
result <- list()
for (i in 1:10){
  result_nested <- list() # initialize an empty list within the loop
  for (nested in 1:5){
    result_nested[[nested]] <- nested # populate the results from the nested loop.
  }
  result[[i]] <- result_nested # populate the result from the nested loop to the parent loop
}


text:
Q: Use NSFetchRequest to get all results of relationship I have two entities: Author and Book. I want to get the list of all books by a particular author.
Here's the code I'm using:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Books"];
[fetchRequest setPredicate[NSPredicate predicateWithFormat:@"ANY author == %@", author]];
books = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

However, this returns only one book of the author.
How can I get ALL books of a particular author?
I read a bunch of other topics but none of the solutions seem to work for me.
Thanks!

A: Did you try like this ?
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Books"];
request.predicate = [NSPredicate predicateWithFormat:@"author = %@", author ];
NSArray *matches = [moc executeFetchRequest:request error:nil];

A: The issue was in the data model: relationship author -> book should be "To many" instead of "To one".
After updating the relationship I had to reinstall the app in the simulator, but everything worked properly after that.


text:
Q: "xhost +" produce access control disabled message but do not works When under kubuntu enter command xhost + I got answer:

access control disabled, clients can connect from any host

But when try running X application under different user (su - username) I  got answer:

Error: Can't open display:

Connected link:
"Can't open display" even after access with xhost
EDIT
Yes, $DISPLAY was empty. I obviously get used that it is always set correctly. Thanks Arjen.

A: X-applications try to connect to the X-server that is referred to in the environment variable DISPLAY. Enter echo $DISPLAY to show its current value. It should look like :0 or localhost:0.
When starting the su-shell with su - username, all environment variables will be cleared. This is a security measure.
You can start the X application in su-mode with DISPLAY=:0 xapplication (substitute :0 with the value that was shown with the echo command).


text:
Q: Two-dimensional lists for Python The function avgavg() takes as input a list whose items are lists of three numbers.  Each three-number list represents the three grades a particular student received for a course.  For example, here is an input list for a class of four students (you never know how many students you will have to process):
[[95, 92, 86], [66, 75, 54], [89, 72, 100], [34, 0, 0]]

The function avgavg() should print, on the screen, two lines.  The first line will contain a list containing every student's average grade.  The second line will contain just one number: the average class grade, defined as the average of all student average grades.
Output given the above data:
[91.0, 65.0, 87.0, 11.333333333334]
63.5833333333

(This is my assignment question.  I have tried to start this a few different ways and I cannot seem to get my inputs to connect to anything.  How would I go about solving this? This is my latest attempt:
COLS = int(input("Enter the number of students: "))
ROWS = int(input("Enter the number of grades per student: "))
def avgavg():
    student_grades = []

    for c in range(COLS):
        student = input("Enter the number of the student: ")
        grades = []

    for r in range (ROWS):
        grade = eval(input("Enter the grades for the student: "))
        grades.append(grade)
    student_grades[student] = grades
    print(grades)

A: To get the average of a list, say [1, 2, 3], you would do it as:
a = [1, 2, 3]
print sum(a)/float(len(a))

Hopefully that is enough to get you started. I will let you figure out the specifics. Also, I will only post the full solution once you have demonstrated sufficiently that you have tried working this out yourself and were unable to get it to work as expected.
Now that you have showed some effort:
Working solution
a = [[95, 92, 86], [66, 75, 54], [89, 72, 100], [34, 0, 0]]

b = [sum(i)/float(len(i)) for i in a]

>>> print b
[91.0, 65.0, 87.0, 11.333333333333334]

print sum(b)/float(len(b))
63.5833333333

A: This is to elaborate on sshashank124's answer and add the user input function. I have also added some error handling code (while loops), so if a user inputs a string instead of a grade, it will ask again:
Remember, don't use this exact code for your submission. This is probably an integrity violation in your class. Try to rewrite the code from scratch and tell what didn't go well
What you did wrong in your code, is that you've put the two for loops by themselves. They need to be nested.
error = "Non integer input. Try again>> " #Error message

def isfloat(value): #Functon to check if a number can be a grade
    try:
       float(value)
       return True
    except ValueError:
       return False

n = raw_input("Enter number of students>> ") #Number of students
while not n.isdigit():
    n = raw_input(error)

g = raw_input("\nEnter number of grades per student>> ") #Number of Grades per student
while not g.isdigit():
    g = raw_input(error)

grades = [] #The two dimensional list
print
#Receiving input from the user
for a in range(int(n)):
    temp = []
    print "Student %i" % (a+1)
    for b in range(int(g)):
        grade = raw_input("Grade %i>> " % (b+1))
        while not isfloat(grade):
            grade = raw_input(error)
        temp.append(float(grade))
    grades.append(temp)
    print

students = [sum(stud)/float(len(stud)) for stud in grades]
#Returning output
print students
print sum(students)/float(len(students))

A: I realize this is an assignment, in the real world I wouldn't hesitate to use numpy:
> grades = [[95, 92, 86], [66, 75, 54], [89, 72, 100], [34, 0, 0]]
> np.average(grades, axis=1)
array([ 91.        ,  65.        ,  87.        ,  11.33333333])
> np.average(grades)
63.583333333333336

A: Here is working code:
lists = eval(raw_input('Enter the class data as a list: '))

def avgavg(lists):
        avg = [float(sum(sub))/float(len(sub)) for sub in lists]
        everything = [item for sub in lists for item in sub]
        allavg = float(sum(everything))/float(len(everything))
        return avg, allavg

avg, allavg = avgavg(lists)
print avg
print allavg

This runs as:
bash-3.2$ python lists.py
Enter the class data as a list: [[95, 92, 86], [66, 75, 54], [89, 72, 100], [34, 0, 0]]
[91.0, 65.0, 87.0, 11.333333333333334]
63.5833333333
bash-3.2$

This code takes input using eval(raw_input(...)) to strip the quotes from the string. We then use list comprehension to get the average of each one, and then uses list comprehension to make all the lists in the list of lists one list (sorry for all the lists :)). We then return it, and at the end print it out.
Don't hesitate to ask any questions below!
Hope this helps.


text:
Q: Is it ok to generate a random string and using it as an ID on a relational database I'm using MYSQL for storing data about my products, I've read on the internet using an auto-incremental number as Primary Key is a really bad idea because anyone could just iterate all through my service and stole my data. For practical proposes it is really handy, now I'm trying to find a better solution,
So far i've created a function in Python that returns a random string of length n from a fixed number of characters to choose from. Now I know it is possible the generated ID was already generated before and stored in DB and the probability that happens is really low at beginning but it will increment with the time, at a point where say half of the IDS are already taken so the probability to fail on creating a new record on DB will fail will be of 50%.
Is it ok to work with IDS this way? or is there any better solution?, how many characters should I use at least to avoid this problem?.
I know UUID exists but I don't think is very userFriendly


text:
Q: Kafka retention policyoverride I have created my topic when the retention policy in server.properties was set to 168 hours (7 days)
then changed the retention policy to 10 days since the topic has created at the time does it inherit server.properties of 7 days has been set as a part of topic creation as topic properties,
I did not alter the topic to customize the topic.

A: If you did not specify an override when you created the topic, it uses the current value from server.properties and every time you update the value in server.properties, the new value will be taken into account when applying the retention policies.
A quick way to double check if you have any override is to run:
./bin/kafka-topics.sh --zookeeper ZK --describe --topic TOPICNAME


text:
Q: Mainmenu layout not appears to be the desired layout I am new in Xamarin. I have problem fixing the Main_Menu.axml layout to my desired layout which is on the link below.How can I put a layout above and my gridview below? I need help in that.
Desired Layout is below

My current Mainmenu.axml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:background="@drawable/background">

    <include
        android:id="@+id/toolbar"
        layout="@layout/sublayout_Toolbar" />
  <android.support.v4.widget.DrawerLayout
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/drawer_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="0.4" />
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.6">
            <GridView
                android:id="@+id/mainMenu_GridView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:numColumns="2"
                android:listSelector="@null"
                android:verticalSpacing="0dp"
                android:horizontalSpacing="0dp" />
        </LinearLayout>
        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:layout_gravity="start"
            android:background="@color/light_blue" />
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

My current layout as below


text:
Q: Sentence beginning with "Between [year] and [year] " I've just been told it is wrong to put a comma after an "introductory time period", for example:
"Between 1990 and 2003, diligent seekers found hundreds of incorrectly placed commas in all manner of texts."
Is this really a hard and fast rule?
If the sentence were very short, I might agree there's no need for a comma, but in the actual case (of which my sample above is an approximation), I see no need to delete it. But the editor has added a note indicating that the comma actually violates a rule, and I'd like to get that confirmed (if it is true).
Looking forward to your comments, thanks!


text:
Q: Comparing and creating a CSV file in C# I am creating a CSV file using C# this contains 200 headers. I'm getting the data from another CSV file which contains 150 headers. My problem is how I'm going to place the data according to its header. For instance I'm giving  and example below.
The CSV file which will be created with C#:
Name, Surname, Locality, DateOfbirth, Age
Joe,  Smith,                          60
Sam,  Brown,                          20

The CSV getting the data from
Name, Surname, Age
Joe,  Smith,   60
Sam,  Brown,   20

This is a sample code (the actual files contains 150 header, and the new CSV file contains 200 headers)
string[] lines = System.IO.File.ReadAllLines(fileUrl);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileUrl))
{
    foreach (string line in lines)
    {
        if (line == lines[0])
        {
            //Changing the header of the first file
            file.WriteLine("Name, Surname, Locality, DateOfBirth, Age");
        }
        else
        {
            string[] values = line.Split(',');
            file.WriteLine(string.Format("{0},{1},{2},{3},{4}",
                                values[0], values[1], values[2], values[3], values[4]));
        } //exception being thrown here since the array is out of range
    }
}

A: You are reading just three columns from the input file, yet are trying to write out five columns. So values[3] and values[4] will be out of range.
I'm puzzled as to where you are expecting to get Location and DateOfBirth from. Wherever it is, it won't be in your values array.

A: Read the data from file that contains 3 columns. Then read Locality and DateOfBirth values from that another file. Clear the first file and then write them all in a new csv file.
    public static List<string[]> Parse(string Path)
    {
        List<string[]> Parsed = new List<string[]>();

        using (StreamReader Reader = new StreamReader(Path))
        {
            string Line;
            char Seperator = ',';

            while ((Line = Reader.ReadLine()) != null)
            {
                if (Line.Trim().StartsWith("//")) continue;
                if (string.IsNullOrWhiteSpace(Line)) continue;

                string[] Data = Line.Split(Seperator);
                Parsed.Add(Data);
            }
        }

        return Parsed;
    }

You can use the method above to read from CSV file. Imagine that you read first file and you get List and string array has 3 values.
Read second file and get other values. For each value in first List find the corresponding item in the second List. Then use these two string array lists to write into a csv file.
List<string[]> File1 = Parse("File1Path");
List<string[]> File2 = Parse("File2Path");

using (System.IO.StreamWriter file = new System.IO.StreamWriter(OutputFile))
{
   // write header first:
   file.WriteLine("Name, Surname, Locality, DateOfBirth, Age");

   foreach (string line in File1)
   {
     var found = File2.Where(x => x[0] == line[0]).FirstOrDefault();
     if(null == found) continue;

     file.WriteLine(string.Format("{0},{1},{2},{3},{4}",
                                line[0], line[1], found[3], found[4], line[2]));
    }
}


text:
Q: What uses does the Camera item have? In the XBLA port of Spelunky, there is a Camera item in some shops. The journal doesn't say anything much about it. It didn't seem to have any effect on the enemies I used it on, though it does stun damsels and I've heard it enrages shopkeepers.
Does this item have any useful purpose?

A: It stuns enemies as well providing you catch them in the "picture" box, and will light up dark levels when the flash goes off
I can also tell you from experience that people playing with you might not appreciate you flashing them repeatedly with it :)
Update: Just discovered it will kill undead and bats instantly too


text: Q: DB2 SQL Error: SQLCODE=-433, SQLSTATE=22001 when inserting Base64 CLOB data DB2 exception - DB2 SQL Error: SQLCODE=-433, SQLSTATE=22001 is thrown when inserting a Base64 CLOB data with length of 38K characters into DB2 table CLOB field defined with length of 10MB. Database insertion is done via a Stored Procedure called by a MuleSoft flow. We've been unable to find the root cause or solution to this. Has anyone seen this behaviour?


text:
Q: Use SharePoint 2013 "like" button as a "Sign up" button for events I'm trying to create an SP 2013 list which I'm planning to use as Events calendar and hope you'll be able to help me with some ideas.
The idea is the following:
Everyone will be able to create his own event and open it for registration to the public. The creator of the list item should be the only one able to edit and delete it. I was planning to use the "like" feature in SP 2013 as a "Sign up" button but in order to achieve that, I need 2 things -
1) limit the number of likes. Saying that every event will have different number of available seats (defined by the item creator) and employees should not be able to "like" the event any more if the limit is reached
2) send an email to the list item creator every time when someone "like" the item. The email should be smth like "*Name of the user" signed up for your event"
Unfortunately I don't have enough SP knowledge to achieve the above so I'm counting on your help and will appreaciate if you can point me the right direction. :)

A: I have created such logic with custom "Likes" list".
List can have just 2 columns – List Guid, Item Guid. The standard Author field stores info about user that have added like.
The values are loaded by JavaScript client object model and users can add likes through JS COM.
In the list item event receiver I control that user can add the like only once, and here you can check if the count of likes have reach maximum value, send email to item author.


text:
Q: Configuration for passing NGINX request to Express? I'm creating a website with NGINX handling Static content, SSL and all that stuff, while my API and non-static websites are handled by Express.
Now, I'd like NGINX to pass stuff like "/update" to Express. However, I'm not sure how to configure that.
Is the example below from DigitalOcean functional for https websites in the first place? Shouldn't I configure the same SSL certificate that NGINX uses to Express, so it redirect to https://website.com/update instead of http://website.com/update?
    location / {
    proxy_pass http://localhost:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

Thanks in advance!

A: To proxy pass any API request starting with /update Example: http://localhost:3000/update, http://localhost:3000/update/test etc.. You can use below nginx config inside server block:
location /update {
        proxy_pass http://localhost:3000;
    }

If you want to redirect http://website.com/update to https://website.com/update . You will need to create a server at 80 port which will redirect any request that come at 80 port will be redirect to https://website.com/update
server {
    listen 80;
    listen [::]:80;
    server_name website.com;
    return 301 https://website.com$request_uri;
}


text:
Q: open and show any file in python I'm practicing python, writing a simple file downloader.
I did it using Tkinter and it works. But the problem is that I can't open/show the downloaded file just after the download process is finished, like when we download and open the file in IDM (Internet Download Manager). actually, I want to add a msg box (after the download process is finished) that has an "open/show downloaded file" button. So, When the user presses the button, the file will be opened.
Thank You All...
IDM screenshot,,,
my little program's GUI screenshot


text:
Q: Java - Map two objects containing List of objects(objects which have different naming but same function) I have two classes:
public class1{
    private int id;
    private List<Student> students;
}

public Student{
    private name;
    private address;
}

public Class2{
    private int id;
    private List<Person> person;
}

public Person{
    private personName;
    private location;
}

I have to map/copy values from class1 to class2. I tried to use dozer bean mapper API, but I could not map List of Student with List of Person as they have different field names but same function. Please help me with dozer mapping or if there is other solution, highly appreciated.
Thanks!

A: Try something like this:
public static List<Person> mapValues() {

    List<Student> students = class1.getStudents(); // Assuming you have getters of students field
    List<Person> persons = class2.getPersons(); // Assuming you have getters of persons field
    for(Student student: students) {
        Person person = new Person();
        person.setPersonName(student.getName);
        person.setLocation(student.getAddress);
        persons.add(person);
    }
    return persons;
}


text:
Q: Как спарсить динамический контент python? Я парсю python-ом сайт https://www.flashscore.com/, а именно - матчи, которые в онлайне (live). Все матчи находятся в блоке div с id="live-table". Добавление матчей в блок div происходит динамически.
Помогите, пожалуйста, получить доступ к списку div? Желательно не используя selenium, ибо у меня не получается установить драйвер для браузера, так как у меня стоит ubuntu.
Можно ли спарсить динамический контент с использованием модуля requests?

A: Открой через браузер, там открой "инспектировать элемент", перезагрузи страничку и смотри вкладку Network. На этом сайте на главной стоит web-socket соединение с зашифрованными данными. На дополнительных страницах стоит полинг - сайт постоянно дергает определенный урл и получает данные. Но и там содержимое зашифрованно.
Гол выглядит так
/fs/fs3_u_1_1SA÷1¬~AA÷xxSiad7m¬SCA÷1590704042¬~A2÷1588627646¬~L@^ '2
/fs/fs3_u_1_1SA÷1¬~AA÷xxSiad7m¬SCA÷0¬AG÷2¬BC÷1¬~L`^ '2

Хотя это не совсем шифр, а скорее бинарная структура. Но как её разобрать - надо смотреть в коде сайта.
Единственный метод - использовать большой браузер и Selenium


text:
Q: Data structure in Java with operation remove all nodes after a node I'm looking for a (predefined)data struture in Java, which will remove all the elements after a node.
A sample representaion given below.
e.g:
Before removal
head
 ┕>1 -> 2 -> 3 -> 4 -> 5 -> 6 ->7

After removal
removeAllFrom(5)
head
┕>1 -> 2 -> 3 -> 4

I checked a lot of java DS, but didn't find a perfect one in java.
(1 . Preferred a data structure which is in java.util.
2 . Insertion at head and iteration are the other operations which i'm using)
Thanks for the help :)

Edit - 1
After finding the element specified for removal(in the sample its 5), we just need to remove the links between the next node.
I checked the implementation of the answers given, but in both the cases it is removing each node separately.
Just curious to know any other way to do it. :)
public void clear() {
    removeRange(0, size());
}

protected void removeRange(int fromIndex, int toIndex) {
    ListIterator<E> it = listIterator(fromIndex);
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        it.next();
        it.remove();
    }
}

A: Well, java.util.LinkedList implements the List interface, which has a subList() method. Using that method, you can obtain a sub-list of the tail of the original list, and by clearing it, truncate the original List:
list.subList(firstIndexToRemove,list.size()).clear();

From the Javadoc:

List java.util.List.subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:
list.subList(from, to).clear();

This requires that you know the index of the node from which you want to remove all the elements.


text:
Q: CKEditor disable link double click dialog from appearing How do I intercept and disable the CKeditor 4 dialog?
I did some reading and got to the function that runs when it first loads. I am thinking this is where it should be disabled?
CKEDITOR.on( 'dialogDefinition', function( ev ) {
    // HERE we should stop it from appearing? How?
});

Or do I need some type of on double click event listener?
Any ideas?

A: I ended up disabling the dialog from forming in the first place with
CKEDITOR.on( 'instanceCreated', function( ev ) {
    var cke = ev.editor;
    cke.on( 'doubleclick', function( evt ) {
        return false;
    } );
});

A: Ben's solution did not work for me in newest CKEDITOR version 4.11.3
After a small modification, I managed to get it to work.
I changed instanceCreated to instanceReady. Here is my working code:
CKEDITOR.on( 'instanceReady', function( ev )
{
    ev.editor.on( 'doubleclick' , function( evt )
    {
        return false;
    });
});

My code is placed inside:
CKEDITOR.editorConfig = function( config ) { [HERE IS MY CODE] };
which is placed in a custom config.js file
On a website my CKEDITOR object is placed using:
CKEDITOR.replace( element, [ config ] );


text:
Q: soul dropping some accented letters from the end of words I'm using soul to letterspace headings in a Hungarian document and compiling it with lualatex.
For some reason soul drops some of the accented letters at the end of a word, but not all. In the example below, only ő and ű are affected:
\documentclass{minimal}
\usepackage{fontspec}
\setmainfont[Ligatures = TeX]{TeX Gyre Pagella}
\usepackage{soul}
\begin{document}
\noindent
\so{áll llá ÁLL LLÁ}\\
\so{íll llí ÍLL LLÍ}\\
\so{űll llű ŰLL LLŰ}\\
\so{őll llő ŐLL LLŐ}\\
\so{üll llü ÜLL LLÜ}\\
\so{öll llö ÖLL LLÖ}\\
\so{úll llú ÚLL LLÚ}\\
\so{óll lló ÓLL LLÓ}\\
\so{éll llé ÉLL LLÉ}
\end{document}

A: The problem is in the font used for testing hyphenation. If you add
\makeatletter
\let\SOUL@tt\relax
\newfontface{\SOUL@tt}{FreeMono}
\makeatother

after loading soul the problem seems to disappear. It probably won't show again characters that are not in the \SOUL@tt font.
Full code:
\documentclass{article}
\usepackage{fontspec}
\setmainfont[Ligatures = TeX]{TeX Gyre Pagella}
\usepackage{soul}
\makeatletter
\let\SOUL@tt\relax
\newfontface{\SOUL@tt}{TeX Gyre Cursor}
\makeatother

\begin{document}
\noindent
\so{áll llá ÁLL LLÁ}\\
\so{íll llí ÍLL LLÍ}\\
\so{űll llű ŰLL LLŰ}\\
\so{őll llő ŐLL LLŐ}\\
\so{üll llü ÜLL LLÜ}\\
\so{öll llö ÖLL LLÖ}\\
\so{úll llú ÚLL LLÚ}\\
\so{óll lló ÓLL LLÓ}\\
\so{éll llé ÉLL LLÉ}
\end{document}


text:
Q: While using Playground - build succes, but no launch and sound When I open playgrounds and press Build (or run), the message "Build Success" appears, but no launch of the code.
Before I set up Xcode Project with AudioKit framework, and built oscillator project successfully with launching on Iphone simulator and produced sound.
But when open playground - only build success and no launch and no messages in console


text:
Q: Protect the session with the key in the session and in the cookie? I'm looking for a way to protect my php session that contains important information. Using an IP verification is not a good idea for people on the phone. That's why I thought it might be smart to store a randomly generated key in the session and in a classic cookie. Then every x minutes check that the two keys match. Is this a good idea? I didn't find anything about this in my search.
Thank you for your feedback,
Jesver

A: It's partially a good idea.
Usually it is enough to protect a session with a (personal) account and a password (a key). The accountname should not be too generic like 'admin' or 'root', and the password should contain enough entropy, which makes passwords hard to predict (and hard to remember, hence the usage of password managers).
One reason to add an extra crypto safe key via JavaScript is to prevent cross-site request forgery (CSRF). The key is only known to the JS context and also stored in the session. The CSRF token must then be sent along with every HTTPS request, and it must match the value from the session, otherwise the request must be rejected.
You can read all about this and other prevention mechanisms on the OWASP Cheat Sheet Series site.

A: Built in Session Management is a more matured solution than you writing your own cookie and managing it. You then have to worry about session expiration etc.
You could add an additional layer of security by storing the IP (if blank) of a new session, and then on all subsequent requests, verifying the session's IP matches the user's IP.
This way, if the session expires or the user changes network, you can request the user to re-authenticate.
A quick link to common session management vulnerabilities and how to address them https://krify.co/session-management-vulnerabilities-security-testing/


text:
Q: Getting bash: java: command not found while using java -jar I'm new to everything I mention here so this makes it a little bit hard for me.
I wanted to install Selenium driver to run codeception acceptance tests.
I downloaded selenium server, copied the selenium-server-standalone-3.0.0-beta2.jar in the same path as I save my tests.
then I ran the java -jar selenium-server-standalone-3.0.0-beta2.jar on Git Bash according to codeception help on installing Web Driver. I got the error

bash: java: command not found

anybody knows what's wrong here?

A: java is not installed or it isn't present in PATH.


text:
Q: CSS height: 100% vs height: inherit I've seen the question asking the difference between height: 100%; and height: auto;, but what's the difference between height: 100%; and height: inherit;?
I basically want this element's height to fill/match it's container. Would there be a reason to use 100% over inherit or vice versa?

A: height: 100% will match the height of the element's parent, regardless of the parent's height value.
height: inherit will, as the name implies, inherit the value from it's parent. If the parent's value is height: 50%, then the child will also be 50% of the height of it's parent. If the parent's size is defined in absolute values (e.g. height: 50px), then height: inherit and height: 100% will have the same behaviour for the child.

A: height: inherit The inherit keyword specifies that a property should inherit its value from its parent element.
height: 100% Defines the height in percent of the containing block
For examples, look here


text:
Q: Wordpress change metabox title Actually, I'm working on woocommerce customization...
I've read this question about the title change in metabox:
Customizing WooCommerce Short Description Metabox title
It help me a lot. But, in the product, how can I find the "metabox tag" callback name?
function epptm_rename_meta_boxes(){
    remove_meta_box( 'tagsdiv-product_tag', 'product', 'side' );
    add_meta_box( 'tagsdiv-product_tag', __( 'This metabox is awesome', 'your-plugin' ), 'CALLBACK?', 'product', 'side' );
}
add_action( 'add_meta_boxes', 'epptm_rename_meta_boxes', 40 );

A: here is another solution found:
/**
 * hook to the 'add_meta_boxes' action to modify title
 */
function change_meta_box_titles() {
    global $wp_meta_boxes; // array of defined meta boxes
    // cycle through the array, change the titles you want
    $wp_meta_boxes['product']['side']['core']['tagsdiv-product_tag']['title']= 'Here is my new title';
}
add_action('add_meta_boxes', 'change_meta_box_titles');


text:
Q: Value of pointer when address of the pointer not initialized #include <iostream>

int main()
{
    int a;
    int *p = &a;
    std::cout << *p << "\n";
}

In this program, when I leave a uninitialized and try getting the output
of the pointer, it gives me -2. But when I initialize a with a value, printing *p gives me that value. Why does it give -2 when I leave a uninitialized?

A: Because using uninitialized variables, whether direct or indirect (through a pointer or reference), is undefined behavior[1][2][3].

[1] This basically means that those uninitialized variables would have indeterminate values.
[2] I'm sure you'll never like undefined behavior anywhere in your code.
[3] Golden rule: beware of undefined behavior.

A: a is allocated on stack. It contains whatever was there by chance, when it got allocated. Unlike global, local variables in C are not implicitly initialized to 0 (or anything else).
Probably if you run program multiple times, it will give different value (or not).

A: it is illegal in c++ to assign a pointer to a undefined value . a is uninitialized . When you are dereferencing it , it just points to a garbage value .


text:
Q: Video doesn't fully clipped in circle path Flutter I want to clip a video widget inside a circle path with CustomClipper<Path>.
Here is the empty circle clip :

And here is the video wrapped by the clipper

The video is not fully clipped inside the circle and somehow drawn above the painter. This is happening while playing and not playing, and according my tests only on IOS
I'm using the better player to display video : https://pub.dev/packages/better_player .
I opened an issue on this lib because I suppose this could be a video problem. I'm facing this issue only with video in my app.
Here is the issue and the full code sample to run :   https://github.com/jhomlala/betterplayer/issues/696
Does anyone ever seen this behavior even with another case and know how to solve this ?


text:
Q: Grab images from URL and display them I have a question about document object model in javascript.
I'm attempting to build a program that grabs images from a url and outputs them, I have actually done this in php using the code below but my question is how would I perform the same function in javascript?
<?php

    $url = 'http://lockerz.com/s/104049300';

    $doc = new DOMDocument();
    @$doc->loadHTMLFile($url);

    // Get all images
    $images_list = $doc->getElementsByTagName('img');

    foreach($images_list as $image) {
      echo $image;
    }

?>

A: You can't send a request to http://lockerz.com/ using ajax (assuming it's not your own domain), so you will need some server side script anyways. You might as well just use what you've got working in php, but change it to take the url as a parameter and return a JSON array like:
<?php

    $url = $_GET['url'];
    // sanitize url here, possible verify that it begins with http://lockerz.com, or something

    $doc = new DOMDocument();
    @$doc->loadHTMLFile($url);

    // Get all images
    $images_list = $doc->getElementsByTagName('img');

    $out = '[';
    foreach($images_list as $image) {
      $out .= $image.',';
    }

    echo substr($out, 0, -1).']';

?>

Then use javascript to send ajax requests to your own php page and do what you want with the array returned.

A: Pure client side solution based on AJAX or iframe will violate the same origin policy. That is once using AJAX (or iframe) to get pages not on your web site, browser will ban this behavior.
I suggest using server side to fetch the page and pass it back to client.
Server side: http://your-host/fetch.php
<?php
$url = $_GET['url'];
echo file_get_contents($url);
?>

Client side (based on jQuery):
<script>
    $.get('http://your-host/fetch.php', {url: 'http://lockerz.com/s/104049300'}, function(data) {
        var imgs = $('<div/>').html(data).find('img');
        imgs.each(function(i, img) {
            alert(img.src); // show a dialog containing the url of image
        });
    });
</script>

A: You can get the content of a website using jQuerys .load() method.
After you got the html you can parse the html source.
http://api.jquery.com/load/
hope that helps


text:
Q: How to convert System.Byte[] to bitmap? I'm doing a job for the school but I'm having problems with the images.
I get System.Byte [] from my web service and I've tried several solutions and I can't convert to bitmap and add my ImageView. In my database the column "Image" appears .
Can someone help me? thanks
Here is my android code.
private String NAMESPACE = "http://tempuri.org/";
private String URL = "http://X.X.X.X/ProjetoFinal/WSGestao.asmx?WSDL";
private String METHOD_NAME = "List_Images";
private String SOAP_ACTION = "http://tempuri.org/List_Images";
private String[] List;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_layout);

    new MyAsyncTask().execute();

}

private class MyAsyncTask extends AsyncTask<Void,Void,String[]> {

    protected String[] doInBackground(Void... strings) {

        //connection to the web service
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.debug = true;

        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapObject response = (SoapObject) envelope.getResponse();

            //Fetch the server's response and add the list
            List = new String[response.getPropertyCount()];

            for (int i = 0; i < response.getPropertyCount(); i++) {

                List[i] = response.getProperty(i).toString();

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

        return List;
    }

    @Override
    protected void onPostExecute(String[] result) {
        super.onPostExecute(result);

        //convert to Bitmap

    }
}

The web service sends:
<ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">
<string>System.Byte[]</string>
<string>System.Byte[]</string>
<string>System.Byte[]</string>
<string>System.Byte[]</string>
<string>System.Byte[]</string>
<string>System.Byte[]</string>
<string>System.Byte[]</string>
<string>System.Byte[]</string>
</ArrayOfString>

A:   public static void setImageViewWithByteArray(ImageView view, Byte[] data) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        view.setImageBitmap(bitmap);
    }

Use this code to display byte [] on imageView

A: Your web service send you strings. And you trying to convert System.Byte[] string to image. But it is string, not image. Thats why it doesn't work.
result[0].getBytes() shows you this:

Here in data array there are 13 elements (length of "System.Byte[]" string is also 13). Each byte here is just utf8 code of symbol in "System.Byte[]" string.
83 is big S symbol, 121 is y, 115 is s  etc.
So you need to provide correct byte array of real image and use setImageViewWithByteArray method from Destroyer answer.


text:
Q: How to assign a string to a character pointer in C? How do I assign a string to a character pointer in C ?
Suppose I have a string like "1234788654446" and when I assign it to a char pointer, I am getting error like "missing terminating character". What's wrong with the following code ?
The actual problem statement is this : I have a 1000 digit number and i have to find the greatest product of 5 consecutive digits. so when i store the number in a string, I am getting warning: ""Integer constant is too large for its type" and error "Invalid digit 9 in octal constant" .
My code is :
#include<stdio.h>

int main(){

int i=0;

 int a,b,c,d,e,pro,max=0;

char str[] = "73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450";

while(str[i+4] !='\0'){

     a = str[i]-'0';
     b = str[i+1]-'0';
     c = str[i+2]-'0';
     d = str[i+3]-'0';
     e = str[i+4]-'0';;

     pro = a*b*c*d*e;
     if(pro>max)
       max = pro;

i++;
}

 printf("%d",max);

return 0;

}

A: It looks like the problem is that you're assigning the string over multiple lines. If you're going to do that, make sure you have a \ followed by no other characters at the end every line during the string assignment so the compiler knows that the string continues below.
Alternative solutions would be to assign the string on one singular line, or wrap each line in quotes.
Example:
char str[] = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450";

A: Line breaks aren't your friend. You need to do ...
    char str[] = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
...
71636269561882670428252483600823257530420752963450";

(Notice the \ on the end of each line, and no leading whitespace on subsequent lines. You can't split a quoted string over multiple lines in C without using \)
Option B is:
char str[] = "73167176531330624919225119674426574742355349194934"
             "96983520312774506326239578318016984801869478851843"
             ...
             "71636269561882670428252483600823257530420752963450";

A: You can't wrap strings like that.  You can concatenate them by putting "s around each line:
char str[] = "123"
             "432"
             "543";

Or you can use a backslash \ to continue lines if you ensure there is no extra whitespace at the beginning.
char str[] = "123\
456\
789";

The warnings are coming because the compiler is interpreting subsequent lines as integers, which are too large to be stored.  And a line of digits starting with 0 is interpreted as an octal number, which explains the "invalid digit 9"  error.


text:
Q: How can I remove my controller name from the url using .htaccess How can I remove the controller name from the URL when I access the index function of that controller?
This is my root :-
www.abc.com/sample/dev/
This is the controller name :-
home
Therefore :- If www.abc.com/sample/dev/home is the url, then it should become www.abc.com/sample/dev/. Also, how can I remove the index.php from this url :-
www.abc.com/sample/dev/index.php,
so that it becomes
www.abc.com/sample/dev/

as well.


text:
Q: Exit remote python program when ssh connection closes I'm writing a python program to run on a remote machine.
When I execute the program on the remote machine like this.
ssh remotemachine foo.py
and I stop the ssh connection with CTRL-c the program keeps running for sometime.
I know I can start the ssh connection with a pseudo terminal like this.
ssh -t remotemachine foo.py
Then the program will catch the CTRL-c event and I can handle it in the program. But I was wondering if there is a better solution.

A: you can get pid of instance of this app/script and send kill command


text:
Q: How to print all lines except the line before a pattern in file using awk How can we do this with awk?
Input file
Line 1
Line 2
####PATTERN####### (Line 3)
Line 4
Line 5
Line 6
####PATTERN####### (line 7)
Line 8
####PATTERN####### (Line 9)

etc..
output file
Line 1
Line 3
Line 4
Line 5
Line 7
Line 9

A: sed '$!N;s/.*####PATTERN####### \(.*\)/\1/;P;D' text

Output
Line 1
(Line 3)
Line 4
Line 5
(line 7)
(Line 9)

The N command grabs the next line from the input into the pattern space so that we can perform a pattern matching against two lines. If we discover ####PATTERN###### in the middle, we only keep the second part so that the previous line is deleted. The P command prints the resulted pattern.

A: Code for sed:

sed -nr '/####PATTERN#######/!{x;1!p;x};$p;h' file

$ sed -nr '/####PATTERN#######/!{x;1!p;x};$p;h' file
Line 1
####PATTERN####### (Line 3)
Line 4
Line 5
####PATTERN####### (line 7)
####PATTERN####### (Line 9)

Code for GNU awk:
awk '{if ($0 ~ /PATTERN/ && NR>1) {delete l[(NR-1)]}; l[NR]=$0}END {for (a in l) print l[a]}' file

$ awk '{if ($0 ~ /PATTERN/ && NR>1) {delete l[(NR-1)]}; l[NR]=$0}END {for (a in l) print l[a]}' file
Line 1
####PATTERN####### (Line 3)
Line 4
Line 5
####PATTERN####### (line 7)
####PATTERN####### (Line 9)

A: Here is one way with awk:
awk '/PATTERN/{for(;i<NR-2;)print lines[++i];i=NR;delete lines;print $0}{lines[NR]=$0}' file

Output:
$ cat file
Line 1
Line 2
####PATTERN####### (Line 3)
Line 4
Line 5
Line 6
####PATTERN####### (line 7)
Line 8
####PATTERN####### (Line 9)
$ awk '/PATTERN/{for(;i<NR-2;)print lines[++i];i=NR;delete lines;print $0}{lines[NR]=$0}' file
Line 1
####PATTERN####### (Line 3)
Line 4
Line 5
####PATTERN####### (line 7)
####PATTERN####### (Line 9)


text:
Q: How to add tables and relations to generated Asp.Net Core MVC Identity database? I have a project where I have to make an ASP.NET Core MVC Web Application in which I should include user sign up, login, and an SQL database with basic CRUD operations and corresponding views. For login and signup I decided to use Asp.Net Core Identity following this tutorial: https://youtu.be/CzRM-hOe35o. Everything works and looks fine for signup and login but I can't figure out how to use my database with the database generated by Identity.
My idea for a project database was to have a table for a User and Article (there are more tables but I'm going to keep it simple to explain my problem) with one to many relation. Now that I have a generated database for all things about Users(from Identity tutorial) how can I include this Article table in the databse and make a one to many relation between AspNetUsers and Article?
Or can I use two databases in my project, one with Users and the other one with other project tables? But then how to make relations between tables from different databases, and is it even possible?

A: First of all, you should know that you can use two databases but never on this case.
To do what you want, follow those steps:
Step 1 - Create a class called "User" in project folder called "Data". Class will be like this:
public class User : IdentityUser
{

}

Step 2- Create another class called "Article" in the same folder called "Data".
 public class Article
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public virtual User User { get; set; }
}

Step 3 - Go to "User" class that you created in the step one and edit it to look like this
 public class User : IdentityUser
{
    public virtual ICollection<Article> Articles { get; set; }
}

Step 4 - In the same folder where you added those two classes you have another class called "ApplicationDbContext". Open it and register User and Article classes.
 public class ApplicationDbContext : IdentityDbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Article> Articles { get; set; }
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

Step 5 - delete in your local database the existing db generated from your project before.
After that "Add-migration" and "Update-database"
For more information about how Entity Framework Core works see the link : https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship#:~:text=The%20easiest%20way%20to%20configure,public%20class%20Author


text:
Q: add active/disable to child element on click I'm working on this simple selection that add 'active' class to the clicked element, and add 'disable' class to the element at opposite container.
My problem is how can move the active/disabled class from .col-md-5ths to their child element .num.
kindly check code.
Thanks.

$('.numChoice > .col-md-5ths').click(function() {
    if (!$(this).hasClass('disabled')) {
        var otherSide = $(this).parent().hasClass('first-row') ? '.second-row' : '.first-row';
        var otherElement = $(otherSide).children().removeClass('disabled').eq($(this).index());
        $(this).toggleClass('active').siblings().removeClass('active');
        $(this).hasClass('active') ? otherElement.addClass('disabled') : otherElement.removeClass(
            'disabled');
        $(this).hasClass('disabled') ? otherElement.removeClass('active') : otherElement.removeClass(
            'active');

    } else {
        $(this).removeClass('disabled');
        var otherSide = $(this).parent().hasClass('first-row') ? '.second-row' : '.first-row';
        var otherElement = $(otherSide).children().removeClass('disabled').eq($(this).index());
        $(this).toggleClass('active').siblings().removeClass('active');
        $(this).hasClass('active') ? otherElement.addClass('disabled') : otherElement.removeClass(
            'disabled');
        $(this).hasClass('disabled') ? otherElement.removeClass('active') : otherElement.removeClass(
            'active');

    }

});
.numChoice{
  display: block;
}
.num{
  width: 20px;
  height: 20px;
  background-color: #DDD;
  text-align: center;
  float: left;
  cursor: pointer;
}
.col-md-5ths.active{
    color: green;
}
.col-md-5ths.disabled{
    color: red;
}

1

2

3

4

5

1

2

3

4

5

A: Here is a shorter version

$('.numChoice > .col-md-5ths > .num').on("click", function(e) {
  e.preventDefault(); // stop the link
  var $this = $(this);
  if ($this.is(".disabled")) return; // assuming you cannot click on a disabled
  $this.toggleClass('active');
  var act = $this.is(".active");
  var idx = $this.parent().index();
  var $otherSide = $this.closest(".numChoice").siblings(); // plural but only one
  var $otherElement = $otherSide.find(".num").eq(idx);
  $otherElement.toggleClass('disabled', act);
});
.numChoice {
  display: block;
}

.num {
  width: 20px;
  height: 20px;
  background-color: #DDD;
  text-align: center;
  float: left;
  cursor: pointer;
}

.num.active {
  color: green;
}

.num.disabled {
  color: red;
}

1

2

3

4

5

1

2

3

4

5

A: You can can achieve that in a more simplified way like the following:

$('.numChoice .num').click(function() {
  $('.num').removeClass('active').removeClass('disabled');
  var parent = $('.first-row').has(this).length == 0?'.first-row' : '.second-row';
  var idx = $(this).parent().index();
  $(this).toggleClass('active');
  $(parent+' .num').eq(idx).toggleClass('disabled');
});
.numChoice{
  display: block;
}
.num{
  width: 20px;
  height: 20px;
  background-color: #DDD;
  text-align: center;
  float: left;
  cursor: pointer;
}
.active{
    color: green;
}
.disabled{
    color: red;
}

1

2

3

4

5

1

2

3

4

5

A: You can do it like this...

$('.numChoice > .col-md-5ths').click(function(index,el) {
    var thisind = $(this).index() + 1;
    if($(this).parent().hasClass('first-row')){
      $(this).addClass('active');
      $(this).siblings().removeClass('active');
      $('.second-row .col-md-5ths').removeClass('disabled');
      $('.second-row .col-md-5ths:nth-child('+thisind+')').addClass('disabled');
    }
    else {
      $(this).addClass('disabled');
      $(this).siblings().removeClass('disabled');
      $('.first-row .col-md-5ths:nth-child('+thisind+')').addClass('disabled');
    }
});
.numChoice{
  display: block;
}
.num{
  width: 20px;
  height: 20px;
  background-color: #DDD;
  text-align: center;
  float: left;
  cursor: pointer;
}
.col-md-5ths.active{
    color: green;
}
.col-md-5ths.disabled{
    color: red;
}

1

2

3

4

5

1

2

3

4

5

A: I created a sample fiddle for you
$('.numChoice > .col-md-5ths').click(function() {
            var otherSide = $(this).parent().hasClass('first-row') ? '.second-row' : '.first-row';
        var otherElement = $(otherSide).children().removeClass('disabled').eq($(this).index());
      var $thisNum = $(this).children();
    if (!$(this).hasClass('disabled')) {
        $thisNum.toggleClass('active').siblings().removeClass('active');
        $thisNum.hasClass('active') ? otherElement.addClass('disabled') : otherElement.removeClass('disabled');
        $thisNum.hasClass('disabled') ? otherElement.removeClass('active') : otherElement.removeClass('active');
    } else {
        $(this).removeClass('disabled');
        $thisNum.toggleClass('active').siblings().removeClass('active');
        $thisNum.hasClass('active') ? otherElement.addClass('disabled') : otherElement.removeClass('disabled');
        $thisNum.hasClass('disabled') ? otherElement.removeClass('active') : otherElement.removeClass('active');

    }

});


text:
Q: How important is $R^2$ when prediction is not the research aim? I have the problem that in my binomial-glmm model with a nested random effects structure (30,000 rows located 30 groups nested in 25 groups) the diagnostic plots look okay (as far as I can tell), residuals do not show heavy patterns and some predictors are even significant.
However, the $R^2$ is 0.055. My goal is not to predict new values but only to understand the relationships in the present dataset. Is $R^2$ still important?
Or is it possible that my structure is nonsense and thus leads to the low $R^2$?
Additional info:
there are 25 Wind energy stations (WEA) beeing build. During building these, noise levels are believed to have an impact on porpoises (dolphin like species). There 30 acoustic stations measuring porpoise noises (they can differentiate between ships and fish), temperature value and noise levels (SEL). the WEA sometimes use a noise-muting-device. The aim is to find out whether this device leads to more porpoise clickx during a certain time period. Measuremnts of the stations were done over a year, every minute. however, of interest is only the 100 hours interval after the WEA-build was finished. This is called the HRW-phase (hour related work). There is always one WEA-build per time, not all together. So WEA can be thought of as an event.
Dependent variable:

*

*ppm (counted porpoise clicks per minute during an hour) so hourly values

*

*zero-inflated count data

Independent variable:

*

*SEL a measure of noise, averaged per day (continous)

*average daily temperature (continous)

*total building time (continuos = minutes)

*locations x/y of the stations (still in geographic system, i.e. 54,333 9,3333)

*hrw (time phase after work, from 0,1,2,...,100. stations do not always measure the full lentgh ,sometimes only 17 hours)

*noise muting device (binary factor)

*month as a factor with 7 level (cat.)

*WEA ID (cat, random effect)

*acoustic station (cat, random effect)

*podid at one station, sometimes pod-acoutstic measure systems per station were exchanged (cat)

*potentially also 4 distance classes

I build the random effects with  (hrw|WEA/station) although I am still not sure if this is the right design. the thing is that WEA is an event (there 25) at during an event 30 stations measure ppm. is this then crossed or nested? i am not sure.
although I expected temporal and spatial autocorrelation I did not find any hints on that.
I hope this clarifies the story a bit more.

A: Assuming you are using a pseudo-$R^2$, as @gung commented, a low value of this means that your model is not explaining much (although you should note that the interpretation of pseudo $R^2$ is not identical to that of $R^2$ in OLS models). You could also look at other effect size measures, such as odds ratios.
The fact that some things are significant even with such small effect sizes is due to your large sample. With 30,000 subjects, nearly any effect will be statistically significant. Whether it is of practical importance is another matter. In most fields, such small effects will not be of practical importance.
If you provide context (e.g. what is your DV and IVs?) then someone may be able to provide more help.


text:
Q: .NET Compact Framework SDK download Where can I find the .NET Compact Framework SDK for developing Compact Framework applications in Visual Studio?

A: Unlike the desktop version of the .NET runtime there isn't a single download for the .NET CF that I am aware of.
You instead need to install a Visual Studio based SDK for each device type you want to support. These SDKs install emulators and other development related support files specific to a given platform that the .NET CF runs on (i.e. XBOX, Zune and Windows Mobile OS variants all have subtle differences even though they all use the  "same" .NET CF).
For example here is the MS downloads page for SDK for Windows Mobile 6.0 Professional and Standard devices. When you install Visual Studio also make sure you select the optional Smart Devices support feature.
If you build something against the WM 6.0 SDK, you should find that for the most part your .NET CF application will work on any Windows Mobile device (i.e. Pocket PC 2003, WM 5.0, WM6.0, 6.1, 6.5...). This of course assumes you don't include something device, or OS version specific.
If you install more than one SDK, its easy enough within the Visual Studio IDE (a Change Platform menu option) to toggle between the various OS versions/platforms within your project to test on different emulators etc.


text:
Q: Most important things about C++ templates… lesson learned What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...common mistakes/oversight/assumptions
I am starting to implement most of my library/API using templates and would like to collect most common patterns, tips, etc., found in practice.
Let me formalize the question: What is the most important thing you've learned about templates?
Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly dry descriptions
Thanks

A: This may not be popular, but I think it needs to be said.
Templates are complicated.
They are awesomely powerful, but use them wisely. Don't go too crazy, don't have too many template arguments... Don't have too many specializations... Remember, other programmers have to read this too.
And most of all, stay away from template metaprogramming...

A: I'd have to say Coplien's Curiously Recurring Template Pattern (CRTP) is the one template trick that I find myself reaching for over & over again.  Essentially it allows you to inject statically customized functionality into a derived class by inheriting from a base class that is parameterized on the derived class name.  Mind boggling, but amazingly useful (some call it static polymorphism).
Also, I'll second Neil Butterworth's advice to read "C++ Templates" and throw in Alexandrescu's Modern C++ Design.

A: Template Tip of the Day:
Did you know you can specialize chosen functions of template instantiations:
#include <iostream>
#include <vector>

namespace std {
    template<>
    void vector<int>::clear() {
    std::cout << "Clearing..." << std::endl;
    resize(0);
    }
}

int main() {
    std::vector<int> v;
    v.push_back(1);
    v.clear();
}

ouputs:
Clearing...
Of course, this is only an example and, as @Desmond Gold noticed, changing behaviour of standard containers may leads to undefined behaviour.

A: This question is a bit like "I'm going to implement most of my library using functions, what are the common mistakes in using functions?" It's hard to come up with sensible answers to such questions, but here's my advice - read a good book. I recommend "C++ Templates" by Vandevoorde & Josuttis,

A: One common mistake is that a template constructor or assignment operator will not suppress the compiler generated one:
template <typename T>
class A {
public:
  template <typename S>
  A(A<S> const &);

  template <typename S>
  A & operator=(A<S> const &);

private:
  int * i;
};

Although these functions look like the copy constructor and copy assignment operator, the compiler does not see it that way and generates the implicit versions anyway.   The result is that any actions performed by these functions (eg. deep copy of a member) will not take place when the object is copied or assigned to from the same type:
void foo (A<int>);

void bar () {
  A<int> a1;
  foo (a1);   // Implicitly generated copy ctor called

  A<long> a2;
  foo (a2);   // Template ctor called.

  A<int> a3;
  a3 = a1;   // Implicitly generated copy assignment operator called

  a3 = a2;   // Template assignment operator called
}

The reason for this behaviour is due to a special rule in overload resolution (13.3.3):

Given these definitions, a viable
  function F1 is defined to be a better
  function than another viable function
  F2 if for all arguments i, ICSi(F1) is
  not a worse conversion sequence than
  ICSi(F2), and then

[...]

— F1 is a non-template function
  and F2 is a function template
  specialization, or, if not that,

In the examples above, overload resolution sees two functions with the same signature, one of which is a template.  The non template function (the implicitly generated copy constructor/copy assignment operator) wins and so is called.

A: From "Exceptional C++ style", Item 7: function overload resolution happens before templates specialization. Do not mix overloaded function and specializations of template functions, or you are in for a nasty surprise at which function actually gets called.
template<class T> void f(T t) { ... }   // (a)
template<class T> void f(T *t) { ... }  // (b)
template<> void f<int*>(int *t) { ... } // (c)
...
int *pi; f(pi); // (b) is called, not (c)!

On top of Item 7:
Worse yet, if you omit the type in template specialization, a different function template might get specialized depending on the order of definition and as a result a specialized function may or may not be called.
Case 1:
template<class T> void f(T t) { ... }  // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f(int *t) { ... }      // (c) - specializes (b)
...
int *pi; f(pi); // (c) is called

Case 2:
template<class T> void f(T t) { ... }  // (a)
template<> void f(int *t) { ... }      // (c) - specializes (a)
template<class T> void f(T *t) { ... } // (b)
...
int *pi; f(pi); // (b) is called

A: The STL is your friend.

A: Here are some rules:

*

*Don't write any templates unless you're writing a very, very generic library (STL and Boost are two prominent examples).

*Don't instantiate any non-trivial template too many times. Instantiating huge template classes is especially overkill. You should consider using inheritance and polymorphism (the simple way, I mean, using virtual functions).

*If you're writing any templates, knowing when to use const, mutable and volatile will save users of the template both compile and execution time.

*If you're instantiating any templates, use a good compiler.

A: Read Meyers's Effective STL and C++ books, and Alexandrescu's Modern C++ Design.
Meyers will give you the basics on easy mistakes to make and how to avoid them.  Alexandrescu introduces you to a template-based programming model that should have you asking "Is this really a good idea?" the entire book.

A: I tend to use templates quite a lot to avoid duplication of code, and to increase safety through compile checks.
In general, it helps to think while typing about what the compiler is going to do, and how the code will be generated for each type.
Being very iterative in development and building the template complexity little by little has helped me avoiding sinking in compile error messages. Don't forget to keep a simple (or mock) instantiation of the template somewhere, otherwise you might have some nasty surprises when you instantiate a monster template for the first time.
Finally, when there is no way out, get to read these compile error messages! They might look quite scary at first, but they really are helpful. Maybe at first extracting the first one, copying it in a text editor and making it look pretty will help getting used to them, and it quickly becomes second nature to read through.

A: It's important to understand separate compilation and the possibility of resulting executable size increases. If you instantiate the template with the same type in several C++ files, you will get the type reproduced multiple times, at least on some compilers.

A: I've used c++ and templates a lot, including more advanced template metaprogramming and my feeling is that their usefulness is overrated.  They were originally added to the c++ language, well after the creation of c++, to tack on a generic programming capability.  This simply allows one to focus on the logic of the code without regard for types, potentially making code clearer and reusable.
My programming philosophy is to understand the original purpose and design of the language and it's features in order to really appreciate the language.  I feel template metaprogramming is bastardization of templates and should be avoided.  Templates are however useful for defining higher level generic types such as the case of Tuples.


text:
Q: what does this bash if statement mean? What does the following bash script mean:
if [ -d "directory name" -a ! -L "directory name" ]; then
  # do something
fi

I can understand up to here:

if [ -d "directory name"

but I'm lost after that.  Extra consideration if, in addition to explanation, docs that explain -a ! -L

A: The -L operator tests whether its argument is a symbolic link. It can also be written as -h.
The ! is the logical negation operator, and -a is logical "and".
So this:
if [ -d "directory name" -a ! -L "directory name" ]; then

means "if whatever is a directory and is not a symbolic link".  (-d will return true if the target is a symbolic link to a directory.
The [ syntax is actually a synonym for the test command. Either man test or info test on your system should show you the documentation. [ is also a built-in command in bash, so info bash will also show you the documentation; search for
`test'

A: *

*-d is "directory exists," but you seem to know that.

*-a is "logical and."

*! is "expression is false"

*-L is "file exists and is a symbolic link (same as -h)"

So in english this would read
If "directory name" exists and is a directory and "directory name" exists and is not a symobolic link, then...
The documentation you want is man test.

A: I believe the second portion is:
...and (-a) "directory name" is not (!) a symbolic link (-L)

A: The -a is an extension to the POSIX standard version of test to serve as a boolean AND operator. Its use is discouraged by the standard itself (see the Application Usage section) in favor of two separate test commands using the regular shell && operator.
if [ -d "directory name" ] && [ ! -L "directory name" ]; then
    # do something
fi

The linked page also defines the -d, ! and -L operators:

*

*-d  pathname
True if pathname resolves to an existing directory entry for a directory. False if pathname cannot be resolved, or if pathname resolves to an existing directory entry for a file that is not a directory.

*!  expression
True if expression is false. False if expression is true.

*-L  pathname
True if pathname resolves to an existing directory entry for a symbolic link. False if pathname cannot be resolved, or if pathname resolves to an existing directory entry for a file that is not a symbolic link. If the final component of pathname is a symbolic link, that symbolic link is not followed.

A: *

*[ -d FILE ] - True if FILE exists and is a directory.

*[ -a File] - True if FILE exists.

*[ -L FILE ] - True if FILE exists and is a symbolic link.

*[ ! EXPR ] - True if EXPR is false.