text:
Q: Backref package for page reference I'm using the backref package within the hyperref package:
\usepackage[backref]{hyperref}

I get the following result:
Philip Hall. On representatives of subsets. Journal of the LMS, 10, 1935. 3.2, 4.1

where 3.2 and 4.1 are hyperlinks to sections in which this bibliographic entry is referenced. Is it possible to get pages instead of sections?

A: Use
\usepackage[pagebackref]{hyperref}

instead of
\usepackage[backref]{hyperref}


text:
Q: Escape spaces in File Path I am wondering how I can programmatically add \ in front of spaces that appear in file paths. I am using fs.readdir to get the contents of directories and if I don't escape the spaces out of the path then I get an ENOENT error because unescaped paths are invalid in UNIX. I'd like get below result :
/path/with\ spaces/in/them/

However, I am running into a problem with a REGEX in the NODE REPL. When I do :
var path = '/path/with spaces/in/them/';
var escapedPath = path.replace(/(\s)/, "\\ ");

I get as result :
'/path/with\\ spaces/in/them/'

When I try to  run this same code inside of the Chrome console I get :
"/path/with\ spaces/in/them/"

Which is the desired effect.
I am not sure if I am missing something or if this is a bug. I am confused because Node runs on the same Javascript engine as Chrome so I would think that these expressions would be interpreted the same.
Please let me know if anyone knows a way to do get around this. Maybe I am missing something. I just need to be able to escape the paths before passing them into fs.readdir so that I can avoid these errors.
Thanks!

A: try either this
var path = "'file:///Users/kevin/folder with space'";

or this
var path = "\"file:///Users/kevin/folder with space\"";

A: fs.readdir doesn't require you to escape paths. I was able to recursively pass fs.readdir output directories back into fs.readdir without any issues.
The issue above with the REGEX was only occuring in the Node REPL. Once I tested the above code inside of a file I was able to run it through Node and get the same output I saw in the Chrome console.
I ended up finding a bug in my code that was a little hard to track down. I first thought that it came from not escaping the path I was sending into fs.readdir but it was actually an issue where I was fs.stat the output of fs.readdir and then checking if the output was a file or a directory and treating it accordingly.
It turns out that a few results from the stat were neither Files or Directories and my function didn't have any way to deal with this so it just returned. Since I had no handlers for this my node program just stopped abrubtly. All I had to do was add an extra else condition to catch the non-file/directories cases (which I don't care about anyway).
Now its working fine!

redpajama_set_name: RedPajamaStackExchange


text:
Q: React plotly bar chart: color bars dependend on x value I got the following code:
 x: [1, 2, 3,4],
 y: ['Who?', 'Where?', 'When?','What?'],
 name: 'Subject',
 orientation: 'h',
 marker: {
   color: 'rgba(55,128,191,0.6)',
   width: 1
 },
 type: 'bar'
};

var data = [trace1];
var layout = {
 title: 'Colored Bar Chart',
 barmode: 'stack'
};

Plotly.newPlot('myDiv', data, layout, {showSendToCloud:true});

The label 'Who?' should be red, 'Where?' should be orange, 'When?'should be yellow and 'What?' should be green. How do I archive this?
I already looked at colorscale but couldnt make it work.

A: https://plot.ly/javascript/reference/#bar-marker-color

Sets themarkercolor. It accepts either a specific color or an array of
  numbers that are mapped to the colorscale relative to the max and min
  values of the array or relative to marker.cmin and marker.cmax if
  set.

Like this:
marker: {
  color: ['#ff0000', '#ff2200', 'rgba(55,128,191,0.6)', '#00ff00'],
  width: 1
},

First color in array corresponds to first bar, 2nd to 2nd, etc


text:
Q: HTML Agility Pack  tag I'm trying to scrape website that has a "pre" tag using the HTML Agility Pack in C#.  I can find plenty of "table tr td" examples but cannot find any "pre"examples. Here is my code with the formatted text "pre"  inline.

private void PreformattedTextButton_Click(object sender, EventArgs e)
    {
        var url = @"http://www.thepredictiontracker.com/basepred.php";
        var data = new MyWebClient().DownloadString(url);
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(data);

        //            m _        a _        e d     d d     d d     d l     n
        //e       h d       v r    1     2     3     4     5     6     2     s

        //  BAL D.BUNDY TAM C.ARCHER     7.5  7.48  8.08  7.00  5.58  4.70.     .    6.46
        //  CIN H.BAILEY ATL S.NEWCOMB    9.0  9.72 10.08 10.00 11.62 11.51.     .   10.73

        foreach (HtmlNode pre in doc.DocumentNode.SelectNodes("//pre"))
        {
            textBox1.Text += pre.InnerText + System.Environment.NewLine;
        }
    }

I want to capture the lines that look like the 3rd and 4th lines ignoriing the preceeding lines.

The foreach is executed, but it has  pre.InnerText.Length of 1642 which is the total of the pre-formatted text.  I want to capture a line of data.  e.g. Line 3 & 4.

A: By definition <pre> tags are preformatted text, so you need to parse the InnerText property yourself. The sample you gave above is consistently formatted, so split the InnerText into a collection of lines, and then use a Regex to capture the lines you want. Tested and working code example:
var url = @"http://www.thepredictiontracker.com/basepred.php";
HtmlDocument doc = new HtmlWeb().Load(url);
var regexMatch = new Regex(
    @"^\s*[A-Z]{3}\s+[A-Z]\.[A-Z]+\s+[A-Z]{3}",
    RegexOptions.Compiled
);
foreach (HtmlNode pre in doc.DocumentNode.SelectNodes("//pre"))
{
    foreach (var line in pre.InnerText.Split(new char[] { '\r', '\n' }))
    {
        if (regexMatch.IsMatch(line))
        {
            Console.WriteLine(line.Trim());
        }
    }
}


text:
Q: YUI, sync many objects I am evaluating YUI's model syncing framework. If I understand correctly, it is designed so that each model synchronizes with server by itself.
In my case, though, I'll probably have up to a hundred of distinct objects of different types (it's a complex web application). I don't want to spawn 100 distinct requests to retrieve their data one by one—I'd like to be able to aggregate requests and send them in a single request to save time and bandwidth.
How should I design my code to make this possible with YUI models?

A: Implement a sync for ModelList, rather than Model.
You might want to take a look at the example "GitHub Contributors" app, which can load data representing multiple GitHub repos in a single call. Or look at the code for the more generic ModelSync.REST object, which can load data for multiple Models using a single request from a ModelList. In fact, if you're talking to a REST API, you might be able to use ModelSync.REST as-is.


text:
Q: PHP session not working after upgrading php version to 7.2 simple website works perfectly on php 5.3 but after upgrading my php version error is happening on sessions . But to login to my website admin page i have been using the following code.
login.php
<?php
session_start();
$msg = "";
include 'connection/conn.php';
if(isset($_POST['submit']))
{
    $email = $conn-> real_escape_string($_POST['email']);
    $password = $conn-> real_escape_string($_POST['password']);
    $error="Check Your Inputs";

    $sql = $conn-> query("SELECT id ,passwor FROM users WHERE email='$email'");
    if ($sql->num_rows > 0) {
        $data = $sql ->fetch_array();
        if (password_verify($password, $data['passwor']))
        {
            $_SESSION['logedinemail'] = $email;
             header("Location: Dash");
                        exit();

        }
        else
    {
      $msg ="Please Check Your Inputs";

    }

    }

}

?>

and my dashboard
<?php
session_start();
if ($_SESSION['logedinemail']==true) {

  }
 else
 {

   header("Location: index.php");
 }

?>

But recently i upgraded my php version to 7.2 and the following error shows up
PHP Notice:  Undefined index: logedinemail in /home/xx/yy/zz/Dash.php on line 3
thanks

A: If you aren't logged in or your user was not found in your DB or the password is incorrect you have not created the index 'logedinemail' in the session array.
When you do $_SESSION['logedinemail'] == true, PHP tries to compare the value but the index in $_SESSION wasn't created and you get the error you are looking at.
Either initiate this superglobal with $_SESSION['logedinemail'] = false globally in your login.php (before doing if(isset($_POST['submit']))) or check if it's set with (in dashboard):
if (isset($_SESSION['logedinemail']) && $_SESSION['logedinemail'] === true) { ... }
Also, it is better to always compare type secure with === instead of ==.


text:
Q: Change of Variables in triple integrals there is a region bounded by $x=1$ and $y=2$ on the sides, by $z=3$ below and by the plane $x+y+z=10$ above.
I want to calculate the function $y$ over this region, so I've written and solved the following integral:
\begin{equation}
\int_{3}^7 \left(\int_{2}^{9-z} \left(\int_{1}^{10-y-z}y\,dx\right)\,dy\right)dz=32
\end{equation}
However I was wondering if I could simplify the problem with a change of variable. I'm really not sure about how to do it, I know the formula, however the result that I get is very different.
My change of variable was $x'=x-1$, $y'=y-2$, $z'=z-3$.
I got the following integral:
\begin{equation}
\int_0^4\int_0^{4-z'}\int_0^{4-y'-z'}y'-2\, dx\,dy\,dz \neq 32
\end{equation}
Why I do not get the same answer? I've changed the function from $y$ to $y'-2$ and I've calculated the determinant of the Jacobian, which is 1, since the Jacobian is the Identity.
Please tell me if I could do a different change of variables or how I can get the same result.

A: The Jacobian is indeed 1, but you made a couple mistakes in your integral. We have $x'=x-1$, $y'=y-2$, $z'=z-3$, therefore $x=x'+1$, $y=y'+2$, $z=z'+3$. The integral becomes:
\begin{equation}
\int_0^4\int_0^{6-z'}\int_0^{5-y'-z'}(y'+2)\, dx\,dy\,dz
\end{equation}
You should get the same answer if you work this one out! :)


text:
Q: Override ToString() of not user's class I need to override .ToString() method of XElement.
How can I do this ?

A: Without creating a new derived type from the class, you cant override a method like that. I would recommend taking a look at writing an extension method instead. a link.


text:
Q: Condition will not match the other i have this if else statement that always return ( other than 0 ) 'hey', but when the condition == 0, it will not display the 'ho' value.
Appreciate advice. Thanks.
$('#icNumber').on('change', function(){
    let num = $(this).val().substr(13,1) %2

    if(num){
        $('#tortrix')
        .removeClass('d-none')
        .addClass('d-block form-control animated fadeIn')
        .attr('value', function(i, oriVal){
            if(num == 0) {
                console.log('ho')
                return 'value','Testatrix';
            } else {
                console.log('hey')
                return 'value','Testator';

            }
        })
    }
        else if (num == "") {
        $('#tortrix').removeClass('d-block').addClass('d-none')
    }
})


text:
Q: C thread synchronization I have a problem of using multiple threads and sync them in a proper order. The problem states the following: I have 44 threads from 1-44. I can have a maximum of 4 threads that can enter the critical area at a moment. Thread number 12 must close only when there are 4 threads in the critical area, including them. The problem is the following: sometimes the thread closes well, sometimes it doesn't. I don't know when it is going to come, it might be the last one, so i forced it to be the first one that enters the critical area. This is the code sample that sync the 44 threads:
void *thread_sync_P7(void *arg){
    int *val = (int*)arg;

    if(*val != 12) {
        sem_wait(&semP7_2);
    }

    sem_wait(&semP7_1);
    info(BEGIN, 7, *val);

    if(*val == 12) {
        sem = 0;
        for(int i = 0;i < threadP7 - 1;i++){
            sem_post(&semP7_2);
        }
    }

    info(END, 7, *val);
    sem_post(&semP7_1);

    return NULL;
}

