text:
Q: Detect previous path in react router? I am using react router. I want to detect the previous page (within the same app) from where I am coming from. I have the router in my context. But, I don't see any properties like "previous path" or history on the router object. How do I do it?

A: You can pass down state using the <Link> component, in this case a pathname:
<Link to={{pathname: '/nextpath', state: { prevPath: location.pathname }}}>Example Link</Link>

You can then access prevPath from this.props.location.state in the next component

A: Instead of checking what the previous page is, approach the problem from a different angle. Pass the current page as props to the component or link that you're going to navigate to.
In the previous page or component that I'm calling history.push or clicking the link from, I add a state of the current page that I'm on e.g.
history.push(`/device/detail`, { from: 'device detail page' } );

I can then access what the previous page was using history.location.state.from

A: If you are using the <Redirect /> component, you can add a from property that will be added into location.state in the component you redirects to.
// in the redirecting component
<Redirect
to={{
  pathname: '/login',
  state: { from: location }
}}
/>

//in the other component you redirected to
...
const { location } = props.location.state;
...

A: Using context you can store the previous location pathname:
const RouterContext = React.createContext();

const RouterProvider = ({children}) => {
  const location = useLocation()
  const [route, setRoute] = useState({ //--> It can be replaced with useRef or localStorage
    to: location.pathname,
    from: location.pathname //--> previous pathname
  });

  useEffect(()=> {
    setRoute((prev)=> ({to: location.pathname, from: prev.to}) )
  }, [location]);

  return <RouterContext.Provider value={route}>
    {children}
  </RouterContext.Provider>
}

Then in some component under RouterProvider:
const route = useContext(RouterContext);
//...
<Link to={route.from}>
  Go Back
</Link>

Or
history.push(route.from);

Note: RouterContext should be under Router component and If you don't want to update the state you can use useRef instead. If you need more persistence use localStorage

A: You could listen and build a back stack using history.listen. Here's a hook that does just that.
import { Location } from 'history';
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router';

const useBrowserBackStack = () => {
  const history = useHistory();
  const [backStack, setBackStack] = useState<Location[]>([]);
  useEffect(() => {
    history.listen((location, action) => {
      setBackStack(backStack => {
        switch (action) {
          case 'POP':
            return backStack.slice(0, backStack.length - 1);
          case 'PUSH':
            return [...backStack, location];
          case 'REPLACE':
            return [...backStack.slice(0, backStack.length - 1), location];
        }
      });
    });
  }, [setBackStack, history]);
  return backStack;
};

export default useBrowserBackStack;

Then use in your top level component like this
const backStack = useBrowserBackStack();

A: You can save previous path in a componentWillReceiveProps lifecycle method. The logic is very close to the example provided in troubleshooting section of react-router docs.
<Route component={App}>
  {/* ... other routes */}
</Route>

const App = React.createClass({
  getInitialState() {
    return { prevPath: '' }
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.location !== this.props.location) {
      this.setState({ prevPath: this.props.location })
    }
  }
})

And lately, access it from the state.

A: If you're using react-router-redux you can create a reducer which hooks into the events dispatched by react-router-redux.
export default function routerLocations(state = [], action) {
  switch (action.type) {
    case "@@router/LOCATION_CHANGE":
      return [...state, action.payload]
    default:
      return state;
  }
}

A: As of 08/2022, for those using React Router v6, you can either use Navigate component, Link component or useNavigate hook to pass the previous url to the next component:
In the redirecting component:
// with Navigate component (same as with Link component):
const location = useLocation();
...
<Navigate to="/nextpath" state={ { from: location } } />
...

// with useNavigate hook:
const navigate = useNavigate();
const location = useLocation();
....
navigate("/nextpath", { state: { from: location } });
...

In the component you redirected to:
...
const location = useLocation();
let from = location.state?.from?.pathname;
...

A: This answer uses a similar approach to @AlexandrLazarev, but implements it via React Hooks.  This ensures that all changes to the path are captured regardless of how they are initiated.  The previous path value is stored in the top level component's state which can then be passed down to children as props or if you're using a global state provider like Redux can be added to a store:
import { useEffect, useState } from 'react'

cont App = ({ location }) => {
  const [currentPath, setCurrentPath] = useState(null);
  const [previousPath, setPreviousPath] = useState(null);

  useEffect(() => {
    if (location.pathname !== currentPath) {
      setPreviousPath(currentPath);
      setCurrentPath(location.pathname);
    }
  }, [location.pathname]);
}

The implementation in the markup would look something like the below snippet.  I've been using Reach Router, but given that its been merged with React Router it should work there as well. The Router component makes the location prop available to all of its children and holds the value of the current path under its pathname attribute
<Router>
  <App path="/*" />
<Router/>

A: Use useHistory hook of react-router to go to the previous path in stateless of functional component. For more information follow the link https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md#useroutematch
import { useHistory } from "react-router-dom";

function demo () {
    let history = useHistory();
    const goToPreviousPath = () => {
        history.goBack()
    }
    return (
      <div>
        <Button
          onClick={goToPreviousPath}
        >
          Back
        </Button>
      </div>
    ):
}

A: If it's help, see this solution if you don't want the component to re-render and still get the previous path..
location.js:
import { useLocation } from 'react-router-dom';

export default () => {
  const location = useLocation();
  const path = location.pathname;
  const store = window.localStorage;
  let url = '';
  let prevUrl = '';

  url = store.getItem('url');
  store.setItem('prevUrl', url);
  store.setItem('url', path);

  url = store.getItem('url');
  prevUrl = store.getItem('prevUrl');

  return { url, prevUrl };

}

In other file
import Location from './location.js'

const { url, prevUrl } = Location()

A: React - Get previous path using props
console.log(props.history.location.state && props.history.location.state.from.pathname);

if you redirect using <Link> OR <Redirect> ? pathname : undefined

A: Use the useNavigate() hook, e.g. const navigate = useNavigate();.
Call the navigate() function passing it -1 - navigate(-1).
Calling navigate with -1 is the same as hitting the back button.
const previousPageHandler = () => {
    navigate(-1);
}

A: I needed a way to conditionally navigate only if previous path equals a specific route. With a functional component it worked out like this. The && will fire the .push() method only if route is '/cart'.
import {useHistory} from "react-router-dom";

const history = useHistory();

history.location.pathname === '/cart' && history.push('/checkout');

A: For those looking how to navigate to n pages backwards or forwards,
with react-router-v6 you can use the useNavigate API,
import {useNavigate} from 'react-router-dom'

const navigate = useNavigate()

Then you can pass a function to an onClick event on a button for example
<button onClick={() => navigate(-1)}>Previous</button>

note that negative integers are for backwards and positive for forwards.
For further reading, check out the docs : https://reactrouter.com/docs/en/v6/upgrading/v5#use-usenavigate-instead-of-usehistory


text:
Q: hr should be longer (width) than div i have a webpage and use the
 tag for separation of content when the page is displayed on tablets. it look like this:

at the red rectangle the line should continue. however, it does not. what do i have to change in html/css in order to let the
 continue until the border of the page?
the page is here: http://crossroads-festival.org/test2015/en/film/almaen
please note to redue the browser width to at least 811px for the horizontal line to show up.
thanks for your help!
UPDATE:
the css for
 is
hr {
  height: 0;
  border: none;
  border-bottom: 1px solid #c1c1c1;
  margin-bottom: 1.5em;
  background: none;
}

the css for the divider-mobile class is:
.divider-mobile {
  margin-top: 3.125em;
  margin-bottom: 3.125em;
  overflow: visible;
  border: none;
  color: #888888;
  background-color: #888888;
  height: 1px;
  width: 150%;
  margin-left: -25%;
}

in the html i use it like this:

A: In your CSS you have:
#filmcontent {
  overflow-x: hidden;
}

That is preventing the negative margin on your
 from going to the edge of the page.
You'll also want to remove the width: 150%; and margin-left: 25% on the
 and instead do...
margin-left: -20px;
margin-right: -20px;

(Where 20px is equal to the padding on #content .entry-content)
That will get you your desired effect!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having difficulty configuring php debugging using netbeans UPDATE 2:
Nevermind, figured it out, in netbeans I had an extra ) in tools > options > general > web browser > edit > arguments was -remote {url}), so I changed it to -remote {url}.
I now have netbeans debugging php on my new laptop.
UPDATE 1:
I've been comparing my old laptop with my new laptop as debugging works on my old laptop.  The only difference I have seen is the url in the browser when I click debug.
Old laptop:
http://localhost/PhpProject1/index.php?XDEBUG_SESSION_START=netbeans-xdebug
New laptop:
http://localhost/PhpProject1/index.php?XDEBUG_SESSION_START=netbeans-xdebug)
When I remove the ending ) from the new laptop url manually, debugging starts to work...  Why does the new laptop setup have an ')' at the end and the old setup doesn't?
ORIGINAL QUESTION:
I'm trying to configure xdebug for php debugging via netbeans on a localhost.  I have tried following a couple of guides, but can't seem to get it to work.  I've had it configured on an old laptop, but can't seem to remember how.  At the moment, when I add a breakpoint and click "debug project", it opens up a browser and displays waiting for connection (netbeans-xdebug).  The "step over" and "step into" options are disabled.
How do I resolve this issue?
I have done the following so far:
I have installed lamp, php5-xdebug, and the php plugin for netbeans.
I have the following in /etc/php5/apache2/conf.d/xdebug.ini:
zend_extension=/usr/lib/php5/20090626+lfs/xdebug.so
xdebug.remote_enable=On
xdebug.remote_host="localhost"
xdebug.remote_port=9000
xdebug.remote_handler="dbgp"
xdebug.remote_enable=1

I have done service apache2 restart.
I can see that xdebug is enabled with phpinfo();
In netbeans - tools > options > php, I have done the following:
PHP 5 Interpreter = /usr/bin/php
Bebugger Port = 9000
Session ID = netbeans-xdebug

A: Sounds like netbeans is waiting for php to callback. Did you add xdebug to php?
For more info see this article

A: The solution to the problem can be seen in update 2 in the original question, which is:
In netbeans I had an extra ) in tools > options > general > web browser > edit > arguments was -remote {url}), so I changed it to -remote {url}.


text:
Q: Why can't I use System.ValueType as a generics constraint?
*

*Why can't I use a constraint of
where T : System.ValueType?

*Why does Microsoft prevent this type
from being a constraint?

Example:
Why can't I do the following?
// Defined in a .Net class
public void bar<T>(T a) where T : ValueType {...}

// Defined in my class
public void foo<T>(T a) where T : ValueType
{ bar<T>(a); }

What is the difference in using struct over ValueType?
// Defined in my class
public void foo<T>(T a) where T : struct
{ bar<T>(a); }

A: There are two differences between using
where T : struct

and
where T : ValueType

*

*the latter would allow T to be ValueType itself, which is a reference type.

*the latter would also allow T to be a nullable value type

The first of these differences is almost never what you want. The second could occasionally be useful; Nullable<T> is slightly odd in that it satisfies neither the where T : struct nor where T : class constraint.
More useful would be the constraint
where T : struct, System.Enum

which is prohibited by C# for no good reason that I can tell. See my blog post and the Unconstrained Melody project for more on this.

