text:
Q: HTML CSS height 100% only goes as tall as the screen resolution, not the body height I can't figure out how to make my seasonal overlay div the full height of the html. Right now its the height of the screen, but scrolling down cuts off part of the image. Does anyone know the right way to make the sesasonal overlay div extend the whole height of the html? The div is part of a server side include so I can't close the underlay div after my content. Also, half my closed online sales don't use javascript, so it needs to be an html/css solution please.
You can save time from reading below by just seeing my JSFIDDLE.
Thanks.
CSS:
html{
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#C5CEFF', endColorstr='#F8D0FD',GradientType=0 );
    background: -webkit-gradient(linear, left top, left bottom, from(#C5CEFF), to(#F8D0FD)) fixed;
    background: -moz-linear-gradient(top, #C5CEFF, #F8D0FD);
    margin:0px;
    padding:0px;
    min-height:100%;
}

body{
    margin:0px;
    padding:0px;
    overflow-x: hidden;
    min-height:100%;
    display:block;
}

.background-overlay-season
{
    position:absolute;
    left:0px;
    top:0px;
    z-index:-1;
    width:100%;
    background-image:url(http://sonosmile.com/images/fall.png);
    margin:0px;
    padding:0px;
    overflow-x: hidden;
    min-height:100%;
    display:block;
}

HTML:

a bunch of content....

A: Right, I think I've found it.
Firstly, I think the image should be set on the body, but you said that didn't work in IE, and you were right.
If we remove the filter from the html CSS and the body background-image appears, but obviously that's not too helpful as we've lost the gradient in IE.  Ok.  So, trying to find out why, I tested creating a new gradient from Colorzilla.  When I put that in, it worked:
background: #c5ceff; /* Old browsers */
background: -moz-linear-gradient(top,  #c5ceff 0%, #f8d0fd 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#c5ceff), color-stop(100%,#f8d0fd)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #c5ceff 0%,#f8d0fd 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #c5ceff 0%,#f8d0fd 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #c5ceff 0%,#f8d0fd 100%); /* IE10+ */
background: linear-gradient(to bottom,  #c5ceff 0%,#f8d0fd 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#c5ceff', endColorstr='#f8d0fd',GradientType=0 ); /* IE6-9 */

Great.  But why?  After some debugging, it turns out that unless you specify the first background (background: #c5ceff; /* Old browsers */), it won't work, the background on the body just won't show. And it's not just a background-image, it won't work for a solid color either.  No idea why.
But there you go.  Here's your new CSS, with your leaves background-image on the body, and working in IE.
html {
  background: #c5ceff; /* Old browsers */
  background: -webkit-gradient(linear, left top, left bottom, from(#C5CEFF), to(#F8D0FD)) fixed;
  background: -moz-linear-gradient(top, #C5CEFF, #F8D0FD);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#C5CEFF', endColorstr='#F8D0FD',GradientType=0 );
  margin:0px;
  padding:0px;
}

body{
  margin:0px;
  padding:0px;
  background:url(http://sonosmile.com/images/fall.png);
}

http://jsbin.com/eBOcuLE/4/edit

Note that I removed all your styling for the empty div.  Using that div as your background won't work, because although you can make it 100% height, it will only be the height of the viewport.  It has no content in it, so it has no idea that the page content is going longer that the viewport.

A: Hmmm, I think I may have an answer for you.
Remember that when using position:absolute, the element ends up being relative to the first ancestor element it encounters with position:relative. Should one not exist, the container will be considered the . So why doesn't , and hence .background-overlay-season go to the bottom of the document?
You have to consider what the min-height: 100% you specified on  is actually relative to; what exactly is it 100% of? The behaviour suggests that it is actually relative to the browser viewport's height, so the  (and any element using it as a reference for height) can be guaranteed as tall as the viewport. As a result, you'll actually want to make  the container, not , with a simple addition to your CSS:
body{
    position:relative;
}

Here's a JSFiddle showing what this achieves. Note that .background-overlay-season extends to the bottom of the document now. If this isn't what you were looking for, let me know and I'll be happy to (try) helping further! (This was a bit of a learning experience for me too, haha...)

A: If you want background-image on all your body, you can use this
body
{
  background-image: url(http://sonosmile.com/images/fall.png);
  background-size: contain;
}

Try this fiddle

A: Move the content of the div .background-overlay-season to body.
body {
    background-image: url("http://sonosmile.com/images/fall.png");
    display: block;
    left: 0;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
    padding: 0;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: -1;
}


text:
Q: php mail() not working with server <?php

ini_set('display_errors', '1');
include '../application/includes/config.php';

$mailto=$_POST['email'];
$subject="Information";
$message_body="Welcome to the digital world!";
$from="info@mydomain.com";

$mail = mail($mailto,$subject,$message_body,"From:".$from);

if($mail){
  echo "Thank you for using our mail form";
}else{
  echo "Mail sending failed.";
}
?>

I have tested this code on other website. It's working there but on my server it only displays "Mail sending failed" error..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle SQL using Distinct and Group By I've a table below
+-----+------+-----------+------------+
| id  | type | last_name | first_name |
+-----+------+-----------+------------+
|   1 | A    | Billy     | John       |
|   2 | B    | Bob       | Joe        |
|   3 | A    | Joe       | Zeb        |
|   4 | C    | Billy     | John       |
| ... | ...  | ...       | ...        |
+-----+------+-----------+------------+

I want to return all records that has the same LAST_NAME and FIRST_NAME, but have different TYPE.
Would I need to do a subquery to first get the same names, then to filter it for the TYPE?
What I would like to return:
+-----+------+-----------+------------+
| id  | type | last_name | first_name |
+-----+------+-----------+------------+
|   1 | A    | Billy     | John       |
|   4 | C    | Billy     | John       |
| ... | ...  | ...       | ...        |
+-----+------+-----------+------------+

A: Here is one possible method using a correlated subquery:
select t.*
from table1 t
where exists
(
    select 1 from table1 u
    where
    u.last_name = t.last_name and
    u.first_name = t.first_name and
    u.type <> t.type
)

Or, perhaps using joins:
select t.*
from table1 t inner join
(
    select u.last_name, u.first_name
    from table1 u
    group by u.last_name, u.first_name
    having min(u.type) <> max(u.type)
) q
on t.last_name = q.last_name and t.first_name = q.first_name

Change table1 to suit your table name.

A: maybe I have overseen something. What do you think about:
select * from table
group by last_name, first_name
having count(type) = 1

A: This should be straightforward using window functions, which are available in Oracle since early versions :
SELECT x.id, x.type, x.last_name, x.first_name
FROM (
    SELECT t.*, COUNT(DISTINCT type) OVER (PARTITION BY last_name, first_name) cnt
    FROM mytable t
) x WHERE x.cnt > 1

The inner query assigns to each record a count of distinct types for the current first/last name tuple, and the outer query fiters out rows with a count of 1.
Demo on DB Fiddle :

ID | TYPE | LAST_NAME | FIRST_NAME
-: | :--- | :-------- | :---------
 1 | A    | Billy     | John
 4 | C    | Billy     | John


text:
Q: Suggestions For Syncing Audio With Audio Queue Services? I'm decoding a video format that has an accompanying audio track in a separate file. Per the specs, I render a frame of video every 1/75th second. And the length of the video file is the same as the length of the audio track.
I'm playing the audio with Audio Queue Services (which I chose because I figured there would be situations where I needed precise timing control -- just the sort of situation I'm encountering!). It's a big API and I haven't progressed much past the sample code in Apple's programming guide (though I have wrapped things up in a nicer ObjC API).
In ideal situations, things work fine with the basic playback setup. The video and audio stays synced and both end at the same time (within my own ability to tell the difference). However, if performance hiccups (or I attach the Leaks Instrument or something), they quickly get out of sync.
This is the first time I've ever written something of this nature: I have no prior experience with sound or video. I certainly have no experience with Audio Queue Services. So I'm not sure where to go from here.
Have you done something like this? Do you have some advice or tips or tricks to offer? Is there some fundamental piece of documentation I need to read? Any help would be greatly appreciated.

A: First off, I've never actually coded anything like this so I'm shooting from the hip.  Also, I've done a decent amount of programming with the HAL and AUHAL but never with AudioQueue so my approach might not be the best way to use AQ.
Obviously the first thing to decide is whether to sync the audio to the video or the video to the audio.  From the question it seems you've decided the video will be the master and the audio should sync to it.
I would approach this by keeping track of the number of frames of video rendered, along with the frame rate.  Then, when enqueuing your audio buffers, rather than passing a monotonically increasing value for the startTime adjust the buffer's start time to match any discontinuities observed in the video.  This is a bit vague because I don't know exactly where your audio is coming from or how you are enqueuing it, but hopefully the principle is clear.


text:
Q: Query Mysql For Unique Values I have a database table for fuel with the following details

The fID is the fuel id, vID is the vehicle id, volume is the amount of fuel in litres, price is the price of fuel per litre, date is the date of filling up the vehicle, type is the type/grade of fuel.
I wanted to make a query that would return the cost of fuel by multiplying the cost of fuel per litre with the volume of fuel filled up, plus another field for distance which should be the difference between the previous fill up meter and the latest meter. In the table, there will be a lot of cars, so I just want to return records of a specific vehicle (the vID will be repeated but the fID is unique).
I have the following query so far but it returns empty if there's only one fuel entry in the database, plus I can't figure out how to calculate the cost in Mysql.
Select
t1.*, t2.meter - t1.meter as distance
From fuel t1 left join fuel t2
on t1.date > t2.date
where t1.vID = t2.vID
order by t1.date desc

How should I go about it the right way?
Here is the schema:
CREATE TABLE IF NOT EXISTS `fuel` (
  `fID` int(11) NOT NULL AUTO_INCREMENT,
  `vID` int(11) DEFAULT NULL,
  `volume` varchar(100) DEFAULT NULL,
  `price` varchar(100) DEFAULT NULL,
  `meter` varchar(100) DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `vendorID` int(11) DEFAULT NULL,
  `notes` text,
  `type` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`fID`)
) ENGINE = MyISAM DEFAULT CHARSET = latin1;

INSERT INTO `fuel` (`fID`, `vID`, `volume`, `price`, `meter`, `date`, `vendorID`, `notes`, `type`)
VALUES
  (7, 28, '15', '800', '5000', '2018-05-27 05:53:00', NULL, 'Entry number one for this vehicle', 'Unleaded'),
  (6, 27, '5', '1000', '2000', '2018-05-27 05:50:00', NULL, 'This is the second fill up for this vehicle', 'Leaded'),
  (5, 27, '15', '1200', '1200', '2018-05-27 04:58:00', NULL, 'Hey there vendors!', 'Leaded'),
  (9, 26, '25', '750', '4500', '2018-05-27 05:57:00', NULL, NULL, 'Leaded'),
  (10, 26, '20', '750', '6000', '2018-05-27 05:58:00', NULL, NULL, 'Leaded');

This is how I want to output the data that will be returned. This picture takes an example of getting all fuel history logs for a vehicle vID 27. The first entry should return distance 0. The second one should subtract its current meter reading from the previous record that also has a vID of 27 (here its 800)... Any ideas how I can achieve this?

Following Nick's answer, I implemented the following in PHP, but it throws an error. However, when I run it in mysql sql command it returns the results as expected...
$vID = 27;
$pdo = $this -> con -> query("
     select date_format(f1.date, '%y-%m-%d %H:%i:%s') as date,
             f1.meter as mileage,
             case when f2.meter is null then 0
             else f1.meter - f2.meter end as distance,
              f1.volume, f1.volume * f1.price as cost from fuel f1
     left join fuel f2
     on f2.date = (select max(date)
     from fuel where fuel.vID = f1.vID and fuel.date < f1.date)
     where f1.vID = ? order by f1.date ");

if($pdo -> execute([$vID]) && $pdo -> rowCount()) {
     $res = $pdo -> fetchAll(5);
     $this -> response($this -> json($res), 200); // send fuel logs
} else {
   $this -> response('', 204);  // If no records "No Content" status
}

Here is the error I get after executing the code through php.

A: This query will give you the individual rows that you want. The query works by joining fuel to itself using the latest fill-up date for this vehicle prior to the current fill-up date. If there is no prior fill-up date, the CASE expression produces a 0 result for distance.
SELECT DATE_FORMAT(f1.date, '%y-%m-%d %H:%i:%s') AS date,
  f1.meter AS mileage,
  CASE WHEN f2.meter IS NULL THEN 0
       ELSE f1.meter - f2.meter
       END AS distance,
  f1.volume,
  f1.volume * f1.price AS cost
FROM fuel f1
LEFT JOIN fuel f2
  ON f2.date = (SELECT MAX(date)
                FROM fuel
                WHERE fuel.vID = f1.vID AND fuel.date < f1.date)
WHERE f1.vID = 27
ORDER BY f1.date

Output:
date                mileage     distance    volume  cost
18-05-27 04:58:00   1200        0           15      18000
18-05-27 05:50:00   2000        800         5       5000

Demo
If you don't want to sum the rows in PHP, the query can produce a summary row with a minor change to the query (adding an aggregation function and a GROUP BY WITH ROLLUP clause):
SELECT DATE_FORMAT(f1.date, '%y-%m-%d %H:%i:%s') AS date,
  f1.meter AS mileage,
  CASE WHEN f2.meter IS NULL THEN 0
       ELSE f1.meter - f2.meter
       END AS distance,
  f1.volume,
  SUM(f1.volume * f1.price) AS cost
FROM fuel f1
LEFT JOIN fuel f2
  ON f2.date = (SELECT MAX(date)
                FROM fuel
                WHERE fuel.vID = f1.vID AND fuel.date < f1.date)
WHERE f1.vID = 27
GROUP BY f1.date WITH ROLLUP

Output:
date                mileage     distance    volume  cost
18-05-27 04:58:00   1200        0           15      18000
18-05-27 05:50:00   2000        800         5       5000
(null)              2000        800         5       23000

You can detect the summary row in PHP by the fact that the date column is null. Demo

A: Nicks solution will work, but the given join condition is a sub-query which runs for every join. You can also try this one, for the expected result.
select f3.date, f3.meter, f3.cost, f3.volume, f3.price, min(f3.distance) as distance from (
  select  f1.date,
    f1.meter,
    case when f2.`meter` is NULL then 0
      else f1.meter - f2.meter end
      as distance,
    (f1.price * f1.volume) as cost,
    f1.`volume`,
    f1.`price`,
    f1.fID
  from fuel f1
  left join fuel f2
  on f1.vid = f2.vid and f1.`date` > f2.date
  where f1.vid = 27
  group by f1.fID, distance
  order by date, distance asc) f3
group by f3.fID;

@Nick thanks for the feedback. Hope this query will work.

A: OK SQL can also achieve what you wanted, but it is more intuitive through store procedure. (i will also mention that controller and view i.e. PHP and jquery could also achive what you want but much more hard that way. In jquery case; mysql just needs to return that vehcle recordset.)
Here is the code
-- Proceuodo code
-- create a temporary table
-- set next_mileage = 0;
-- set pre_mileage = 0;
-- get a recordset of the desire vehicle
-- now loop through this recordset based on mileage
    -- if pre_mileage = 0 then pre_mileage = mileage(i);
    -- set next_mileage = mileage(i);
--        calculate distance (by subtracting next_mileage from previous_mileage) and other fields

DELIMITER @@
DROP PROCEDURE get_vehicle_info @@
CREATE PROCEDURE get_vehicle_info
    (IN vid INT)
BEGIN

    DECLARE v_vID BIGINT;
    DECLARE v_volume BIGINT;
    DECLARE v_price BIGINT;
    DECLARE v_meter BIGINT;
    DECLARE v_date datetime;
    DECLARE done INT DEFAULT FALSE;
    DECLARE cur1 CURSOR FOR SELECT vID, volume, price, meter, `date` FROM vehicle_records;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    DROP TEMPORARY TABLE IF EXISTS vehcle_info;
    CREATE TEMPORARY TABLE vehcle_info (`Date` datetime, Mileage BIGINT, Distance BIGINT, Volume BIGINT, Cost BIGINT);
    SET @sqlStr = CONCAT('CREATE OR REPLACE view vehicle_records as SELECT vID, volume, price, meter, `date` FROM fuel WHERE vID = ', vid, ' ORDER BY meter');
    PREPARE stmt FROM @sqlStr;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    SET @pre_mileage = 0;
    SET @next_mileage = 0;

    OPEN cur1;
    read_loop: LOOP
        FETCH cur1 INTO v_vID, v_volume, v_price, v_meter, v_date;
        IF done THEN
            LEAVE read_loop;
        END IF;

        IF @pre_mileage = 0 THEN
            SET @pre_mileage = v_meter;
        END IF;
        SET @next_mileage = v_meter;

        INSERT INTO vehcle_info VALUES (v_date, v_meter, @next_mileage - @pre_mileage, v_volume, v_price * v_volume);
        SET @pre_mileage = v_meter;
    END LOOP;
    CLOSE cur1;
    SELECT * FROM vehcle_info;

    DROP VIEW IF EXISTS vehicle_records;
    DROP TEMPORARY TABLE vehcle_info;
END @@
DELIMITER ;

CALL get_vehicle_info(27);


text:
Q: Github URL to create new file with specific name? I know you can use the URL github.com/<username>/<project_name>/new/<branch_name>/<path_to_create_file> to create a new file at a given path of a project.
Is there a way to do the same but from the URL specify the name of the new file?
So hitting something like the below in the browser:
http://github.com/Pithikos/C-Thread-Pool/new/master/tests/newtest.py

Would get me to Github's online editor and I would be able to start typing for newtest.py.

A: Answer: Yes.
You can set the parameter filename in the URL. You can even add some content to the new file. For instance, to create a new file called newtest.py with default value PUT YOUR CODE HERE, use the following URL:
https://github.com/Pithikos/C-Thread-Pool/new/master/tests?filename=newfile.py&value=PUT%20YOUR%20CODE%20HERE


text:
Q: How to find the array from the string? const str = "[1,2,3,4],5,6";

const getArray = (str) => {
...
return arr;
}

console.log(getArray(str));  //[1,2,3,4]

[1,2,3,4] is the expected array.
How can I get this one?

A: You can use regex for extracting the numbers enclosed by [] then run a map for sanitize. Check this-

const str = "[1,2,3,4],5,6";

const getArray = str => {
    const regex = /(\[([^\]]+)\])/;
    const match = regex.exec(str);

    return match?.[2] ? match[2].split(',').map(x => x.trim()) : [];
}

console.log(getArray(str));

A: This will give you an array of all arrays within your string.

const str = "[1,2,3,4],5,6";

const getArray = (str) => {
  const ans = []
  let stack = []
  let isStack = true
  for (let i = 0; i < str.length; i++) {
    if (str[i] == '[') {
      isStack = true;
    } else if (str[i] == ']') {
      isStack = false;
      ans.push(stack)
      stack = []
    } else if (isStack && str[i] != ',') {
      stack.push(parseInt(str[i]))
    }
  }
  return ans;
}

console.log(getArray(str)) // [ [ 1, 2, 3, 4 ] ]
console.log(getArray(str)[0]) // [ 1, 2, 3, 4 ]

A: You can use the JavaScript method lastIndexOf() to find the [ and ].
This will give you all characters in-between [ and ].
Then you can use the split() method to convert the array.
Using map() and Number you can convert string to number

const str = "[1,2,3,4],5,6";

function getArray(str){
  var myArray = str.substring(
    str.lastIndexOf("[") + 1,
    str.lastIndexOf("]")
  );
  return myArray.split(",").map(Number);

}

console.log(getArray(str));

A: Assuming that str contains exactly one pair of enclosing square brackets:
const getArray = (str) => {
  const idxStart = str.indexOf('[') + 1
  const idxEnd = str.indexOf(']')
  arr = str.slice(idxStart, idxEnd)
  return arr.split(',')

}

A: You can use RegEx to match the string enclosed in []

const str = "[1,2,3,4],5,6";

const getArray = (str) => {
  arr = str.match('/\[.*\]/')[0]
  return arr;
}

console.log(getArray(str));


text:
Q: PowerShell array, loop first row I have a problem with array as following with only one line:
$list = @()
$list =  (("ResourceGroup","Vm1"))

$list | ForEach-Object -Parallel {

    write-output $_[0] $_[1]

}

If I loop that array with one line, PowerShell prints the first 2 letter of each word. If I put 2 or more row like following:
    $list = @()
    $list =  (("ResourceGroup","Vm1"),`
              ("ResourceGroup","Vm2")
)

PowerShell print correctly the values inside.
There is a way to print correctly the value of an array with only one line?

A: ("ResourceGroup","Vm1") is interpreted as one array with two string elements, where as (("ResourceGroup","Vm1"), ("ResourceGroup","Vm2")) is interpreted as one array with 2 array elements, can be also called a jagged array. If you want to ensure that the first example is treated the same as the second example, you can use the comma operator ,:
$list = , ("ResourceGroup","Vm1")
$list | ForEach-Object -Parallel {
    Write-Output $_[0] $_[1]
}

To put it in perspective:
$list = ("ResourceGroup","Vm1")
$list[0].GetType() # => String

$list = , ("ResourceGroup","Vm1")
$list[0].GetType() # => Object[]

Write-Output with the -NoEnumerate switch combined with the Array subexpression operator @( ) can be another, more verbose, alternative:
$list = @(Write-Output "ResourceGroup", "Vm1" -NoEnumerate)
$list | ForEach-Object -Parallel {
    Write-Output $_[0] $_[1]
}


text:
Q: Validity of an integral The question is: Integrate the function $\left(\dfrac{9}{(6x-5)}\right)^{1/2}$, with no limits given.
I can get the integral, which is $(6x+5)^{1/2}+c$, but the second part is , hence, find the range of values for the integral to be valid, showing your working clearly.
I would like to know under what conditions an integral is valid, as I get the answer $x$ is more than or equal to $\frac{5}{6}$ but my teacher says it is just $x$ is more than $\frac{5}{6}$.

A: $$\sqrt{\frac9{6x-5}}$$ will remain  real if $\displaystyle6x-5\ge0$
but will remain finite if $\displaystyle6x-5\ne0$

A: Because the original function doesn't exist at $ x = 5/6 $. Sure the integral can still be evaluated, but it won't be a standard integral (I'm assuming you haven't got to improper integrals yet).


text:
Q: How to have a subview create a new view every time it is rendered I have a JSF page that contains two subviews. Depending on which commandButton is executed, one of the subviews is rendered. However, if validation fails on one of the subviews, the error messages stay visible and the components are still invalid the next time the subview is rendered. I have a workaround in my bean to remove the messages but the components stay invalid. Is there a way to set the components as valid or create a new view for the subview only?
Here is my work around for the messages:
Iterator messageIterator = FacesContext.getCurrentInstance().getMessages();
    while (messageIterator.hasNext())
    {
            messageIterator.remove();
    }

A: This is caused by the fact that when rendered is false the component is not shown, but it still is in the component tree for the view. So the component does not show but its values and state are still there.
There are several ways around this:

*

*Use JSTL tags such as <c:if /> (if at all possible) instead of rendered. Page elements inside a <c:if/> tag will be in the tree only if the condition is true.

*Don't do a postback when passing from one subview to the other. This effectively recreates the tree from scratch. For example perform a GET instead of a POST.

*Invalidate the view so that the tree is recreated. Make the commandButton that switches subviews immediate="true" and invalidate the view adding this code:
public void clearComponentTree() {
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    ViewHandler viewHandler = application.getViewHandler();
    UIViewRoot viewRoot = viewHandler.createView(context, context.getViewRoot().getViewId());
    context.setViewRoot(viewRoot);
    context.renderResponse();
}

*

*Directly manipulate the component tree deleting unwanted components (similar to the above, but limited to specific components). Here I assume we want to delete all components under a subview with id sub1 (this requires immediate="true" as well):

public void clearSubtree() {
    FacesContext context = FacesContext.getCurrentInstance();
    context.getViewRoot().findComponent(":sub1").getChildren().clear();
}

this link provides other minor ways of achieving this.

A: Try using primefaces extension: resetInput to reestablish the input's state:
<p:commandButton value="Load Subview" action="#{bean.startSubview}" update="subview" process="@this" >
    <pe:resetInput for="subview"/>
</p:commandButton>


text:
Q: Qualification title for French "diplôme d'ingénieur" My Google-fu has maybe failed me, but I couldn't find an authoritative source about the correct English qualification title for a French diplôme d'ingénieur.
Some sources say the title is M.Sc., others MEng., so I'm not sure which one suits it best.

A: The most generic term which would be understood in the majority of English speaking academic circles is a Masters of Engineering. The names can vary enormously depending on the institution offering the degree, but most people should understand Masters of Engineering. Some examples:

*

*Harvard

Engineering Sciences: Electrical Engineering (S.M., M.E., Ph.D.)
Engineering Sciences: Environmental Science and Engineering (S.M.,
  M.E., Ph.D) Engineering Sciences: Mechanical Engineering (including a
Materials Science track) (M.S.E.)

*MIT

The Department of Civil and Environmental Engineering's Master of Engineering (M.Eng.) is a nine-month program that provides a practice-oriented education.

*Oxford

The advanced research degrees which may be awarded to graduate students in the Department are Master of Science (MSc) by research and Doctor of Philosophy (DPhil):

*Cambridge

MPhil in Energy Technologies
MPhil in Engineering for Sustainable Development
MPhil in Industrial Systems, Manufacturing and Management
MPhil in Nuclear Energy
MRes Photonics Systems Development
MRes in Ultra Precision
MSt Construction Engineering

A: I usually present my Diplome d'Ingenieur as a MSc in Engineering, on the basis that MEng programmes in the UK are shorter and considered slightly less thorough than BSc+MSc programmes. In fact, MEng is an undergraduate degree, whilst the French DI is closer to a French MSc and would be a postgraduate degree.
However, some universities also offer MSc in Engineering programmes in France, which are distinct from the DI. I personally do not care to make a distinction between University and Grandes Ecoles, but if the distinction is usually recognised in a specific industry (i.e. if the industry specifically wants certified engineers), one would be better off explicitly stating that their degree is a certified Diplome d'Ingenieur.


text:
Q: How can I use USB interface to send real time data using Beaglebone My professor ask me to find a way to stream ADC data to PC (or Matlab) using a Beaglebone Black Board (BBB) at 10khz~20kHz or more frequencies over usb.
I know that I can use PRUs to program in real time and I know that USB protocol has isochronous transfer mode to stream data. Or I can use USB-serial to archive it.
So my idea is using PRU to capture ADC data and send it over usb to Matlab.
I found a python Library that captures ADC data using PRU, but I don't know how to adapt it to transfer data to PC.
Link:
https://github.com/pgmmpk/beaglebone_pru_adc

A: USB standard has the USB CDC device class. It can emulate a COM port (RS 232).
https://en.wikipedia.org/wiki/USB_communications_device_class
You can implement this on the Beaglebone (Beaglebone as device not as host) and then use standard RS 232 libraries in matlab or C to get the data. On linux you see a USB CDC (ACM) device as /dev/ttyACMx or /dev/ttyUSBx
According to this https://groups.google.com/forum/#!topic/beagleboard/-HBwQdkuzes the Beaglebone has implemented USB CDC (ACM) RS232-over-USB yet. This is the easiest way because you can use the standard RS-232 commands in matlab to get the data.
If you use linux plug in the BBB and run dmesg or lsusb -v to see the inbuilt USB interfaces of the BBB.
this is a very good overview over USB http://www.beyondlogic.org/usbnutshell/usb1.shtml


text:
Q: Prime subfield when $ch(F) = 0$; shouldn't it be prime subring isomorphic to $\mathbb{Z}$? Suppose $ch(F)=0$ and let $\phi: \mathbb{Z} \to F$ with $\phi:n \mapsto n \cdot 1_F$. Since the characteristic is $0$, we have $\ker \phi = \{0 \}$. By the First Isomorphism Theorem, we have $\mathbb{Z} / \{ 0\}\cong \text{Im}(\phi)$. But the ring on the right is just $\mathbb{Z}$, and the ring on the left is the prime "subfield" of $F$. Could someone point out the problem please?

A: Your $\phi$ is the morphism of the initial object in the category of unital rings to the ring $F$. If the codomain is a field of prime characteristic, then the image of the morphism is not just a subring, but a subfield. This is due to the fact that the prime non-zero ideals of $\Bbb Z$ are also maximal. If not, then it's just a subring.

A: The image of $\varphi$ is not the prime subfield of $F$, which is isomorphic to $\mathbb{Q}$. The problem is that $\phi$ is a morphism of rings, and not a morphism of fields. Therefore, you could think of $\operatorname{im}(\varphi)$ as being a sort of "prime subring" associated to $F$, but it is not a field. In general, for any field of characteristic 0, there is a unique field homomorphism $\psi:\mathbb{Q} \to F$ whose image is the prime subfield associated to $F$, and which is isomorphic to $\mathbb{Q}$.


text:
Q: Are ranks of Jacobians over number fields unbounded? Fix a number field $K$.

*

*Is the rank of $J(K)$ unbounded, where $J$ ranges over the Jacobians of all smooth, projective, geometrically connected curves over $K$?

*Does there exist an integer $g$ such that the rank of $J(K)$ is unbounded, where $J$ now ranges over the Jacobians of all smooth, projective, geometrically connected curves of genus $g$ over $K$?
I expect (perhaps naively) that the answer to 1. is "yes". Maybe one can write down an explicit family of superelliptic curves and use descent to show that their ranks are not bounded. Or else there may be a construction that, given an elliptic curve $E$ and integer $r$, produces a curve $C$ such that $\mathrm{Jac}(C)$ contains a factor $E^r$ up to isogeny. But I can't make either approach work.
On the other hand, I would be surprised if 2. were known, since it is so famously open in the case $g=1$.

A: The answer to 1. is yes. Take $J_0(N)$ the Jacobian of the modular curve $X_0(N)$ over the rationals. Since all elliptic curves of conductor dividing $N$ are factors of $J_0(N)$ and there are infinitely many isogeny classes of elliptic curves over the rationals with positive rank. My guess, just like yours, is that 2. is open.

A: The answer to Question 1 is already contained in the following paper:
ANDRÉ NÉRON,
Problèmes arithmétique et géométriques rattachés à la notion de rang d'une courbe algébrique dans un corps, Bulletin de la S. M. F., tome 80 (1952), p. 101-166.
http://archive.numdam.org/ARCHIVE/BSMF/BSMF_1952__80_/BSMF_1952__80__101_0/BSMF_1952__80__101_0.pdf
The corollary to Theorem 7 (see page 155 of the article) says that for any given number field $K$, there are infinitely many curves $C$ of genus $g$ such that $\text{Jac}(C)(K)$ has rank at least $3g+5$. (With a bit more work, one can get $3g+6$. And with even more work, for $g=1$, the author gets up to rank at least $11$.)


text:
Q: Open-source Java server-side implementations of HTTP auth decoding I have a requirement to perform HTTP authentication logic within a servlet application, rather than delegating this task to the container.
Specifically, I need a way of taking the headers of an HttpServletRequest which contains HTTP auth headers, and having them decoded into a data structure representing the supplied credentials, which the application can then process.  Both basic and digest auth should be supported.
I could write this by hand, it wouldn't be too much of a chore, the RFCs are all well documented, but I'd quite like to use an off-the shelf library to do it for me.
My first thought was Spring Security, but from what I can tell this delegates this task to the container (I'm a bit unclear on that, it's a complicated code base).
Anyone know of any others?

A: *

*For BASIC, it is very easy to implement - just read the header, base64 decode it and split it on the ':' character. You can also use use Spring's BasicProcessingFilter, and supply your instance of AuthenticationManager.

*With Digest, you cannot get the password from the request (that's the whole point...). Implementing all the details is not a trivial task, even thought the protocol is well documented. Therefore I'd go with Spring's DigestProcessingFilter. In this case you need to supply the UserDetailsService who provides the user's password based on the username (for the digest).

A: Here is my decoder:
public static String[] decodeBasicAuth(String authorization) {
    if (authorization == null)
        throw new RuntimeException("Invalid Authorization String.");
    if (authorization.length() < 9)
        throw new RuntimeException("Invalid Authorization String.");
    if (authorization.length() > 64)
        throw new RuntimeException("Invalid Authorization String.");
    String s[] = authorization.split("\\s", 3);
    if (s.length < 2)
        throw new RuntimeException("Invalid Authorization String.");
    for (int i = 0; i < s.length; i++) {
        String part = s[i];
        if (part.compareTo("Basic") == 0) {
            String userPassBase64 = s[i + 1];
            if (!userPassBase64.isEmpty()) {
                String userPass = null;
                try {
                    userPass = new String(DatatypeConverter.parseBase64Binary(userPassBase64));
                } catch (RuntimeException e) {
                    throw new RuntimeException("Authorization cannot be decoded.", e);
                }
                String userPassArray[] = userPass.split(":");
                if (userPassArray.length == 2) {
                    return userPassArray;
                } else {
                    throw new RuntimeException("Invalid Authorization String.");
                }
            } else {
                throw new RuntimeException("Invalid Authorization String.");
            }
        }
    }
    throw new RuntimeException("Authorization cannot be decoded.");
}

A: I don't know of a framework off hand, but unless you're using BASIC authentication, you might not be able to get the password for the user.
If you are using BASIC authentication, it's pretty trivial to Base64Decode the Authentication header.


text:
Q: Differential Backups - How old is too old for the most recent full backup? I'm migrating my application from one place to another, and the full is around 80 GB and difficult to move. It's is currently about 2 weeks old, and the differentials aren't growing in size too much so that's not a concern.
Are there any other concerns to be aware of using a 3-4 week old full backup and restoring the most recent differential?

A: The only thing you need to be concerned with is that you need to restore all the log files after the latest differential. The amount of time elapsed between the full and the differential doesn't matter.

A: The answer is found by first determining the maximum acceptable time it takes to perform a full restore, which is a business decision.
Once that is determined, given that the full restore takes a more-or-less constant (but slowly increasing) time, work out the maximum number of incremental backups you can afford to perform after the full restore.
Expressed mathematically:
Given:
  m = max allowable time to complete restoration after failure
  r = time it takes to restore full backup
  i = time it takes to apply an incremental backup
  n = the maximum number of incremental backups between full backups
Then:
  n = (m - r) / i


text:
Q: unwrapping button.titleLabel.text I need to compare the text of a button with a variable.
@IBAction func CheckifATrue(sender: AnyObject) {
    if let thisbutton = sender.titleLabel.text {
        if thisbutton == theAnswer.text {
            score++
            println("Correct")}
    }
}

is giving me an error forcing me to put !! after titleLabel. I can't do this as there is a possibility (actually - a certainty) that the buttons titleLabel will be nil. Why does the if let statement not let me unwrap? is there another way to pull button text where I can safetly remove the optional through an if let and only execute code if valid?

A: You need to change type of sender from AnyObject to UIButton after that you can unwrap it this way:
@IBAction func CheckifATrue(sender: UIButton) {

    if let thisbutton = sender.titleLabel?.text {
        if thisbutton == theAnswer.text {
            score++
            println("Correct")}
    }
}

A:  @IBAction func CheckifATrue(sender: AnyObject) {
    let sender = sender as! UIButton
    if let thisbutton = sender.titleLabel?.text {
      if thisbutton == theAnswer.text {
        score++
        println("Correct")}
    }
  }

A: Thanks everyone!
It was actually a bit of both. I needed to change it to a UIButton and then also set thisbutton = to sender.titleLabel and only then an if statemenet comparing thisbutton.text to theAnswer.text. Posting the solution in case anyone else has this problem in the future
@IBAction func checkifCTrue(sender: UIButton){
    if let thisbutton = sender.titleLabel {
    if thisbutton.text == secretAnsarrrrr.text {
    score++
    println("Correct")}
    }}


text:
Q: How to use inserted loops with keyvalue pipe in Angular My Answer class
import { Question } from './question';

export class Answer {
    AnswerId: number;
    Content: string;
    IsCorrect: boolean;
    Mark: number;
    QuestionId: number;
    Question: Question;
}

My TestStartComponent
    testInfo: Map<string, Answer[]>;
    id: number;
    loaded: boolean = false;

    constructor(private dataService: DataService, activeRoute: ActivatedRoute) {
        this.id = Number.parseInt(activeRoute.snapshot.params["id"]);
    }

    ngOnInit() {
        if (this.id)
            this.dataService.getTestStart(this.id)
                .subscribe((data: Map<string, Answer[]>) => {
                    this.testInfo = data; this.loaded = true;});
    }

My test-start.component.html

                Вопрос
                Вариант 1
                Вариант 2
                Вариант 3
                Вариант 4
                Вариант 5

                {{item.key}}
                {{item.value}}

I want to see all key and values for them in my test-start.component.html, but I cant use nested(inserted) loop for outputing values.
So, the question is, how to output all values for every key?

A: keyvalue pipe is for iterating through object properties, not for arrays. You have an array of Answers, so you can simply pass it to the ngFor. If you want however, you can print all the key-values of an Answer as well.

  {{answer.answerId}}
  {{answer.content}}

    {{item.key}} : {{item.value}}

A: That how I solve my problem

                {{item.key}}

                    {{s.content}}


text:
Q: Enumerate all the triplets of consecutive values in the array Can not find solution for this question:
Enumerate all the triplets of consecutive values in the array, considering the last element of
the array as glued to the first one (note that the number of such triplets is exactly equal to N). The program must be in C language.
int main(int argc, const char * argv[])
{
    int v[DIM] = {10, 20, 30, 40, 50, 60, 70, 80};
    int i,sum,j,k,counter=DIM;

    for (i=0; i<DIM; i++) {
        sum = v[i];
        for (j=i; j<i+2; j++) {
            if (j>=DIM) {
                v[j] = v[0];
                v[j+1] = v[1];
                sum+=v[j];
            }
            sum += v[j+1];
        }
        printf("Triplet %d: %2d + %2d + %2d = %2d\n",i+1,v[i],v[i+1],v[i+2],sum);
    }

    printf("\n\n\n");
    return 0;
}

the correct output should be like this:
Triplet 1: 10 + 20 + 30 = 60
Triplet 2: 20 + 30 + 40 = 90
Triplet 3: 30 + 40 + 50 = 120
Triplet 4: 40 + 50 + 60 = 150
Triplet 5: 50 + 60 + 70 = 180
Triplet 6: 60 + 70 + 80 = 210
Triplet 7: 70 + 80 + 10 = 160 only in this step I'm getting wrong output:Triplet 7: 70 + 80 +  0 = 150
Triplet 8: 80 + 10 + 20 = 110

A:
considering the last element of the array as glued to the first one

A common way to do it is with the % operator:
printf("Triplet %d: %2d + %2d + %2d = %2d\n",i+1,v[i],v[(i+1)%DIM],v[(i+2)%DIM],sum);

The nested for loop should be rewritten, too, because it destroys the values of v, and also causes undefined behavior (this line v[j+1] = v[1]; dereferences an int past the end of the array):
for (j=0; j<3; j++) {
    sum += v[(i+j)%DIM];
}

A: This is not an answer but issue with your code,
    if (j>=DIM) {
        v[j] = v[0];
        v[j+1] = v[1];
        sum+=v[j];
    }

Your v array is only size DIM so you should not access it beyond it. when j>=DIM you shouldn't refer to v[j]

A: I think this works better:
//Zero-th triplet
for (i=0; i<3; i++) sum += v[i];
printf("Triplet 0: %2d + %2d + %2d = %2d\n",v[0],v[1],v[2],sum);

//for next ones subtract unused element, and add the next one
for (i=1; i<DIM; i++) {
  sum -= v[i-1];
  sum += v[(i+2) % DIM]; // "wrapping" done by modulo
  printf("Triplet %d: %2d + %2d + %2d = %2d\n",i,v[i],v[(i+1)%DIM] ,v[(i+2)%DIM],sum);
}


text:
Q: How I refresh a HttpWebRequest object on Windows Phone I'm writing a windows phone application where I need to do a http request. This request return to me a random value it changes always when I request its url.
So I have a app with a button when I click it I receive the random value that I want, but, if I click the button again I receive the same random value!! I put a breakpoint on the server side and it is reached just once, if a click the button 10 times it will reach the breakpoint just the first time!! I need whenever I click the button I have a new random value!
And I need to use a CookieContainer because on my server I need to keep some objects defined in this session. If I dont use CookieContainer I cant keep the session, so when I call the second request I haven't no objects there.
private async Task<string> requestURLData(HttpWebRequest request)
{

HttpWebResponse response = (HttpWebResponse) await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);

var responseStream = response.GetResponseStream();
var sr = new StreamReader(responseStream);

string received = await sr.ReadToEndAsync();

return received;
}

private async Task<string> requestUrl(string url, CookieContainer cookie)
{
var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
request.CookieContainer = cookie;

return await this.requestURLData(request);

}

private async Button_Click(object sender, RoutedEventArgs e)
{

CookieContainer cookie = new CookieContainer();
var result = await this.requestUrl(this.urlBase + "getRandomNum", cookie);

result = await this.requestUrl(this.urlBase + "getAnotherValue", cookie);

}

A: You're running into response caching - append a random string to the end of your url that your server ignores to guarantee that you don't hit the cache:
Random _rand = new Random();

private async Button_Click(object sender, RoutedEventArgs e)
{

   CookieContainer cookie = new CookieContainer();
   var result = await this.requestUrl(this.urlBase + "getRandomNum&rubbish=" + _rand.Next(), cookie);
   ...
}


text:
Q: Setting up postfix as relay but also as smtp I've set up a postfix server that relays email to another server, this is working fine. I managed this using the relayhost variable.
example:
relayhost = 192.2.123.25

This means all incoming emails are sent to that server, which is good. However, local email sent from the server where postfix is installed, for example using:
$ mail -s "subject example" mike@example.com

are also being sent to the relay host, however, I only want this server to use relayhost for incoming email, for outgoing emails it should use itself as smtp. How can I achieve this?

A: Relayhost sets your next hop for all email that hits the postfix server.  You could use transport maps to forward emails for a specific domain.
/etc/postfix/transport
example.com   smtp:
.example.com  smtp:
*         smtp:[192.2.123.25]

postmap /etc/postfix/transport
postfix -e transport_maps = hash:/etc/postfix/transport
RTFM


text:
Q: Haskell Reader monad and argument passing I was following this tutorial https://blog.ssanj.net/posts/2014-09-23-A-Simple-Reader-Monad-Example.html
It has tree functions that is embarrassing to me
tom :: Reader String String
tom = do
  env <- ask
  return (env ++ " This is tom.")

jerry :: Reader String String
jerry = do
  env <- ask
  return (env ++ " This is Jerry.")

tomAndJerry :: Reader String String
tomAndJerry = do
   t <- tom
   j <- jerry
   return (t ++ "\n" ++ j)

runJerryRun :: String
runJerryRun  = (runReader tomAndJerry) "Who is this?"

These functions receive no arguments but still they access the reader monad, what magic is happening here? What is the intuition behind this?
I reader monad a kind of global?

A: Each of the first two functions returns its own instance of a Reader monad. Then, you can compose them together (in the third function).
For the sake of the argument, let's replace Reader with IO and do something similar, with none of these functions receiving any argument:
getIntFromFile :: IO Int
getIntFromFile = do
    x <- readFile "myfile.txt"
    pure $ read x :: Int

getIntFromStdin :: IO Int
getIntFromStdin = do
    x <- getLine
    pure $ read x :: Int

As you can see, both use the IO monad but they don't share anything in common. However, since they both use the IO monad, you can (and that's the beauty of it) compose them together as follows:
-- | the equivalent of your `tomAndJerry` function
main :: IO ()
main = do
    x <- getIntFromFile
    y <- getIntFromStdin
    print $ x + y

This is exactly the same logic at play with the example from the tutorial, except with Reader instead of IO.

A: I think one important misunderstanding was addressed by Daniel Wagner in a comment. The Reader is (well, wraps) a function, so it does take arguments. In light of this, I guess your final question

I reader monad a kind of global?

has an answer: yes, in the sense that the reader monad gives you a way to pass an immutable state/environment through chained computations; so it kind of reads the same value everytime it's invoked (via ask) along the chain.
Which in the case of your code means that the two asks (or, equivalently, tom and  jerry) both read the same environment, represented by the string "Who is this?".
Imho, this becomes a bit clearer by desugaring the dos:
tom :: Reader String String
tom = ask >>= \env -> return (env ++ " This is Tom.")

jerry :: Reader String String
jerry = ask >>= \env -> return (env ++ " This is Jerry.")

tomAndJerry :: Reader String String
tomAndJerry = tom >>= \t -> jerry >>= \j -> return (t ++ "\n" ++ j)

Here >>= expects a function that returns a monad, but you don't have it, you have the "ordinary" function (e.g. \env -> env ++ " This is Tom."), so you have to use return to wrap the result back into the monad. Then instead of using >>= and return . f, why don't we use fmap f, since we only have to apply a function inside the monad?
Which means that we can go further and simplify by using Functor for tom and jerry and Applicative for tomAndJerry.
tom :: Reader String String
tom = fmap (++ " This is Tom.") ask

jerry :: Reader String String
jerry = fmap (++ " This is Jerry.") ask

tomAndJerry :: Reader String String
tomAndJerry = (\t j -> t ++ "\n" ++ j) <$> tom <*> jerry

Both tom and jerry are asking for the environment, and each of them applies a function to it. Then tomAndJerry is just a way of composing them via a binary function, as pointed out in the accepted answer.
By the way, the language server tells me of asks, which allows to write
tom :: Reader String String
tom = asks (++ " This is Tom.")


text:
Q: How to handle an interrupt from the GPIO Expander(PCA953X) I use a GPIO Expander like PCA9575.
But I don't know how to handle an interrupt from the expander..
From the gpio-pca953x.c, the following code is the ISR for the expander.
static irqreturn_t pca953x_irq_handler(int irq, void *devid)
{
    struct pca953x_chip *chip = devid;
    uint16_t pending;
    uint16_t level;

    pending = pca953x_irq_pending(chip);

    if (!pending)
        return IRQ_HANDLED;

    do {
        level = __ffs(pending);
        handle_nested_irq(level + chip->irq_base);

        pending &= ~(1 << level);
    } while (pending);

    return IRQ_HANDLED;
}

If Interrupt is activated from GPIO(Input) pin 3 of expander, this routine jumps into the GPIO pin 3 service routine from this ISR. Isn't it right?
If so, I have the following question..
How to register the GPIO Pin 3 service routine??
If not, How to handle the the GPIO Pin 3 service routine??
Thanks for your reading.


text:
Q: Выполнение метода Java во время выполнения долгого запроса в бд Oracle Подскажите, есть ли способ реализовать подобный кейс:
Выполняется соединение с бд и последующий запрос (условный SELECT). Если же попытка соединения висит больше 10 секунд, то текущую сессию не обрывать, но выполнить сторонний метод (логирование - метод реализован уже, тут вопросов нет).
Получается, что нужно во время попытки соединения с бд при превышении определенного времени параллельно выполнить логирование такого запроса не обрывая самой сессии.


text:
Q: SQL Statement with Select Atleast Two state(code, name, country, population)
statelanguage(statecode, statelanguage, isofficial, percentage)

In table state, code refers to the code of a state, the rest of the attributes are trivial. In table statelanguage, statecode refers the code for a particular state, statelanguage is a language that is spoken in this state, isofficial is a boolean on whether this language is the states official langauge and percentage is the percentage of people who speak the state language.
What I am trying to do is write an SQL statement to select the statecode where atleast two different languages are spoken.
My idea was to first get the statecode for the states that speak only 1 language then subtract this from the original table and project only the statecode. But I am struggling on how to do this.  Thanks

A: select *
  from state
 where ( select count(distinct statelanguage)
           from statelanguage
          where statecode = state.code ) >= 2

A: Use an aggregate function to count languages for each state:
   select statecode, count(distinct statelanguage)
   from statelanguage
   group by statecode

Now limit the states with a HAVING
   select statecode, count(distinct statelanguage)
   from statelanguage
   group by statecode
   having count(distinct statelanguage) >=2


text:
Q: showing that the untwisted Whitehead double of a slice knot is slice Let $K$ be a slice knot (i.e. there is a smooth embedding of a disc into $D^4$ such that its boundary is precisely $K$). To obtain the positive (or negative) untwisted Whitehead double of $K$, push a copy $K'$ of $K$ slightly into a Seifert surface of $K$ and add a positive (or negative) clasp as shown here for example for the trefoil: https://www.researchgate.net/figure/A-Whitehead-double-of-a-trefoil-knot-is-a-satellite-knot-whose-companion-knot-is-a_fig10_339015556
Now if the starting knot is slice (this is not the case for the trefoil), then the knot resulting from this construction is slice. Here is how I think one can show this:
Since $K$ and $K'$ are both slice, they bound smooth discs in $D^4$. If I could isotope these surfaces (with their boundaries staying in S^3) such that they do not intersect, I could just attach a twisted band in $S^3$ from one knot boundary to the other, such that the result would be the creation of the clasp. The resulting surface would be a disc since it was obtained my attaching a band to two disjoint discs. But I am stuck on the first part of showing that I can make both slice discs disjoint. I know that one has to use the fact that $K'$ is obtained from $K$ by pushing it inside a Seifert surface, else their linking number would be non-zero which obstructs the discs from being disjoint by Lemma 8.13 in "An Introduction to Knot Theory" by Lickorish (The lemma states precisely that for two disjoint slice discs of two knots, their linking number is $0$). So here is my question:
How can I get the link $K\cup K'$ to bound two disjoint smoothly embedded discs in $D^4$?
Somehow I think one should just be able to shrink the slice disc of $K$ into a slice disc of $K'$ so that they do not intersect. What I worry about here is a kind of phenomenon where two surfaces in a 4-manifold will always intersect, like for $CP^1 \subset \mathbb{C}P^2$. So maybe I can argue by saying something about the trivial intersection form of $D^4$ or $S^4$? Most likely there is a way simpler answer, but I am also curious about when in general, one can push a surface away from itself to make it disjoint.
Thank you for your time.


text:
Q: Does partial of $f(w+y,y)$ w.r.t $y$ hold $w+y$ constant, or just $w$ (or something else) The partial means we hold everything else constant, but I am unsure of what we mean by everything else (does it mean all other arguments -- in which case we would hold $w+y$ constant -- or does it mean all other endogenous variables are held constant -- in which case $w+y$ changes but $w$ doesn't. or maybe it means something else)?
Edit 2: (additional question) If $\frac{\partial f}{\partial y}$ refers to the partial derivative holding the variable $y$ constant then does $\frac{\partial f}{\partial y} = f_1 + f_2$ , where $f_i$ denotes the partial derivative w.r.t to the $i$'th argument?

*

*My logic behind this being that changing $y$ by an small amount changes both the first and second arguments by a small amount.

Edit: i realize that an answer is probably just "This is bad notation, avoid it". I've come across this kind of notation sometimes and it confuses me though. Maybe the answer is that context needs to be used to tell if they mean differentiation w.r.t an argument or w.r.t a variable.

A: When you take the partial of a function of several variables, the variables might be independent of each other, or might be related in some other way.
When all the arguments of a function are independent variables, then the partial of the function with respect to one of them is just the derivative of the function with regard to that variable, holding all the others constant. But this only applies when all the variables are independent.
On the other hand, when the arguments have a relationship between them, as in your case here, one applies the chain rule. That is, for a function $f(w+y,y),$ we have that $$f_y=f_{w+y}(w+y)'+f_y(y)'=f_{w+y}+f_y,$$ where the primes denote differentiation with respect to $y.$


text:
Q: Extract data from multiple inputs in form react So I am still relatively new to React. I want to get data from three form inputs (and eventually post that to database). I have been using the internet to help, but I figured would try my luck here. Right here I am trying to just log out what the user texts in the inputs.
import React from 'react';

export default class AddForm extends React.Component {
constructor(props) {
super(props);
}

handlePlace(e) {
e.preventDefault();
  const text = this.place.value.trim();
  console.log(text);
}

handleDate(e) {
  const text = this.date.value
  console.log(text);
}

handleNotes(e) {
  const text = this.notes.value
  console.log(text);
}

render() {
 return(
  <form className="form">

Add a Memory

Keep track of all the fun and amazing places you
    have been.

     <input  type="text" name="place" placeholder="place" ref={input =>
     this.place = input}></input>

    <input  placeholder="time" ref={input => this.date = input}></input>

    <input  className="notes" placeholder="notes" ref={input => this.notes =
    input}></input>

    <button className="save" type="button" onClick=
    {this.handleSave}>Save</button>
  </form>
 );
}
 handleSave() {
  console.log(this.handlePlace)
  console.log(this.handleDate)
  console.log(this.handleNotes)
 }
}

A: While it is possible to use refs to do this, it is not recommended to actually touch the dom unless it is necessary.  I think it would be helpful
to think about this the 'react way'.
In React, the state of your application drives the view, including inputs.  So what you 'should' be doing is letting the state populate the values of your inputs and then update the state to change what is in those inputs. Something like this:
export default class AddForm extends React.Component {
  constructor(props) {
  super(props);
  //change here
  this.handlePlace = this.handlePlace.bind(this);
  this.handleDate = this.handleDate.bind(this);
  this.handleNotes = this.handleNotes.bind(this);
  this.handleSave = this.handleSave.bind(this);
  this.state = {
    placeText: '',
    timeText: '',
    noteText: '',
  };
}
// all changed
handlePlace(e) {
  this.setState({ placeText: e.target.value });
}

handleDate(e) {
  this.setState({ dateText: e.target.value });
}

handleNotes(e) {
  this.setState({ notesText: e.target.value});
}

render() {
 return(
  <form className="form">

Add a Memory

Keep track of all the fun and amazing places you
    have been.

     // change here
     <input  type="text" name="place" placeholder="place" value={this.state.placeText} onChange={(e) => this.handlePlace(e)}></input>

    // change here.  e is implicitly passed to the onChange handler
    <input type="text" placeholder="time" value={this.state.dateText} onChange={this.handleDate}></input>

    //change here
    <input  className="notes" placeholder="notes" value={this.state.notesText} onChange={this.handleNotes}></input>

    <button className="save" type="button" onClick=
    {this.handleSave}>Save</button>
  </form>
 );
}
 handleSave() {
  console.log(this.state.placeText)
  console.log(this.state.dateText)
  console.log(this.state.notesText)
 }
}

It seems tedious, but this declarative style really pays off in the long run when you're hunting down bugs.  It becomes easier to follow the flow of your data through your application.


text:
Q: How can I upload a file using chilkat? EDIT: Found the issue.
I was not typing the entire folder structure when trying to save the file.
The problem is now solved.
I'm trying to upload a file using c# and chilkat to a customer, but i keep getting an error code.
I work for a logistics company, and we have many types of integration with our customers. We use c# and chilkat for a while, and it works with every other customer we have. This is a new customer but i made tests using FileZilla, and everything works (create, delete, download, upload), the credentials are the same.
Our Chilkat license is updated (today) and we have the latest version.
I have tested with other customers, the same code, and it works (more than 10 other customers)
string username = "login";
string password = "pass";

Chilkat.SFtp sftp = new Chilkat.SFtp();
bool success = sftp.UnlockComponent("Hello World");
if (success != true)
    throw new Exception("Invalid License");

sftp.ConnectTimeoutMs = 5000;
sftp.IdleTimeoutMs = 10000;
success = sftp.Connect("address", 22);
if (success != true)
    throw new Exception("Host could not be reached. Invalid Host.");
success = sftp.AuthenticatePw(username, password);
if (success != true)
    throw new Exception("Invalid Credentials.");

success = sftp.InitializeSftp();
if (success != true)
    throw new Exception("Connection could not be initialized.");

string[] fileList = Directory.GetFiles(@"c:\files\");
foreach (string item in fileList)
{
    string handle = sftp.OpenFile("IN/" + Path.GetFileName(item), "writeOnly", "createTruncate");
    if (handle == null)
    {
        string lastErrorText = sftp.LastErrorText;
        //throw new Exception("Could not create a handle for the desired file");
    }
    else
    {
        success = sftp.UploadFile(handle, item);
        if (success != true)
            throw new Exception("Could not Upload the File");
        else
            Console.WriteLine("File {0} uploaded", item);

        success = sftp.CloseHandle(handle);
        if (success != true)
            throw new Exception("Could not close the handle");
        else
            File.Delete(item);
    }
}

I expected the file to be uploaded, but it fails.
The "LastErrorText" Variable comes back with the following text:
ChilkatLog:
  OpenFile:
    DllDate: Mar 18 2019
    ChilkatVersion: 9.5.0.77
    UnlockPrefix: Start my 30-day Trial
    Architecture: Little Endian; 32-bit
    Language: .NET 4.6 / x86 / VS2017
    VerboseLogging: 0
    SshVersion: SSH-2.0-SSHD-CORE-1.7.0
    SftpVersion: 3
    sftpOpenFile:
      remotePath: IN/214KCF_S903211745.txt
      access: writeOnly
      createDisposition: createTruncate
      v3Flags: 0x1a
      Sent FXP_OPEN
      StatusResponseFromServer:
        Request: FXP_OPEN
        InformationReceivedFromServer:
          StatusCode: 3
          StatusMessage: operation not permitted
        --InformationReceivedFromServer
      --StatusResponseFromServer
    --sftpOpenFile
    Failed.
  --OpenFile
--ChilkatLog


text:
Q: Errorcodes in exception I have a proprietary C# library that is basically a wrapper around some C++ code.
The functions it provides look like this:
public int func(in params, out params...)

The int returned signals success (0), some error code (<0) or some data (>0, e.g. number of bytes successfully read).
Additionally, the library provides a public EnumErrorCode GetLastError() function
My task is to write yet another wrapper, that translates each function with error codes to function that throw exceptions
While it's easy to get the returncode into the exception
public class MyException : Exception
{
    public int RetVal { get; }
    public MyException(int retVal) : { RetVal = retVal;}
    public MyException(string message, int retVal) : base(message) { RetVal = retVal; }
}

used like
public void func(int a)
{
    var retVal = api.func(a);
    switch (retVal)
    {
        case 0: return;
        case -1: throw new MyException("same error across all funcs", retVal);
        case -2: throw new MyException("func specific error", retVal);
        default: throw new MyException(retVal);
    }
}

I have trouble figuring out right way to also get the EnumErrorCode GetLastError() into the exception
First of all, should I introduce a new property public EnumErrorCode ErrorCode { get; }, with EnumErrorCode being defined in the proprietary C# library or should I just store an int?
Secondly, is it ok to call GetLastError() while throwing the exception?
case -1: throw new MyException("Mayhem!", retVal, GetLastError());

Doesn't seem right to make another call into foreign unknown code while throwing. What other possibilities are there?

Thanks Fildor for your detailed answer.
I think I´ll mix in that function specific message (provided by the API-documentation) and use a dictionary for the EnumErrorCode mapping in the Create function
public interface IMyExceptionFactory
{
    MyException Create(string funcSpecificCodeMsg, int returnCode, int errorCode);
}

// snip
int returnCode = CallToThirdParty();
if (returnCode < 0)
{
    int errorCode = -1;
    try
    {
        errorCode = (int)GetLastError();
    }
    catch (Exception) { }
    switch (returnCode)
    {
        case -1: throw _exceptionFactory.Create("invalid handle", returnCode, errorCode);
        case -2: throw _exceptionFactory.Create("func specific error -2", returnCode, errorCode);
            ...
        default: throw _exceptionFactory.Create("Unknown returnCode", returnCode, errorCode);
    }

}

A: First: To reiterate points from comments:

*

*If you need that to be thread-safe, you'd need to make both calls "atomic" to your clients.

*I'd enclose GetLastError with another try/catch just to be safe.

Using the 3rd party Enum
This depends on much you want to hide the 3rd party from the clients of your adapter.
If they shouldn't be aware (at least while using your adapter, of course, they would probably know there is a 3rd party) of the 3rd party, then you would need to hide the original Enum.
This could be done by making your own "copy" of that Enum. This is possible, but it has serious pitfalls: On each update of the 3rd party, you'd need to check if the enum has changed and change your code accordingly. Which could lead to breaking changes, even.
What I have done in the past is just using and exposing the integer value and providing a ErrorCodeToString function that basically casts the int to the 3rd Party enum and then does a ToString. That was enough for my purposes, but of course I don't claim that to be the or even a "best practice".
Creating Exceptions
Recap what we have:

*

*Functions can have return codes of

*

*0 == "ok"

*>0 (only some of them) == some integer valued result.

*<0 , where ...

*

*'-1' is a common error shared by all functions

*'-2' and smaller are function-specific errors (different meaning per function)

*On top of negative returnCodes, an errorCode (=> enum) can be retrieved by calling GetLastError.

Now, one question would be: Is maintaining an exhausting table of all function-specific returncodes beneficial in addition to just having the ErrorCodeEnum value?
If yes: Things get a little more complicated. But maybe we can set this aside for now and focus on the Enum values.
Of course, you wouldn't want to write a custom handling for each and every function. So, what you want is some kind of Exception-Factory.
My assumptions regarding this are:

*

*You probably want to assign each enum value a different exception message.

*You've already shown a custom MyException type, so you'll probably want to use that.

Now, you need to make a design decision. You can use one exception type and have it have properties. Or you can derive "child" types from your base exception type.
The latter would make it convenient to group or single out exceptions you want/need to handle versus others you (or the client) want to just "bubble up".
Either way, you'll want to have a an interface like
public interface IMyExceptionFactory
{
    MyException Create(int returnCode, int errorCode);
}

to use in your adapter (I guess you'll want to inject it), so it can do its magic, and you can throw whatever it gives you.
For example:
// snip
int returnCode = CallToThirdParty();
if( returnCode < 0 )
{
    int errorCode = GetLastError();
    throw _exceptionFactory.Create(returnCode, errorCode);
}

Inside its implementation, you'll build the appropriate Exception with Message (maybe a derived type) and other properties set to the correct values.
For example you could build a dictionary that lets you lookup messages by errorCodes etc. You could then decide to have that built hardcoded or through a configuration ...


text:
Q: Alternatives to Fisher's exact test I have the following data:

I have a comparison table as follows:

Can someone help me with identifying which statistical test would help me answer the following question:
Are the chances of getting 350/6500 of the Y genes common with mutant X statistically significant compared to obtaining 20/180 of the Z genes common with mutant X?
I know I cannot use Fisher's exact test for this purpose as "Fisher's test requires the rare condition that both row and column marginal totals are fixed in advance. The resultant 2 × 2 table is described as doubly conditioned."3 What is the test that I can use in this case?


text:
Q: Missing argument 1 for method with argument being a service injection in Symfony 3 I have such service linked to one method in my entity:
entity_form:
    class: AppBundle\Entity\EntityForm
    calls:
         - [setDoctrine, ['@doctrine']]

The argument injects (or at least should) doctrine into my entity so that I can get stuff from the db inside methods.
I set it for the getter because I had to omit setting the argument in the __construct because in code the class is never really "constructed"
The entity itself looks like this:
<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 * @ORM\Table(name="entity_form")
 */
class EntityForm
{

    protected $id;

    protected $url;

    protected $name;

    protected $className;

    protected $description;

    private $doctrine;

    public function getId()
    {
        return $this->id;
    }

    /* _All Getters An Setters Here.._ */

    private function setDoctrine($doctrine)
    {
        return $doctrine;
    }

    public function createEntity($id)
    {
        $this->setDoctrine();

        $entityPath = sprintf('AppBundle:%s:%s', __NAMESPACE__, $this->getClassName());

        var_dump($this->doctrine);
        exit;
        //var_dump is temponary and only for testing the doctrine

        $entity = $this->doctrine->getRepository($entityPath)->find($id);

        return $entity;
    }
}

This entity stores information about forms on the website. With this I would like to nicely and quickly create entity of class for which the form is made, from given Id.

Unfortunately
Running such code gives me this error:

Warning: Missing argument 1 for
  AppBundle\Entity\EntityForm::setDoctrine(), called in
  C:\PHP\Repos\centaur\src\AppBundle\Entity\EntityForm.php on line 139
  and defined

What could be the reason for this error to happen? How can I fix it?
Any help would be amazing

A:
The argument injects (or at least should) doctrine into my entity so
  that I can get stuff from the db inside methods.

No.
You defined entity_form service that is nothing more than AppBundle\Entity\EntityForm with setter-injected doctrine service.
So your EntityForm with injected service is available in container, it won't be injected into every created EntityForm.
Looks like you should read more about responsibilities. What you want to achieve in createEntity method should be a part of application service layer, not a model itself.
Model is not aware of application/infrastructure concepts, so injecting ORM is not ok.
About mentioned error, considering only service definition and that call:
$this->setDoctrine();

You want to call setter without required argument, and probably missed that your service definition already did setter-injection.
As I mentioned before, entity is basically not a service, so move that part into specific class and inject database-related service there using standard DI.


text:
Q: cURL / PHP cant fetch this - but all browser can? I cant acces this site with any of Bellow methods, the $url adress Works in all my browsers but, i just cant fetch data from that site.... how is that possible ? Not even the robots.txt ('https://www.natterer-modellbau.de/robots.txt) cant be fetched, other than in a browser....
I see results on Google from that website, how can Google acces the site when I cant ?
The page has rejected my crawler from first try, så they cant have bloked my servers IP allready ? and my script can acces all other URL`s -- im frustrated :) please help...
$url = 'https://www.natterer-modellbau.de/Flugzeuge';

$pageHeaders = get_headers($url,1); // DOES NOT WORK - TIMES OUT
file_get_contents($url); // DOES NOT WORK -Times OUT

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$res = curl_exec($ch);
$rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch) ;
echo $res; // DOES NOT WORK - TIMES OUT

A: Works for me. You may be behind a proxy.
php > $url = 'https://www.natterer-modellbau.de/Flugzeuge';
php >
php > $pageHeaders = get_headers($url,1); // DOES NOT WORK - TIMES OUT
php > file_get_contents($url); // DOES NOT WORK -Times OUT
php >
php > $ch = curl_init();
php > curl_setopt($ch, CURLOPT_URL, $url);
php > curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
php > curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
php > curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
php > $res = curl_exec($ch);
php > $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
php > curl_close($ch) ;
php > echo $res;
<!DOCTYPE html>
<html lang="de">
<head>

        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
        <meta name="description" content="Elektro, Segler/E-Segler, Verbrenner">
        <meta name="keywords" content="Elektro, Segler/E-Segler, Verbrenner">

.... Many lines omitted
finally end of html
        </script>

    <script>
        jtl.load(["asset/plugin_js_head?v=4.05","asset/jtl3.js?v=4.05","asset/plugin_js_body?v=4.05",]);
            </script>

</body>
</html>
php >


text:
Q: Cannot run video or webcam with OpenCV, Python, and VS Code I want to run the following Python code from this OpenCV tutorial in VS Code:
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

I also get the following error from VS Code's terminal:
[ WARN:0@0.015] global /private/var/folders/sy/f16zz6x50xz3113nwtb9bvq00000gp/T/abs_506zufg7xt/croots/recipe/opencv-suite_1664548331847/work/modules/videoio/src/cap_gstreamer.cpp (862) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created

I believe that my interpreter/virtualenv is correct. My camera's little green light does seem to turn on, if only briefly. The camera works perfectly fine in other situations. But I don't seem to get past the first line of code cap = cv.VideoCapture(0) when I run it. Any ideas on what is going on?

A: You appear to be on Mac OS. Use this:
cap = cv.VideoCapture(0, apiPreference=cv.CAP_AVFOUNDATION)

Explicit apiPreference skips auto-detection of a backend, so the gstreamer backend won't even be attempted.

A: It says that your OpenCV needs Gstreamer as backend to access your camera, but you haven't compiled a Gstreamer-enabled OpenCV.


text:
Q: How to maintain alignment and spacing in Viewbox I have a list of labels and values. For instance (this sample is for illustrative purposes):
Tim        0.333
Fred       0.357
Fernando   0.300

I would like to be able to add to this list and have the text shrink so the list will fill the available space but not exceed it. I would also like to be able to resize the window and have the list fill the available space. I tried using a Viewbox to accomplish this and failed in two different ways:
1) I tried using a grid and surrounding each label and value with a Viewbox. This maintained my spacing between the label and value, but the labels and values were different sizes. Here is the code for the user control that displays the player information:
<UserControl x:Class="Viewbox.Player"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Viewbox Grid.Column="0">
            <TextBlock FontSize="30" Margin="5" Text="{Binding Name}" HorizontalAlignment="Left"/>
        </Viewbox>
        <Viewbox Grid.Column="1" HorizontalAlignment="Right">
            <TextBlock FontSize="30" Margin="5" Text="{Binding Average, StringFormat={}{0:0.000}}" HorizontalAlignment="Right"/>
        </Viewbox>
    </Grid>
</UserControl>

And here is the result:

2) I tried surrounding the grid with the Viewbox. This sized the text as I wanted, but now my spacing was gone and each line was centered.
<UserControl x:Class="Viewbox.Player"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Viewbox>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <TextBlock Grid.Column="0" FontSize="30" Margin="5" Text="{Binding Name}" HorizontalAlignment="Left"/>
            <TextBlock Grid.Column="1" FontSize="30" Margin="5" Text="{Binding Average, StringFormat={}{0:0.000}}" HorizontalAlignment="Right"/>
        </Grid>
    </Viewbox>
</UserControl>

I have been dancing around this issue for a while now. Can anyone help me with this?
Thanks!

A: I was able to solve the problem by inserting a blank column. This preserves the alignment and font sizes (up to a point):
<UserControl x:Class="Viewbox.Player"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Viewbox Grid.Column="0">
            <TextBlock Margin="5" Text="{Binding Name}" HorizontalAlignment="Left"/>
        </Viewbox>
        <Viewbox Grid.Column="2">
            <TextBlock Margin="5" Text="{Binding Average, StringFormat={}{0:0.000}}" HorizontalAlignment="Right"/>
        </Viewbox>
    </Grid>
</UserControl>

Unfortunately, it breaks down a bit when the window is sized very tall:

However, for my purposes, I am able to limit the total height, so this is not a problem.


text:
Q: Phonegap interop capability With Phonegap, I read you can access native OS methods. What about the other way round ? Can native app that wraps the js module call javascript methods inside that module ?

A: totally possible here's an example -
NSString * jsCallBack = [NSString
                                 stringWithFormat:@"someJSFunction();"];
        [self.webView stringByEvaluatingJavaScriptFromString:jsCallBack];

I've got a blog post about the localNotifications plugin, it goes into detail about having the native iOS make callbacks to your JS
http://www.drewdahlman.com/meusLabs/?p=117

A: But of course, it would be pretty useless otherwise.


text:
Q: Increase line size in quiver3 plot matlab I use quiver3() command in matlab and specify the points and its normals. i specify three points and corresponding 3 normals but when i plot in on an existing figure, the lines appear very small in size.

How to increase the line size? In LineSpec, they only give line width option. i use the command like this:
    quiver3(pts(:,1),pts(:,2),pts(:,3),n(:,1),n(:,2),n(:,3),'LineWidth',3,'color','g');
pts and n are 3x3 matrices.

A: You can find a solution in this link line size in quiver 3. Setting the 'AutoScale' property to 'off' and adjusting your vector norm to control line size seems to be the solution.


text:
Q: MySQL InnoDB: Having a multiple column key vs a single md5 hash key Let's say I have a table with a composite primary key consisting of 3 varchar(256) columns: A, B, and C.  There's also an index on B, and the composite key acts as an index on A.  This table has millions of rows and has lots of INSERTS and SELECTS, but no UPDATES (except for using ON DUPLICATE KEY UPDATE with INSERTS).
If I changed this table to have a single column char(32) primary key of md5(A,B,C) (as well as an index on A and an index on B) would this setup be more efficient for INSERTS?   The possibility for collisions doesn't bother me.
MySQL 5.5, using InnoDB

A: In InnoDB the primary key is a clustered key - the data on the disk is physically organized based on the order of the PK. This means that if you are not using auto-increment or something other that increases the value of PK over time, you will got a lot of random writes and this will kill your performance as soon as the size of the table is larger than the buffer_pool size.
Having in mind this, md5() won't be much better than the compound index for the inserts. Having smaller PK is good for 2 reasons: the size of the PK affects the size of all secondary indexes (because all secondary indexes contain the PK) and using smaller indexes is better ('cause you can load more values into memory at once)


text:
Q: Assertion Error In python When trying to run this code

for i in range(N):
    jobs.append(mp.Process(None,G_Sim,(lmbda,mu,c,skip_cost,simulation_time,Policy,warmup_period,False,)))
for j in jobs:
    j.start()
    j.join()

I get an assertion Error: Name must be a string

A: Process expects its third parameter to be the process name, not a tuple of arguments.

A: The mp.Process() function call is defined as below:
multiprocessing.Process([group[, target[, name[, args[, kwargs]]]]])

The third argument should be a name for the process, as a string. You are passing the following tuple:
    (lmbda,mu,c,skip_cost,simulation_time,Policy,warmup_period,False,)
You should name your arguments. Something like:
jobs.append(mp.Process(group=None, target=G_Sim, args=(lmbda,mu,c,skip_cost,simulation_time,Policy,warmup_period,False,)))


text:
Q: How do I loop through a deeper json array with AJAX? I've looked through other questions on looping through arrays using the .each element, and I still can't get my function to work - I get reference errors on undefined elements and I imagine I'm just not going 'deep enough' in my nested .each statements.
My function returns on success a variable 'response', which should contain many objects/arrays.
$.each(response, function(){
     console.log(response.first_name);
}

This is obviously incorrect, as it doesn't go 'deep enough' so to speak, but I'm confused on how to add multiple $.each loops inside of it. Other questions have names listed where 'response' is or they have function(x, test) to show an index as they loop through. I'm lost.
My json is structured as such, according to the console in Google Chrome:
Object {data: Array[2]}
    data: Array[2]
        0: Object
            User: Object
                  first_name: "Steve"
                  last_name: "Ramsey"
        1: Object
            User: Object
                  first_name: "Bob"
                  last_name: "Ramsey"

As you can see, the name of one of the fields increments, so I know I need one variable as an index while looping through the number. The idea is that I'll then use this data to spit out 'Bob Ramsey', 'Steve Ramsey', etc. on the page along with any other information that could be in the object.

A: well first_name looks to be part of an object call User so you would need to reference User first.
var response = {
    data: [{
        User: {
            first_name: "Steve",
            last_name: "Ramsey"
        }
    },{
        User: {
            first_name: "Bob",
            last_name: "Ramsey"
        }
    }]
};

$.each(response.data, function (index, value) {
    console.log(value.User.first_name);
});

JSFiddle: http://jsfiddle.net/8LfXF/1/


text:
Q: Express.js inject middleware output an error I am using express.js server and try to inject a middleware to the app instance.
app.configure(function() {
 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(app.router);
 app.use(express["static"](PUBLIC_PATH));
});

hello = function(req, res, next) {
 console.log("hello world");
 next();
};

app.configure('development', function() {
 app.use(hello());
 app.use(express.errorHandler({
 dumpExceptions: true,
 showStack: true
 }));
});

I am trying to inject Hello() function in to the current app instance. But when I run the code from console, it returns the "hello world", but with some errors in the console too. Where did I do wrong.
hello world

/Users/mma/Desktop/mustdelete/aaron/server/app.coffee:13
  return next();
         ^
TypeError: undefined is not a function
at Object.module.exports.exports.hello (/Users/mma/Desktop/mustdelete/aaron/server/app.coffee:13:14)
at Function.module.exports.app.configure.app.set.layout (/Users/mma/Desktop/mustdelete/aaron/server/app.coffee:16:30)
at Function.app.configure (/Users/mma/Desktop/mustdelete/aaron/node_modules/express/lib/application.js:395:61)
at module.exports (/Users/mma/Desktop/mustdelete/aaron/server/app.coffee:15:9)
at Object.<anonymous> (/Users/mma/Desktop/mustdelete/aaron/server/index.js:2:34)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)

A: You don't have to pass the return of the function (with parentheses) hello(), just the name of the function (without parentheses), app.use(hello).


text:
Q: Prob with buildozer apk and custom python package Is anyone can run this code on android with buildozer compilation :
(for me, it compiles, but crash on android)
.../main.py
__version__ = '0.1'

from code.app import MyApp

if __name__ == '__main__' :

    MyApp().run()

.../code/__init__.py
nothing

.../code/app.py
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):

    def build(self):
        return Label(text='Hello !')

.../buildozer.spec
[app]

title = Test
package.name = myTest
package.domain = org.test
source.dir = .
source.include_exts = py
version.regex = __version__ = ['"](.*)['"]
version.filename = %(source.dir)s/main.py
requirements = kivy
orientation = portrait
fullscreen = 1

[buildozer]
log_level = 1
warn_on_root = 1

adb logcat : (extract)
D/OpenGLRenderer( 9422): Enabling debug mode 0
V/WindowManager(  857): Adding window Window{2584f44 u0 SurfaceView} at 3 of 11 (before Window{fdf5dd6 u0 org.test.myloging/org.renpy.android.PythonActivity})
I/SDLSurface( 9422): Choose egl configuration
I/SDLSurface( 9422): Try to use graphics config R8G8B8A8S8
W/SDLSurface( 9422): Create egl surface
I/python  ( 9422): presplash-fit is null
I/ActivityManager(  857): Displayed   org.test.myloging/org.renpy.android.PythonActivity: +218ms
I/python  ( 9422): presplash (fit=null) mx=0,703125,my=1,156250
I/libSDL  ( 9422): Physical screen resolution is 720x1184
I/python  ( 9422): Initialize Python for Android
W/InputMethodManager( 9422): Ignoring onBind: cur seq=1016, given seq=1015
I/Timeline( 9422): Timeline: Activity_idle id: android.os.BinderProxy@22de304a time:52888036
I/python  ( 9422): ['/data/data/org.test.myloging/files/lib/python2.7/site-packages', '/data/data/org.test.myloging/files/lib/site-python']
I/python  ( 9422): Android path ['/data/data/org.test.myloging/files/lib/python27.zip', '/data/data/org.test.myloging/files/lib/python2.7', '/data/data/org.test.myloging/files/lib/python2.7/lib-dynload', '/data/data/org.test.myloging/files/lib/python2.7/site-packages', '/data/data/org.test.myloging/files', '/data/data/org.test.myloging/files/_applibs']
I/python  ( 9422): Android kivy bootstrap done. __name__ is __main__
I/python  ( 9422): Run user program, change dir and execute main.py
I/python  ( 9422): Traceback (most recent call last):
I/python  ( 9422):   File "/home/romuald/Kivy/Login/.buildozer/android/app/main.py", line 4, in
I/python  ( 9422): ImportError: No module named app
I/python  ( 9422): Python for android ended.
I/art     ( 9422): System.exit called, status: 0
I/AndroidRuntime( 9422): VM exiting with result code 0, cleanup skipped.
I/WindowState(  857): WIN DEATH: Window{fdf5dd6 u0 org.test.myloging/org.renpy.android.PythonActivity}
I/WindowState(  857): WIN DEATH: Window{2584f44 u0 SurfaceView}
I/ActivityManager(  857): Process org.test.myloging:python (pid 9422) has died
W/ActivityManager(  857): Force removing ActivityRecord{250b9f13 u0 org.test.myloging/org.renpy.android.PythonActivity t170}: app died, no saved state


text:
Q: Docker build takes long time for nodejs application I am experiencing long build times for nodejs applications when building image with docker build command.
There is one big hang that takes couple of minutes
08:03:15  Step 1/11 : FROM node:14.1.0-alpine AS build
08:03:15   ---> 0854fcfc1637
08:03:15  Step 2/11 : COPY server/package*.json /nodejs/server/
08:03:15   ---> Using cache
08:03:15   ---> 4996283ff991
08:03:15  Step 3/11 : WORKDIR /nodejs/server
08:03:15   ---> Using cache
08:03:15   ---> 93e5b63fa81d
08:03:15  Step 4/11 : RUN npm ci
08:03:15   ---> Using cache
08:03:15   ---> 2c825e02ea01
08:03:15  Step 5/11 : COPY server ./
08:03:15   ---> Using cache
08:03:15   ---> 69c024cde79f
08:03:15  Step 6/11 : WORKDIR /nodejs
08:03:15   ---> Using cache
08:03:15   ---> 49d7f8bd9514
08:03:15  Step 7/11 : COPY package*.json ./
08:03:16   ---> e82bee625c3e
08:03:16  Step 8/11 : RUN npm ci
08:03:16   ---> Running in ecfd57702906
...
08:03:49  added 1483 packages in 26.419s
08:09:40  Removing intermediate container ecfd57702906
...
08:09:40   ---> 7c6b67d85b0b
08:09:40  Step 9/11 : COPY *.json ./
08:09:43   ---> 0165efd1c97d
08:09:43  Step 10/11 : COPY src ./src/
08:09:51   ---> 42e54cee6b91
08:09:51  Step 11/11 : RUN npm run build:prod
08:09:51   ---> Running in af6f9b013d27

This does not happen when building Java images.
My Dockerfile
FROM node:14.1.0-alpine AS build
COPY server/package*.json /nodejs/server/
WORKDIR /nodejs/server
RUN npm ci
COPY server ./

WORKDIR /nodejs
COPY package*.json ./
RUN npm ci
COPY *.json ./
COPY src ./src/
RUN npm run build:prod
...

I tried using buildkit but it has the same behaviour
08:37:20  #17 exporting to image
08:37:20  #17 exporting layers
08:50:12  #17 exporting layers 766.8s done

I also added node_modules to .dockerignore file but with no change.
Docker version 19.03.6, build 369ce74a3c
What could be the problem?
What is happening between "added 1483 packages..." and "Removing intermediate container"?

A: I have found the cause of the problem and wanted to share if someone encounters similar issue.
The long "export layers" time was caused by node_modules folder that was present in one of the layers. Removing it solved the problem but it's really a workaround.
I merged npm ci and npm run build... steps together and removed node_modules in the same step.
RUN npm ci && npm run build:prod && rm -rf node_modules

So the final build stage in Dockerfile looks like this
FROM node:14.1.0-alpine AS build
COPY server/package*.json /nodejs/server/
WORKDIR /nodejs/server
RUN npm ci
COPY server ./

WORKDIR /nodejs
COPY package*.json ./
COPY *.json ./
COPY src ./src/
RUN npm ci && npm run build:prod && rm -rf node_modules
...

As I said it's just a workaround and I think the root cause is that Docker is having problems with exporting layers with a lot of small files such as the ones in node_modules.


text:
Q: Templated virtual member functions
Possible Duplicate:
Template member function virtual?

Why are templated virtual member functions not allowed?
I was just playing around a bit with some sample code and the following code snippet gives me the error
"member function templates cannot be virtual"

#include<iostream.h>
#include<stdio.h>
class Base
{
    public:
    template <class T> virtual void doSomething(T genVar,int val){}

};

class derivedCl:public Base
{
    public:
    template <class T> virtual void doSomething(T genVar, char ch){}
};

Is this a rule which the standard dictates and if so why?
Edit: I did a search before asking the Q but the dup never showed up. Now that Sbi pointed it out, I would vote for closing this one. Thanks!


text:
Q: Webscraping with BeautifulSoup FindAll I want to download the hrefs of the 4 articles right above NEED TO KNOW on the following website:
http://www.marketwatch.com/
but I cannot identify them uniquely with FindAll. The following approaches give me the articles, but also a bunch of others, that also fit those criteria.
trend_articles  = soup1.findAll("a", {"class": "link"})
href= article.a["href"]

trend_articles  = soup1.findAll("div", {"class": "content--secondary"})
href= article.a["href"]

Does someone have a suggestion, how I can get those 4, and only those 4 articles?

A: It seems works for me:
from bs4 import BeautifulSoup
import requests

page = requests.get("http://www.marketwatch.com/").content
soup = BeautifulSoup(page, 'lxml')
header_secondare = soup.find('header', {'class': 'header--secondary'})
trend_articles = header_secondare.find_next_siblings('div', {'class': 'group group--list '})[0].findAll('a')

trend_articles = [article.contents[0] for article in trend_articles]
print(trend_articles)


text:
Q: How to prepopulate a search bar and let user change value? I have a simple search bar and I want to pre-populate it with some data. I've tried using value but it doesn't let the user change the value in the search bar afterward.
<input type="search" class="navBarSearchForm3 form-control rounded searchterm2" placeholder="search term" value={comparelinks}></input>

I'd like the searchbar to already have a value and let the user be able to change it. Do I need some JS for it or can it be done with just HTML?

A: You are missing the handle of the change. So, you need to edit the value when the user changes something on the input it would be like:
In this case, I'd use React Hooks (useState) to be able to set one default value and being able to change it.
And finally, use that seCompareLinks when user onChange in the input.
You can see it working here: https://codesandbox.io/s/practical-dewdney-wj7j2?file=/src/App.js:0-543
import React from 'react';
import "./styles.css";

export default function App() {
  const [comparelinks, setComparelinks] = React.useState('default value');

  const handleChange = (e) => {
    setComparelinks(e.target.value);
  }

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <input type="search" class="navBarSearchForm3 form-control rounded searchterm2" placeholder="search term" value={comparelinks} onChange={handleChange}></input>

  );
}

A: You have to handle the update of the input as well, considering you use hooks:
const [comparelinks, setCompareLinks] = useState()

const handleChange = (event) => {
  setCompareLinks(event.target.value)
}

<input type="search" class="navBarSearchForm3 form-control rounded searchterm2" placeholder="search term" value={comparelinks} onChange={handleChange}></input>


text:
Q: How can i run an intellij project in eclipse/sts? I am trying to work on a school project with a friend who works in intelliJ. I just cloned his project repo but I am not sure how to go about running/testing the app as the file structure is slightly different and I cannot right click and run as spring boot app like I can with my projects created in spring tool suite. Is there anyway to run the project without having him export as eclipse in intellij?(All of my research leads me to that answer otherwise)

A: It highly depends on the dependency and build management technology that you use for the project. If you use Maven, you can import the project in STS using the Import Existing Maven Project... import wizard. If you use Gradle, you need to install the Buildship support for Gradle for Eclipse and then import the project as existing Gradle project.
If you don't use any dependency resolution and build technology, and instead defined your dependencies manually in the project configuration, I am not aware of any way to import an existing IntelliJ project into Eclipse/STS as is. You can import the project from the file system as a new project in Eclipse/STS and then configure the dependencies, source folders, output folders, etc. manually. That should work for most project structures. But I would highly recommend to switch over to use a build/dependency management solution, it is way easier than doing everything manually yourself.