sempP7_1 sync the critical area to stop more than 4 threads being there at one, and semP7_2 makes sure that the first thread to enter the area is thread with id 12.
Sometimes this happens:
[T] BEGIN P7 T12 pid=24850 ppid=24848 tid=825038592

[T]  END  P4 T3 pid=24848 ppid=24846 tid=900572928

[T] BEGIN P7 T2 pid=24850 ppid=24848 tid=908965632

[T]  END  P4 T1 pid=24848 ppid=24846 tid=917358336

[T] BEGIN P7 T3 pid=24850 ppid=24848 tid=900572928

[T]  END  P5 T0 pid=24851 ppid=24847 tid=925882176

[T]  END  P7 T12 pid=24850 ppid=24848 tid=825038592

[T] BEGIN P7 T4 pid=24850 ppid=24848 tid=892180224

As you can see, P7 T12 is the thread with id 12. It is followed by T2 an T3, but it closes and there are only 3 threads displayed. How can i sync them better?

A: You have several ways to implement this:

*

*(waiting) Use a condition variable associated with the final condition.  Your thread number 12 will be waiting for that condition to be true, and the other threads will evaluate the condition and awaken it when the condition becomes true.  As each thread enters into the critical region, it evaluates the condition and if true, awakens the thread.  As each thread gets out of the critical region, reevaluates the condition (this mean to increment/decrement a variable with the number of threads in the critical region)  Onde the thread 12 is awaken, it can close (with closing meaning whatever you want)  In this case your thread is waiting for the condition to happen to close.

*(polling) In case your thread has something to do until it is about to decide if to close or not to close, just evaluate the condition on the other threads on entry to the critical region and store it (you need a critical region nested on the first to achieve this).  You can have also a boolean variable indicating if the condition has been reached in the past (we have already reached the four threads inside, even if now there are not those four threads)  Then, your thread has freedom to make another task and only evaluate if it has to close at certain points in time.

*(signalled) In case you have to asynchronously signal the process to leave what it can be doing and close, just send it a signal.  This will interrupt the thread execution and you can decide to abort your task or continue after the signal on your signal handler.  Beware that handling signals (you send signals to a process, which normally is a group of threads) and attaching them to specific threads of a process is something difficult to properly achieve, you have to decide which threads are going to handle what kind of signals, and this is an elaborate thing.


text:
Q: Animate two containers width using Animated container I have two widgets,
Widget FirstWidget()
{
 return Container(
          height: 40,
          child: new Text('Food Products',style: TextStyle(color: Colors.gray))
          decoration: new BoxDecoration(
              borderRadius: new BorderRadius.all(new Radius.circular(4.0)),
              border: Border.all(width: 2, color:Colors.gray)),
          padding: new EdgeInsets.all(12.0),
        )
}

Widget SecondWidget()
{
 return Container(
          height: 40,
          child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text('Food Products',
              TextStyle(color: Colors.blue),
          SizedBox(width:8),
          Icon(Icons.check,color:Colors.blue ,size: 24,)
        ],),
decoration: new BoxDecoration(
              borderRadius: new BorderRadius.all(new Radius.circular(4.0)),
              border: Border.all(width: 2, color:Colors.red)),
          padding: new EdgeInsets.all(12.0),
        )
}

Now, i need to animate the two widgets based on selection,
class BasicProduct extends StatefulWidget {
  final String name;
  final bool isSelected;

  BasicProduct({Key key, @required this.name, this.isSelected = false});

  @override
  State<StatefulWidget> createState() => _BasicProduct(name, isSelected);
}

class _BasicProduct extends State<BasicProduct> {
  final String name;
  bool _isSelected;

  _BasicProduct(this.name, this._isSelected);

  @override
  Widget build(BuildContext context) {
 Widget _myAnimatedWidget = _isSelected ?  SecondWidget() : FirstWidget();
    return new GestureDetector(
        onTap: () {
          setState(() {
            _isSelected = !_isSelected;
_myAnimatedWidget =
        _isSelected
            ? SecondWidget()
            : FirstWidget();

          });
        },
        child: AnimatedContainer(
        key : _animatedContainerKey
        duration: const Duration(seconds: 1),
width: boxWidth
        child: _myAnimatedWidget
);
  }
}

How to get the width for the two widgets to animate?
Tried Calling WidgetsBinding.instance.addPostFrameCallback((_)=> getSize) in the initState to get the Size
getSize()
{
var boxWidth = _animatedContainerKey.currentContext.findRenderObject().size.width;
}

This Size returning for the SecondWidget only, when firstWidget is changed, the Size returning for SecondWidget only.
Can anyone help how to resolve the issue?

A: I would take a different approach to this. For one, if you can, you should try using the AnimatedCrossFade  widget - it automatically handles both the fade and the size change between two different widgets. If you can make it so that instead of having to specify an exact size in your widgets (always a bad idea) they simply fit to the available space, then this should do what you want. However, without more details of what you're actually trying to accomplish with the animation & size of the widgets, it's a bit difficult to help.
If this doesn't work, then you should consider using an AnimationController and a widget inheriting AnimatedWidget. This way, you have complete control over the build process of your two widgets - you can size, position, and fade them however you want with a stack + opacity or whatever else works best for you.
I would normally write out an example but I think it's a bit beyond the scope of this answer, however you can find out an example of an animated widget here: https://api.flutter.dev/flutter/widgets/AnimatedWidget-class.html. If you do need to go down this route and can't figure out, it would help if you could add more details about what it is you're trying to accomplish instead of what you've attempted to do to accomplish it.


text:
Q: How to use Matlab to transfer learning using pre-trained CIFAR-10 network? I am trying to classify a set of images using transfer learning approach. All of the tutorials I came across used Alexnet to fine tune and transfer learning. However, I am trying to use a less complicated model like CIFAR-10. I went through this Matlab Tutorial. At the point where they start transfer learning, they used Matlab's sample data. They loaded the ground truth data in a table,
%Load the ground truth data
data = load('stopSignsAndCars.mat', 'stopSignsAndCars');
stopSignsAndCars = data.stopSignsAndCars;

The table contains the image filename and ROI labels for stop signs, car fronts, and rears. Each ROI label is a bounding box around objects of interest within an image. Then they kept only labels for stop signs.
What should I do, if I want to use my own images for this network in a similar approach used for Alexnet,
net=alexnet;
layersTransfer = net.Layers(1:end-3);

readAllDir=uigetdir('','Select All directory to read scaled image files');
AllSample=imageDatastore(readAllDir, 'IncludeSubfolders', true, 'LabelSource','foldernames');

By the similar approach, I mean making the 'imageDatastore' for all the labelled images and using them to train the network.


text:
Q: Not able to load data into partitioned table in hive I am not able to load data into the partitioned table as it is showing "Dynamic partition strict mode requires at least one static partition column. To turn this off set hive.exec.dynamic.partition.mode=nonstrict
" the above error  even on setting set hive.exec.dynamite.partition.mode=nonstrict;
hive> set hive.exec.dynamite.partition=true;
 these parameter i am getting the same error.
Kindly suggest me the better solution.
Thanks in advance;

A: You have various typos (and an interesting affinity to blowing things up):
hive.exec.dynamite.partition.mode=nonstrict

should be
hive.exec.dynamic.partition.mode=nonstrict

So, change dynamite to dynamic (/stop destroying things ;))  and see if you can make better progress.

A: yeah typos can be a very dangerous thing.
With previous versions of hive(0.12 and previous) hive doesn't validate the hints that you write. Basically you can write anything and hive wont complain. It will only pick the correct ones.
However hive 0.13 onwards, Hive verifies the hints. if something is not correct hive will simply throw an error(Boss check the parameter you have set)


text:
Q: Powershell accessing an object in AD SearchResultCollection I have the following Powershell code:
$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$directorySearche.PageSize = 100
$directorySearcher.SearchScope = [System.DirectoryServices.SearchScope]::SubTree
$searchResults = $directorySearcher.FindAll()
#$searchResults
$searchResults.Item(0).Path

If I uncomment #$searchResults then I can see hundreds of entries with "Path" and "Properties" as the objects' properties.
However when $searchResults.Item(0).Path is executed, it just says "Running script/selection. Press ctrl+break to stop." and has been like that for 10 mins so far.
Why can't I access an individual object from the SearchResultCollection ?

A: Turns out there were just way too many results.
I used a filter to narrow it down and now I can access individual objects since there are now only 347 results.
Before I couldn't even find out the count because there were too many.


text:
Q: Consider of drawing one card from a deck of $52$. Prove that the events of a spade being drawn and an ace being drawn are independent events.
Consider of drawing one card from a deck of $52$. Prove that the events of a spade being drawn and an ace being drawn are independent events.

Let $A$ be the event that a spade is drawn and let $B$ be the event that an ace is drawn.
Then, $\text P(A) = 4/52 = 1/13$ and $\text P(B) = 4/52 = 1/13$.
How can I calculate $\text P(A\cap B)$? And how can I prove that these events are independent since the question specifically asked to prove that they are independent?

A: You didn't compute the probability of event $A$ correctly. There are $13$ spades in a standard deck. So $P(A)=13/52=1/4$. Note that $A\cap B$ corresponds to drawing the ace of spades and hence
$$
\frac{1}{52}=P(A\cap B)=\frac{1}{4}\times\frac{1}{13}=P(A)P(B)
$$


text:
Q: Manage fragment life cycle with navigation drawer I have an architectural issue in my application . I have used one activity with navigation drawer and several fragments .Now ,
Suppose I have two fragments A and B . navigation structure is somewhat:
A
   A1
   A2

B
   B1
   B2

where A1,A2 are of type A fragment and B1,B2 are of type B fragment. The only difference between same type of fragments eg. A1,A2 is of data .
my first approach :
whenever user click on A1,A2,B1,B2 . I just create a new instance of that type and replace the fragment.
  Fragment fragment =A.newInstance();

 private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.content_frame, fragment).commit();
        mDrawerLayout.closeDrawer(rlDrawer);
    }

Note : I do not want to add them to back stack.
Later on I realize this approach is inefficient as every time it will crate a new instance on that fragment even if they are of same type . As I said before the difference is only in data .So, I move to next approach
Second Approach :
Now my activity has Data member (references) of Fragment A and B . Now I will check if it is null only then create a new instance else just change the data :
   if (A == null) {
            a = A.newInstance();
        } else {
            ((A) a).changeData();
        }
        replaceFragment(a);

Problem with this approach is that when I switch from fragment A1 to B1 the A1 fragment get destroyed but its reference remain with activity . Now When i switch back from B1 to A1 it will not create a new instance as you can see in above code but at the same time onCreate() method gets called on Fragment A.
Should I remove the reference from activity as soon as onDestroy() is called on a Fragment ?
Does my second approach is correct ?
Is there any better approach for this?
Thanks in advance.

A: I would slightly modify your first approach.
Use string tags for your fragment.
When you are replacing a fragment use the replace method with three parameters, example:
  fragmentManager.beginTransaction()
                .replace(R.id.content_frame, fragment, TAG_A1).commit();

where TAG_A1 is a unique String tag.
You can use the method findFragmentByTag from the FragmentManager to check if the fragment was already created before you do a replace.
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragmentA1 = fragmentManager.findFragmentByTag(TAG_A1);
if(fragment == null) {
    fragment = A.newInstance();
}
fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, fragment, TAG_A1).commit();