A: Using struct as a generic constraint is functionally equivalent to a "ValueType" constraint.  In .NET, a struct is a value type.

A: ValueType is not the base class of value types, it is simply a container for the value when it is boxed. Since it is a container class and not in any sort of hierarchy for the actual types you're wanting to use, it is not useful as a generic constraint.

A: I think the example below covers a lot of use cases that one would expect from ValueType.  The parameter type of T? allows nullables, and the type constraints restrict it to structs that implement IFormattable which is true for the common value types I can think of.
public void foo<T>(T? a) where T : struct, IFormattable

Note that this allows types such as decimal, datetime, timespan.
https://learn.microsoft.com/en-us/dotnet/api/system.iformattable?view=netcore-3.1


text:
Q: How to stop php curl from rewriting cookies My code:
<?php

function access_page($url,$data){
    $fp = fopen("cookie.txt", "w");
    fclose($fp);
    $login = curl_init();
    curl_setopt($login, CURLOPT_COOKIEJAR, "cookie.txt");
    curl_setopt($login, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($login, CURLOPT_TIMEOUT, 40000);
    curl_setopt($login, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($login, CURLOPT_URL, $url);
    curl_setopt($login, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($login, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($login, CURLOPT_POST, TRUE);
    curl_setopt($login, CURLOPT_POSTFIELDS, $data);
    curl_setopt($login, CURLOPT_ENCODING ,"");
    ob_start();
    return curl_exec ($login);
    ob_end_clean();
    curl_close ($login);
    unset($login);
}

?>

Every time I run this function, my cookie.txt file gets deleted and rewritten with new cookies even when the cookies don't colide.
For example:
access_page("http://examplepage.com/session","");
access_page("http://examplepage.com/login","username=123&password=123");

I want this to write both session and login cookies in my cookie.txt file however the first request gets rewritten by the second one even though the cookies are different.
How can I keep both of these cookies in the cookie jar?

A: From the fopen manual page

'w' Open for writing only; place the file pointer at the beginning of
  the file and truncate the file to zero length. If the file does not
  exist, attempt to create it.

(bold emphasis mine).
So these lines are actually removing all of the content, so remove these lines...
$fp = fopen("cookie.txt", "w");
fclose($fp);


text:
Q: Why is there No more Kubernetes for Latest version of Ubuntu I am trying to install Kubernetes on Ubuntu 20.04 but the latest release is for Ubuntu 16.04. I am following the official tutorial by kubernetes https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/
Is it discontinued for Ubuntu?

A: As @jordanm and @mdaniel mentioned

likely the upstream disagreements in Debian about vendoring k8s dependencies. Lot of dev discussion about whether or not k8s should even be included in a stable release. OS provided packages are probably the least-common way to provision a cluster.
Related to that, kubernetes binaries are statically linked golang
programs, and thus have very little in the way of "dependency upon.  Ubuntu whatever" so it's likely fine to just use the 16.04 repo.

Read: minikube-ubuntu-20.04.
See also: kubernetes-on-ubuntu.


text:
Q: Link Pages in OnesenUI without toolbar I'm new to OnesenUI. I have been able to use the  tag to link pages using the toolbar. However, I would want to know how do I link a text in the page to another screen.
e.g. if I have text "Register" then, the user should be able to go the register.html screen.
I don't want to have a toolbar button for this.
Any help will be appreciated.
Thanks!
login.html Code:
<form>

Email
<input id="emaillogin" type="text" placeholder="email" class="form-control">

Password
<input id="passwordlogin" type="password" placeholder="password" class="form-control">

<button type="submit" onclick="javascript:Login();" class="btn btn-template-outlined"> Log in</button>

</form>

If you are not enrolled, you can sign-up now.

<button type="button" href="register.html" class="btn btn-template-outlined"> Sign Up</button>


text:
Q: Question about a distribution definition in $D'(\Omega)$ So, let $\Omega :=B_1(0) \subset R^3$ and $\{x_n\} \subset \Omega$. If $x_n \rightarrow x \in \partial B_1(0)$, $T:= \sum_{n \in N}\delta_{x_n}$ define a distribution on $D'(\Omega)$? How can I check it?
One idea of mine was to check if there is a function $f$ so that $T_f$ can be identified with the function (with an abuse of notation).
Using the definition I'll have:
$\langle T_f,\phi \rangle = \int_{- \infty}^{+ \infty}  \sum_{n \in N}\delta_{x_n} \phi dx=\sum_{n \in N}\int_{- \infty}^{+ \infty}  \delta_{x_n} \phi dx$
for $\phi \in C_c^\infty(\Omega)$
But here I don't know how to formalize the check. Any tips?


text:
Q: How to set phpmyadmin to use the filename as the Table Name when importing a CSV? If I import mydatabase.csv into phpmyadmin as a new table, it will automatically be renamed to 'TABLE XX' (where XX is the next consecutive table number. How do I set it to use the filename 'mydatabase' as the title for the table?
When doing this, I'd also like to set it to 'Use first line of the file as column names' by default.

A: You can build a command string and execute it using prepared statements, e.g.:
SET @file_name = 'data1';  -- file name, without extension

SET @sql = CONCAT(
'LOAD DATA INFILE ', @file_name, '.csv INTO TABLE ', @file_name,
' FIELDS TERMINATED BY '';'' LINES TERMINATED BY ''\r'' IGNORE 1 LINES');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


text:
Q: Artifactory access token works via Bearer, not user Artifactory OSS
5.4.6 rev 50406900
Trying to get access token to work.
I created token...
e.g. curl -uadmin:adminpw -X POST "myserver:8081/artifactory/api/security/token" -d "username=moehoward"
Returned msg looks like success...
{
  "scope" : "member-of-groups:readers api:*",
  "access_token" : <very-long-string>
  "expires_in" : 3600,
  "token_type" : "Bearer"
}

I can see it in the gui (admin -> Security -> Access Tokens) with "Subject" = to the user ("moehoward" in the example above) and with a "Token ID" that's a lot shorter, something like...
f2eb693a-d4ff-4618-ba52-764dc975c497
To test, I tried to ping using example in the docs...
curl -umoehoward:<very-long-string> myserver:8081/artifactory/api/system/ping

Fails with a 401 (bad credentials).
I replace the token with the "token id" I see in the gui, same result.
I replace again with the hardcoded pw of the "moehoward" user and that works (responds with "OK").
I tried the "-H"Authentication: Bearer " approach using the long string and that worked.  So I guess the very long string is the token and not the "Token ID" in the gui.
Q: Any idea why this works for Bearer" and not the user by name ?

A: So you are right that this is supposed to work for both standard authentication and the Authentication HTTP header.
I did the test on a server with the same version Artifactory OSS 5.4.6 and the following works fine here
Inject the proper variables
export SERVER=server-artifactory
export APIKEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Create and use an access token for user moehoward
curl -u "admin:$APIKEY" -X POST "http://$SERVER/artifactory/api/security/token" -d "username=moehoward" -d "scope=member-of-groups:readers" > token.log
export TOKEN=`cat token.log | jq -r '.access_token'`
curl -u "moehoward:$TOKEN" "http://$SERVER/artifactory/api/system/ping"
curl -H "Authorization: Bearer $TOKEN" "http://$SERVER/artifactory/api/system/ping"

I get "OK" from the last two commands. Can you run exactly these commands and report back?
I have personally experienced the same problem (Bearer header working, standard user credentials not working) with an old version of curl. The obvious workaround is to use Bearer, the more complex workaround is to upgrade curl (or use another tool).
What is the version of curl you use? Any curl from 2015 or more recent should work fine.


text:
Q: Excecute a query from MySql to Mongodb I am trying to run a query on MongoDb-3.2, but I cant get the results that I want.
This is the original query on MySQL:
SELECT c.cdg,ten,IFNULL(efe,0) as efe,tcreated_at
FROM
(SELECT numB as cdg,COUNT(*) as ten,created_at as tcreated_at
FROM dat_records cdr
WHERE  LEFT(numB,@longitud)= @cod_prov AND type=4
GROUP BY cdg ) c
LEFT JOIN
    (SELECT COUNT(*) as efe, numB,MAX(created_at) as ecreated_at
FROM dat_records
WHERE LEFT(numB,@longitud)= @cod_prov AND dat_records.time > 1 AND type=4 GROUP BY numB) d
ON c.cdg=d.numB AND tcreated_at=ecreated_at
WHERE ten > 40
GROUP BY c.cdg
HAVING (efe/ten)*100 <30
ORDER BY ten DESC
LIMIT 25

This is what I am trying on MongoDB-3.2:
I have this, but I need to include all documents who has or not "efectivas". So, I know the 3rd match is affecting results.

db.archivos_cdr.aggregate([
   {$match: {$and:[{numB:{$regex:'^7' }},{ tipo_llamada:4}]}},
   {$group : {_id : "$numB",tentativas: { $sum: 1 }}},
   {$match:{'tentativas': {'$gt': 4}}},
   {$sort:{"tentativas":-1}},
   {$lookup:{"from": "archivos_cdr","localField": "_id","foreignField": "numB","as": "efecList" } },

    { "$unwind": "$efecList" },
    { "$match": { $or:[ {"efecList.tiempo_conv": {"$gt": 0}}] }},
    {
    "$group": {
        "_id": "$efecList.numB",
        "tentativas": { "$first": "$tentativas" },
        "efectivas": { "$sum": 1 }
        }
    }

])

I have this result:
{ "_id" : "123456789", "tentativas" : 5, "efectivas" : 4 }

But this is what I want:
{ "_id" : "123456789", "tentativas" : 5, "efectivas" : 4 }
{ "_id" : "325987741", "tentativas" : 13, "efectivas" : 0 }

Thanks for your help!

A: I have my own answer!!!! I got it!!!!!
db.dat_records.aggregate([
  {$match: {$and:[{numB:{$regex:'^7' }},{ tipo_llamada:4}]}},//WHERE  LEFT(numB,@longitud)= @cod_prov AND type=4
  {$group : {_id : "$numB",//GROUP BY cdg
    ten: { $sum: 1 },//COUNT(*) as ten
    efec:{$sum:{$cond:[{$gt:["$tiempo_conv",0]},1,0]}},//
    efec_ner:{$sum:{$cond:[{$setIsSubset:[["$causa_fallo"],causas_efec_ner]},1,0]}}}//COUNT(*) as efe_ner
           },
           {$match: { 'ten': {$gt: 40} }},//WHERE ten > 40
           {$sort:{"ten":-1}},//ORDER BY ten DESC
           { $project: {_id:0,
           numeracion:"$_id",
           ten: 1,
           efec: 1,
           efec_ner: 1,
           asr: { $divide:[{$multiply: [ "$efec", 100 ]},"$ten"]},
           ner: { $divide:[{$multiply: [ "$efec_ner", 100 ]},"$ten"]},
           peso: { $multiply:[{$divide: [ "$ten", total_inter ]},100]}  }},
           {$match:{ $and:[ {"asr":{$lt:30}},//HAVING (efe/ten)*100 <30
{"peso":{$gt:10}}  ]}},//I had add this tent/total)>10(*100
    ])

This is the result (All I need!!!!):
{ "ten" : 13, "efec" : 0, "efec_ner" : 13, "numeracion" : "12364567", "asr" : 0, "ner" : 100, "peso" : 10.56 }

Thanks anyway!!!! I hope this helps someone.


text:
Q: i want to make a comment system by using php and notepad i want to create a simple comment system and i want to use the notepad or access to save the database (COMMENTS )  ,
i tend to use this codes below but it didnt work ,  I WANT TO ASK
1- IS IT RIGHT TO USE NOTEPAD FOR IMPLEMENT PHP CODES ?
2- IS IT RIGHT TO WRITE THE ALL PATH OF DESIRED FILE (WHICH I WILL SAVE ON IT ) ?
3- WHY THE COMMENT DIDNT SAVED IN THE NOTEPAD .
<?php
if ($_post)
{
    $name = $_POST('name');
    $content = $_POST('commentcontent');
    $handle = fopen("C:\Users\User\Desktop\simester8\text.txt", "a+");
    fwrite($handle,' $name  ', ' $content ');
    fclose($handle);

}

?>

A: *

*you could use mysql database

*you don't have to

*check out this page : http://www.tizag.com/phpT/filewrite.php
if(isset($_POST['submit']))
{
$handle = fopen("text.txt", "a+") or die("can't open file");
$name   = $_POST['name'];
$content = $_POST['commentcontent'];
fwrite($handle, $name , $content );
fclose($handle);
}

<form method="POST" action="<?=$_SERVER['PHP_SELF']?>">
<input type=text name="name" id="name">
<input type=text name="commentcontent" id="commentcontent">
<button type="submit" value="submit" name="submit" class="btn">submit</button>
</form>


text:
Q: How to create VHD file fixed size of window 2003 server I am trying to create a VHD file fixed size of window 2003 R2 server.
As Hyper V role and Azure CLI is not supported i am not able to create it.
Though Disk2VD creates VHD file but it is dynamic.
Can someone tell me how to create VHD file of window 2003 R2 server fixed size ?
I am trying to migrate aws EC2 window 2003 to azure.

A: You can convert the VHD with Hyper-V Manager.

Launch the Edit Disk action within Hyper-V Manager then select the
  dynamic VHD. On the Action screen, shown here, select the Convert
  option to make the dynamic VHD a fixed VHD. You'll be prompted for a
  new name for the fixed VHD.

A: You can use Hyper-V Manager to make the conversion:

*

*select the Edit Disk option within Hyper-V Manager

*select the dynamic VHD

*on the Action screen select the Convert option to make the dynamic VHD a fixed VHD

*give a new name for the fixed VHD.
Alternately, from powershell you could use Convert-VHD cmdlet:
Convert-VHD -Path D:\HardDiskDyn.vhd -DestinationPath D:\HardDiskFixed.vhd -VHDType Fixed

For the command to work, you need to Import-Module ServerManager


text:
Q: Selenium Hidden File upload in Drag Drop UI I am trying to add image in the following input using selenium web-driver.
<input type="file" multiple="multiple" class="dz-hidden-input" accept="image/gif,image/jpg,image/jpeg,image/png,application/zip" style="visibility: hidden; position: absolute; top: 0px; left: 0px; height: 0px; width: 0px;">

When used sendKeys it gives ElementNotVisible: Element is not currently visible as visibility is hidden.
Tried to execute using Java script set value it gave web-driver exception saying "The operation is insecure."
I found this closed issue similar to mine.
Tried :
executor.executeScript("arguments[0].style.visibility='visible';",fileInput);

executor.executeScript("arguments[0].style.display='block';", fileInput);

To enable the visibility but send keys failed with same error.
I found similar question Uploading a file through selenium but file input element is hidden but my element never becomes visible.
I tried with selenium IDE its working with type command.
Please let me know if any one has faced same issue and how it got fixed.
Thanks in Advance

A: Try to set Opacity for the Input element to 1 and then use SendKeys to provide file path. Opacity can be set using following code:
executor.executeScript("arguments[0].style.visibility='visible';",fileInput);
executor.executeScript("arguments[0].style.height='200px';",fileInput);
executor.executeScript("arguments[0].style.width='200px';",fileInput);

And then execute sendKeys method.
Lemme if that helps!

A: In case you are having problems targeting dz-hidden-input with multiple dropzones on one page, you should do this:
  init: function() {
    this.hiddenFileInput.className = "dz-hidden-input dz-hidden-input-one";
  }

Then you can target the hidden input with $(".dz-hidden-input-one")


text:
Q: How do I start animating applications in winforms? I would like to get some references or examples on how to animate my winform applications.
When I click on a button it should transform group of objects to small or big, move it's position, change the color, etc. I would also accept a library as an answer.

A: I have used dot-net-transitions and I have no issues with is so far. It contains 8 type of animations and basically allows you to animate any controls with them.

TransitionType_Linear is a linear animation with objects moving at a
  constant rate throughout the transition.
TransitionType_Acceleration starts the transition at zero velocity and
  builds up at a constant rate of acceleration to be at full-speed by
  the end of the transition.
TransitionType_Deceleration starts the transition at full-speed and
  decelerates at a constant rate to be at zero velocity by the end of
  the transition.
TransitionType_CriticalDamping is a declerating transition, using an
  exponentially decaying velocity. It is good (for example) for
  animating properties such as needles on dials.
TransitionType_EaseInEaseOut starts at zero velocity and accelerates
  until halfway through the transition, then decelerates back to zero
  velocity by the end of the transition.
TransitionType_Bounce accelerates to the destination value by halfway
  through the transition and then decelerates back to the original value
  by the end. This is similar to acclerating downwards with gravity and
  then bouncing back against gravity.
TransitionType_ThrowAndCatch is the counterpart of the Bounce
  transition above. It decelerates to the destination value by halfway
  through the transition and then acclerates back to the original value
  by the end.
TransitionType_Flash lets you specify a number of flashes and the time
  for each flash. Each flash animates the properties to their
  destination value and back again using an ease-in-ease-out transition.

They have a decent documentation on how you can implement the features, you can find it at http://code.google.com/p/dot-net-transitions/wiki/CodingWithTransitions
Also they have an .exe sample that basically shows all the animations so you know what to expect.


text:
Q: How to remove ?wp-mce from page source? After check GT Metrix I found Remove query strings from static resources results is 50% and then found that's because some URL have ?wp-mce-4103-20162941 and no plugin can remove this so can use a code like this:
function _remove_script_version( $src ){
   $parts = explode( '?wp-mce-', $src );
   return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );

To solve the problem?
This's a example of the issue:
/wp-includes/js/tinymce/plugins/charmap/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/colorpicker/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/fullscreen/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/hr/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/image/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/lists/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/media/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/paste/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/tabfocus/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/textcolor/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wordpress/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wpautoresize/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wpdialogs/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wpeditimage/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wpembed/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wpgallery/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wplink/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wptextpattern/plugin.min.js?wp-mce-4103-20162941
/wp-includes/js/tinymce/plugins/wpview/plugin.min.js?wp-mce-4103-20162941


text:
Q: How to store a zip in a sql server 2005 only with sql? I'm using SQL Server 2005 and I only can use Management Studio (it's a staging/production server). I need to save a zip file from local machine (server) into a blob field.
I do this:
create table CFile (id int, thefile varbinary(max))

INSERT INTO CFile
    (id, thefile)
    SELECT 1,
        BulkColumn FROM OPENROWSET(
            Bulk 'C:\test.zip', SINGLE_BLOB) AS BLOB

and was ok, but then when:
SELECT * FROM CFile

I saw the row but I can't see the data in thefile field, and is not null (checked also with ISNULL function)
So there is the data but I'cant read it? why? How i retrieve it from Management Studio again, at least as varchar?
I try with
INSERT INTO CFile (id, thefile) VALUES (3,cast('asasdfadsfadsfdsafadsfasdfadsfasdfd' as varbinary))

and it works, I can see the content of the field.
Any help or tip in this will be preciated.
Thanks

A: I'm pretty sure SQL management viewer does not have a BLOB viewer.  You will have to save it back to a file.
You can check with DATALENGTH(thefile) to test if the field was loaded.


text: Q: Restoring to a new phone without the restore password I have a new phone and want to restore settings from the old one but can't remember my restore password. I can't seem to reset the password but can I reset iTunes somehow, do a new backup on the old phone then restore to the new one?


text:
Q: Use bullets as navigation with Swipe JS I've been banging my head off a wall for a few hours and I'd really appreciate some help with this. I know it's going to be easy solution but so far it's not going well.
I'm using Swipe Js for a slider and I want to use some bullets as navigation (without the next and prev). I tried to use getPos() a built in swipe function but I keep getting a 'no method' error in my console.
Here's my HTML:

Here's my JS:
I've pulled it back to what's working. I just want to click on a dot and make it go to the corresponding slide.
   var slider = Swipe(document.getElementById('slider'), {
      auto: 6000,
      continuous: true,
      callback: function(pos) {

        var i = bullets.length;
        while (i--) {
          bullets[i].className = ' ';
        }
          bullets[pos].className = 'on';
      }

    });

  var bullets = document.getElementById('position').getElementsByTagName('li');

Any help is really appreciated
Link to my code http://codepen.io/veryrobert/pen/sHjwo
Link to the plugin https://github.com/bradbirdsall/Swipe

A: This should work:
$('li').on('click', function(event){
  event.preventDefault();
  var index = $("li").index(event.currentTarget);
  slider.slide(index);
});

Basically, you need to workout the index of corresponding li and pass that to swipes .slide method. This will then slide to the requested slide.
Hope that helps.

A: To make bullets clickable, you can use the plugin's pagination module and initialise it as follows:

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

In this way, swiper takes care of creating the bullets inside the element that is given as a parameter and set clickable: true
Remember to include/import the paging module with Swiper or include/import the Swipern bundle for navigation to work:
From NPM:
// core version + pagination module:
import Swiper, { Pagination } from 'swiper';

// configure Swiper to use module
Swiper.use([Pagination]);

// init Swiper:
const swiper = new Swiper(...);

From CDN:


text:
Q: how to access query string in controller and routes of laravel when I will click on a tag it go to specific url if no id found then go to reference
My view
<a href="{{URL::to('user/')}}/?reference={{$user->username}}">
                    go there
                  </a>

my route
Route::get('/user/{id}/{reference?}', 'UserController@index')->name('/user');

A: The query string is considered part of the inputs and not part of the URI for routing. If you want the 'id' part of the URI to be optional you would have to adjust your definition. Then in your controller you can access your reference query string parameter.
Route::get('user/{id?}', 'UserController@index')->name('user');

public function index(Request $request, $id = null)
{
    $reference = $request->input('reference');
    ...
}


text:
Q: Fullcalendar v1.6.4 refetch events from mysql Hello everyone!
Im using Fullcalendar in version 1.6.4 combinated with php and mysql. My only source for events is Mysql database where I have start time, end time, etc for any event.

I want that user don't have to reload page every second to see if any
  events has been added.

I found methods called refetchEvents and
rerenderEvents. But if I use them, the calendar has no reaction.

1# Ajax call
Here is my ajax call to add event to the database:
$( document ).ready(function() {
        $("#pridat_akci").click(function() {
        var procedura = $.cookie('kontrola_procedury');
        var start = $.cookie('datum')+' '+$.cookie('formDate');
        var lpg = $.cookie('lpg_check');
        var oboje = $.cookie('navazujici');
        var info = $.cookie('clovek_info');
        var typ_paliva = $.cookie('typ_paliva');
         $.ajax({
            url: 'http://mydomain/zapsat_udalost_uziv_admin.php',
            data: {
                'procedura':procedura,
                'kontakt': info,
                'start': start,
                'LPG': lpg_bool,
                'typpaliva': typ_paliva,
                },
            type: "POST",
            success: function( data ) {
            alert('Done!');
            $('#calendar').fullCalendar( 'rerenderEvents' );

            }

           });

});
});

#2 Calendar declaration
I have declared calendar into calendar div
var calendar = $('#calendar').fullCalendar({.....});

A: Try this : addEventSource
    $('#calendar').fullCalendar('addEventSource', source)
    $('#calendar').fullCalendar('refetchEvents');


text:
Q: Best practice to implement Retrofit callback to recreated activity? I'm switching to Retrofit and trying to understand proper architecture for using it with async callbacks.
For example I have an interface:
interface RESTService{
    @GET("/api/getusername")
    void getUserName(@Query("user_id") String userId,
                     Callback<Response> callback);
}

And I run this from main activity:
RestAdapter restAdapter = new RestAdapter.Builder()
        .setServer("WEBSITE_URL")
        .build();
RESTService api = restAdapter.create(RESTService.class);
api.getUserName(userId, new Callback<Response> {...});

Then user rotates the device and I have newly created activity... What was happen here? How can I get response to the new activity (I assume that api call in background will execute longer than first activity life). Maybe I must use static instance of callback or what? Please show me the right way...

A: I highly recommend you watch this video given at Google I/O.
It talks about how to create REST requests by delegating them to a service (which is almost never killed). When the request is completed it is immediately stored into Android's built-in database so the data is immediately available when your Activity is ready.
With this approach, you never have to worry about the lifecycle of the activity and your requests are handled in a much more decoupled way.
The video doesn't specifically talk about retrofit, but you can easily adapt retrofit for this paradigm.

A: Use otto.
There are a lot of samples to mix otto and retrofit, for example https://github.com/pat-dalberg/ImageNom/blob/master/src/com/dalberg/android/imagenom/async/FlickrClient.java
Or read this post http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html
It answers on almost all questions

A: For potential long running server calls i use an AsyncTaskLoader. For me, the main advantage of Loaders are the activity-lifecycle handling. onLoadFinished is only called if your activity is visible to the user. Loaders are also shared between activity/fragment and orientation changes.
So i created an ApiLoader which uses retrofits synchronous calls in loadInBackground.
abstract public class ApiLoader<Type> extends AsyncTaskLoader<ApiResponse<Type>> {

    protected ApiService service;
    protected ApiResponse<Type> response;

    public ApiLoader(Context context) {
        super(context);
        Vibes app = (Vibes) context.getApplicationContext();
        service = app.getApiService();
    }

    @Override
    public ApiResponse<Type> loadInBackground() {
        ApiResponse<Type> localResponse = new ApiResponse<Type>();

        try {
            localResponse.setResult(callServerInBackground(service));
        } catch(Exception e) {
            localResponse.setError(e);
        }

        response = localResponse;
        return response;
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        if(response != null) {
            deliverResult(response);
        }

        if(takeContentChanged() || response == null) {
            forceLoad();
        }
    }

    @Override
    protected void onReset() {
        super.onReset();
        response = null;
    }

    abstract protected Type callServerInBackground(SecondLevelApiService api) throws Exception;

}

In your activity you init this loader like this:
getSupportLoaderManager().initLoader(1, null, new LoaderManager.LoaderCallbacks<ApiResponse<DAO>>() {
        @Override
        public Loader<ApiResponse<DAO>> onCreateLoader(int id, Bundle args) {
            spbProgress.setVisibility(View.VISIBLE);

            return new ApiLoader<DAO>(getApplicationContext()) {
                @Override
                protected DAO callServerInBackground(ApiService api) throws Exception {
                    return api.requestDAO();
                }
            };
        }

        @Override
        public void onLoadFinished(Loader<ApiResponse<DAO>> loader, ApiResponse<DAO> data) {
            if (!data.hasError()) {
                DAO dao = data.getResult();
                //handle data
            } else {
                Exception error = data.getError();
                //handle error
            }
        }

        @Override
        public void onLoaderReset(Loader<ApiResponse<DAO>> loader) {}
    });

If you want to request data multiple times use restartLoader instead of initLoader.

A: I've been using a kind of MVP (ModelViewPresenter) implementation on my Android apps. For the Retrofit request I made the Activity calls it's respective Presenter, which in turn makes the Retrofit Request and as a parameter I send a Callback with a custom Listener attached to it (implemented by the presenter). When the Callback reach onSuccess or onFailure methods I call the Listener's respective methods, which calls the Presenter and then the Activity methods :P
Now in case the screen is turned, when my Activity is re-created it attaches itself to the Presenter. This is made using a custom implementation of Android's Application, where it keeps the presenters' instance, and using a map for recovering the correct presenter according to the Activity's class.
I don't know if it's the best way, perhaps @pareshgoel answer is better, but it has been working for me.
Examples:
public abstract interface RequestListener<T> {

    void onSuccess(T response);

    void onFailure(RetrofitError error);
}

...
public class RequestCallback<T> implements Callback<T> {

    protected RequestListener<T> listener;

    public RequestCallback(RequestListener<T> listener){
        this.listener = listener;
    }

    @Override
    public void failure(RetrofitError arg0){
        this.listener.onFailure(arg0);
    }

    @Override
    public void success(T arg0, Response arg1){
        this.listener.onSuccess(arg0);
    }

}

Implement the listener somewhere on the presenter, and on the overrode methods call a presenter's method that will make the call to the Activity. And call wherever you want on the presenter to init everything :P
Request rsqt = restAdapter.create(Request.class);
rsqt.get(new RequestCallback<YourExpectedObject>(listener));

A: Use Robospice
All components in your app which require data, register with the spice service. The service takes care of sending your request to the server (via retrofit if you want). When the response comes back, all components which registered get notified. If there is one of them not available any more (like an activity which got kicked because of rotation), it's just not notified.
Benefit: One single request which does not get lost, no matter whether you rotate your device, open new dialogs/fragments etc...

A: Using Retrofit2 to handle orientation change. I was asked this in a job interview and was rejected for not knowing it at the time but here it is now.
public class TestActivity extends AppCompatActivity {
Call<Object> mCall;
@Override
    public void onDestroy() {
        super.onDestroy();
        if (mCall != null) {
            if (mCall.isExecuted()) {
                //An attempt will be made to cancel in-flight calls, and
                // if the call has not yet been executed it never will be.
                mCall.cancel();
            }
        }
    }
    }

A: Firstly, your activity leaks here because this line:
    api.getUserName(userId, new Callback {...})
creates an anonymous Callback class that holds a strong reference to you MainActivity. When the device is rotated before the Callback is called, then the MainActivity will not be garbage collected. Depending on what you do in the Callback.call(), your app may yield undefined behaviour.
The general idea to handle such scenarios is:

*

*Never create a non-static inner class (or an anonymous class as mentioned in the problem).

*Instead create a static class that holds a WeakReference<> to the Activity/Fragment.

The above just prevents Leaks. It still does not help you get the Retrofit call back to your Activity.
Now, to get the results back to your component (Activity in your case) even after configuration change, you may want to use a headless retained fragment attached to your Activity, which makes the call to Retrofit. Read more here about Retained fragment - http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
The general idea is that the Fragment automatically attaches itself to the Activity on configuration change.


text:
Q: Loop for reading txt file with multiple headers and detail items in php I have the following incoming txt file:
H header1 yyyy
I detailofheader1
I detailofheader1
H header2 xxxx
I detailofheader2
I detailofheader2

And the following code:
$action = substr($line_of_text, 0, 1);
if (($action == 'H') )  {
//STORE IN VARIABLES ;
}
if (($action == 'I') )  {
//store in variables and upload header and detail variables to mysql;
}

I would like to have a loop read first header store in variable then read details and everytime it hits 'I' it uploads that line to MYSQL.
How do i go back to the top of the loop once it hits H again?
Thanks from a noobie.

A:
I would like to have a loop read first header store in variable then read details and everytime it hits 'I' it uploads that line to MYSQL.

There are multiple ways to parse your file.
The following approach makes use of explode() for H and I.
So you have a "outer loop" for H (H header1 yyyy I detailofheader1 I detailofheader1) - to process the individual headers.
And an "inner loop" for I (header1 yyyy I detailofheader1 I detailofheader1)
 - to process the header data itself and the details.
SQL-wise:

*

*I don't know your SQL schema - just guessing around on the schema.

*Where i use echo $sql - you could exec the query.

*this is example SQL, escape it properly to make it safe

Anyway, here's something to play around with. Hope that gets you started...
<?php

// example data to work with
$string = 'H header1 yyyy I detailofheader1 I detailofheader1 H header2 xxxx I detailofheader2 I detailofheader2';

// later just
// $string = file("file.txt");

// get rid of the first H (to ease exploding / no empty first array item)
$string =  ltrim($string, 'H');

// explode string into array - by using H as char for the split
$headers = explode('H', $string);

foreach($headers as $idx => $line)
{
    $line = trim($line); // remove spaces at begin/end

    //echo 'Processing: [' . $idx . '] ' . $line . PHP_EOL;

    // second explode, this time using "I"
    $data = explode('I', $line);

    foreach($data as $dataIdx => $details)
    {
        $details = trim($details); // remove spaces at begin/end

        //echo '           ' . $details . PHP_EOL;

        // first dataIdx is the header data "header1 yyyy"
        if($dataIdx === 0) {
            // string contains a space, split
            $headerItems = explode(' ', $details);
            $headerNumber = trim($headerItems[0]); // header1
            $headerString = trim($headerItems[1]); // yyyy`

            // => insert the header

            $sql = "INSERT INTO table_headers (id, name) VALUES ('$headerNumber',' $headerString')";
            echo $sql . PHP_EOL;

            // we are done, skip to next element
            continue;
        }

        // else its a "detailofheaderX"
        // so use details in the insert query

        $sql = "INSERT INTO table_data (header_id, detail) VALUES ('$headerNumber', '$details')";
        echo $sql . PHP_EOL;
    }
}

A: Your loop will be what reads each line of the file, providing a value for $line_of_text. Two ways of doing this:
$handle = fopen("/file/name.txt", "r");
while (!feof($handle)) {
    $line_of_text = fgets($handle);
    // do stuff with line of text
    ....
}
fclose($handle);

Or, my preferred method:
$all_lines = file("/file/name.txt");
foreach ($all_lines as $line_of_text) {
    // do stuff with line of text
    ....
}


text:
Q: Create new Child Component within a Child Component I have an issue about creating new Components with the  resolveComponentFactory. First there is a startComponent (parent component) and from this component there are several buttons and every btn creates an new child Component. For example now I create a "childComponent" and this also works. But now I want to create an new childComponent within the childComponent and this new component shall have the startComponent as parent component, not the childComponent itself. So I Need a way to call the addComponent() method from the startComponent with my childComponent.
Here is the way I'm doing it at the moment:
startComponent.ts:
import {
Component, OnInit, ViewChild,
ComponentFactoryResolver,
ViewContainerRef
} from '@angular/core';

Import { childComponent } from '../childComponent/child.component';
import { DataService } from '../data.service';

@Component({
selector: 'app-start',
templateUrl: './start.component.html',
styleUrls: ['./start.component.css']
})

export class startComponent implements OnInit {
@ViewChild('parent', { read: ViewContainerRef }) container: ViewContainerRef;

constructor(private dataService: DataService, private componentFactoryResolver: ComponentFactoryResolver){}

ngOnInit(){}

addComponent(){

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(childComponent);

let component = this.container.createComponent(componentFactory);
// next Line i save the reference of the "childComponent" to a Service
// so the "childComponent" can get it and destroy himself if wanted
this.createComponentService.setReference(component, type);
}
}

startComponent.html

<button (click)="addComponent()" class="btn">
 </button>

It does work if I want to create a childComponent with my childComponent, but the startComponent is not the parent component then.
I hope you understand my Problem, else I can try to explain it again.

A:
But now I want to create an new childComponent within the
  childComponent and this new component shall have the startComponent as
  parent component, not the childComponent itself. So I Need a way to
  call the addComponent() method from the startComponent with my
  childComponent.

So, in childComponent you should have reference to parentComponent(StartComponent). You can get it by injecting to new added childComponent:
childComponent:
constructor(private parentComp: StartComponent){

}

As you have reference to it, you get access to properties, methods of parent and within childComponent can call addComponent() easily like:
parentComp.addComponent();

Update
Interesting, dynamically created component doesn't have parent component in injector. So, it can't inject parent  StartComponent.
Another solution

*

*Set child component's parent property with StartComponet:
ngOnInit() {
   this.comps.clear();
   let aComponentFactory =
   this.componentFactoryResolver.resolveComponentFactory(this.compArr[0]);
   let aComponentRef = this.comps.createComponent(aComponentFactory);

   (<AComponent>aComponentRef.instance).name = 'A name';
   (<AComponent>aComponentRef.instance).parent = this;
 }

StackBlitz Demo. Look at the console

*Manually inject parent component in child:
constructor(public injector: Injector ) {
    console.log('child injector', injector);
    this.parent = injector.get(AppComponent);
}

ngOnInit() {
   console.log('parent is here', this.parent);
   this.parent.test();
}

StackBlitz Demo. Look at the console


text:
Q: Unable to push Go app inside cloud foundry I'm trying to push Go app into cloud foundry. When I try to build the binary and push it the app crashes and it returns start unsuccessful.
This is my manifest file
---
applications:
- name: project-suspension
  instances: 1
  memory: 256MB
  disk_quota: 512MB
  buildpacks:
  - go_buildpack
  - binary_buildpack
 env:
    GOPACKAGENAME: dev.azure.com/.../service-infrastructure

I tried putting every file inside the root folder of the project but the app is still crashing when I push it. The other thing i tried is using the command flag -c "project-suspension" and it still crashes.

A: As mentioned in the comment, you don't need both buildpacks. Use either the go-buildpack, if you are pushing source code, or the binary buildpack if you are building locally and pushing the binary. If pushing a binary built locally, you need to cross-compile for Linux (unless you are running Linux as your workstation).
Ex:
---
applications:
- name: project-suspension
  instances: 1
  memory: 256MB
  disk_quota: 512MB
  buildpacks:
  - go_buildpack
 env:
    GOPACKAGENAME: dev.azure.com/.../service-infrastructure

or
---
applications:
- name: project-suspension
  instances: 1
  memory: 256MB
  disk_quota: 512MB
  buildpacks:
  - binary_buildpack
  command: ./project-suspension

The latter assumes that the binary you want to run is called project-suspension and that it exists in the same directory from which cf push is run (or the same directory where you've set path: or -p.
Also, be aware that applications can fail to start for other reasons, like if the health check does not pass. The default health check is going to be port-based, so it'll expect your application to be listening on the port number set with $PORT. Make sure your app reads $PORT and listens on that port.


text:
Q: How delete item's sortable JQuery I have the program where there is a accordion with three item.
In the first item's accordion there is one sortable and there is one button, after clicking above, I would like to I delete an item's sortable.
How to delete the item with id="three"???(EXAMPLE)
I don't know.

A: Simply you can remove the #three element with .remove method. for ex,
$('#r').click(function(){
    $('#three').remove();
});


text:
Q: Add dynamic buttons to jpanel in Java I'm trying to do a program in Java that will make a button appears in a JPanel where and when it's clicked. To do that, I have the method run, with the following code:
 public void run(){
    panel.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e){
            JButton button = new JButton();
            button.setVisible(true);
            button.setAlignmentX(e.getXOnScreen());
            button.setAlignmentY(e.getYOnScreen());
            panel.add(button);
            panel.revalidate();
            panel.repaint();
        }
    });
}

The problem is, nevermind where I click, the buttons never appears.

A: This code should make a button appear when the panel is clicked. It will not make it appear at the cursor but that should be easy to add. It will also make a new button every time you click the panel. If you only want one button simply move this line JButton button = new JButton();, outside of the mousePressed event
public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    JPanel panel = new JPanel();
    panel.setSize(500, 500);
    frame.add(panel);
    frame.show();
    run(panel);
}

 public static void run(JPanel panel){
        panel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e){
                JButton button = new JButton();
                button.setVisible(true);
                panel.add(button);
                panel.revalidate();
            }
       });
}

A:
a button appears in a JPanel where and when it's clicked.

button.setAlignmentX(e.getXOnScreen());
button.setAlignmentY(e.getYOnScreen());

You are using a couple of incorrect methods.
To position a component in a panel you need to use:
button.setLocation(...);

However, you can't use the getXOnScreen() method because that is relative to the screen. You need to position the component relative to the panel. So instead you need to use:
button.setLocation(e.getX(), e.getY());

That is still not enough because when you use a null layout you also are responsible for determining the size of the component. So you would also need to use:
button.setSize( button.getPreferredSize() );

You also need to make sure the panel is using a null layout, otherwise the layout manager will override the size/location.

A: This worked for me (even whithout adding buttons labels)
public static void main(String[] args) {

        final JPanel panel = new JPanel();

        JFrame frame = new JFrame("test swing");
        frame.setAlwaysOnTop(true);
        frame.setSize(400, 200);
        frame.add(panel);
        frame.setVisible(true);

        panel.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e){
                JButton button = new JButton();
                button.setVisible(true);
                button.setAlignmentX(e.getXOnScreen());
                button.setAlignmentY(e.getYOnScreen());
                panel.add(button);
                panel.revalidate();
                panel.repaint();
            }
        });
    }


text:
Q: Chrome Extension : Custom Protocol? Are there methods to register a custom protocol with a google chrome extension like you can in firefox :
const kSIMPLEURI_CONTRACTID = "@mozilla.org/network/simple-uri;1";
const kIOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
const nsISupports = Components.interfaces.nsISupports;
const nsIIOService = Components.interfaces.nsIIOService;
const nsIProtocolHandler = Components.interfaces.nsIProtocolHandler;
const nsIURI = Components.interfaces.nsIURI;