text:
Q: knitr: how to get the filename of the current child Rnw file into the latex header I'm writing a book with multiple chapters, all children of the main book.Rnw file, and each chapter can have
multiple child Rnw files for sections, examples, etc.  For ease of reference in the draft document, it is very useful to display the path name of the current child Rnw file in the LateX header.
This question follows up on a similar one, Need the filename of the Rnw when knitr runs in rStudio, where it was suggested to use something like
<<>>=
infile <- knitr:::knit_concord$get("infile")
@

However, I've been unable to make this work automagically with knitr, as I could do when using straight LaTeX.  There, whenever a file is \input{} or \include{}ed, a global LaTeX symbol, @filef@und is automatically updated.  This allows page headers to be updated using the following code in the preamble:
%% Page Headings
\makeatletter
\usepackage{fancyhdr}
\pagestyle{fancy}
%
%% The next two lines are only for draft printing
\def\infoleft{\quad [{\small\ttfamily\@filef@und}]}
\def\inforight{[\number\month-\number\day-\number\year]\quad}
%
\renewcommand{\chaptermark}[1]{%
 \markboth{\thechapter\ #1}{}}
\renewcommand{\sectionmark}[1]{%
 \markright{\thesection\ #1}}
  \lhead[\fancyplain{}{\bfseries\sffamily\thepage}]%
  {\fancyplain{}{{\bfseries\sffamily\rightmark}\infoleft}}
  \rhead[\fancyplain{}{\inforight{\bfseries\sffamily\leftmark}}]%
  {\fancyplain{}{\bfseries\sffamily\thepage}}
\cfoot{}
\makeatother

I think what I'm looking for is a chunk hook that will record the path name of a child document in a global R variable and then gdef that into LaTeX using Sexpr{}.   Something like:
<<ch02-ex1, child="ch02/ex1.Rnw">>=
@

triggers something like below, giving infile = ch02/ex1.Rnw
<<>>=
infile <- knitr:::knit_concord$get("infile")
@

and then inserts something like the following into the .tex output.
\gdef\infile\Sexpr{infile}

A: Instead of knitr:::knit_concord$get("infile"), I think you should be using current_input() nowadays.  But then you'd need to write a simple function for the second part, i.e.
setInfile <- function() cat("\\gdef\\infile ", current_input())

and put a call to this in an "asis" chunk at the top of the child.  (I haven't tried this; you may need some sanitizing of the current_input() result so that line gives legal LaTeX.  You may also need another call in the parent to switch back.


text:
Q: Failed an audit for a post I never reviewed I was reviewing some suggested edits, when suddenly I was informed that I failed an audit. I totally understand that there are audits, I have seen them before, but in this case I did not review that post, or hit the Approve button -- I received the "audit failed" notice without first receiving that same post for review. So, either there is a bug with the audit, or some IDs got mixed up or something. The only non-bug related situation I can think of is that somehow the Approve button was pressed without me even noticing, which I would say is also a bug.
It might be nothing, but I felt a duty to make a report; maybe others have had wrong audits hit them too.
(Another possibly similar bug)

A: Given the timing, it does appear that this was unintentional - right now, we're gonna blame your ISP.
If this happens again, let me know.


text:
Q: Connect an ATmega microcontroller to the HDMI CEC bus i need a little help with a proper circuit for a connection between a microcontroller and the HDMI CEC bus.
Here is the whole plan:

Basically I want to use an ATMega microcontroller to decode the CEC bus signal and communicate via the CEC bus with other coneccted devices (TV/BD-Player/AV).
The current state:
I connected the CEC line to the input capture pin of my microcontroller. And the CEC ground to the ground of the microcontroller. The CEC bus works at 3.3V (max 3.63V) and my microcontroller at 5V. This isn't much of a problem and works fine (due to the switching threshold). A C-program is doing the job of decoding the signal and currently sending it out via UART. This works great and I can read every signal of my CEC capable devices.
Now the problem:
In the current state I can only read signals, but I obviously also want to write something. How do I need to connect my microcontroller to change the state between high/low on the bus?
Maybe the Solution?!:
Because of the different logic levels (3,3V <-> 5V) I first need some level shifting. I would use a simple voltage divider (10k and 6,8k) and connect it on to the CEC line from some output pin (other than the pin I am using to read the signal). Would it work like this? If the line is HIGH and I am applying also a HIGH state with my microcontroller, does this cause any problems? How would I minimize the current going out?
I don't want to damage anything here and my electrical knowlage is just the basic stuff :D

A: Since the HDMI CEC bus is an open-collector configuration with shared pullups like i2c, you should write to it by toggling the port's state (the data direction register or DDR) between input (does not affect the bus, a 1) to output 0 (pull the bus down) and back again. Instead of writing 1 and 0 to the PORT[ABCD] register since the microcontroller doesn't need to pull the line back up.
On other microcontrollers you might configure the port in open-drain mode or use a built-in CEC peripheral.
You should disable the microcontroller's built-in pull-up/down resistors. The bus already has pullups and yours will not match the voltage/current specification required by the bus. A commercial device might provide its own discrete pull-up resistors or rely on the other end depending on the specification.
It would also be a good idea to run your ATMega at 3.3V. It will work at 3.3V; many AVRs are designed to work all the way down to 1.8V.

A: There's a lot of information in this thread at Arduino forum, there's a schematic for both receive and transmit, see below. Reply #81, on page 6, have complete Cadsoft Eagle schematic and layout files.
It could be useful to connect also I2C to the HDMI-port to get EDID-information from the TV, no circuits are needed if the AVR is running at 3.3V, just connect data and clock pins straight from AVR to HDMI (see the eagle schematic).
They also wrote some kind of library, I'm not sure how useful it is since it's written for Arduino, but the code can be found on Google Code.
Please share your C library for AVR, I would love to have something to start with myself. :)
,

A: all you need is the circuit below.

Please, could you share your project?


text:
Q: Android source code - Copying downloaded code to mirror I have already downloaded Android source code using
repo init -u https://android.googlesource.com/platform/manifest -b android-4.0.1_r1
Now I want to create a mirror for other people to access over LAN
repo init -u https://android.googlesource.com/mirror/manifest --mirror
Can I copy already downloaded source inside mirror dir so that download usage will be low?

A: I think yes, you can. The only thing that you should do is to correct manifest file. For instance, you can read here how to do this.


text:
Q: How ro pass an List/array from javascript controller to helper I have the following attribute in my lightning component
<aura:attribute name="serverList" type="Opleiding__c[]"/>

I can call this in my javascript controller with
var serverList = component.get("v.serverList");

I want to be able to pass its value to my javascript helper
I tried in my helper
({
selectedTrue : function(serverList) {..}
})

or
    ({
        selectedTrue : function(serverList){
var serverList = component.get("v.serverList");}
    })

Both do not work, am i missing something?

A: <aura:attribute name="serverList" type="Opleiding__c[]"/>

Your component controller should look like:

someFunction: function(component, event, helper) {
    helper.helperMethod(component, component.get("v.serverList") );
}

Your component helper should look like:

helperMethod : function(component, Servers) {
    console.log('Server List********', Servers);
}

I have the same logic working but i pass accounts from component to helper like above.
You were missing component in below statement
({
    selectedTrue : function(serverList) {
        var serverList = component.get("v.serverList");
    }
})

Hope the solution helps!!


text:
Q: How to access to PHP function on wordpress I have a php file in my file manager that shows a search bar on a Wordpress page, which will show the items in the database as a suggestion, calling another php script that is located in the same folder. I call it like this:
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);

But when I type something in the search box, it shows a GET 404 error in the console and nothing appear.
Also, if I try to access the php function directly like "www.example.com/backend-search.php" or "www.example.com/index.php/backend-search.php", Wordpress shows that the page doesn't exist.
How can I access then that php file from another php code or just inside Wordpress?
Thank you!


text:
Q: create a trigger before insert I want to create a trigger before insert and check inside the trigger function the summary_id values of the new row to be inserted, to see if the summary_id already exists in the table. if it exists then the trigger should return null as I don't want to insert duplicate values. I have written this function, but, when I tried to add a new duplicate row, it was inserted successfully!
CREATE OR REPLACE FUNCTION trigger_ack_bi()
RETURNS trigger AS $$
--DECLARE
--    max_points INTEGER;
BEGIN

   IF(TG_OP = 'INSERT') THEN
        IF NEW.ack_summary_id = (SELECT ack_summary_id FROM scm_main.tbl_ack WHERE scm_main.tbl_ack.ack_summary_id = NEW.ack_summary_id LIMIT 1) THEN
               RETURN NULL;
        ELSE
               RETURN NEW;
        END IF;

    END IF;
END;
$$LANGUAGE plpgsql;

CREATE TRIGGER trigger_ack_bi BEFORE INSERT ON
scm_main.tbl_ack
FOR EACH ROW
EXECUTE PROCEDURE trigger_ack_bi()

ALTER FUNCTION trigger_ack_bi() OWNER TO postgres;

A: I'd recommend setting column to be NOT NULL and creating a PK on it...
alter table scm_main.tbl_ack alter column ack_summary_id set NOT NULL;
alter table scm_main.tbl_ack add primary key (ack_summary_id);

A: it seems the trigger function is correct. But, it is running in silent mode. raising an exception was what I needed to make sure that duplication had been prevented. Thank you for your other solutions.
    CREATE OR REPLACE FUNCTION trigger_ack_bi()
RETURNS trigger AS $$
--DECLARE
--    max_points INTEGER;
BEGIN

   IF(TG_OP = 'INSERT') THEN
        IF NEW.ack_summary_id IS NULL THEN
             RAISE EXCEPTION 'summaryID cannot be null';
        END IF;

        IF NEW.ack_summary_id = (SELECT ack_summary_id FROM scm_main.tbl_ack WHERE scm_main.tbl_ack.ack_summary_id = NEW.ack_summary_id LIMIT 1) THEN
             RAISE EXCEPTION 'duplication prevented..';
               RETURN NULL;
        ELSE
               RETURN NEW;
        END IF;

    END IF;
END;
$$LANGUAGE plpgsql;

CREATE TRIGGER trigger_ack_bi BEFORE INSERT ON
scm_main.tbl_ack
FOR EACH ROW
EXECUTE PROCEDURE trigger_ack_bi()


text:
Q: Show that $\dfrac{d}{dt}\left(ml^2\dot\theta\right)+mgl\sin\theta=l\dfrac{d^2\theta}{dl^2}+2\dfrac{d\theta}{dl}+\dfrac{g}{v^2}\theta$ I have the following question from my textbook:

Suppose that a simple pendulum has the length $l$ of it's string increased at a steady rate (for example, a weight swaying as it is lowered by a crane). Find the equation of motion for small oscillations.
For a simple pendulum; it's equation of motion is given by $$\dfrac{d}{dt}\left(ml^2\dot\theta\right)+mgl\sin\theta=0\tag{1}$$
  Let the length $l$ of the string at time $t$ be $$l=l_0+vt\tag{2}$$ and change from $t$ to $l$ as the independent variable. For small oscillations, we may replace $\sin \theta$ by $\theta$.
Hence show that equation $(1)$ becomes
  $$l\dfrac{d^2\theta}{dl^2}+2\dfrac{d\theta}{dl}+\dfrac{g}{v^2}\theta=0\tag{3}$$
  Hint: From equation $(2)$ $dl=v\,dt$, so $$\dfrac{d}{dt}=v\dfrac{d}{dl}$$

My attempt:
Using the hint, equation $(1)$ becomes $$v\dfrac{d}{dl}\left(ml^2\dot\theta\right)+mgl\theta=0$$
$$\implies v\dfrac{d}{dl}\left(l^2\frac{d\theta}{dt}\right)+gl\theta=0$$
$$\implies v\left(2l\frac{d\theta}{dl}+l^2\frac{d^2\theta}{dl^2}\cdot v\right)+gl\theta=0\tag{a}$$
Where in $(\mathrm{a})$ I used the product rule along with the chain rule for the second term, namely $$\frac{d}{dl}\frac{d\theta}{dt}=\frac{d}{dl}\frac{d\theta}{dl}\frac{dl}{dt}=\frac{d^2\theta}{dl^2}\cdot v$$
Simplifying $(\mathrm{a})$ gives $$2v\frac{d\theta}{dl}+lv^2\frac{d^2\theta}{dl^2}+g\theta=0$$
$$\implies l\frac{d^2\theta}{dl^2}+2\frac{1}{v}\frac{d\theta}{dl}+\frac{g}{v^2}\theta=0$$ which is identical to $(3)$ with the exception of the $\dfrac{1}{v}$ factor in the second term.
I have already checked the errata list for the book and there is no error. So this leads me to believe I am making a mistake somewhere.
Is there any chance someone could point out the error in my calculation?

A:
$$v\dfrac{d}{dl}\left(l^2\frac{d\theta}{dt}\right)+gl\theta=0$$
  $$\implies v\left(2l\frac{d\theta}{dl}+l^2\frac{d^2\theta}{dl^2}\cdot
 v\right)+gl\theta=0\tag{a}$$

Here, you made the mistake:

$$v\frac{d\theta}{dt}\dfrac{d}{dl}\left(l^2\right)=2vl\frac{d\theta}{dl}$$

The $dt$ in the term $\dfrac{d}{dl}$ changed to $dl$ for no reason.
Actually, it should be
$$v\frac{d\theta}{dt}\dfrac{d}{dl}\left(l^2\right)=2vl\frac{d\theta}{dt}=2vl\frac{d\theta}{dl}\cdot \frac{dl}{dt}=2v^2l\frac{d\theta}{dl}$$
Hope this helps.


text:
Q: z index is not working after using rotateY I am trying to do a page flip effect. for this I need two div overlapped. In my structure both divs are originally by side and second div is given -webkit-rotateY(180deg). z-index of first div is 2 and second div is 1. So first div should be overlapping second div.
Issue is, even though z index of second div is less than the first div, second div is appearing above the first div. How can I fix this? I am using safari 5.1.7.
HTML-

CSS-
    .CoverPage{
position:absolute;
height:80%;
width:35%;
top:12%;
left:50%;
overflow:hidden;
z-index:2;
-webkit-transform-origin : 0% 0%;
-webkit-transition:transform  1s ease-in-out;
background:orange;
}

.LastPage{
position:absolute;
height:80%;
width:35%;
top:12%;
left:15%;
overflow:hidden;
z-index:1;
background:blue;
-webkit-transform-origin:100% 100%;
-webkit-transform:rotateY(180deg);

}

A: Is #bookmaindiv position relative? If not try that.


text:
Q: Unable to locate element using xpath Am very new to Selenium just learnt few things and trying to automate.Unable to locate an element in Selenium webdriver for the below one:

TASKS

I have written code like
driver1.findElement(By.xpath("//*[Contains(@class,'content tasks')]")).click();

Anyone please help me.
And also please suggest some sites or links to learn more about locators especially xpath. I tried  few but not getting it in depth.
Thanks in advance.

A: Start contains with a lower case c:
driver1.findElement(By.xpath("//*[contains(@class, 'content tasks')]")).click();

A:

driver1.findElement(By.xpath("//a[@class='content tasks']")).click();


text:
Q: JMeter : Run all tests in a file I have around 4 files named:
Test_1.csv
Test_2.csv
...

Each line in each test file has the following format:
method;request

Where, method is the URL that I call and request is the request I make to it. Everything is configured to pick up these values and form URLs.
However, first Test_1.csv must run, then Test_2.csv must run and so on. To do that, I have created 5 thread groups in the following hierarchy:
Test Plan
 |
 +- Step 1
     |
     +- HTTP request
     +- CSV Data Set Config <- Reads from Test_1.csv
     +- Uniform Random Timer
 +- Step 2
     |
     +- HTTP request
     +- CSV Data Set Config <- Reads from Test_2.csv
     +- Uniform Random Timer

And I have also selected the Run thread groups consecutively option in my test plan. Each thread group is configured for 20 threads. Now, what I want it to do is that, Step 1 should run each and every test in Test_1.csv, then Step 2 should execute and run each and every line in Test_2.csv. However, what is happening is that, Step 1 runs the first 20 lines from Test_1.csv and then Step 2 starts, runs 20 tests and continues. Then, after all steps are done, Step 1 runs again and runs the very same 20 lines from Test1.csv. I want it to just run once, loop through all the lines in the test file and then quit and hand over control to the next thread.
How do I go about this?

A: Try to use the following schema:

Test Plan
    Thread Group #1
    Number of Threads: N
        . . .
        While Controller
        Condition: ${__javaScript("${request}"!="<EOF>",)} - until the EOF
            CSV Data Set Config
            Filename: [path to your file with test-data] - Test_1.csv in this case
            Variable Names: method,request
            HTTP Request
                Uniform Random Timer
            . . .
    Thread Group #2
        . . .
        [same for Test_2.csv]
    Thread Group #3
        . . .
        [same for Test_3.csv]

A: jMeter Plugins' ParameterizedController can help you call parts of your test plan like you call functions in a regular programming language. More importantly, you can parametrise those calls with variables.


text:
Q: SQL Syntax Error Group By I've got a sql syntax and it gives me the error:

Msg 8120, Level 16, State 1, Line 1 Column 'VEHICLEMASTR.cconduction'
  is invalid in the select list because it is not contained in either an
  aggregate function or the GROUP BY clause.

Here is the SQL syntax:
SELECT A.cplateno,A.cconduction,A.cname,A.cbatterymodel
,A.dbattery,A.DlastChange,A.nlastoilkm,A.naveragekmday
,A.dkmreading,A.dfranacq,A.dfranexp,A.nlimit,A.dreading
,CONVERT(varchar(2),month(MAX(B.dinsexp)))+'/'+CONVERT(varchar(2),day(MAX(B.dinsexp)))+'/'+CONVERT(varchar(4),year(MAX(B.dinsexp))) as dinsexp
,C.corno,CONVERT(varchar(2),month(MAX(C.dregexp)))+'/'+CONVERT(varchar(2),day(MAX(C.dregexp)))+'/'+  CONVERT(varchar(4),year(MAX(C.dregexp))) as dregexp
FROM VEHICLEMASTR A
LEFT JOIN VEHICLEINSURANCE B
ON A.cplateno = B.cplateno
LEFT JOIN VREGISTRATION C
ON A.cplateno = C.cplateno
GROUP BY A.cplateno

Can anybody tell what went wrong?

A: The "group by" clause must name every column selected, except those columns that are aggregate functions.
FYI an "aggregate" function is one that returns a single value for many rows, like sum(), count(), etc

A: a.cconduction needs to be in the group by clause.
When using a Group By clause, a column must either have an aggregate function (i.e. COUNT) or be defined in the group by.
A sample group by statement with multiple grouping:
SELECT column1_name, column2_name, aggregate_function(column_name3)
 FROM table_name
 WHERE column_name1 operator value
 GROUP BY column_name1, column_name2;

A: You must include all fields that you mentioned in your select except the column that has aggregate function so in your case it would be:
GROUP BY
a.cplateno, a.cconduction,a.cname,a.cbatterymodel,a.dbattery,
a.DlastChange,a.nlastoilkm,a.naveragekmday,
a.dkmreading,a.dfranacq,a.dfranexp,a.nlimit,a.dreading

instead of
GROUP BY a.cplateno

Edit:
If you want only the a.cplateno then you don't include the rest of the fields except aggregate function and a.cplateno like:
SELECT  A.cplateno
,CONVERT(varchar(2),month(MAX(B.dinsexp)))+'/'+CONVERT(varchar(2),day(MAX(B.dinsexp)))+'/'+CONVERT(varchar(4),year(MAX(B.dinsexp))) as dinsexp
,CONVERT(varchar(2),month(MAX(C.dregexp)))+'/'+CONVERT(varchar(2),day(MAX(C.dregexp)))+'/'+  CONVERT(varchar(4),year(MAX(C.dregexp))) as dregexp
FROM VEHICLEMASTR A
LEFT JOIN VEHICLEINSURANCE B
ON A.cplateno = B.cplateno
LEFT JOIN VREGISTRATION C
ON A.cplateno = C.cplateno
GROUP BY A.cplateno


text:
Q: How do I create a desktop wallpaper slideshow? How do  I create a desktop wallpaper slideshow with my own set of images?

*

*With the images coming from a pictures folder, or pre-selected

*With the images displayed in order, or randomly

*With the images changing every few minutes, or after random periods of time

A: Wallch
In software center there are two wallpaper changer - wallch for Gnome-Shell/Unity/Gnome-Classic and Wally for KUbuntu.
Lets concentrate on Wallch.
Sadly the version of Wallch in the software centre is outdated and has many issues especially with 14.04! There's a repository with the recent version.
To install, add the repository (you don't need to do this on 16.04):
sudo add-apt-repository ppa:wallch/wallch-daily

Then install Wallch:
sudo apt-get update && sudo apt-get install wallch

Then start from Dash:

Lets now launch the application preferences:

Let's untick the bubble notification - its annoying - at the same time you could disable sounds!

At the same time you can define the start-up options:

Save - and add a folder of pictures - in this example, use /usr/share/backgrounds for the default wallpapers that come with Ubuntu

Now we've got two choices:
Start up choice 1
(thanks @Naruto)
keep wallch in in the launcher

exit wallch and start changing wallpapers

Start up choice 2
start wallch on login without needing to have a launcher
From the dash:

Then create a new startup application with the command wallch --constant

N.B. - for some computers this will not work.  The solution is to introduce a delay to the startup of the wallch daemon as per the following Q&A:
Wallch not auto-cycling backgrounds on log in

A: For gnome 3, generate the xml using one of the previous answers, then you could add the generated xml via the command line:
gsettings set org.gnome.desktop.background picture-uri 'file:///home/pykler/.backgrounds/realtime/background.xml'

Another Solution (this will add your bg to the Appearance area under gnome-control-center):
mkdir -p ~/.local/share/gnome-background-properties/

cat >~/.local/share/gnome-background-properties/custom-wallpapers.xml <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE wallpapers SYSTEM "gnome-wp-list.dtd">
<wallpapers>
  <wallpaper deleted="false">
    <name>Pykler</name>
    <filename>/home/pykler/.backgrounds/realtime/background.xml</filename>
    <options>zoom</options>
  </wallpaper>
 </wallpapers>
EOF

Replace the name "Pykler" and the path "/home/pykler/.backgrounds/realtime/background.xml" as needed.

A: For 11.04 and previous versions
There's a program for creating wallpaper slideshows called CREBS. Check out this article about it: http://www.omgubuntu.co.uk/2010/05/crebs-the-ultimate-wallpaper-slideshow-application
A simpler app that has fewer features but is easier to use can be found here: http://gnome-look.org/content/show.php/Wallpaper+Slideshow?content=125178

A: For Gnome 3, you can use the Wallpaper Slideshow App.

According to its developer, it has the following features:

*

*Lets you choose the folder via a browser.

*Lets you set the timeout in seconds.

*Lets you chose depth of subdirectory.

*You can enable or disable it with a single click.

*Full-feature tooltips

To download:
git clone git://gitorious.org/gnome-3-wp/gnome-3-wp.git

Then run wp-show in the gnome-3-wp folder in your home folder.
For more information, see here and here.

A:     Variety
Homepage: http://peterlevi.com/variety
Github: https://github.com/varietywalls/variety

Variety is a wallpaper manager for Linux systems. It supports numerous
  desktops and wallpaper sources, including local files and online
  services: Flickr, Wallhaven, Unsplash, and more.
Where supported, Variety sits as a tray icon to allow easy pausing and
  resuming. Otherwise, its desktop entry menu provides a similar set of
  options.
Variety also includes a range of image effects, such as oil painting
  and blur, as well as options to layer quotes and a clock onto the
  background.

Install
It's available in the Universe repo. To install it, run
sudo apt install variety

Also you can install it from Peter Levi's PPA by running
sudo add-apt-repository ppa:peterlevi/ppa
sudo apt-get update
sudo apt-get install variety

A: Use cortina, it works pretty well.
It can set the desktop background picture to be set a random file from a given directory.
It can be installed via Ubuntu Software Center.

A: Ok here is how I did it, which is probably not the best way to do it but it worked and I didn't have to install anything to do it.  Back in 11.10 I found the below python script (slideshow.py) which generates a slideshow.xml file (run from directory with the images in it).  This is still the file needed in 12.04 but you also need another XML file.  Put the XML file generated by slideshow.py script in /usr/share/backgrounds/contest and chown it to root.  Once that is done you'll need to run the second python script (wallpapers.py) which was adapted from the first.  Put the file generated from wallpapers.py in /usr/share/gnome-background-properties and again chown it to root.  At that point you should be able to go into "System Settings" -> Appearance and pick your slideshow or any of the pics in it.
slideshow.py:
#!/usr/bin/env python
#coding=utf-8
# slideshow.py
import glob, os
import shutil
import time
import Image

filelist=[]
def filelie(path):
    if os.path.isfile(path):
       wenjian=os.path.splitext(path)[1][1:]
       if wenjian=="jpg" or wenjian=="png" or wenjian=="gif":
        try:
          kuan,gao = Image.open(path).size
          if kuan>=1024 and gao>=768:
            filelist.append(path)
        except IOError:
         pass
    elif os.path.isdir(path):
        for item in os.listdir(path):
            itemsrc = os.path.join(path, item)
            filelie(itemsrc)

curdir = os.getcwd()
filelie(curdir)
currentImageFiles = filelist
#print filelist
if os.path.isfile('slideshow.xml'):
 os.remove('slideshow.xml')

currentTime = time.localtime()
length = len(currentImageFiles)

f = file('slideshow.xml', 'w')

f.write('<background>\n')
f.write('\t<starttime>\n')
f.write('\t\t<year>' + str(currentTime.tm_year) + '</year>\n')
f.write('\t\t<month>' + str(currentTime.tm_mon) + '</month>\n')
f.write('\t\t<day>' + str(currentTime.tm_mday) + '</day>\n')
f.write('\t\t<hour>' + str(currentTime.tm_hour) + '</hour>\n')
f.write('\t\t<minute>' + str(currentTime.tm_min) + '</minute>\n')
f.write('\t\t<second>' + str(currentTime.tm_sec) + '</second>\n')
f.write('\t</starttime>\n')
f.write('<!--This animation will start at the time it created-->\n')

for i in currentImageFiles:
 length = length - 1
 f.write('\t<static>\n')
 f.write('\t\t<duration>96.0</duration>\n')
 f.write('\t\t<file>' + currentImageFiles[length] +'</file>\n')
 f.write('\t</static>\n')
 f.write('\t<transition>\n')
 f.write('\t\t<duration>3.0</duration>\n')
 f.write('\t\t<from>' + currentImageFiles[length] + '</from>\n')
 if length >= 1:
  f.write('\t\t<to>' + currentImageFiles[length-1] + '</to>\n')
 if length <1:
  f.write('\t\t<to>' + currentImageFiles[len(currentImageFiles)-1] + '</to>\n')
 f.write('\t</transition>\n')

f.write('</background>\n')
f.close()

wallpapers.py:
#!/usr/bin/env python
#coding=utf-8
import glob, os
import shutil
import time
import Image

filelist=[]
def filelie(path):
    if os.path.isfile(path):
       wenjian=os.path.splitext(path)[1][1:]
       if wenjian=="jpg" or wenjian=="png" or wenjian=="gif":
        try:
          kuan,gao = Image.open(path).size
          if kuan>=1024 and gao>=768:
            filelist.append(path)
        except IOError:
         pass
    elif os.path.isdir(path):
        for item in os.listdir(path):
            itemsrc = os.path.join(path, item)
            filelie(itemsrc)

curdir = os.getcwd()
filelie(curdir)
currentImageFiles = filelist
#print filelist
if os.path.isfile('mywallpapers.xml'):
 os.remove('mywallpapers.xml')

currentTime = time.localtime()
length = len(currentImageFiles)

f = file('mywallpapers.xml', 'w')

f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
f.write('<!DOCTYPE wallpapers SYSTEM "gnome-wp-list.dtd">\n')
f.write('<wallpapers>\n')
f.write('\t<wallpaper deleted="false">\n')
f.write('\t\t<name>My custom Wallpapers</name>\n')
f.write('\t\t<filename>/usr/share/backgrounds/contest/slideshow.xml</filename>\n')
f.write('\t\t<options>zoom</options>\n')
f.write('\t</wallpaper>\n')

for i in currentImageFiles:
 length = length - 1
 f.write('\t<wallpaper>\n')
 f.write('\t\t<name>' + os.path.basename(currentImageFiles[length]) +'</name>\n')
 f.write('\t\t<filename>' + currentImageFiles[length] +'</filename>\n')
 f.write('\t\t<options>zoom</options>\n')
 f.write('\t\t<pcolor>#000000</pcolor>\n')
 f.write('\t\t<scolor>#000000</scolor>\n')
 f.write('\t\t<shade_type>solid</shade_type>\n')
 f.write('\t</wallpaper>\n')

f.write('</wallpapers>\n')
f.close()

A: You might be interested in a program that automatically creates such a wallpaper-slideshow.
According to this OMG! Ubuntu post, you have for example 'Wallpaper Gallery'. It takes as input data tagged photos from your Shotwell gallery. Therefore it becomes very easy to add & remove photos for instance.
First select the tags concerning the photos you want to be displayed, then configure as you wish the switching time, the order, etc. Here some screenshots :

A: Yes, you can.
Locate an already made animated wallpaper and modify it.
For example, there should be one in /usr/share/backgrounds/contest (at least on Precise Pangolin).
The file is called precise.xml in my case and it is an XML file. All you need to know to modify it is that any tag like <background> contains other tags and texts and must be closed with </background>.
Try to find out what these tags mean (see below), change the name of these pictures and save as... somewhere. Call it whatever_you_want.xml.
Then change your background: choose a new wallpaper by browsing your computer and, instead of choosing a .jpg, choose your .xml.
Some tags:
<background> contains everything. Your file must begin with it and end with </background>. It's called the root tag.
<starttime> defines when the diaporama starts. A precise date must be given, any date.
<static> contains the definition of a still image.
<transition> is used to fade from one image to the other.
<duration> gives in seconds the time during witch the picture is displayed or the fading time.
<file> contains a single image to show as still.
<from> and <to> contain single images which are respectively the one at the beginning and at the end of a fading.
Some additional hints:
By adding the number of seconds of all the <duration> tags in the file, you'll know how much time it takes to perform a complete loop of the diaporama.
The nicest configuration is this one (simplified, without durations):
<static>
    <file>image1</file>
</static>
<transition>
    <from>image1</from>
    <to>image2</to>
</transition>
<static>
    <file>image2</file>
</static>
<transition>
    <from>image2</from>
    <to>image3</to>
</transition>
...

Don't forget to end your diaporama with a transition to your first picture, or else it will abruptly change from one static to another.
I tried to do an animated background, once. Images displayed less than 1 second each. You can try it for fun, but frankly, you'll want to throw your mouse to the monitor before the end of the day.

A: I wanted the changing wallpaper and custom wallpaper pictures to appear under the default options for selecting a wallpaper in Ubuntu 12.04,so I did the following
Using Terminal navigate to:
/usr/share/gnome-background-properties

typing ls will list all files in that folder you should see a file called precise-wallpapers.xml, back it up in case something goes wrong
sudo cp ./precise-wallpapers.xml ~

then edit it to add wallpapers that you want to appear in your default wallpaper options
sudo gedit precise-wallpapers.xml

this is how I added a polarbears wallpaper, previously I copied the precise.xml located in the contest folder and edited it with pictures that I wanted to display:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE wallpapers SYSTEM "gnome-wp-list.dtd">
<wallpapers>
  <wallpaper deleted="false">
    <name>Ubuntu 12.04 Community Wallpapers</name>
    <filename>/usr/share/backgrounds/contest/precise.xml</filename>
    <options>zoom</options>
  </wallpaper>
  <wallpaper>
    <name>polarbears</name>
    <filename>/usr/share/backgrounds/polarbears/polarbears.xml</filename>
    <options>zoom</options>
  </wallpaper>
  <wallpaper>
    <name>Delicate Petals</name>
    <filename>/usr/share/backgrounds/Delicate_Petals_by_lefthandgergo.jpg</filename>
    <options>zoom</options>
    <pcolor>#000000</pcolor>
    <scolor>#000000</scolor>
    <shade_type>solid</shade_type>
  </wallpaper>
  <wallpaper>

you can add regular jpg or png files, I recommend copying them to the /usr/share/backgrounds then adding them to this xml file.
I hope this helps.

A: Change it from appearance, under system settings as seen below

Or you can do so, by installing Desktop Nova.  To install, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below:
sudo apt-get install desktopnova desktopnova-tray desktopnova-module-gnome

Once installed, search for it in Dash, and click on it, and when the program open, add your images, and setup the time interval.

Command complements of Desktopnova

A: If you use it to manage your photos and like it easy I recommend to use Shotwell, which should be installed by default.
Open it:

Select the photos you want to be set as background slideshow:

Open File → Set as Desktop Slideshow or press Ctrl+B:

Adjust time settings:

Done.

A: Create an XML file yourself. Use this script as a starting point with caution, it may have some errors.
#!/bin/bash

FILE="background.xml"
DURATION=10.0
TRANSITION=0.0

CURRENTDIR=$PWD
TRANSITION_XML="
<static>
    <duration>$DURATION</duration>
    <file>$CURRENTDIR/%s</file>
</static>
<transition>
    <duration>$TRANSITION</duration>
    <from>$CURRENTDIR/%s</from>
    <to>$CURRENTDIR/%s</to>
</transition>
"

# Random order
shopt -s nullgob nocaseglob        # ignore non-existant extensions, case-insensitve
IMGS=( *.{jpg,jpeg,png,gif} )
INDICES=( $(shuf -e ${!IMGS[@]}) ) # randomize indices of images
INDICES+=(${INDICES[0]})           # go back to first image after last
COUNTER=${#IMGS[@]}

exec > "$FILE"                     # all further output to the XML file
echo "<background><starttime></starttime>"

for ((i = 0; i < COUNTER; i++))
do
    index=${INDICES[i]}
    printf "$TRANSITION_XML" "${IMGS[index]}" "${IMGS[index]}" "${IMGS[index + 1]}"
done

echo "</background>"

Instructions:
Once the background.xml file has been generated, right-click on the desktop, select Change Background Image, click Add..., then navigate to the directory containing the XML file. Just above the "Open" button change the selector from "Image" to "All files", then select the background.xml file and click on the "Open" button. The file can be renamed to be more descriptive, such as my_family.xml, landscapes-3.xml, etc., allowing one to have multiple slide show playlists.

A: I wanted to do the same thing a while back; here is my script: http://pastebin.com/FkaxaN3J
Just stick it in the directory, make executable, and run.

A:     Desk Changer for GNOME shell
by egach
In case you use gnome-shell (version > 3.8, default in Ubuntu 17.10 and later), use this nice extension.

Simple wallpaper changer with multiple profile support. Supports
  integration into the system menu or its own panel icon. The daemon is
  written in Python and runs independently of the extension.

Extension Homepage: https://github.com/BigE/desk-changer/

Install
First you have to install gnome-tweaks
sudo apt install gnome-tweaks

Visit the gnome-extension homepage and switch the slide on. Afterwards you can configure the extension to change the background's change time and the backgrounds itselfs. To do so open gnome-tweaks, go to the Extension tab and click on the Configure icon of the desk-changer.

A: After seeing this request, I was curious about a solution and found something to be able to get your wallpaper image to be a part of the default wallpaper selection when going into System Settings >> Appearances. Follow the steps below in a terminal:

*

*cd /usr/share/gnome-background-properties

*

*This will take you to the specific path mentioned

*sudo cp ./ubuntu-wallpapers.xml ~

*

*This will copy the file ubuntu-wallpapers.xml into your home
directory

*sudo vim ./ubuntu-wallpapers.xml

*

*The command vim is a terminal editor but you can change it to gedit if you wish

Once you are in that file, you will see tags called <wallpaper> and </wallpaper> that is around the other tags like <name> and <options>. You will need to copy that and paste it right below that entry. Once done, you should edit that extra entry you added to match what you want. An example can be found below:

In this example, I made changes to the <name>, <filename>, <pcolor>, and <scolor> information to match what I needed for the wallpaper I wanted. Now I see the wallpaper as a default selection in the wallpaper section of the System Settings -> Appearance GUI:

If anything doesn't work, use the following command to import back the save file we made from above:
sudo cp ~/ubuntu-wallpapers.xml /usr/share/gnome-background-properties/
Hope this helps.

A:     Random Wallpaper for GNOME shell
by iFlow

In case you use gnome-shell (version > 3.12, default in Ubuntu 17.10
  and later), use this nice extension.  This extension fetches a random
  wallpaper from an online source and sets it as desktop background.
  The desktop background can be updated periodically or manually.
Online sources:
  - unsplash.com
  - desktopper.co
  - wallheaven.cc
  - reddit.com
  - basic JSON APIs or Files (See the GitHub wiki for more information) (Chromecast, Bing, NASA, Google Earth View, etc.)

Extension Homepage: https://github.com/ifl0w/RandomWallpaperGnome3

Install
First you have to install gnome-tweaks
sudo apt install gnome-tweaks

Visit the gnome-extension homepage and switch the slide on. Afterwards you can configure the extension. To do so open gnome-tweaks, go to the Extension tab and click on the Configure icon of the random-wallpaper.

A: try slidewall as well, it has clock displayed..

A: Go to System Settings > Appearance then mark the photo with clock on it at the right side.

A: feh, an imlib2 based image viewer is a very flexible, efficient and and powerful X11 image viewer aimed mostly at console users. "Unlike most other viewers, it does not have a fancy GUI, but simply displays images. It is controlled via commandline arguments and configurable key/mouse actions."
I'm doing randomized slideshows of a set of many thousands of images with it, in a deep directory structure.  When running in window mode, rather than desktop background, I can add comments to them easily when I see one I like, and go into sequential mode to look for similar ones.


text:
Q: Running Python IDLE only works with remote into desktop? An extremely odd issue.  I have python scripts I use, pretty straight forward.  I use them to automate printing of maps in Arcmap (10.2).  I work from home and in my office.  When I work from home I remote into my desktop at my office. I open IDLE to run one of my scripts, If I remote into my computer it works fine.  When I am in the office and using my desktop directly, IDLE crashes saying "Python.exe has stopped working" and that's it.
Any ideas what could be causing this or potential fixes?
I am running python 2.7


text:
Q: Problem with installing mathstone package I am trying to use the Stone Sans and Serif fonts in Texworks, which runs with Texlive. I downloaded the files for the font package to the relevant folders but was surprised by the following error message:
 Document Class: book 2014/09/29 v1.4h Standard LaTeX document class
 (c:/texlive/2016/texmf-dist/tex/latex/base/bk11.clo))
 (c:/texlive/2016/texmf-dist/tex/latex/amsfonts/amssymb.sty
 (c:/texlive/2016/texmf-dist/tex/latex/amsfonts/amsfonts.sty))(./mathstone.sty)
 (./template.aux) (c:/texlive/2016/texmf-dist/tex/latex/mathstone/ot1pst.fd)
 [1{c:/texlive/2016/texmf-var/fonts/map/pdftex/updmap/pdftex.map}]
 (./template.aux)name = pstr8r, rootname = pstr8r, pointsize =
 mktexmf: empty or non-existent rootfile!
 Cannot find font pstr8r in map file(s).

 kpathsea: Running mktexmf pstr8r.mf

 The command name is C:\texlive\2016\bin\win32\mktexmf
 Cannot find pstr8r.mf .
 I try ps2pk --> gsftopk --> ttf2pk --> hbf2gf.
 ps2pk cannot be used.
 I try gsftopk.
 gsftopk.exe pstr8r 657
 gsftopk cannot be used.
 Next I try ttf2pk.
 ttf2pk.exe -q pstr8r 657
 ttf2pk failed.
 Finally I try hbf2gf.
 hbf2gf.exe -q -p pstr8r 657
 All trials failed.
 )
 !pdfTeX error: pdflatex.exe (file pstr8r): Font pstr8r at 657 not found
 ==> Fatal error occurred, no output PDF file produced!

Is there any way to fix this?


text:
Q: collect heap dump in java 1.4.0 in windows I am trying to collect heap dump for my application. It's running a java 1.4.0 on Windows platform. The option like -xxheapdump options won't work. Do v have any tool to achieve this.
Highly appreciate the help.

A: have you tried it like this? -XX:+HeapDumpOnCtrlBreak
maybe this link is of use to you: http://www.startux.de/index.php/component/content/article/25-java/45-java-heap-dump
This link is also interesting:
http://blogs.oracle.com/alanb/entry/heap_dumps_are_back_with


text:
Q: Updating a page's html with another and its impact on google search/ meta tags I am trying to build a website that has functionality like that of Material Design by Google here:
https://material.io/design/layout/applying-density.html#baseline-grid
I need to update the content of the page, URL and meta tags on clicking certain buttons as you can see on Material Design (left navigation bar visible on larger displays). So it is not just about changing content in one id in the HTML body. It might be more than one id as observed on inspecting changes made on Material Design.
I would like to refer to this question here:
How to update page html and url without actual page refresh
From the above case, I learnt about pushState and have understood that bit. But it does not explain to me how I can build something like Material Design as it feels very seamless, yet retains the meta tags etc.
I am trying to understand the concept so I don't have any HTML to share. Please educate me on this matter and I will be grateful if you could provide me with a solution. Thank you!

A: The material design website probably uses a framework, which is just a way of coding so that the framework will handle a lot of your stuff, one example of such framework is "ReactJS" made by facebook.
in react you could just do something like:
function MainContent() {
  return(
    <div id="main page">
      {{
        pageNumber == 0 ? <Page1 /> :
        pageNumber == 1 ? <Page2 /> :
        // etc etc....
      }}
    </div>
  );
}

more examples of these "frameworks" are: vuejs, angular, svelte.
if you're not going to use any framework, you will simply have to deal with a lot of document.getElementById's and a lot of nasty DOM manipulation


text:
Q: Unit test a page with an ion-list containing a [virtualScroll] attribute I'm wondering how to make sure that an ion-list displays the correct content.
The ion-list looks like this:
<ion-list [virtualScroll]="list" [approxItemHeight]="'132px'">
  <ion-item *virtualItem="let item">
    <span item-start>{{item.foo}}</span>
  </ion-item>
</ion-list>

The unit test:
it('should display the correct content', () => {
  comp.list = [ { foo: 'bar' } ];
  fixture.detectChanges();

  de = fixture.debugElement.query(By.css('ion-content'));
  el = de.nativeElement;

  console.log(el);
});

This outputs:
<ion-list class="list list-md virtual-loading" ng-reflect-virtual-scroll="[object Object],[object Object" ng-reflect-approx-item-height="132px">
    <!---->
</ion-list>

How to trigger karma to render an ion-item in the ion-list?

A: You have manually emit the update event in the test:
const virtualScrollComponent = fixture.debugElement.query(By.directive(VirtualScrollComponent)).componentInstance;
virtualScrollComponent.update.emit(list);


text:
Q: how do I replace this html using regex I'm kinda new to regex and if you can help me understand how I can replace
the escaped chars back to literal html string using regex , I would really appreciate it.
I tried using string.replace and it only replaced certain portion of the code not all.
ex: string.replace("<","<") ; //this works but only on one line, when it becomes a loop it's a problem, and for those who are familiar with the code, yes this is a SP blog code where SP converts the html literal tag to escaped chars.

&ltiframe src=&quot

            http://player.vimeo.com/video/32001208?portrait=0&ampampbadge=0
    "
    width="420" height="281" frameborder=&quot0&quot
    webkitAllowFullScreen mozallowfullscreen allowFullScreen&gt&lt/iframe>

A: if your string is encoded HTML you may be better to run it through Server.HtmlDecode(). this will convert it back to HTML.
I.E
    '' In VB
    Dim myHtml as String = Server.HtmlDecode(YourConcatonatedEncodedHTML)

    // in C#
    string myHtml = Server.HtmlDecode(YourConcatonatedEncodedHTML);


text:
Q: Logging Tomcat 8's own logs through slf4j/logback I try to manage the internal logs of Tomcat (commons-daemon.log, localhost_access_log, localhost, catalina,...) through slf4j/logback mainly to be able to have a rolling file policy on it.
I put the needed jars in Tomcat lib directory (jul-to-slf4j-1.7.25.jar, logback-classic-1.2.2.jar, logback-core-1.2.2.jar and slf4j-api-1.7.25.jar).
I put a very simple logback.xml in Tomcat lib directory too, just to test :
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug = "true">
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>C:/temp/MyLog.log</file>
        <encoder>
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </encoder>
    </appender>

    <root level="INFO">
    <appender-ref ref="FILE" />
    </root>
</configuration>

In logging.properties, I only put the following line :
handlers = org.slf4j.bridge.SLF4JBridgeHandler

My problem is that the MyLog.log file is created, but it seems to contains only what is normally logged in the localhost.log file.
The commons-daemon.log and localhost_access_log stay in the basic Tomcat logs directory, as before, and the catalina.log, manager.log and host-manager.log arent' there at all.
To be complete, I run my Tomcat as a service and in the Java Options of the service, I have those lines :
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
-Djava.util.logging.config.file=C:\Program Files\Apache Software Foundation\Tomcat 8.5.5\conf\logging.properties

I was expecting that all log contents will be in my MyLog.log file.
I guess I miss something, but what ?
Thank you,
Seb


text:
Q: Excel, Stop update NOW(), when other cell changed value or string I've in a single row of excel
Start Time, End Time, Duration & Status

End time is being calculated using NOW(), function of excel. I want this to be stop updating value. If status cell in the row is changed to Stop from Running.
This Stop is being done by manually.

A: A possible solution to this problem is to use drop-down lists with data validation. (This can be done without VBA.)
Data validation drop-down lists are always non-volatile, even if you choose a volatile value from the drop-down list.
Simple example that you can use to apply to your spreadsheet:
Assume cell A1 contains the formula = NOW(), and that cell B1 is set up with data validation in the following way:

Now cell B1 will take a "snapshot" of NOW() whenever you choose the only available option from the drop-down list, and it will keep that value indefinitely until you reselect from the drop-down.

Any cells that need NOW() can instead just use $B$1, which is basically just NOW() but it is frozen in time until you reselect again from the drop-down list.
This is a sneaky way to convert a volatile cell to a non-volatile one (without using VBA).

A: If you want to use vba, Range("A1").Value = Now() is essentially the Now formula that runs only when the macro is triggered.
Of course, switch out Range("A1") with whatever cell you need the date. Without seeing your code I can't offer any suggestions. Personally I've used offset to select the paste location.


text:
Q: Haskell how to resolve this error: Unsupported extension: MultiWayIf while trying to install the friday package, I got the error
Preprocessing library friday-0.2.2.0...

src/Vision/Detector/Edge.hs:3:14: Unsupported extension: MultiWayIf
cabal: Error: some packages failed to install:
friday-0.2.2.0 failed during the building phase. The exception was:
ExitFailure 1

How to resolve this error?
I am using ghc version 7.4.1 and
cabal-install version 0.14.0
using version 1.14.0 of the Cabal library

A: MultiWayIf was introduced in the 7.6 branch of GHC. You're going to have to upgrade the compiler or patch the library.


text:
Q: Is it possible to avoid the need for copy/move constructors in the following code? Please consider the following code for a type that can compose different mixin types. The constructor of the composition type takes a variadic list of tuples that represent the arguments for the constructors of the composed types:
#include <string>
#include <tuple>
#include <utility>

struct MixinBase {
  MixinBase() = default;
  // Note; want to delete these instead of default them.
  MixinBase(const MixinBase&) = default;
  MixinBase(MixinBase&&) = default;
};

struct MixinA : public MixinBase {
  MixinA(int, const std::string&, const std::string&) {}
};

struct MixinB : public MixinBase {
  MixinB(const std::string&, const std::string&) {}
};

template <typename... Mixins>
struct Composition : private Mixins... {
  template <typename... Packs>
  Composition(Packs&&... packs)
      : Mixins(constructMixin<Mixins>(
            std::forward<Packs>(packs),
            std::make_index_sequence<std::tuple_size_v<Packs>>{}))...
  {
  }

private:
  template <typename Mixin, typename Pack, size_t... Indexes>
  Mixin constructMixin(Pack&& arguments, std::index_sequence<Indexes...>) const
  {
    return Mixin(std::get<Indexes>(std::forward<Pack>(arguments))...);
  }
};

int main()
{
  std::string a{"a"};
  std::string b{"b"};

  Composition<MixinA, MixinB>(
      std::forward_as_tuple(7, a, b), std::forward_as_tuple(a, b));

  return 0;
}

This works perfectly fine, however, I would like to avoid the indirection through constructMixin, and directly construct every inherited mixin object so that the need for a copy/move constructor on the mixin type can be avoided. Is this possible?

A: You can define a helper class to support piecewise construction:
template <typename T>
struct Piecewise_construct_wrapper : T {
    template <typename Tuple>
    Piecewise_construct_wrapper(Tuple&& t) :
        Piecewise_construct_wrapper(std::forward<Tuple>(t),
                                    std::make_index_sequence<std::tuple_size_v<Tuple>>{}) {}

    template <typename Tuple, size_t... Indexes>
    Piecewise_construct_wrapper(Tuple&& t, std::index_sequence<Indexes...>) :
        T(std::get<Indexes>(std::forward<Tuple>(t))...) {}
};

Then you can make your Composition inherit Piecewise_construct_wrapper<Mixins>...:
template <typename... Mixins>
struct Composition : private Piecewise_construct_wrapper<Mixins>... {
    template <typename... Packs>
    Composition(Packs&&... packs)
        : Piecewise_construct_wrapper<Mixins>(std::forward<Packs>(packs))...
    {
    }
};

A:
I would like to avoid the indirection through constructMixin, and directly construct every inherited mixin object so that the need for a copy/move constructor on the mixin type can be avoided. Is this possible?

You would need the Mixins to opt-in to allowing piecewise construction directly. Unfortunately that's pretty repetitive, so you could use a macro like:
#define PIECEWISE_CONSTRUCT(Type)                               \
  template <typename Tuple>                                     \
  Type(std::piecewise_construct_t, Tuple&& tuple)               \
    : Type(std::piecewise_construct,                            \
        std::forward<Tuple>(tuple),                             \
        std::make_index_sequence<std::tuple_size_v<Tuple>>())   \
  { }                                                           \
  template <typename Tuple, size_t... Indexes>                  \
  Type(std::piecewise_construct_t, Tuple&& tuple,               \
        std::index_sequence<Indexes...>)                        \
    : Type(std::get<Indexes>(std::forward<Tuple>(tuple))...)    \
  { }

To be used as:
struct MixinA : public MixinBase {
  MixinA(int, const std::string&, const std::string&) {}

  PIECEWISE_CONSTRUCT(MixinA)
};

struct MixinB : public MixinBase {
  MixinB(const std::string&, const std::string&) {}

  PIECEWISE_CONSTRUCT(MixinB)
};

template <typename... Mixins>
struct Composition : private Mixins... {
  template <typename... Packs>
  Composition(Packs&&... packs)
      : Mixins(std::piecewise_construct, std::forward<Packs>(packs))...
  { }
};

Guaranteed copy elision unfortunately can't work in constructing subobjects - so this might be your best bet. I don't think you can do this any more directly without having some kind of nested packs? It's very possible that I'm just not creative enough though and would be very curious if somebody comes up with something better.


text:
Q: Pushing array without duplicate and change the property value of object in Javascript? I have an object and i'm pushing into array while pushing i need to restrict the duplicate and also if there is any changes in the property then update the array accordingly ?
    [{
    Id: "a134",
    Name: "Name -",
    Company: "001",
    Product :"01"
    quantity :1
    },
   {
    Id: "a135",
    Name: "Name -1",
    Company: "002",
    Product :"03"
    quantity :2  -----> (Previous event.target.name)
    },
    {
    Id: "a135",
    Name: "Name -1",
    Company: "002",
    Product :"03"
    quantity :3  ---> (current event.target.name)
    }
  ]

if i'm pushing into array there might be chance to update quantity how to achieve the below result
[{
        Id: "a134",
        Name: "Name -",
        Company: "001",
        Product :"01"
        quantity :1
        },
        {
        Id: "a135",
        Name: "Name -1",
        Company: "002",
        Product :"03"
        quantity :3  ---> (current event.target.name)
        }
      ]

and now my code is
 if(event.target.value!='')
                  {

                    const searchObj = this.myList.find(({ Id,Product, Company  }) => Product === index);
                    if (searchObj)
                    {
                        console.log('searchObj',searchObj);

                       resultVal = { ...searchObj, quantity:parseInt(event.target.value)};

                       if (!this.newProductList.some(e => e.Product === resultVal.Product))
                        {
                         this.newProductList.push(resultVal);
                        }

                    }

                  }

A: This is best solved by using a different data structure: use a plain object, keyed by Id:
let data = {
    "a134": {
        Id: "a134"
        Name: "Name -",
        Company: "001",
        Product: "01"
        quantity: 1

    },
    "a135": {
        Id: "a135",
        Name: "Name -1",
        Company: "002",
        Product: "03"
        quantity: 2
    },
};

To update/add don't push, but set the object key's value. For example:
// Let's say we want to add/update with this object:
let objToAdd = {
    Id: "a135",
    Name: "Name -1",
    Company: "002",
    Product: "03"
    quantity: 3
}
// ...then just do:
data[objToAdd.Id] = objToAdd;

This will either update or "insert". In the above case, it will update:
let data = {
    "a134": {
        Id: "a134"
        Name: "Name -",
        Company: "001",
        Product: "01"
        quantity: 1
    },
    "a135": {
        Id: "a135",
        Name: "Name -1",
        Company: "002",
        Product: "03"
        quantity: 3
    },
};

If you ever need the array-format, then just do:
let arr = Object.values(data);

...but trying to stick with the array is a guarantee for inefficient code. It just isn't the right tool for the job here. You should adapt your code to work with the plain object representation throughout. You can iterate over the values in an object, you can remove items from an object, update, add, ...etc.

A: I think an array is the wrong data type. I would prefer using a map.
This of course only works if the Id is unique since that is what is best used as key:
const myMap = new Map([["a134",{
                               Name: "Name -",
                               Company: "001",
                               Product :"01",
                               quantity :1
                              }]]);

And then it is easy to check if an item is already present, before updating the quantity or adding a new item.
const id = "a134"; // or "a135" for a new entry
const newItem = { Name: "Name B",
                  Company: "002",
                  Product :"012",
                  quantity :1
                  }
if(myMap.has(id)){
  const item = myMap.get(id);
  myMap.set(id, {...item, quantity: item.quantity +1})
} else {
   myMap.set(id,newItem);
}
console.log(myMap) // Map {'a134' => { Name: 'Name A', Company: '001', Product:'01', quantity: 2 } }


text:
Q: Blackberry Build Creation Without Using BB JDE I am working on a blackberry application and I want to package and sign the blackberry application without using the Blackberry JDE. Is it feasible to do so ?
Any help is much appreciated. Thanks in advance !!

A: The best and easiest is using bb-ant-tools. Also please review this question where you'll find build file and it's usage.


text:
Q: How to change string parsed from inline SVG into  element I want to get the inline SVG string in the form of text
Expected output:
const fetchedText =
"<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
    <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>"

I have tried with DOMParser but somehow this is not working here.
Any suggestion for this error please. What i am doing wrong here ?
InlineSvg.js
import React from 'react';
export default () =>
    <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
        <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>

App.js
export function getSvg() {
  const text = JSON.stringify(InlineSvg());
  const oParser = new DOMParser();
  const oDOM = oParser.parseFromString(text, "image/svg+xml");
  const root = oDOM.documentElement;
  console.log(root.firstChild.innerHTML)
}

Console.log
"{"type":"svg","key":null,"ref":null,"props":{"width":"100","height":"100","xmlns":"http://www.w3.org/2000/svg","children":{"type":"circle","key":null,"ref":null,"props":{"cx":"50","cy":"50","r":"40","stroke":"green","stroke-width":"4","fill":"yellow"},"_owner":null,"_store":{}}},"_owner":null,"_store":{}}"

Without Json.stringyfy()

Output
"<parsererror xmlns="http://www.w3.org/1999/xhtml" style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
This page contains the following errors:

error on line 1 at column 1: Document is empty

Below is a rendering of the page up to the first error.
</parsererror>"


text:
Q: Replace elements in the array by elements from another array I need to replace elements in array by elements from another array by orderID key of the object. If the element is not in the array then it should be added.
I have implemented it (the example in code snippet below) and it mostly works.
The problem is that my implementation uses filter inside loop and it can be performance issue for large data.
Can it be implemented without loop inside loop?

let storageOrders = [
  {orderID:1, data:'data1'},
  {orderID:2, data:'data2'},
  {orderID:3, data:'data3'},
  {orderID:4, data:'data4'},
];
let summaryOrders = [
  {orderID:2, data:'data2_new'},
  {orderID:3, data:'data3_new'},
  {orderID:5, data:'data5'},
];
summaryOrders.forEach((order) => {
  storageOrders = storageOrders.filter(storageOrder => storageOrder.orderID !== order.orderID);
  storageOrders.push(order);
});
console.log(storageOrders);

A: You can create a mapping from orderID to object using both storageOrders and summaryOrders (one after the other so that values from summaryOrders take precedence for ids that are already there). Then you can recreate your final array with Object.values:

let storageOrders = [
  {orderID:1, data:'data1'},
  {orderID:2, data:'data2'},
  {orderID:3, data:'data3'},
  {orderID:4, data:'data4'},
];
let summaryOrders = [
  {orderID:2, data:'data2_new'},
  {orderID:3, data:'data3_new'},
  {orderID:5, data:'data5'},
];

storageOrders = Object.values([...storageOrders, ...summaryOrders].reduce((a, c) => {
  a[c.orderID] = c;
  return a;
}, {}));
console.log(storageOrders);

A: You could create an object from the existing orders and then loop through the new / updated orders to update your existing order object. This could be a better way to store your data altogether, but, if needed, you could convert the updated object back to a list of objects.

const mergeOrders = (a, b) => {
  const obj = a.reduce((acc, order) => {
    acc[order.orderID] = order.data;
    return acc;
  }, {});

  for (const order of b) {
    obj[order.orderID] = order.data;
  }

  return Object.entries(obj).map(([id, data]) => ({ orderID: id, data: data }));
};

const storageOrders = [{ orderID: 1, data: 'data1' }, { orderID: 2, data: 'data2' }, { orderID: 3, data: 'data3' }, { orderID: 4, data: 'data4' }];
const summaryOrders = [{ orderID: 2, data: 'data2_new' }, { orderID: 3, data: 'data3_new' }, { orderID: 5, data: 'data5' }];
const orders = mergeOrders(storageOrders, summaryOrders);
console.log(orders);
// [{ orderID: 1, data: 'data1' }, { orderID: 2, data: 'data2_new' }, { orderID: 3, data: 'data3_new' }, { orderID: 4, data: 'data4' }, { orderID: 5, data: 'data5' }]


text:
Q: Transform an operation to generic method I am working in visual c++, usually I do it on .NET, because I need a method which is available only on this language. What I want to do is obtain the frames per second of a video file. The best I could make was creating a project with this main() method, in which (after Debug) I could see the result is saving fine in the res variable.
void main()
{
    // initialize the COM library
    CoInitialize(NULL);

    // get a property store for the video file
    IPropertyStore* store = NULL;
    SHGetPropertyStoreFromParsingName(L"C:\\Users\\Public\\Videos\\Sample Videos\\Wildlife.wmv",
        NULL, GPS_READWRITE, __uuidof(IPropertyStore), (void**)&store);

    // get the frame rate
    PROPVARIANT variant;
    store->GetValue(PKEY_Video_FrameRate, &variant);
    int res = variant.intVal;
    store->Release();
}

Now, I want to create this method generic, in order to obtain the frameRate of any video. For example, if the method's name is frameRate:
 char* path = "C:\\Users\\Public\\Videos\\Sample Videos\\Wildlife.wmv";
 int fps = frameRate(path);

Thanks

A: If you don't want to recompile your code for every video path, then you can read the path from the program parameters. To do that, modify you main() as follows:
int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cout << "You have to specify the video path!" << std::endl;
        return 1;
    }

    const char* path = arg[1];

    // Rest of the program logic

    return 0;
}

You can pass more than one parameter, if you want to. Note that there is always at least 1 argument (arg[0] is the program name). For further reading on the topic go here.

A: Does this not work?
int getFrameRate(std::wstring path)
{
    // initialize the COM library
    CoInitialize(NULL);

    // get a property store for the video file
    IPropertyStore* store = NULL;
    SHGetPropertyStoreFromParsingName(path.c_str(),
        NULL, GPS_READWRITE, __uuidof(IPropertyStore), (void**)&store);

    // get the frame rate
    PROPVARIANT variant;
    store->GetValue(PKEY_Video_FrameRate, &variant);
    int res = variant.intVal;
    store->Release();

    return res;
}

The assumption here is that SHGetPropertyStoreFromParsingName takes a string as its first parameter.  In C++ I recommend staying away from char*, std::string is preferable in almost all situations.  The only difficulty I see is making sure path is the correct type.


text:
Q: Specify all php files in Nginx config in order to make said php app more safe (nginx) I got an idea for to write a simple script to create an Nginx config file based on a set of files that would be allowed to be run. In my case they would be .php files from an application. The script would simply create an Nginx config entry for every single .php file in a directory, where the .php files would be.
In my view specifying every single application file would prohibit unauthorized execution, and when the application in question is run very simply from said php files, it should be easy to implement in an Nginx config. Perhaps the script could also be able understand to set general ratelimits for user accessible php files and files that would never need to be seen by the user.
Thus how I see an ideal script, it would create config based on at least these properties:

*

*executable name, .php, .py, .pl etc

*folders not required to be directly accessible (but still create config based on every file in these folders)

*ratelimits per folder, or at least for the user facing files

I am asking the question in order to gather evidence for going further, and also since I couldn't readily find a script that would be directed at such config creation for nginx. (Maybe just because it is so easy to write..). Ultimately the goal is extra security, and thus I'm also seeking opinions on how such configuration of Nginx would affect it, and if it is a good idea at all.

A: A web service is usually a public service. Everything (every file) you store within your web root folder or any sub folder of your web root folder is public. You can define exceptions of this behavior in your web server configuration.
To protect files, scripts and folders from public access I recommend to store them not in or below of your web root folder.
Following these generic rules is a good approach in getting a secure web server or web application server.
To be more specific regarding your case I would recommend to store (as Michael Hampton already mentioned) only your index.php (and all required images and public JavaScripts) in your web root folder.
All the PHP classes you will need to provide your API or application should be stored apart from your web root folder as well as your Composer files (usually stored in the folder "vendor").
Example structure:
/project_root
  /htdocs (web root folder)
    index.php
    favicon.ico
    robots.txt
    /images
      logo.png
      background.png
    /javascript
      script.js
  /src
    /php
      /api
        /controller
          /overview
            get.php
          /login
            get.php
            put.php
            delete.php
            post.php
    /javascript
      base.js
      /reload
        plugin.js
  /vendor
    autoload.php

For above example following Nginx config would provide your application:
server {

  ...

  # take care to deliver public static content if file exists
  # or execute /index.php if not
  location / {
    try_files $uri /index.php;
  }

  ...

  # do not execute /index.php if requested image or JavaScript does not exists
  location ~ ^/(images|javascript)/ {
    try_files $uri =404;
  }

  ...

  # execute PHP files
  location ~ \.php$ {
    try_files            $uri /index.php;
    include              fastcgi_params;
    fastcgi_keep_conn    on;
    fastcgi_pass         unix:/run/php/php7.2-fpm.sock;
    fastcgi_param        SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param        SCRIPT_NAME     $fastcgi_script_name;
  }
}


text:
Q: A series of radial gauge controls in a Reporting services report I have the following sql:
SELECT
    project_title + ' (' + pack_type + ')' AS label
    , ordered
    , received
FROM [v_stock_and_despatch] ORDER BY [order]

that returns the following table:
label    ordered received
Item A   60      76
Item B   63320   63960
Item C   415240  415226
Item D   23150   23150
Item E   147948  187992

Now, in Reporting services I need to show this as a sequence of radial gauges.
I know how to create a one off guage, but I don't know how to create a collection.
The value field for a one off guage looks like this:
=Fields!received.Value /(Fields!ordered.Value) * 100

Can anyone help?

A: Create a table for your data details, and drag a Gauge item into one of the cells. Your existing expression should work for the gauge's value. The table will give you a row for each of your projects, and the gauge on each row will use the Received and Ordered values for that project.

In my example I've switched the column labels for Received and Ordered, so the values appear as less than 100%.
The same technique will work with Chart items.


text:
Q: Estimating kernel bandwidth function with cross-validation gwrr package? I am relatively new to R. I am attempting to use the gwrr package because I suspect that local collinearity may be an issue in my geographic weighted regression model.
If I am not mistaken, I first estimate the kernel bandwidth function using cross-validation. Below please find my R script. Diab is a spatial data set projected in Albers Equal Area Conic.
tt<-gwr.bw.est(dia2013~pctblacks + pcthis + pctpov+ lcollege+ newden+hosden10 +optden13 + totmdden13 + phyden13 + den13  +  nurseden13 + nohealthin + unemploy + transport, data=diab, kernel = "gauss", cv.tol=30)

However, I get the following error:
Error in (function (classes, fdef, mtable)  :

unable to find an inherited method for function 'geometry' for signature '"numeric"'
Does anyone know what is going on?

A: The issue is that you haven't actually specified the coordinates to perform the function.
In the vignette example found below. They had the data parameter set to a variable 'columbus' then they set the locs paramter to
c(columbus$x,columbus$y).

https://cran.r-project.org/web/packages/gwrr/gwrr.pdf
I'm not sure how your data is set out but you would need to change it to something like this
 tt<-gwr.bw.est(dia2013~pctblacks + pcthis + pctpov+ lcollege+ newden+hosden10 +optden13 + totmdden13 + phyden13 + den13 + nurseden13 + nohealthin + unemploy + transport, locs = c(diab$X,diab$Y) data=diab, kernel = "gauss", cv.tol=30)

You would just need to change the X and Y to whatever your coordinate labels are in your data frame.


text:
Q: HDMI and DVI cable I have bought a cable: one end is DVI and the other is HDMI. This DVI cable has  3x3 plus 3x3 pins with a space
between these 2 groups.
But the PC end has 8x3 pins. Can I insert the cable into the PC safely ?
I haven't unpacked the cable: I will wait until someone answers my Q.
This is the cable. I need to connect a TV to my PC to detect why there are imperfections on my LCD display.

A: From the picture provided, we can tell that the cable you purchased is a DVI-D (Single-Link):

By '8*3', you most probably mean DVI (Dual-Link)
If your PC's DVI input looks like this:

or this:

You should be good to go.
There is another post on this subject if you would like to know more here:

A: It sounds like your PC has a dual-link DVI port (the "8x3" you mentioned). As long as that is the case, it is compatible with any other DVI cable, as long as you don't try to insert a DVI-I cable into a DVI-D port. As far as I know, DVI-I went the way of the dinosaur along with analog displays, so you likely have a DVI-D dual-link port on your PC and the cable you linked is DVI-D single-link. You're good to go. Here's a reference image for you.