I want the protocol:
xyz:
Not xyz://
Is this possible?

A: Chrome does not offer a way to set custom handlers for the xyz: scheme.
There are some ways to emulate the behavior though:

*

*Use Content scripts to set up an event listener for clicks on links which point to xyz:....

*Use the webRequest API to intercept and redirect all requests from the default search provider to a custom URL. I'm using this method for catching wildcard search keywords, but it can also be used for supporting fake schemes. Unfortunately, the extension would be quite specific to the user's search settings, because it would do something like this:
Redirect http://google.com/search?q=xyz%3Awhatever
      to chrome-extension://.../whatever

in both cases, you won't see xyz:whatever in the omnibox, though.
navigator.registerProtocolHandler should be the best way to register a xyz: handler. Unfortunately, it is quite limited at the moment. Custom protocols must be prefixed with web+. Also take a look at the list of open bugs for this API.

A: The new way would be using declarativeNetRequest
Create a rule rules.json that does a redirect.
[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "regexSubstitution": "chrome-extension://xxxxxxxxxxxxxxxx/redirect.html#\\1"
      }
    },
    "condition": {
      "regexFilter": "^https://mohamedmansour.com/join/([\\w]+)",
      "resourceTypes": ["main_frame"]
    }
  }
]

Then within your redirect.html script, handle it, you can use chrome.runtime.sendMessage to act upon it.
function closeCurrentTab() {
  chrome.tabs.getCurrent(tab => chrome.tabs.remove(tab.id, () => {}))
}

if (location.hash)
  chrome.runtime.sendMessage({ command: 'AppLink', data: location.hash }, () => closeCurrentTab())
else
  closeCurrentTab()

That is how you can do App Deep Linking within Extensions with a fake URL link.


text:
Q: Is it possible for a subset of a non-context free language to be context-free? For example, if I have a non-context free language of B, is there such a context free language A such that A is a subset of B? I have been thinking of examples but unable to think of any valid ones.
 I thought I got it when I said that A = {A = {w | w is of even length and w ∈ {a, b, c}}, which is context-free, and B = {ww | w ∈ {a,b,c}}, which is not context free. However, I realized that there are some strings A can produce that B cannot, and therefore, A is not a subset of B.
Does anyone know of any examples that could be valid in my situation?

A: Any finite set of strings is a context-free language. (Indeed, it is a regular language.) So any finite subset of a language is context-free, regardless of what the language is.
Another trivial case is the language L = L1 ∪ L2 where the alphabet of L1 is Σ1 and the alphabet of L2 is Σ2 and Σ1 ∩ Σ2 = ∅. Now L is context-free only if both L1 and L2 are context-free. (This is not the case if the alphabets are not disjoint.) So if exactly one of L1 and L2 is context-free, then it is a subset of the non-context-free language L.
If neither of those are interesting enough for you, then the language { a* } (where a is a symbol) is a subset of { ww | w ∈ {a, b}* }. Another subset of the same classic non-context-free language is { ww | w ∈ {a, b}* ∧ w = wR } (that is, the language of all duplicated even-length palindromes) which is context-free because it is exactly the same as { wwR | w ∈ {a, b}* ∧ w = wR }, as a result of the second condition.


text:
Q: Notification action button does not fire pending intent I try to send intent to BroadcastReceiver from notification action button my problem is that when I click the button the intent in not fired or not getting to the BroadcastReceiver.
Here is my code:
The notification:
Intent accept = new Intent(this, ChallengesActionReceiver.class);
accept.setAction("com.soinfit.utilities.CHALLENGE_CLICK");
accept.putExtra("reqId", extras.getString("reqId"));
accept.putExtra("answer", "1");
PendingIntent acceptIntent = PendingIntent.getActivity(this, 1, accept, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

.setLargeIcon(image)
.setSmallIcon(R.drawable.app_icon_small)
.setContentTitle("soInFit")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setAutoCancel(true)
.addAction(R.drawable.app_icon_small, getString(R.string.accept), acceptIntent)
.setContentText(msg);

mBuilder.setContentIntent(contentIntent);

Notification nof = mBuilder.getNotification();

nof.defaults|= Notification.DEFAULT_SOUND;
nof.defaults|= Notification.DEFAULT_LIGHTS;
nof.defaults|= Notification.DEFAULT_VIBRATE;

nof.flags = Notification.FLAG_AUTO_CANCEL;

NotificationManager notificationManager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
notificationManager.notify(id+1, nof);

The BroadcastReceiver
public class ChallengesActionReceiver  extends BroadcastReceiver

{

    @Override
    public void onReceive(Context context, Intent intent) {

       Log.i("test", "test");
}

}

Manifest:
<receiver
    android:name="utilities.ChallengesActionReceiver"
    android:enabled="true" >

     <intent-filter>
    <action android:name="com.soinfit.utilities.CHALLENGE_CLICK" />
       </intent-filter>

If I call this code:
    Intent accept = new Intent(this, ChallengesActionReceiver.class);
    accept.setAction("com.soinfit.utilities.CHALLENGE_CLICK");
    accept.putExtra("reqId", extras.getString("reqId"));
    accept.putExtra("answer", "1");
    PendingIntent acceptIntent = PendingIntent.getActivity(this, 1, accept, PendingIntent.FLAG_CANCEL_CURRENT);

this.sendBroadcast(accept);

Its working fine.

A: I had to change
PendingIntent.getActivity

to
PendingIntent.getBroadcast

A: Use method .setContentIntent(), instead of .addAction() to launch pending intent.


text:
Q: Linux: Random kernel oops in mmap functions For the last month or so I've been getting seemingly random kernel oopses. I've started to notice a pattern: from looking at the traces, the call trace always involves mmap functions.
Whenever one of these happens, the process that it occurred under (Chromium in the trace below) hangs and trying to kill it with SIGKILL only results in the kill command hanging as well. To return stability to the system I have to completely power off the box and reboot.
Until a recent kernel update, the computer would just randomly turn off completely. No warnings and nothing in the logs. Thankfully, that has seemed to stop.
Question: Is this indicative of a hardware problem? Mmap failures suggest RAM problems (I ran memcheck for 12+ hours with no errors though). Or is this really just a bug in the kernel? If so, what can I do about it?
$ uname -a
Linux [name] 3.11.0-15-generic #23-Ubuntu SMP Mon Dec 9 18:17:04 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

Trace from dmesg:
[252563.113569] BUG: unable to handle kernel paging request at 0000020000000018
[252563.113589] IP: [<ffffffff811619e0>] vma_interval_tree_insert+0x30/0x90
[252563.113607] PGD 0
[252563.113612] Oops: 0000 [#1] SMP
[252563.113620] Modules linked in: serpent_avx_x86_64 serpent_sse2_x86_64 serpent_generic twofish_generic twofish_avx_x86_64 twofish_x86_64_3way twofish_x86_64 twofish_common xts hidp pci_stub vboxpci(OF) vboxnetadp(OF) vboxnetflt(OF) vboxdrv(OF) vmw_vsock_vmci_transport vsock vmw_vmci parport_pc ppdev rfcomm bnep binfmt_misc usblp x86_pkg_temp_thermal kvm_intel kvm eeepc_wmi asus_wmi sparse_keymap snd_hda_codec_hdmi snd_hda_codec_realtek snd_hda_intel joydev snd_hda_codec btusb bluetooth cdc_acm snd_hwdep snd_pcm microcode snd_page_alloc snd_seq_midi snd_seq_midi_event snd_rawmidi snd_seq snd_seq_device snd_timer psmouse snd serio_raw mei_me mei lpc_ich soundcore mac_hid coretemp lp parport dm_crypt raid10 raid456 async_memcpy async_raid6_recov async_pq async_xor async_tx xor hid_generic raid6_pq raid0 multipath linear hid_logitech_dj usbhid hid raid1 mxm_wmi radeon crct10dif_pclmul crc32_pclmul ghash_clmulni_intel aesni_intel aes_x86_64 lrw gf128mul glue_helper ablk_helper cryptd i2c_algo_bit ttm ahci libahci drm_kms_helper e1000e drm video ptp pps_core wmi
[252563.113870] CPU: 3 PID: 13428 Comm: Chrome_IOThread Tainted: GF          O 3.11.0-15-generic #23-Ubuntu
[252563.113890] Hardware name: ASUS All Series/MAXIMUS VI HERO, BIOS 0224 04/25/2013
[252563.113906] task: ffff88079bc9aee0 ti: ffff880768020000 task.ti: ffff880768020000
[252563.113922] RIP: 0010:[<ffffffff811619e0>]  [<ffffffff811619e0>] vma_interval_tree_insert+0x30/0x90
[252563.113943] RSP: 0018:ffff880768021d90  EFLAGS: 00010206
[252563.113954] RAX: 0000020000000000 RBX: ffff8806d7f4c980 RCX: 0000000000000000
[252563.113969] RDX: ffff88079bb7bd70 RSI: ffff88079bb7bd70 RDI: ffff88038fa57c38
[252563.113984] RBP: ffff880768021d98 R08: 000000000000007f R09: 0000000000000000
[252563.114000] R10: ffff88038fa57c38 R11: 00007f3f14132000 R12: ffff88038fa57c38
[252563.114015] R13: ffff880100babae8 R14: ffff880100babaf0 R15: ffff88079bb7bd88
[252563.114030] FS:  00007f3f4fffe700(0000) GS:ffff88081ecc0000(0000) knlGS:0000000000000000
[252563.114047] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[252563.114059] CR2: 0000020000000018 CR3: 00000007ed0b8000 CR4: 00000000001407e0
[252563.114074] Stack:
[252563.114079]  ffffffff8116b698 ffff880768021dd8 ffffffff8116c275 ffff880100babac8
[252563.114097]  ffff880100babaf0 00007f3f140b2000 ffff880100babae8 ffff8806daf9fd00
[252563.114114]  ffff880100babac8 ffff880768021e60 ffffffff8116e77c ffff8806daf9fd00
[252563.114132] Call Trace:
[252563.114139]  [<ffffffff8116b698>] ? __vma_link_file+0x48/0x80
[252563.114153]  [<ffffffff8116c275>] vma_link+0x75/0xc0
[252563.114164]  [<ffffffff8116e77c>] mmap_region+0x48c/0x610
[252563.114177]  [<ffffffff8116ec05>] do_mmap_pgoff+0x305/0x3c0
[252563.114190]  [<ffffffff8115a3fd>] vm_mmap_pgoff+0x8d/0xc0
[252563.114202]  [<ffffffff8116d253>] SyS_mmap_pgoff+0x1d3/0x270
[252563.114215]  [<ffffffff81017402>] SyS_mmap+0x22/0x30
[252563.114227]  [<ffffffff816f721d>] system_call_fastpath+0x1a/0x1f
[252563.114240] Code: 48 8b 47 08 48 2b 07 49 89 fa 4c 8b 8f 98 00 00 00 48 89 f2 31 c9 48 c1 e8 0c 4d 8d 44 01 ff eb 27 66 2e 0f 1f 84 00 00 00 00 00 <4c> 39 40 18 73 04 4c 89 40 18 4c 3b 48 40 48 8d 48 08 48 8d 50
[252563.114312] RIP  [<ffffffff811619e0>] vma_interval_tree_insert+0x30/0x90
[252563.114327]  RSP <ffff880768021d90>
[252563.114335] CR2: 0000020000000018
[252563.117845] ---[ end trace eb82b12e51fc5733 ]---

A: Since you already have run memtest for a sufficient amount of time, the most obvious hardware suspect has been disculpated. I take it that you have noticed whether the line
 BUG: unable to handle kernel paging request at 0000020000000018

carries the same or a different address every time, right?
I cannot help you with this report, but may I suggest you use Apport for collecting info on your crashes? Apport is Ubuntu's official package for data collection in cases of crashes and bugs, you find a good Intro here.
You need to activate it, (edit as sudo /etc/apport/crashdb.conf, find this line,
  'problem_types': ['Bug', 'Package'],

and add a hash symbol, # at its beginning), and it will produce a full trace of the call that generated the crash. No need to worry about ulimit either in  recent versions of Ubuntu, since Apport is able to circumvent its indication, even if set to 0.
By and large, the best thing to do is to upload the crash report to Launchpad; Apport does this automatically. Yet there is some info that may be helpful even to the unexperienced user. The Intro referenced above states:
Some fields warrant further details:

SegvAnalysis: when examining a Segmentation Fault (signal 11), Apport attempts to review the exact machine instruction that caused the fault, and checks the program counter, source, and destination addresses, looking for any virtual memory address (VMA) that is outside an allocated range (as reported in the ProcMaps attachment).

SegvReason: a VMA can be read from, written to, or executed. On a SegFault, one of these 3 CPU actions has taken place at a given VMA that either not allocated, or lacks permissions to perform the action. For example:

SegvReason: reading NULL VMA would mean that a NULL pointer was most likely dereferenced while reading a value.

SegvReason: writing unknown VMA would mean that something was attempting to write to the destination of a pointer aimed outside of allocated memory. (This is sometimes a security issue.)

SegvReason: executing writable VMA [stack] would mean that something was causing code on the stack to be executed, but the stack (correctly) lacked execute permissions. (This is almost always a security issue.)

In the past, this has allowed me to pinpoint a program with a bug (VirtualBox) which caused the crashes. After a full purge and re-install, the problem evaporated. I just wish you the same luck.


text:
Q: How to pass two parameters into lambda functions in map I wish to use map to do the following thing:
res = []
arr1 = [1, 2, 3]
arr2 = [5, 0, 10]
for n, m in zip(arr1, arr2):
    res.append(n - 0.5 * m)

This is equivalent to do in list comp:
res = [n - 0.5 * m for n, m in zip(arr1 ,arr2)]

But it fails using map:
res = map(lambda x, y: x - 0.5 * y, zip(arr1, arr2))

TypeError: <lambda>() takes exactly 2 arguments (1 given)

Is there a neat way to do this using map?

A: You zipped the arr1 and arr2 into a single argument
>>> res = []
>>> arr1 = [1, 2, 3]
>>> arr2 = [5, 0, 10]
>>> res = map(lambda x, y: x - 0.5 * y, arr1, arr2)
>>> res
[-1.5, 2.0, -2.0]

A: >>> map(lambda (x, y): x - 0.5 * y, zip(arr1, arr2))
[-1.5, 2.0, -2.0]

Like that you could take a tuple in lambda to fix it but I prefer what DTing suggested.


text:
Q: Logging in via sessions - what is the proper way? I just built a simple login system that uses sessions. When the script verifies that the username and password are both correct, it sets $_SESSION[username] and $_SESSION[role], and then on every page of the site it just checks whether these 2 session variables are set.
Considering that the server handles the sessions, this should be a secure solution, right? Or should I set $_SESSION[md5(password)] as well when logging in, and then check on each page of the site whether all session variables match the user data in the database?

A: Storing the password in your session is a bad idea, it also doesn't add any security to your website, since sessions are managed by the server.
You are however still vulnerable for session hijacking. Take a look at this question to learn more about how to prevent it.

A: Don't store passwords outside your database.  Don't even return passwords from your database.  All you should need to get for session storage is the userID.  store that in the session and use it to lookup role level and name data when required.  If you are concerned about someone hacking the session data and changing the userID number then you can store a hash of the userID number in the session aswell (I recommend using something a bit more secure than a simple md5 though, there are plenty of rainbow tables around for that nowadays)  and compare the hash in the session to the hash of the userID at lookup and verify nothing untoward has been happening.


text:
Q: Error extracting data from a text file, with grep command in bash I generate an output file named "silence.txt" with ffmpeg. When I try to extract lines containing the word "silencedetect", I've got a strange extract.
Here is my original "silence.txt" file :
ffmpeg version 2.6.3 Copyright (c) 2000-2015 the FFmpeg developers
  built with Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/2.6.3 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-libx264 --enable-libmp3lame --enable-libvo-aacenc --enable-libxvid --enable-libfreetype --enable-libtheora --enable-libvorbis --enable-libvpx --enable-librtmp --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libass --enable-ffplay --enable-libspeex --enable-libschroedinger --enable-libfdk-aac --enable-libopus --enable-frei0r --enable-libopenjpeg --disable-decoder=jpeg2000 --extra-cflags='-I/usr/local/Cellar/openjpeg/1.5.1_1/include/openjpeg-1.5 ' --enable-nonfree --enable-vda
  libavutil      54. 20.100 / 54. 20.100
  libavcodec     56. 26.100 / 56. 26.100
  libavformat    56. 25.101 / 56. 25.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 11.102 /  5. 11.102
  libavresample   2.  1.  0 /  2.  1.  0
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'test4.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: mp41avc1
    creation_time   : 2015-06-20 22:41:18
    playback_requirements: QuickTime 6.0 or greater
    playback_requirements-eng: QuickTime 6.0 or greater
    encoder         : vlc 2.2.1 stream output
    encoder-eng     : vlc 2.2.1 stream output
  Duration: 00:05:25.93, start: 0.000000, bitrate: 1761 kb/s
    Stream #0:0(fra): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      creation_time   : 2015-06-20 22:41:18
      handler_name    : SoundHandler
    Stream #0:1(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 720x576 [SAR 64:45 DAR 16:9], 1625 kb/s, 24.96 fps, 25 tbr, 1000k tbn, 50 tbc (default)
    Metadata:
      creation_time   : 2015-06-20 22:41:18
      handler_name    : VideoHandler
Output #0, null, to 'pipe:':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: mp41avc1
    encoder         : Lavf56.25.101
    playback_requirements: QuickTime 6.0 or greater
    playback_requirements-eng: QuickTime 6.0 or greater
    Stream #0:0(eng): Video: rawvideo (I420 / 0x30323449), yuv420p, 720x576 [SAR 64:45 DAR 16:9], q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc (default)
    Metadata:
      creation_time   : 2015-06-20 22:41:18
      handler_name    : VideoHandler
      encoder         : Lavc56.26.100 rawvideo
    Stream #0:1(fra): Audio: pcm_s16le, 48000 Hz, stereo, s16, 1536 kb/s (default)
    Metadata:
      creation_time   : 2015-06-20 22:41:18
      handler_name    : SoundHandler
      encoder         : Lavc56.26.100 pcm_s16le
Stream mapping:
  Stream #0:1 -> #0:0 (h264 (native) -> rawvideo (native))
  Stream #0:0 -> #0:1 (aac (native) -> pcm_s16le (native))
Press [q] to stop, [?] for help
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 993 >= 993
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 5602 >= 5602
frame=  139 fps=0.0 q=0.0 size=N/A time=00:00:07.03 bitrate=N/A
frame=  316 fps=311 q=0.0 size=N/A time=00:00:14.11 bitrate=N/A
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 734723 >= 734723
[silencedetect @ 0x7feb4b40d9e0] silence_start: 15.056
[silencedetect @ 0x7feb4b40d9e0] silence_end: 15.6482 | silence_duration: 0.592229
frame=  488 fps=321 q=0.0 size=N/A time=00:00:21.04 bitrate=N/A
frame=  631 fps=312 q=0.0 size=N/A time=00:00:26.75 bitrate=N/A
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 1476678 >= 1476678
[silencedetect @ 0x7feb4b40d9e0] silence_start: 30.5347
[silencedetect @ 0x7feb4b40d9e0] silence_end: 31.0626 | silence_duration: 0.527958
frame=  839 fps=333 q=0.0 size=N/A time=00:00:34.08 bitrate=N/A
frame=  975 fps=322 q=0.0 size=N/A time=00:00:39.52 bitrate=N/A
frame= 1150 fps=325 q=0.0 size=N/A time=00:00:46.52 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 54.051
[silencedetect @ 0x7feb4b40d9e0] silence_end: 54.5362 | silence_duration: 0.485292
frame= 1366 fps=339 q=0.0 size=N/A time=00:00:55.16 bitrate=N/A
frame= 1505 fps=332 q=0.0 size=N/A time=00:01:00.72 bitrate=N/A
frame= 1645 fps=327 q=0.0 size=N/A time=00:01:06.32 bitrate=N/A
frame= 1780 fps=321 q=0.0 size=N/A time=00:01:11.72 bitrate=N/A
frame= 1957 fps=324 q=0.0 size=N/A time=00:01:18.80 bitrate=N/A
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 4067886 >= 4067886
[silencedetect @ 0x7feb4b40d9e0] silence_start: 84.4542
[silencedetect @ 0x7feb4b40d9e0] silence_end: 85.4725 | silence_duration: 1.01831
frame= 2150 fps=329 q=0.0 size=N/A time=00:01:26.52 bitrate=N/A
frame= 2289 fps=325 q=0.0 size=N/A time=00:01:32.08 bitrate=N/A
frame= 2460 fps=326 q=0.0 size=N/A time=00:01:38.92 bitrate=N/A
frame= 2584 fps=321 q=0.0 size=N/A time=00:01:43.88 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 104.986
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 5058544 >= 5058544
[silencedetect @ 0x7feb4b40d9e0] silence_end: 105.482 | silence_duration: 0.495979
frame= 2763 fps=323 q=0.0 size=N/A time=00:01:51.04 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 115.327
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 5557968 >= 5557968
[silencedetect @ 0x7feb4b40d9e0] silence_end: 115.983 | silence_duration: 0.656042
frame= 2939 fps=324 q=0.0 size=N/A time=00:01:58.08 bitrate=N/A
frame= 3101 fps=324 q=0.0 size=N/A time=00:02:04.56 bitrate=N/A
frame= 3264 fps=324 q=0.0 size=N/A time=00:02:11.08 bitrate=N/A
frame= 3474 fps=329 q=0.0 size=N/A time=00:02:19.48 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 138.695
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 6679615 >= 6679615
[silencedetect @ 0x7feb4b40d9e0] silence_end: 139.415 | silence_duration: 0.719875
frame= 3636 fps=328 q=0.0 size=N/A time=00:02:25.96 bitrate=N/A
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 7178004 >= 7178004
[silencedetect @ 0x7feb4b40d9e0] silence_start: 149.206
[silencedetect @ 0x7feb4b40d9e0] silence_end: 149.883 | silence_duration: 0.677187
frame= 3811 fps=329 q=0.0 size=N/A time=00:02:32.96 bitrate=N/A
frame= 3968 fps=329 q=0.0 size=N/A time=00:02:39.24 bitrate=N/A
frame= 4132 fps=329 q=0.0 size=N/A time=00:02:45.80 bitrate=N/A
frame= 4296 fps=329 q=0.0 size=N/A time=00:02:52.36 bitrate=N/A
frame= 4492 fps=331 q=0.0 size=N/A time=00:03:00.28 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 179.842
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 8652662 >= 8652662
[silencedetect @ 0x7feb4b40d9e0] silence_end: 180.44 | silence_duration: 0.597313
frame= 4655 fps=331 q=0.0 size=N/A time=00:03:06.80 bitrate=N/A
frame= 4821 fps=331 q=0.0 size=N/A time=00:03:13.44 bitrate=N/A
frame= 4985 fps=330 q=0.0 size=N/A time=00:03:20.00 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 205.278
[silencedetect @ 0x7feb4b40d9e0] silence_end: 205.806 | silence_duration: 0.527937
frame= 5167 fps=332 q=0.0 size=N/A time=00:03:27.28 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 206.216
[silencedetect @ 0x7feb4b40d9e0] silence_end: 206.659 | silence_duration: 0.442667
frame= 5339 fps=332 q=0.0 size=N/A time=00:03:34.16 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 215.789
[silencedetect @ 0x7feb4b40d9e0] silence_end: 216.274 | silence_duration: 0.485271
frame= 5539 fps=334 q=0.0 size=N/A time=00:03:42.16 bitrate=N/A
frame= 5708 fps=334 q=0.0 size=N/A time=00:03:48.92 bitrate=N/A
frame= 5870 fps=334 q=0.0 size=N/A time=00:03:55.40 bitrate=N/A
frame= 6051 fps=334 q=0.0 size=N/A time=00:04:02.64 bitrate=N/A
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 11837448 >= 11837448
[silencedetect @ 0x7feb4b40d9e0] silence_start: 246.309
[silencedetect @ 0x7feb4b40d9e0] silence_end: 246.742 | silence_duration: 0.432
frame= 6232 fps=335 q=0.0 size=N/A time=00:04:09.88 bitrate=N/A
frame= 6385 fps=334 q=0.0 size=N/A time=00:04:16.00 bitrate=N/A
frame= 6540 fps=334 q=0.0 size=N/A time=00:04:22.20 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 266.596
[silencedetect @ 0x7feb4b40d9e0] silence_end: 267.209 | silence_duration: 0.613229
frame= 6740 fps=335 q=0.0 size=N/A time=00:04:30.20 bitrate=N/A
frame= 6908 fps=335 q=0.0 size=N/A time=00:04:36.92 bitrate=N/A
frame= 7082 fps=336 q=0.0 size=N/A time=00:04:43.88 bitrate=N/A
frame= 7243 fps=335 q=0.0 size=N/A time=00:04:50.32 bitrate=N/A
frame= 7431 fps=336 q=0.0 size=N/A time=00:04:57.84 bitrate=N/A
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 14273127 >= 14273127
[silencedetect @ 0x7feb4b40d9e0] silence_start: 297.191
[silencedetect @ 0x7feb4b40d9e0] silence_end: 297.677 | silence_duration: 0.485292
frame= 7600 fps=336 q=0.0 size=N/A time=00:05:04.60 bitrate=N/A
frame= 7775 fps=336 q=0.0 size=N/A time=00:05:11.60 bitrate=N/A
[null @ 0x7feb4b810600] Application provided invalid, non monotonically increasing dts to muxer in stream 1: 15255582 >= 15255582
[silencedetect @ 0x7feb4b40d9e0] silence_start: 317.553
[silencedetect @ 0x7feb4b40d9e0] silence_end: 318.144 | silence_duration: 0.591896
frame= 7980 fps=338 q=0.0 size=N/A time=00:05:19.80 bitrate=N/A
frame= 8135 fps=338 q=0.0 Lsize=N/A time=00:05:26.08 bitrate=N/A
video:763kB audio:61036kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown

I used the following grep command...
grep silencedetect silence.txt > extract.txt

...to get this "extract.txt" file :
[silencedetect @ 0x7feb4b40d9e0] silence_start: 15.056
[silencedetect @ 0x7feb4b40d9e0] silence_end: 15.6482 | silence_duration: 0.592229
[silencedetect @ 0x7feb4b40d9e0] silence_start: 30.5347
[silencedetect @ 0x7feb4b40d9e0] silence_end: 31.0626 | silence_duration: 0.527958
frame=  839 fps=333 q=0.0 size=N/A time=00:00:34.08 bitrate=N/A
frame=  975 fps=322 q=0.0 size=N/A time=00:00:39.52 bitrate=N/A
frame= 1150 fps=325 q=0.0 size=N/A time=00:00:46.52 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 54.051
[silencedetect @ 0x7feb4b40d9e0] silence_end: 54.5362 | silence_duration: 0.485292
[silencedetect @ 0x7feb4b40d9e0] silence_start: 84.4542
[silencedetect @ 0x7feb4b40d9e0] silence_end: 85.4725 | silence_duration: 1.01831
frame= 2150 fps=329 q=0.0 size=N/A time=00:01:26.52 bitrate=N/A
frame= 2289 fps=325 q=0.0 size=N/A time=00:01:32.08 bitrate=N/A
frame= 2460 fps=326 q=0.0 size=N/A time=00:01:38.92 bitrate=N/A
frame= 2584 fps=321 q=0.0 size=N/A time=00:01:43.88 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 104.986
[silencedetect @ 0x7feb4b40d9e0] silence_end: 105.482 | silence_duration: 0.495979
frame= 2763 fps=323 q=0.0 size=N/A time=00:01:51.04 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 115.327
[silencedetect @ 0x7feb4b40d9e0] silence_end: 115.983 | silence_duration: 0.656042
frame= 2939 fps=324 q=0.0 size=N/A time=00:01:58.08 bitrate=N/A
frame= 3101 fps=324 q=0.0 size=N/A time=00:02:04.56 bitrate=N/A
frame= 3264 fps=324 q=0.0 size=N/A time=00:02:11.08 bitrate=N/A
frame= 3474 fps=329 q=0.0 size=N/A time=00:02:19.48 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 138.695
[silencedetect @ 0x7feb4b40d9e0] silence_end: 139.415 | silence_duration: 0.719875
[silencedetect @ 0x7feb4b40d9e0] silence_start: 149.206
[silencedetect @ 0x7feb4b40d9e0] silence_end: 149.883 | silence_duration: 0.677187
frame= 3811 fps=329 q=0.0 size=N/A time=00:02:32.96 bitrate=N/A
frame= 3968 fps=329 q=0.0 size=N/A time=00:02:39.24 bitrate=N/A
frame= 4132 fps=329 q=0.0 size=N/A time=00:02:45.80 bitrate=N/A
frame= 4296 fps=329 q=0.0 size=N/A time=00:02:52.36 bitrate=N/A
frame= 4492 fps=331 q=0.0 size=N/A time=00:03:00.28 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 179.842
[silencedetect @ 0x7feb4b40d9e0] silence_end: 180.44 | silence_duration: 0.597313
frame= 4655 fps=331 q=0.0 size=N/A time=00:03:06.80 bitrate=N/A
frame= 4821 fps=331 q=0.0 size=N/A time=00:03:13.44 bitrate=N/A
frame= 4985 fps=330 q=0.0 size=N/A time=00:03:20.00 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 205.278
[silencedetect @ 0x7feb4b40d9e0] silence_end: 205.806 | silence_duration: 0.527937
frame= 5167 fps=332 q=0.0 size=N/A time=00:03:27.28 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 206.216
[silencedetect @ 0x7feb4b40d9e0] silence_end: 206.659 | silence_duration: 0.442667
frame= 5339 fps=332 q=0.0 size=N/A time=00:03:34.16 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 215.789
[silencedetect @ 0x7feb4b40d9e0] silence_end: 216.274 | silence_duration: 0.485271
[silencedetect @ 0x7feb4b40d9e0] silence_start: 246.309
[silencedetect @ 0x7feb4b40d9e0] silence_end: 246.742 | silence_duration: 0.432
frame= 6232 fps=335 q=0.0 size=N/A time=00:04:09.88 bitrate=N/A
frame= 6385 fps=334 q=0.0 size=N/A time=00:04:16.00 bitrate=N/A
frame= 6540 fps=334 q=0.0 size=N/A time=00:04:22.20 bitrate=N/A
[silencedetect @ 0x7feb4b40d9e0] silence_start: 266.596
[silencedetect @ 0x7feb4b40d9e0] silence_end: 267.209 | silence_duration: 0.613229
[silencedetect @ 0x7feb4b40d9e0] silence_start: 297.191
[silencedetect @ 0x7feb4b40d9e0] silence_end: 297.677 | silence_duration: 0.485292
[silencedetect @ 0x7feb4b40d9e0] silence_start: 317.553
[silencedetect @ 0x7feb4b40d9e0] silence_end: 318.144 | silence_duration: 0.591896

The problem is that it gives me more than the line I ask with for instance "frame= 4655 fps=331 q=0.0 size=N/A time=00:03:06.80 bitrate=N/A", etc...
So my question is how to get the lines I want using grep command? Next, if you can help me more, the idea is to get each silence_start and silence_end values to launch another command with ffmpeg and split video in several segments.

A: I'd try
grep silencedetect silence.txt | cat -n -v

or
grep silencedetect silence.txt | less -N -S

or
grep silencedetect silence.txt | hexdump -C

Because what appears to be extraneous lines might be

*

*Just be the end of matched lines wrapped.

*Lines containing control characters that obscure the match (e.g. CR).

For the second part of your question
egrep 'silencedetect.*silence_(start|end)' silence.txt

or the equivalent in awk or perl so that you can capture the times
and issue the ffmpeg commands.

A: I tried it on my Mac and it seems to work as expected. I suspect the grep command you have as be altered either via an alias, or by another one which comes first in the path. Try this:
/usr/bin/grep silence.txt  # On Mac
/bin/grep silence.txt      # On Linux

and see if you get the desired output.

A: If you pass your file through
cat -vet

you can see any special characters. In this case you have carriage-return
(shown as ^M in the output) which is separating lines instead of newline.
Eg:
...  bitrate=N/A    ^M[silencedetect ...

You can translate these to newlines, and use awk to extract the times, eg:
tr '\r' '\n' < silence4.txt |
awk '
/silence_start/{ start = $5 }
/silence_end/ { end = $5; printf "%s to %s\n",start,end }'


text:
Q: How to Use Checkbox in Custom Option Page Using The Setting API Can you please let me know how I can add a checkbox to Setting API in creating Custom Options Page? I am using the following code to add a txt box which is working perfectly but I am totally confused how to add chechbox to the setting API and options. I just tried ti update the input type to checkbox but I am not sure what to put in Value besides when I save the form the check box still appears unchecked!
 add_settings_field('the_option_label',
                    'Display Paragraph:',
                     array($this,'the_option_label_setting'),
                     __FILE__,
                     'hte_main_section');

 public function the_option_label_setting()
    {
       echo "<input name='My_Theme_Options[the_option_label]' type='text' value='{$this->options['the_option_label']}'/>";
    }

Thanks

A: Have a look at: The Complete Guide To The WordPress Settings API (Part 8: Validation, Sanitisation, and Input II):
add_settings_field(
    'Checkbox Element',
    'Checkbox Element',
    'sandbox_checkbox_element_callback',
    'sandbox_theme_input_examples',
    'input_examples_section'
);

function sandbox_checkbox_element_callback() {

    $options = get_option( 'sandbox_theme_input_examples' );

    $html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1"' . checked( 1, $options['checkbox_example'], false ) . '/>';
    $html .= '<label for="checkbox_example">This is an example of a checkbox</label>';

    echo $html;

}

EDIT: Check box fields do not use the value attribute to determine if the box is checked. They use a checked attribute. The $html line above has been edited using the code from later in the article referenced above. Read the articles for details.


text:
Q: WordPress Shortcode output is duplicated on page I created an ACF image field that I want to add in my product description.
I then created a shortcode via this code:
function imgun_shortcode() {
$imgun = get_field('imgun')['sizes']['thumbnail']; // (thumbnail, medium, large, full or custom size)?>

    <img src="<?php echo $imgun;?>">

 <?php
}

add_shortcode('imgun', 'imgun_shortcode');

I then add this shortcode in the extension "block":

I add this page via a shortcode in my product description, the image field is positioned in 2 times and not at the place of the shortcode I do not understand why. My other ACF "text" fields do not have this problem.

Do you have an idea?

A: You can't echo the output from a shortcode.  Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. https://codex.wordpress.org/Shortcode_API
You could either do this...
function imgun_shortcode() {
    ob_start();
    $imgun = get_field( 'imgun' )['sizes']['thumbnail']; // (thumbnail, medium, large, full or custom size)?>

        <img src="<?php echo esc_url( $imgun ); ?>">

 <?php
    return ob_get_clean();
}
add_shortcode( 'imgun', 'imgun_shortcode' );

Or you could do this...
function imgun_shortcode() {
    $imgun = get_field('imgun')['sizes']['thumbnail']; // (thumbnail, medium, large, full or custom size).
    return '

';
}

add_shortcode('imgun', 'imgun_shortcode');


text:
Q: Android 3rd Party Library Integration this is kinda crazy. I already worked often with 3rd party librarys. All I had to do was adding the compile command in the build gradle but in this case its something different. This is the github link of the lib i want to implement:
Link to github
I tried to integrate the files I need manually but i got a amount of errors.
In the README the developer says:
This library is provided as the AAR format. The source jar file won't be downloaded automatically (due to the current Gradle and Android Studio limitation), so javadoc comments are not displayed on IDE.
Can somebody help me how to integrate this the best way.

A: If you have a look below, they have already provided a workaround
buildscript {
    repositories {
        maven { url 'https://raw.github.com/xujiaao/mvn-repository/master/releases' }
    }

    dependencies {
        classpath 'com.github.xujiaao:aarLinkSources:1.0.0'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'aar-link-sources'

android {
    ...
}

dependencies {
    compile ('com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.0@aar'){
        transitive=true
    }
    aarLinkSources 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.0:sources@jar'
}


text:
Q: Is it possible to split XMLGregorianCalendar value? I have the below method,
public static XMLGregorianCalendar stringToXMLGregorianCalendar(String s)
        throws ParseException,
                DatatypeConfigurationException
    {
    XMLGregorianCalendar result = null;
    Date date;
    SimpleDateFormat simpleDateFormat;
    GregorianCalendar gregorianCalendar;
    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                    date = simpleDateFormat.parse(s);
                    gregorianCalendar =
                        (GregorianCalendar)GregorianCalendar.getInstance();
                    gregorianCalendar.setTime(date);
                    result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
                    return result;
    }

It returns me 2014-04-29T13:22:51.000+05:30 but i dont want the timezone part and the milliseconds part as well. Is it possible to split its value and get it like 2014-04-29T13:22:51 . Any suggestion?

A: You have to set the timezone field part as undefined after you assign value to the result.
....
result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
result.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
return result;