text:
Q: Make real async requests for jasmine integration testing I've got an angular app going with some jasmine testing. I recently added a new method to make a query to elastic search within one of my services, it looks like this.
test:
    function(){
        return "Working";
    },

executeSearch:
    function(field, value, size, page_number){
        return service.executeRegExSearch(field, value, size, page_number);
    },

//new method
executeRegExSearch:
    function(field, value, size, page_number){
        //main search body, I know it works because
        //I am getting expected results in the browser
    }

And then in my jasmine tests, I've got something like this.
//initialization stuff
var $httpBackend;
var searchAPI;

beforeEach(inject(function($injector){
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;
    $httpBackend = $injector.get('$httpBackend');
    searchAPI = $injector.get('searchAPI');
}));

it("is loaded properly", function(){
    expect(searchAPI.test() == "Working").toBe(true);  //passes
});

it("can make a request", function(){
    var field = "col_name";
    var value = "bb.*";  //this is matching in my browser/application
    var size = 10;
    var page_number = 1;

    var res;

    searchAPI.executeSearch(field, value, size, page_number).then(function(res){
        res = res;
        alert(JSON.stringify(res));
        done();
    });
    $httpBackend.flush();

});

But when I run, I get the error
Unexpected request: GET http://myserver/index-1/_search?source={"query":{"regexp":{"col_name":{"value":"bb.*"}}}}"&size=10&from=0 No more request expected in http://localhost:8081/js/angularjs/angular-mocks.js (line 1180)

I'm not sure about how to use the mocks, or am even aware that I was doing it. All I want to do is be able to run a suite of tests that make actual calls to my backend to confirm that things are being integrated properly... you know.. integration tests.
Anyone have any advice?

A: I didn't want to do tests with Selenium stuff, so to test my app with real backend calls I used a modified version of angular-mocks
It works just like for unit-tests in Jasmine.
I'm using it with Jasmine 2.0, so a test looks like following :
it(' myTest', function (done) {
    _myService.apiCall()
        .then(function () {
            expect(true).toBeTruthy();
            done()
        });
});

NB: the done is needed because of the async call.

A: If you want to do end to end e2e test for angular applications you definitely must use protractor (was created by the angular team), you could create your tests using jasmine and run them against your application, if you are just using unit testing I think the best way is to mock the httpBackend.
https://github.com/angular/protractor
https://docs.angularjs.org/guide/e2e-testing


text:
Q: Syncing Outlook personal distribution lists to I have a BlackBerry 8330 that is activated on our BES server. Is it possible to have personal distribution lists sync to the BlackBerry?

A: If you mean lists that you have created that are stored in Outlook's Contacts section, then the answer is no.  (At least for me, BB 8900 firmware 4.6, BES 4.1.5, Exchange 2003)

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS RDS Message For gp2 Message : The gp2 burst balance credits for the RDS database instance are low. To resolve this issue, reduce IOPS usage or modify your storage settings to enable higher performance.
I am getting the following message from AWS via email, a bit new to new to RDS any help will be appreciated,  as to how to fix this problem

A: You have two choices if you don't want to limit usage of your db:

*

*Increase size of your storage, as for gp2, the bigger the size the more IOPS you get.

*Change from gp2 to Provisioned IOPS SSD where you can specify fixed IOPS that you require. Provisioned IOPS SSD will be probably also more expensive.


text:
Q: How to fixed stripe payment integration error I have integrate stripe payment on my website; work fine on local machine when check it on server; there is no response from server.
here is live url
http://eglobalsoft.com/stripe-checkout-demo/

A: Your server is returning a 500 error. Check your server's error log, which you can likely access in a location such as /var/log.
Additionally as you are using PHP, you could try adding error_reporting(E_ALL);
ini_set("display_errors", 1); to the top of your script temporarily and see if any errors are displayed in place!


text:
Q: Delete Local File after Sync Aws S3 CLI I have some data inside my Debian server which I want at upload to the AWS S3 by using CLI. So I am succeeded to uploading the data from my server to S3 using this command
aws s3 sync /var/lib/recordings/ s3://mybucket/recordings/ --recursive --acl public-read
Now I want to delete that recordings from my debian server after successfully uploading to S3, How should I do this? I just want to delete the debian server recordings data.
Thanks and Regards


text:
Q: Need to open a jquery modal from a flash movie I have a flash carousel with products. The products are being loaded from a xml file.
When you click on a product in the carousel a dialog modal needs to popup.
im using in the flash geturl function. But what should i put in here? got to be something like
javascript:openFunction()
but this doesnt work, anyone have some ideas?
and what should i write for the openFunction() in my jquery file?.
I dont need the complete script, just a step in the right direction is fine too :)
Thnx

A: The most common is to use the ExternalInterface to call javascript functions:
Actionscript :
ExternalInterface.call('popupMessage','hello');

Javascript :
function popupMessage(msg)
{
    alert(msg);
}

Documentation :
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html
If this doesn't work either you may at least be able to catch the errors and debug it easier than getUrl (you are working in as2, right?).


text:
Q: Why is this character required in matter.js? I am trying to port matter.js to another language. Javascript is not my strongest language.
This function supposedly parses a string containing ordered x y pairs separated by spaces (and optionally commas) into a particular object:
 * @method fromPath
 * @param {string} path
 * @param {body} body
 * @return {vertices} vertices
 */
Vertices.fromPath = function(path, body) {
    var pathPattern = /L?\s*([\-\d\.e]+)[\s,]*([\-\d\.e]+)*/ig,
        points = [];

    path.replace(pathPattern, function(match, x, y) {
        points.push({ x: parseFloat(x), y: parseFloat(y) });
    });

    return Vertices.create(points, body);
};

Later, there is a call to this function where the following string is passed to Vertices.fromPath:
vertices: Vertices.fromPath('L 0 0 L ' + width + ' 0 L ' + width + ' ' + height + ' L 0 ' + height)

Where width and height are numbers. What is the purpose of the L character? I thought the method was supposed to split comma or space separated x,y pairs into numbers so I can't figure out the relevance of the L character.
Can anybody enlighten me?

A: L is a "Line To" command. Please refer to the SVG Path syntax (MDN, spec), which matter.js can accept as a path specification.


text:
Q: Parsing links via epdf library with luatex I'm trying to get links and their destinations from external pdf.
Using TL2018 luatex version 1.07. Documentation points to getAnnots and getLinks but in this version they are undefined.
<Object> = <Page>:getAnnots()
<Links> = <Page>:getLinks(<Catalog>)

errors:
attempt to call method 'getLinks' (a nil value)
attempt to call method 'geAnnots' (a nil value)

I can get a Links object with <PDFDoc>:getLinks() but this supports only
one method getNumLinks.I checked  <Catalog>:getDests() but its returned object is nil.
<Catalog>:findDest(<name>) found destination but I need to know all the names.
Is there any way to find out available methods of objects?
How can I get links and their destinations? Any hints would be very helpful.
local function parse_links (pdf)
    local doc = epdf.open(pdf)
    local cat = doc:getCatalog()
    local anns = cat:findDest("a1.label")
    print (anns:getKindName())               -- output "FitH"
    local pages_num = doc:getNumPages()
    local page_num  = 1
    print ('Pages: ' .. pages_num)

    while page_num <= pages_num do
        local page = cat:getPage(page_num)
        -- local links = page:getLinks(cat)  -- error "attempt to call method 'getLinks' (a nil value)"
        -- local annots = page:getAnnots()  -- error "attempt to call method 'geAnnots' (a nil value)"
        local links = doc:getLinks(page_num)
        local dests = cat:getDests()
        print (dests, dests:isNull())        -- output "Object: 002DE700        true"
        num_links = links:getNumLinks()
        print ("num links:", num_links)

        page_num = page_num + 1
    end
end

Output:
FitH
Pages: 3
Object: 00B3DF20        true
num links:      2
Object: 00B3DF20        true
num links:      3
Object: 00B3DF20        true
num links:      3

A: To access all the links on a page, you can use getAnnotsObject because every link is an annotation.
The undocumented getAnnotsObject is like the decumented getAnnots except that it actually exists. Attention: This is a <Object> containing an array, not the Annots type.
Then you have to parse the Annots manually to determine which annotations are links:
Just look into the Subtype field of the Annotation directory.
If you find an annotation dictionary with subtype Link, you can try to determine the destination.
According to the PDF specification this is either in Dest or in a action dictionary in A. A could also contain other kinds of action, but we ignore these.
Also some destinations might be specified directly without a name, these can not easily be wrapped in a LinkDest object:
local function parse_links (pdf)
  local doc = epdf.open(pdf)
  local cat = doc:getCatalog()

  for page_num=1,doc:getNumPages() do
    print("Analysing page " .. page_num .. ".")
    local page = cat:getPage(page_num)
    local annots = page:getAnnotsObject():getArray()
    if annots then
      for i = 1,annots:getLength() do
        local annot = annots:get(i)
        annot = annot and annot:getDict()
        if annot and annot:lookup"Subtype":getName() == "Link" then
          local dest = annot:lookup"Dest"
          if dest:isNull() then
            local a = annot:lookup"A":getDict()
            if a and a:lookup"S":getName() == "GoTo" then
              dest = a:lookup"D"
            end
          end
          if dest:isString() or dest:isName() then
            dest = cat:findDest(dest:getString() or dest:getName())
          else
            -- In this case we get a direct reference to the destination array
            -- This is *NOT* a LinkDest object, but all the information could be extracted manually
            -- This case will not appear with LaTeX/hyperref documents AFAICT, so we ignore it
          end
          local rect = annot:lookup"Rect":getArray()
          -- Let's print the position on the page and the destination object
          print(rect:get(1):getNum(), rect:get(2):getNum(), rect:get(3):getNum(), rect:get(4):getNum(), dest)
        end
      end
    end
  end
end

As you can see the epdf library is very verbose and it feels like half of the implementation is missing. Also some stuff might not even be possible: For example you can access the Dests list through :getDests, but modern PDF documents contain their destinations in the Name tree aand not in Dests.
There does not seem to be any way to access the name tree directly.
For current versions of LuaTeX, epdf has been replaced by pdfe.
The pdfe library works on a lower level: It does not know anything about annotations, links or the name tree, instead it provides access to the raw PDF objects and you have to interpret them yourself.
For example all links with their destination could be listed using pdfe with
local function lookup_name(tree, name)
  -- A PDF name tree is a tree of multiple arrays with name object pairs,
  -- where each node documents the names it is responsible for using /Limits
  -- For details, read the PDF specification
  local sub = tree.Limits
  if sub then
    if name < sub[1] or name > sub[2] then
      return
    end
  end
  sub = tree.Names
  if sub then
    for i = 1,#sub,2 do
      if sub[i] == name then return sub[i+1] end
    end
    return false
  end
  sub = tree.Kids
  for i = 1,#sub do
    local r = lookup_name(sub[i], name)
    if r ~= nil then
      return r
    end
  end
  return false
end
local dest_to_string_workers = { -- How to print the destination, you could add e.g. FitH
  XYZ = function(p, d)
    return ("page %i at position (%f,%f), zoom factor %s"):format(p, d[3], d[4], d[5] or "none")
  end,
}
local function dest_to_string(d, dest)
  if dest.D then dest = dest.D end
  local page_no
  for i = 1,#d.Pages do
    if tostring(d.Pages[i]) == tostring(dest[1]) then
      page_no = i
      break
    end
  end
  return (dest_to_string_workers[dest[2]] or function()return""end)(page_no, dest)
end
function show_links(filename)
  local d = pdfe.open(filename)
  if not d then error(([[Unable to open "%s".]]):format(filename)) end
  for i=1,#d.Pages do
    local annots = d.Pages[i].Annots
    if annots then -- We have annotations on this page
      for j = 1,#annots do
        local annot = annots[j]
        if annot.Subtype == "Link" then -- We found a link
          local dest = annot.Dest or (annot.A and annot.A.S == "GoTo" and annot.A.D)
          if dest then
            if type(dest) == 'string' then
              local dest_name = dest
              dest = lookup_name(d.Catalog.Names.Dests, dest)
              print("On page " .. i .. " at position (" .. annot.Rect[1] .. "," .. annot.Rect[2] .. ") we found a link with destination \"" .. dest_name .. "\" on " .. dest_to_string(d, dest))
            else
              print("On page " .. i .. " at position (" .. annot.Rect[1] .. "," .. annot.Rect[2] .. ") we found a link with destination on " .. dest_to_string(d, dest))
            end
          else
            print[[This destination is not supported...]]
          end
        end
      end
    end
  end
end

pdfe also allows to iterate over the name tree to list all destination tree:
local function show_name_list(tree)
  local sub = tree.Names
  if sub then
    for i = 1,#sub,2 do
      print(sub[i])
    end
    return
  end
  sub = tree.Kids
  for i = 1,#sub do
    show_name_list(sub[i])
  end
end

function show_dests(filename)
  local d = pdfe.open(filename)
  if not d then error(([[Unable to open "%s".]]):format(filename)) end
  show_name_list(d.Catalog.Names.Dests)
end


text:
Q: Check and compare two strings in PHP I want to check two strings. I want to use the method to check similarity or matching between two strings.
Example:
$str1 = "Samsung Galaxy Note 5";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

I want the result is match, because both strings have keyword "Samsung Galaxy Note 5".
The other example:
$str1 = "Samsung Galaxy Note 4";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

The result is not match, because both string don't have same keyword.
What method can I use?

A: You can try this -
$str1 = "Samsung Galaxy Note 4";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

if(strpos(str_replace(' ', '', $str2), str_replace(' ', '', $str1)) !== 0) {
   echo "Not Matched!";
}

For the examples you have provided it should work.

A: Since you are matching NOTE 5 and NOTE5 so you need to replace space and with the use of strpos
$str1 = "Samsung Galaxy Note 5";
$str1 = str_replace(" ", "", $str1);
$str2 = "Samsung Galaxy Note 5 Black Smartphone";
$str2 = str_replace(" ", "", $str2);

if (strpos($str2,$str1) !== false) {
    echo 'true';
}else{
echo "not found";
}

A: You can use preg_match along with preg_replace like as
$str1 = "Samsung Galaxy Note 5";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

if(preg_match("/(".preg_replace('/[\h]/','',$str1).")/i",preg_replace('/[\h]/','',$str2))!==false){
    echo "match";
}

Demo


text:
Q: Nginx does not Read Symbolic Linked Files? Nginx was installed from Repository. Initially, it was working fine. However, I un linked default conf file in sites-enabled and added new virtual hosts file in sites-available folder and linked it using ln -s. nginx -t passes after restarting but it does not listen on port 80.
However if i copy the actual virtual hosts file in sites-enabled folder. After restart,it works once again. On a side note, same happens for default virtual hosts file. Here is the out put of ls -lR for nginx diretory
.:
total 60
drwxr-xr-x 2 root root 4096 Nov  3 03:38 conf.d
-rw-r--r-- 1 root root  898 Nov  3 03:06 fastcgi_params
-rw-r--r-- 1 root root 2258 Nov  3 03:06 koi-utf
-rw-r--r-- 1 root root 1805 Nov  3 03:06 koi-win
-rw-r--r-- 1 root root 2085 Nov  3 03:06 mime.types
-rw-r--r-- 1 root root 5287 Nov  3 03:06 naxsi_core.rules
-rw-r--r-- 1 root root  287 Nov  3 03:06 naxsi.rules
-rw-r--r-- 1 root root 2123 Dec 30 17:16 nginx.conf
-rw-r--r-- 1 root root  131 Nov  3 03:06 proxy_params
-rw-r--r-- 1 root root  465 Nov  3 03:06 scgi_params
drwxr-xr-x 2 root root 4096 Dec 30 17:29 sites-available
drwxr-xr-x 2 root root 4096 Dec 30 17:29 sites-enabled
-rw-r--r-- 1 root root  532 Nov  3 03:06 uwsgi_params
-rw-r--r-- 1 root root 3071 Nov  3 03:06 win-utf

./conf.d:
total 0

./sites-available:
total 4
-rw-r--r-- 1 root root 102 Dec 30 17:29 default

./sites-enabled:
total 0
lrwxrwxrwx 1 root root 23 Dec 30 17:29 default -> sites-available/default

A: Permissions are fine, but symbolic link is broken -- it should point to ../sites-available/default


text:
Q: Is the ubuntu system I am using distributed free of charge I installed my system with this file:
ubuntu-14.04.3-desktop-amd64.iso

md5:

md5sum ubuntu-14.04.3-desktop-amd64.iso

cab6dd5ee6d649ed1b24e807c877c0ae

I just want to make sure that this file is distributed free of charge, and is not a pirated copy. This might be a dummy question, but I am not familiar with the new system yet.

A: Ubuntu is a free software. It is perfectly legal to redistribute it or/and modify it. You can this question for more info: Under what license is Ubuntu? Can it be legally modified and distributed?
So when you see Ubuntu, even modified one, it is probably legal.Such popular distros as Linux Mint,Elementary OS,etc. would not exist if Ubuntu licensing didn't allow modifying and distributing it freely.

A: Yes, according to here, this file is the official version.
source
Ubuntu Hashes


text:
Q: How to switch between ports to connect to browsers ,in spec file using protractor I am automating custom browser, that is inside desktop application using protractor. Initially I have to connect to some port, and then later I have to switch to a custom browser running at another port in between script (spec file).
For initial connection I am mentioning the port in capabilities:
capabilities : {
        'browserName': 'chrome',
        'chromeOptions': {'debuggerAddress': '127.0.0.1:8088'}

    },

Is there a way to switch the port in between the script execution?

A: Whoohaa, such a cool usage of protractor!
Try to use protractor wrapDriver() (http://www.protractortest.org/#/api?view=ProtractorBrowser.wrapDriver) function, and pass WebDriver instance of selenium-webdriver js (http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html)
You can try to use thru constructor:
new WebDriver(session, executor, opt_flow)

or with static functions:
.attachToSession()

http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html#WebDriver.attachToSession
.createSession()

http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html#WebDriver.createSession
Notice, that createSession() accepts capabilities as second parameter.
Hope that some of this might help

A: Got solution to this, by adding browser.restart() in my spec file.


text:
Q: Improving SQL Exists scalability Say we have two tables, TEST and TEST_CHILDS in the following way:
creat TABLE TEST(id1 number PRIMARY KEY, word VARCHAR(50),numero number);
creat TABLE TEST_CHILD (id2 number references test(id), word2 VARCHAR(50));

CREATE INDEX TEST_IDX ON TEST_CHILD(word2);
CREATE INDEX TEST_JOIN_IDX ON TEST_CHILD(id);

insert into TEST SELECT ROWNUM,U1.USERNAME||U2.TABLE_NAME, LENGTH(U1.USERNAME) FROM ALL_USERS U1,ALL_TABLES U2;
INSERT INTO TEST_CHILD SELECT MOD(ROWNUM,15000)+1,U1.USER_ID||U2.TABLE_NAME FROM ALL_USERS U1,ALL_TABLES U2;

We would like to query to get rows from TEST table that satisfy some criteria in the child table, so we go for:
SELECT /*+FIRST_ROWS(10)*/* FROM TEST T WHERE EXISTS (SELECT NULL FROM TEST_CHILD TC WHERE word2 like 'string%' AND TC.id = T.id ) AND ROWNUM < 10;

We always want just the first 10 results, not any more at all. Therefore, we would like to get the same response time to read 10 results whether table has 10 matching values or 1,000,000; since it could get 10 distinct results from the child table and get the values on the parent table (or at least that is the plan that we would like). But when checking the actual execution plan we see:
-----------------------------------------------------------------------------------------------
| Id  | Operation                       | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                |             |     1 |    54 |     5  (20)| 00:00:01 |
|*  1 |  COUNT STOPKEY                  |             |       |       |            |          |
|   2 |   NESTED LOOPS                  |             |       |       |            |          |
|   3 |    NESTED LOOPS                 |             |     1 |    54 |     5  (20)| 00:00:01 |
|   4 |     SORT UNIQUE                 |             |     1 |    23 |     3   (0)| 00:00:01 |
|   5 |      TABLE ACCESS BY INDEX ROWID| TEST_CHILD  |     1 |    23 |     3   (0)| 00:00:01 |
|*  6 |       INDEX RANGE SCAN          | TEST_IDX    |     1 |       |     2   (0)| 00:00:01 |
|*  7 |     INDEX UNIQUE SCAN           | SYS_C005145 |     1 |       |     0   (0)| 00:00:01 |
|   8 |    TABLE ACCESS BY INDEX ROWID  | TEST        |     1 |    31 |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(ROWNUM<10)
   6 - access("WORD2" LIKE 'string%')
       filter("WORD2" LIKE 'string%')
   7 - access("TC"."ID"="T"."ID")

SORT UNIQUE under the STOPKEY, what afaik means that it is reading all results from the child table, making the distinct to finally select only the first 10, making the query not as scalable as we would like it to be.
Is there any mistake in my example?
Is it possible to improve this execution plan so it scales better?

A: The SORT UNIQUE is going to find and sort all of the records from TEST_CHILD that matched 'string%' - it is NOT going to read all results from child table.  Your logic requires this.  IF you only picked the first 10 rows from TEST_CHILD that matched 'string%', and those 10 rows all had the same ID, then your final results from TEST would only have 1 row.
Anyway, your performance should be fine as long as 'string%' matches a relatively low number of rows in TEST_CHILD.  IF your situation is such that 'string%' often matches a HUGE record count on TEST_CHILD, there's not much you can do to make the SQL more performant given the current tables.  In such a case, if this is a mission-critical SQL, with performance tied to your annual bonus, there's probably some fancy footwork you could do with MATERIALIZED VIEWs to, e.g. pre-compute 10 TEST rows for high-cardinality WORD2 values in TEST_CHILD.
One final thought - a "risky" solution, but one which should work if you don't have thousands of TEST_CHILD rows matching the same TEST row, would be the following:
SELECT  *
FROM    TEST
WHERE   ID1 IN
            (SELECT ID2
             FROM   TEST_CHILD
             WHERE  word2 like 'string%'
                    AND ROWNUM < 1000)
         AND ROWNUM <10;

You can adjust 1000 up or down, of course, but if it's too low, you risk finding less than 10 distinct ID values, which would give you final results with less than 10 rows.


text:
Q: system of equations which share only one variable? I am trying to build a website that runs on this equation. I know how to solve the equation for two variables that are in both equations but I have no idea how to solve for three variables where the two equations only have one in common. I am only in pre-algebra so if you can answer in a way that i can understand that would be great.
Here is the system of equations:
$10,000=mx+5000$
$y=1000x$

A: Two equations for three unknowns should ring a bell... And indeed one cannot deduce $(x,y,m)$ from the two equations in your post. The most one can do is to write two of them as explicit functions of the third one.


text:
Q: how to verify basis type in quarkus? like Long,String how to verify  basis type in quarkus? like Long,String...
springboot can verify method parameter what is basis type.
now i transfer the code from springboot to quarkus,unit test can't pass.
    public NotifyTemplateDTO getOne(@Valid @NotNull(message = "模板id不能为空") Long templateId) {
        NotifyTemplateDO template = notifyTemplateDomainService.get(templateId);
        return CONVERTER.convertNotifyTemplateDO(template);
    }


text:
Q: Can the MMS's content type hub be on a different farm to the MMS? We have a farm in North America and another in South America. We need a local MMS in each farm but would like to share a single content type hub across these services - we'd like to point the MMS on both farms to the North American content type hub.

Will that work? I assume it depends on whether the service talks to the hub via the object model or via web services.

A: I have learned that the answer is "no".
Some colleagues went through an architecture validation exercise with Microsoft and although I didn't hear a direct answer to this, they proposed that we should replicate the hub. It therefore seems safe to assume that simply pointing to a remote hub is not possible.


text:
Q: How to Download a video from a web site using termial for example how to download a video from a youtube provided the Url of the video.

A: use youtube-dl youtubeUrl. To install youtube-dl.
Run these commands
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install youtube-dl


text:
Q: Increasing Differentiable Functions Suppose that $I$ is an interval and $f : I \rightarrow \mathbb{R}$ is a differentiable function. If $f'(x) > 0$ for all $x \in I$, show that $f$ is strictly increasing.
I have so far that if $f'(x) > 0$, then $f(x) > f(c)$ where $c$ is some constant. Is this a correct starting place and if so where do I go from here?

A: If $x,y\in I$ and $x<y$, then apply the mean value theorem to $f$ on the interval $[x,y]$. You discover that there's a $c\in (x,y)$ such that:
$0<f'(c)=\frac{f(y)-f(x)}{y-x}$.
What does that tell you about $f(y)-f(x)$?
I hope this helps!


text:
Q: How to make API request using PHP cURL? My request requires a token to make API requests. Here is the cURL code they provide as example:
curl -v -L https://api.artsy.net/api/artists/andy-warhol -H 'X-Xapp-Token:myToken'

My code:
$postdata = array();
$postdata['client_id'] = 'myId';
$postdata['client_secret'] = 'myClient';
$postdata['xapp_token'] = 'myToken';
$cc =  curl_init();
curl_setopt($cc,CURLOPT_POST,1);
curl_setopt($cc,CURLOPT_RETURNTRANSFER,1);
curl_setopt($cc,CURLOPT_URL,"https://api.artsy.net/api/artists/andy-warhol");
curl_setopt($cc,CURLOPT_POSTFIELDS,$postdata);
$result = curl_exec($cc);
echo $result;

This should result in a JSON object that looks like:
{
  "id": "4d8b92b34eb68a1b2c0003f4",
  "slug": "andy-warhol",
  "created_at": "2010-08-23T14:15:30+00:00",
  "updated_at": "2017-08-25T17:25:51+00:00",
  "name": "Andy Warhol",
  "sortable_name": "Warhol Andy",
  "gender": "male",
  "birthday": "1928",
  "hometown": "Pittsburgh, Pennsylvania",
  "location": "New York, New York",
  "nationality": "American",
//...

However it results in this result:
{:type=>"other_error", :message=>"405 Not Allowed", "X-Frame-Options"=>"DENY", "X-Robots-Tag"=>"noindex", "Allow"=>"OPTIONS, GET, HEAD"}

I'm not too familiar with cURL so I've hit a wall with trying to translate the example code they provide. Any help would be deeply appreciated!

A: You're using POST
curl_setopt($cc,CURLOPT_POST,1);

and it looks like the API doesn't allow POST.

..."Allow"=>"OPTIONS, GET, HEAD"

You can check this Q&A for an example of how to use GET instead.


text:
Q: Ruby Tkinter scrollbar doesn't appear in its frame and allows scrolling past canvas bounds. What am I doing wrong? I've been fighting with Tkinter in ruby to try and get a proper scrollable frame working.
I've had the most success with this tutorial: https://www.youtube.com/watch?v=VmlgrrXAqb4
I have translated what he does in the video into ruby and it "works", but only kinda. When I run the application I get a window similar to his with all of the buttons, but the scrollbar handle doesn't appear in it's frame and I can scroll past the content of the frame in both directions.
I'm trying to build an application that has a heavy use of scrolling, but I can't get past this. I am posting as a last resort. I've tried most of the examples I can find online, but I keep getting unexpected behavior. It is worth noting that I am on MacOS in case someone tries the code on Windows or Linux and it works for some reason.
require 'tk'
require 'tkextlib/tkimg'

win = TkRoot.new
win.geometry "500x500"
win.resizable false,false

wrapper1 = Tk::Tile::Frame.new win
wrapper2 = Tk::Tile::Frame.new win

mycanvas = TkCanvas.new wrapper1
mycanvas.pack :side => "left", :fill => "both", :expand => "yes"

yscrollbar = TkScrollbar.new :parent => wrapper1, :command => Proc.new {|*args| mycanvas.yview *args}
yscrollbar.pack :side => "left", :fill => "y"

mycanvas.configure(:yscrollcommand => Proc.new {|*args| yscrollbar.set *args })
mycanvas.bind "<Configure>", Proc.new {mycanvas.scrollregion = mycanvas.bbox("all")}

myframe = Tk::Tile::Frame.new mycanvas
TkcWindow.new(mycanvas, 0, 0, :anchor => "nw", :window => myframe)

wrapper1.pack :fill => "both", :expand => "yes", :padx => 10, :pady => 10
wrapper2.pack :fill => "both", :expand => "yes", :padx => 10, :pady => 10

for i in 0..50
    button = TkButton.new(myframe)
    button.text = "Button " + i.to_s
    button.pack
end

Tk.mainloop

A: I figured out what was wrong.
#The line of code below where the Configure event is bound needs to be:
mycanvas.bind "Configure" #...
#instead of:
mycanvas.bind "<Configure>" #...


text:
Q: Is there any way to programmatically set the camera focus off an iOS device to infinity? I am creating an app that locks the camera focus for video recording purposes. I want to lock the focus to infinity without having the user manually adjust the focus. Is this possible? Thanks!

A: Sadly, no. You can set the camera into focus-locked mode, as Artem said; put into autofocus mode (focus, then lock), or continuous autofocus mode, but you can't give the camera a specific distance to focus at.
The best I've been able to come up with (for exposure and white balance control, which are similarly limited) is to have the user point the camera at an appropriate scene (in your case, something far away) and have him/her push a lock button.
Details on the capture device API, such as it is:
https://developer.apple.com/library/mac/#documentation/AVFoundation/Reference/AVCaptureDevice_Class/Reference/Reference.html

A: That is the way to disable focus, it locks it for all the time:
// Find a suitable capture device
    AVCaptureDevice *cameraDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    // SETUP FOCUS MODE
    if ([cameraDevice lockForConfiguration:nil]) {

        [cameraDevice setFocusMode:AVCaptureFocusModeLocked];

        [cameraDevice unlockForConfiguration];
    }
    else{
        NSLog(@"error while configuring focusMode");
    }

What do you mean "lock the focus to infinity"?

A: AVCaptureDevice has function setFocusModeLockedWithLensPosition:completionHandler:
You can use it to set 1.0 in order to achieve "infinity" distance
    func focusTo(value : Float) {
      if let device = captureDevice {
      if(device.lockForConfiguration(nil)) {
         device.setFocusModeLockedWithLensPosition(value, completionHandler: { (time) -> Void in
            //
        })
        device.unlockForConfiguration()
      }
    }

Update:
According to Apple documentation 1.0 does not represent focus at infinity.


text:
Q: Query in Access with a "contains" between columns I need a query in Access with the following:
If Column2, Cell("B1") = "A1" and
Column 1, Cell ("A1")= "B1_A1_DTTROB"
THEN Col3 NEEDS TO SHOW "Contains" or "Correct"
Thanks

A: As @Minty said - Access understands fields and records. It hasn't got a clue about cells, columns or rows.  You can, if you must, think of a field as a column and a record as a row - but you will more than likely get corrected every time you say it out loud.
Saying that, I can see you're trying to compare your first field with the second field on the same record and if it's a match return the text.
SELECT  IIF(Column2 = [Column 1],"Contains","Correct") AS Col3
FROM    MyTableName

This query will return a table containing a single field called Col3.  It will have the same number of records as your original table as it compares the two fields on each record.
To return other fields from your table just add them to the Select clause separated by a comma:
Select Column2, [Column 1], ....
Field names can contain spaces, but you have to wrap the field name in square brackets [].  You can also use reserved words in fields, but again wrap them in square brackets [Name].... using spaces or reserved words can causes problems further down the line, so easier to use Column1 rather than [Column 1] and strName rather than Name.
In the field properties in the table design view there is a Caption property that lets you give the field an alias name, but I find this confusing when writing queries in SQL View - Design view will show the correct field name.


text:
Q: Not able to locate "sdk" in android studio and subsequently, not able to open the software I am new to Android and thought that android studio is the place to begin with.
I downloaded the IDE from here and installed it.
The installation is completed but, I cannot open the program. In the beginning, it said "SDK not found" and incidentally, there was no file or folder named SDK in the Android folder that I just downloaded.
Now, the software is visible in the start menu but won't open.

A: Head to Control Panel -> Uninstall a Program, and then Uninstall Android-Studio.
Now Install Android-Studio again from setup.
This time while installing Android Studio don't cancel any download that will held in the installation process of Android-Studio!


text:
Q: nagios core external agent using python scripting I have a bash script for performing the passive checks i.e., external agent/application. I tried converting the bash script into python but when I execute the file I don't see any kind of responses on my nagios core interface regarding my passive check result.
import os
import datetime

CommandFile='/usr/local/nagios/var/rw/nagios.cmd'
datetime = datetime.datetime.now()
os.stat(CommandFile)
f = open(CommandFile, 'w')
f.write("/bin/echo " + str(datetime) + " PROCESS_SERVICE_CHECK_RESULT;compute-1;python dummy;0;I am dummy python")
f.close()

my bash script code is:
#!/bin/sh

# Write a command to the Nagios command file to cause
# it to process a service check result

echocmd="/bin/echo"

CommandFile="/usr/local/nagios/var/rw/nagios.cmd"

# get the current date/time in seconds since UNIX epoch
datetime=`date +%s`

# create the command line to add to the command file
cmdline="[$datetime] PROCESS_SERVICE_CHECK_RESULT;host-name;dummy bash;0;I am dummy bash"

# append the command to the end of the command file
`$echocmd $cmdline >> $CommandFile`

A: Changed my code, now its working perfectly fine. I can see the response in the Nagios interface.
import time
import sys

HOSTNAME = "compute-1"

service = "python dummy"

return_code = "0"

text = "python dummy is working .....I am python dummy"

timestamp = int(time.time())

nagios_cmd = open("/usr/local/nagios/var/rw/nagios.cmd", "w")

nagios_cmd.write("[{timestamp}] PROCESS_SERVICE_CHECK_RESULT;{hostname};{service};{return_code};{text}\n".format

                    (timestamp = timestamp,

                     hostname = HOSTNAME,

                     service = service,

                     return_code = return_code,

                     text = text))

nagios_cmd.close()


text:
Q: Как получить часть HTML кода другой страницы на том же домене с помощью JavaScript? Как получить часть HTML кода другой страницы на том же домене с помощью JavaScript?
A: Можно использовать jquery load()
$('#result').load('your_page.html #Your_container_with_html');

A: $.get('url.html',function(data){
    alert(data);
});

Вместо алерта - обрабатываем полученную страницу, доставая необходимую ЧАСТь.


text:
Q: Create a loop using SCSS to change background images with CSS3 animate? I have created the beginning of a CSS3 animation as shown below. I have tried to use @for and @each within SCSS to create a loop which will increment the %'s and also the number of each background image. My knowledge of advanced SCSS like this is poor, so everything I have tried has been nonsense and trial and error based on reading the SCSS docs - and really not worth posting here.
Is it possible to use SCSS in this way to save having to type each keyframe?
.perimeterAnim {
    background-image: url('../img/perimeters/PerimeterFountains00.png');
    -webkit-animation: perimeter 5s infinite;
    -moz-animation: perimeter 5s infinite;
    -o-animation: perimeter 5s infinite;
    -ms-animation: perimeter 5s infinite;
    animation: perimeter 5s infinite;
}

@-webkit-keyframes perimeter {
    0% {
        background-image: url('../img/perimeters/PerimeterFountains00.png');
    }

    2.564102564102564% {
        background-image: url('../img/perimeters/PerimeterFountains01.png');
    }

    5.128205128205128% {
        background-image: url('../img/perimeters/PerimeterFountains02.png');
    }

    7.692307692307692% {
        background-image: url('../img/perimeters/PerimeterFountains03.png');
    }

Edit: The reason for creating the animation in this way is that the image is very large, so a sprite sheet is out of the question.

A: Sass can only increment (or decrement) @for loops by 1.  If you want a different interval, you need to use math to get there:
@-webkit-keyframes perimeter {
  @for $i from 0 through 39 {
    #{$i * 2.564102564102564%} {
      background-image: url('../img/perimeters/PerimeterFountains#{$i}.png');
    }
  }
}

Related:  Rounding numbers in Sass and adjusting the amount of decimals


text:
Q: incomprehensible C macro I bumped into the following macro while analyzing a code.
#define __COMMAND_HANDLER(name, extra ...) int name(struct command_invocation *cmd, ## extra)

The function name is passed as an argument to __COMMAND_HANDLER however there is no definition of this function anywhere else in the code. The cmd argument's type (command_invocation) is defined. Basically I couldn't understand the functionality of this macro because I couldn't find the definition of the function name. Is name some kind of pre-defined function in standard C library ? Does this macro definition make sense if name is not defined ?

A: Durning preprocession, the preprocessor will replace all occurrences of __COMMAND_HANDLER(name, extra ...) macro to its body with replacing each occurences of name and extra... inside its body to the tokens you specified.
This means in this case that whatever you enter for name argument, it will be a function name, and extra... will be its additional parameters beside the first one (struct command_invocation *cmd).
For example the following line:
__COMMAND_HANDLER(foo, int param) {
    /* definition */
}

after preprocessing will be:
int foo(struct command_invocation *cmd, int param) {
    /* definition */
}

One important thing has to be clarified: the ## before extra and named variable argument (using extra... instead of ...) are not the part of the c standard but they are GNU extensions. The effect of ## after comma lets you specify nothing for variable argument. Compiling your example with GCC (with -pedantic flag) when it's used as follows, you will see warning messages:
/* The following example will print the following messages:
 * warning: ISO C does not permit named variadic macros [-Wvariadic-macros]
 * warning: ISO C99 requires at least one argument for the "..." in a variadic
 * macro
 */
__COMMAND_HANDLER(bar);

Normally the ## is the operator for token concatenation, i.e. two tokens on either side of a ## operator are combined into a single one. For example:
#include <stdio.h>
#define FOO(name, number) void name##number()

FOO(bar, 1) { puts("I'm first."); }
FOO(bar, 2) { puts("I'm second."); }

int main() {
    bar1();
    bar2();
    return 0;
}

A: This is a macro and name is a parameter.
You use it like this:
__COMMAND_HANDLER(hello, char* world)

During pre-process stage, it would transform your code into:
int hello(struct command_invocation *cmd, char *world);

In this case, name is passed as hello, and extra = char* world.
If you don't pass anything for extra, ## will discard the comma.

A: In short: the macro is creating the function with the name specified by the parameter name and optional additional arguments specified by extra ....
Note: names starting with a double underscore is implementation reserved and shouldn't be used.
The macro is variadic.
The second argument to the macro extra ... provides a name to use instead of the default __VA_ARGS__ inside the function declaration macro. This is a GNU extension
## extra is another GNU extension that specifies to the preprocessor that if the second argument to the macro __COMMAND_HANDLER is omitted, the preceding comma can be removed and the function called without it.
The reason you can't find the declaration of name is because it's a parameter to your macro! The macro itself is declaring a new function with whatever is in name, and the arguments provided, with the default first argument of struct command_invocation *cmd.
Here are some examples:
Calling:
__COMMAND_HANDLER(cmd,char * w)
Would result in the function declaration of:
int cmd(struct command_invocation *cmd,char * w)
Whereas calling:
__COMMAND_HANDLER(cmd2)
would result in the function declaration of:
int cmd2(struct command_invocation *cmd)


text:
Q: How to create a stateful Groovy Binding for interactive Session I am building a groovy-based tool and as an add-in i'd like to provide an interactive command-line, I have this partially working but the binding doesn't keep state between GroovyShell.evaluate() calls, I've gone through the groovy documentation and they have an example using a class called InteractiveGroovyShell, which is not available on version 2.0.x.
Is there a way to configure normal groovy shell to achieve this functionality?
Here is a simplified version of how I'm creating the groovy shell right now:
CompilerConfiguration config = new CompilerConfiguration();
Binding binding = new Binding();
shell = new GroovyShell(binding, config);
shell.evaluate("def a = 20");
shell.evaluate("println a"); //this throws an exception telling the variable does not exist

A: shell.evaluate("def a = 20");

Instead of def a = 20 you need just a = 20. Each evaluate call parses and compiles a separate script, and declarations (whether with def or with an explicit type such as int a = 20) become local variables in that specific script and do not store anything in the binding. Without the def you have a plain assignment to an otherwise undeclared variable, which will go into the binding and so be visible to later evaluate calls.

A: You should reuse the same binding for different shells. The binding itself will maintain the state:
import org.codehaus.groovy.control.CompilerConfiguration

def binding = new Binding()
def shell = new GroovyShell(binding)

shell.evaluate("a = 5")
assert binding.variables == [a:5]

shell.evaluate("println a; b = 6")
assert binding.variables == [a:5, b:6]

def shell2 = new GroovyShell(binding)

// even in a new shell the binding keep the state
shell2.evaluate("c = 7")
assert binding.variables == [a:5, b:6, c:7]

Worked in groovy 2.0.5


text:
Q: How to make a mp3 player play songs when i click on them from my  tag? I made a list of songs in my  tags, and I want the mp3 player to be universal for every song, so when i click on one song(link) from the list it would be played on the player, and it wouldn't have to refresh the page, or open it in another tab to play the song?
Here is my HTML:
<audio preload="auto" src="#"></audio>

Song #1
Song #2
Song #3
Song #4

A: Since you tagged the question with jQuery, you can simply use that to set the src attribute of your audio element.  Something like this:
$('a').on('click', function () {
    $('audio').prop('src', $(this).data('src'));
});


text:
Q: How to change where GVim looks for syntax.vim on windows When I try to use :syntax on I get the following error:
E484: Can't open file C:\Program Files (x86)\Vim\vim82\gvim.exe\syntax\snytax.vim
When I explore the directory, I find that there is a syntax.vim at the directory:
C:\Program Files (x86)\Vim\vim82\syntax\syntax.vim
How do I get gVim to recognize that this is where it should look for the syntax files?
I am using windows 10.

A: I had the same problem.
You have to set $VIMRUNTIME  (Not this variable, as Stun Brick points out in the comment below.) as an environment variable.
If you are using Windows 10, search on your compuer, "Edit the system environment variables" and you can set it.

A: User Tomoki helped me find the answer.
In windows 10, type environment variables in the search bar
click Edit the system environment variables
Under the Advanced tab, click Environment variables
Under the System variables section, find the vim or Vim system variable, and edit the Variable value so that it says C:\Program Files (x86)\Vim\vim82\gvim.exe
it should not have been pointing at the executable in the first place, which is why it could not find a syntax at C:\Program Files (x86)\Vim\vim82\gvim.exe\syntax\snytax.vim


text:
Q: Como criar um ListView com items random? (Android) Estou com problemas no meu ListView. Eu gostaria que ele exibisse seus items de forma random, mas que os items não se repetissem, como está acontecendo agora.
Aqui está o código:
public class AdapterConteudo  extends BaseAdapter{

private Context ctx;
private List<Cardapio> listaCardapio;

public AdapterConteudo(Context ctx, List<Cardapio> listaCardapio){
    this.ctx = ctx;
    this.listaCardapio = listaCardapio;
}

@Override
public int getCount(){
    return listaCardapio.size();
}

@Override
public Object getItem(int posicao){
    return listaCardapio.get(posicao);
}

@Override
public long getItemId(int posicao){
    return listaCardapio.get(posicao).getId();
}

@Override
public View getView(int posicao, View convertView, ViewGroup parent){
    Cardapio cardapio = listaCardapio.get(new Random().nextInt(listaCardapio.get(posicao).getId()));

    View view = LayoutInflater.from(ctx).inflate(R.layout.fragment_lista, null);
    TextView item = (TextView) view.findViewById(R.id.textViewItem);
    TextView conteudo = (TextView) view.findViewById(R.id.textViewConteudo);
    TextView telefone = (TextView) view.findViewById(R.id.textViewTelefone);

    item.setText(cardapio.getItem());
    conteudo.setText(cardapio.getConteudo());
    telefone.setText(cardapio.getTelefone());

    return view;
}

}
No Fragment onde está a listView:
private void preencheLista(){

        listaCardapio = new ArrayList<Cardapio>();

        Cardapio cardapio1 = new Cardapio(1, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio1);

        Cardapio cardapio2 = new Cardapio(2, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio2);

        Cardapio cardapio3 = new Cardapio(3, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio3);

        Cardapio cardapio4 = new Cardapio(4, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio4);

        Cardapio cardapio5 = new Cardapio(5, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio5);

        Cardapio cardapio6 = new Cardapio(6, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio6);

        Cardapio cardapio7 = new Cardapio(7, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio7);

        Cardapio cardapio8 = new Cardapio(8, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio8);

    }

A: Em vez de tentar fazer isso no Adapter faça-o diretamente sobre o ArrayList.
Após preencher a lista use o método shuffle da classe Collections.
Collections.shuffle(listaCardapio);

Os itens de listaCardapio serão "baralhados" de forma aleatória.


text:
Q: Update variable when data in databases has changed Here I have three variables, and the variables are filled by the data from the database and displays it to the screen using the label.
But when I change the data in the database, the variables are not automatically changed.
What would I try to do is create a variable to change automatically when the data in the database changes.
But I do not know how to do because I'm new at this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace vendingInterface
{
    public partial class Form1 : Form
    {

        public MySqlConnection conn;
        private string server;
        private string database;
        private string uid;
        private string password;
        private string produk11;
        private string produk22;
        private string produk33;

        public Form1()
        {
            bacadatabase();
            InitializeComponent();
            info();

        }

I display it using the label
        private void info()
        {
            lbl_produk1.Text = "Jumlah Produk 1 = " + produk11 + " Buah";
            lbl_produk2.Text = "Jumlah Produk 2 = " + produk22 + " Buah";
            lbl_produk3.Text = "Jumlah Produk 3 = " + produk33 + " Buah";
        }

I took the data in the database
        public void bacadatabase()
        {
            string sql = "select *from vanding_machine";
            server = "localhost";
            database = "db_s2u";
            uid = "root";
            password = "";

            string connString = "SERVER=" + server + ";" + " DATABASE=" + database + ";" + " UID=" + uid + ";" + " PASSWORD=" + password + ";";  //conek SQL
            MySqlConnection conn = new MySqlConnection(connString);

            conn.Open();
            //MessageBox.Show("Koneksi Berhasil");

            //command
            MySqlCommand cmd = new MySqlCommand(sql, conn);

            //reader
            MySqlDataReader dataReader = cmd.ExecuteReader();

            while (dataReader.Read())
            {
                produk11 = dataReader["produk1"].ToString();
                produk22 = dataReader["produk2"].ToString();
                produk33 = dataReader["produk3"].ToString();
            }

            dataReader.Close();
            conn.Close();

        }

When I click the button the data will be entered into the database and variables in the show will be updated automatically
        private void button9_Click(object sender, EventArgs e)
        {

            server = "localhost";
            database = "db_s2u";
            uid = "root";
            password = "";

            string connString = "SERVER=" + server + ";" + " DATABASE=" + database + ";" + " UID=" + uid + ";" + " PASSWORD=" + password + ";";  //conek SQL
            MySqlConnection conn = new MySqlConnection(connString);

            conn.Open();
            //MessageBox.Show("Koneksi Berhasil");

            string sql = "update vanding_machine set produk1 = @produk111;";

            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.Parameters.Add(new MySqlParameter("@produk111", tb_produk1.Text));

            //close data reader
            cmd.ExecuteNonQuery();

            //close connection
            conn.Close();

        }

        private void button8_Click(object sender, EventArgs e)
        {

        }

        private void button7_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click_1(object sender, EventArgs e)
        {

        }
    }
}

A: You will have to create timer to check whether was data changed or not in application. The database will not point up the application about any change


text:
Q: Populating a drop down in EXT js grid depending on value of selection of another drop down header: "Root",
 sortable: true,
 renderer: cat_id1,
 dataIndex: 'parent_id',
 width: 90,
        editor: new Ext.form.ComboBox({
      typeAhead: true,
      triggerAction: 'all',
      transform:'cat_id1',
      lazyRender:true,
      listClass: 'x-combo-list-small'
 })

can I make the value of "renderer:" and "transform:" dynamic or dependent on the selection of another dropdown selection?

A: The easiest way to do this, is to actually render a whole new combo box whenever the answer in the first combo box is changed, using the store containing the answers you want.  So add a select listener to your first box, which grabs the second box, hides it, destroys it, and then adds a new box using the store of answers you want the new second box to have available.
Make sure to call destroy() on the combo box you're getting rid of, so you don't have a bunch of hidden elements clogging up the document.


text:
Q: Cloning data partition to other Android devices We have several devices running Android in an industrial environment.
We think about completely setting up one device and then copy the whole /data directory to the other devices. The expected benefit is to configure things like wireless settings and install the required apps and updates only once on one device and somehow bring this onto the other devices.
Is this a good idea?
I am not sure if there is device specific information stored in data such as a device ID or something else that we would mess up with our idea.
Besides this what about 'uid's that are responsible to represent app permissions? Do you expect problems if our apps are not installed onto a device but simply come by a copied /data partition?
Is something specific established on a device after the first boot when /data is created and filled, that should not be replaced with something else?
Would it be better to copy only selected directories or even files? This is much more effort but ok if there is no other way...
I would appreciate any input about what can go wrong and what we should consider.


text:
Q: Calculate minimum distance between two lines and two arc I have two problem first how to calculate the minimum distance between two lines.
For details I am attaching an image here.

In the image describe the line with start and end point. I already have start and end point for both lines but I am not getting any idea how to calculate the minimum distance between two lines.
Another problem is that how to calculate the minimum distance between two arc.
I am attaching another image here

For arc I have the start, end and center point also I have the start and end angle.
This link has lot more things - Shortest distance between a point and a line segment
I also got help from above link.

This is the another issue what I am facing now. In this scenario how to calculate minimum distance between two arc?
Any idea how solve this two issue?

A: Let the two segments be AB and CD. Their parametric equations can be written
P = A + u AB, Q = C + v CD, with u, v in [0, 1].

You want to minimize the (squared) distance
PQ² = (CA + u AB - v CD)², under the given constraints,

and you can cancel the first derivatives with
(CA + u AB - v CD).AB = 0
(CA + u AB - v CD).CD = 0

After resolution of the 2x2 system you get a pair (u, v). If both variables fall in [0,1], there is an intersection and the distance is 0.
Otherwise, clamp u and/or v to the relevant bound of range [0, 1] and compute the corresponding distance.
If one variable was clamped, the distance was between an endpoint and a segment; if two were clamped, it's between two endpoints.

A similar approach can be adopted for the arcs (using trigonometric functions), and lead to an optimization problem under linear constraints. Less easy to handle as the objective function is non-linear, though.

We can also proceed as follows:

*

*find the points that make the shortest distance between the whole circles. There are two cases:

*

*the circles intersect, at two places

*the circles do not intersect; the shortest distance is between the intersection points of the two circles and the center line.

*then check if these points do belong to the arcs by angle comparison. If yes, you are done (the distance is either 0 or the distance between the intersections).

*otherwise, consider the endpoints of an arc against the other circle. The closest point is the intersection of the circle with the line through the point and the center. If the intersection belongs to the arc, keep the distance between the point and the intersection. Repeat this for all four combinations endpoint/arc and keep the closest pair.

*If no valid pair was found, keep the shortest endpoint/endpoint distance.
The picture shows the distances that can be considered. In green, endpoint/circle; in red, endpoint/endpoint. In this case, the circle/circle distance is zero as they intersect. A distance can be considered if it joins two points inside the arcs.

A: Distance between two intersecting lines is 0
 Otherwise, what you want is to calculate the endpoint of one of the line to the other one.
If you want to calculate the distance between a point and a line :

It is the length of the line segment which joins the point to the line and is perpendicular to the line.

For arcs I think arcs are part of circles, distance between them is the distance between their center points and minus their radiuses.
Probably you can find more here: Calculate the minimum distance between two given circular arcs
Example


text:
Q: Specifying a task-dependency in a rake rule I have a rake rule transforming files that also needs to depend on the :environment (meta-)task. However, I keep running into errors. The rule looks as follows:
task :parse => SOURCE_FILES.ext(".md")
rule ".md" => ->(f){ source_for_md(f) } do |t|
  `do stuff ${t.source}`
end

I have tried rule ".md" => [:environment, ->(f){ source_for_md(f)] }
which results in the error:
Don't know how to handle rule dependent: :environment

I have also tried to define the depency upstream in the :parse task:
task parse: [:environment, SOURCE_FILES.ext(".md")]

... with no luck.

A: A workaround that is only slightly inelegant: moving the dependency a further level up in the chain works:
task do_parse: [:environment, :parse]
task :parse => SOURCE_FILES.ext(".md")
rule ".md" => ->(f){ source_for_md(f) } do |t|
  `do stuff ${t.source}`
end


text:
Q: Run function when APN is received I was able to integrate APNS in my app. Now I want to handle the notifications when the user taps it or when the user receives a notification while using the app. I use the code below to show an alert dialog when a notification is received:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        // display the userInfo
        if let notification = userInfo["aps"] as? NSDictionary,
            let alert = notification["alert"] as? String {
            var alertCtrl = UIAlertController(title: "Time Entry", message: alert as String, preferredStyle: UIAlertControllerStyle.Alert)
            alertCtrl.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            // Find the presented VC...
            var presentedVC = self.window?.rootViewController
            while (presentedVC!.presentedViewController != nil)  {
                presentedVC = presentedVC!.presentedViewController
            }
            presentedVC!.presentViewController(alertCtrl, animated: true, completion: nil)

            // call the completion handler
            // -- pass in NoData, since no new data was fetched from the server.
            completionHandler(UIBackgroundFetchResult.NoData)
        }
    }

Is it possible to run a function in my MainViewController instead of showing the dialog? I tried calling my function MainViewController.refreshData() but it always gives me a nil.

A: Yes it is possible by Posting and adding observer.
Use NSNotificationCenter to make it.
I am posting in Objective C code, try to convert to Swift.
@implementation AppDelegate

static void displayStatusChanged(CFNotificationCenterRef center, void *observer,
                             CFStringRef name, const void *object,
                             CFDictionaryRef userInfo) {
if (name == CFSTR("com.apple.springboard.lockcomplete")) {
    [[NSUserDefaults standardUserDefaults] setBool:YES
                                            forKey:@"kDisplayStatusLocked"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
CFNotificationCenterAddObserver(
                                CFNotificationCenterGetDarwinNotifyCenter(), NULL, displayStatusChanged,
                                CFSTR("com.apple.springboard.lockcomplete"), NULL,
                                CFNotificationSuspensionBehaviorDeliverImmediately);
 return YES;
 }

then paste this code in didRecieveRemoteNotification
 [[NSNotificationCenter defaultCenter]postNotificationName:@"TestNotification" object:self];

And in your MainViewController
 - (void)viewDidLoad {

 [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiveTestNotification:)
                                             name:@"TestNotification"
                                           object:nil];

  }

 - (void) receiveTestNotification:(NSNotification *) notification
 {

if ([[notification name] isEqualToString:@"TestNotification"]) {
    NSLog (@"Successfully received the test notification!");

   //perform your operations
   [self refreshData];

  }
 }

A: func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // display the userInfo
    if let notification = userInfo["aps"] as? NSDictionary,
        let alert = notification["alert"] as? String {
            var alertCtrl = UIAlertController(title: "Time Entry", message: alert as String, preferredStyle: UIAlertControllerStyle.Alert)
            alertCtrl.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:  { (UIAlertAction) -> Void in
                            //Your Function call when you click Ok Button.
                          self.YourFunc()
                            }))
            // Find the presented VC...
            var presentedVC = self.window?.rootViewController
            while (presentedVC!.presentedViewController != nil)  {
                presentedVC = presentedVC!.presentedViewController
            }
            presentedVC!.presentViewController(alertCtrl, animated: true, completion: nil)

            // call the completion handler
            // -- pass in NoData, since no new data was fetched from the server.
            completionHandler(UIBackgroundFetchResult.NoData)
    }
}


text:
Q: Is anaconda for Fedora different from anaconda for python? Having only recently learned about conda and anaconda for Python, I was thoroughly confused because the "anaconda" I am familiar with is the Fedora installer by that name.  (This is also what Wikipedia describes.) But upon closer inspection, it turns out that the latter is written in Python.  Are these anacondas actually the same thing after all?

A: No, they are unrelated.  It's quite confusing because they both involve managing software installations.  Since you're already familiar with Anaconda the Fedora installer (and because I don't know it as well), let me explain the different parts of Continuum's Anaconda / conda.
Anaconda is a Python distribution.  The standard Python distribution (CPython) normally installs Python to something like C:\PythonXX on Windows or /usr/local/bin/pythonXX for the executable + /usr/local/lib/pythonXX for site-packages on Linux, whereas the Anaconda distribution normally installs to C:\Anaconda or C:\users\uname\Anaconda or to ~/Anaconda on Linux.  The Anaconda distribution includes hundreds of additional packages that are not standard python distribution.  It is focused on the scientific community, and most of the packages are analytic based.  It has picked version of each of them that do not create dependency conflicts while still being fairly up-to-date.
Miniconda is an alternative Python distribution.  It does not contain the hundreds of scientific packages that Anaconda has and contains a minimal set of packages on top of the normal Python distribution.
Anaconda Server (formally Binstar) lets you host packages + dependency management.  To a degree, it is an alternative to PyPi, but it also integrates with PyPi.  It can host PyPi style packages and Conda style packages.
All three come with conda.  conda is a package management system.  It is both an installer that can replace pip (although similar to Anaconda Server and PyPi, it can integrate with pip).  It is also a tool to create virtual environments similar to vitualenv.  conda is particularly good at cross-platform installations (if you think installing packages on Windows sucks, conda makes it suck less).  It is also particularly good at extension libraries, which are Python packages that contain non-Python code such as C, C++, LLVM, or Fortran.  conda claims that they are language agnostic, but it's almost exclusively used for managing Python packages.


text:
Q: ECB, CFB, OFB cipher modes in Openssl I know that when I use CBC mode with Openssl, I can give as an input which is a multiple of a block size. But how about other modes? ECB, CFB, OFB? I saw a doc but its not all clear to me. Should I call them in a loop?
Lets say, ECB. It encrypts 64 bits at a time. So a pseudocode would look like this (should look like this)?
int len = 512, c = 0;
unsigned char in[len], out[len];
while(c < len)
{
  Aes_ecb_encrypt(in+c, out+c, &enckey, AES_ENCRYPT);
  c += 8;
}

But with the above code it doesnt encrpyt good. When I change c += 8; into c += 16; its ok then. Whats is good way of doing this? I mean, we all know that 8x8 = 64 bits so this should be correct, but it isnt, the encryption/decryption is working only when I have c += 16;.
What about other cipher modes?
Sample for ECB mode (notice, that the question is also about other modes too;)):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#include <openssl/rand.h>

// a simple hex-print routine. could be modified to print 16 bytes-per-line
static void hex_print(const void* pv, size_t len)
{
    const unsigned char * p = (const unsigned char*)pv;
    if (NULL == pv)
        printf("NULL");
    else
    {
        size_t i = 0;
        for (; i<len;++i)
            printf("%02X ", *p++);
    }
    printf("\n");
}

// main entrypoint
int main(int argc, char **argv)
{
    int keylength = 256;
    unsigned char aes_key[keylength/8];
    memset(aes_key, 0, keylength/8);
    if (!RAND_bytes(aes_key, keylength/8))
        exit(-1);

    size_t inputslength = 0;
    printf("Give an input's length:\n");
    scanf("%lu", &inputslength);

    /* generate input with a given length */
    unsigned char aes_input[inputslength];
    memset(aes_input, 'X', inputslength);

    // buffers for encryption and decryption
    const size_t encslength = ((inputslength + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;

    unsigned char paddedinput[encslength];
    memset(paddedinput, 0, encslength);
    memcpy(paddedinput, aes_input, inputslength);

    unsigned char enc_out[encslength];
    unsigned char dec_out[inputslength];
    memset(enc_out, 0, sizeof(enc_out));
    memset(dec_out, 0, sizeof(dec_out));

    AES_KEY enc_key, dec_key;
    AES_set_encrypt_key(aes_key, keylength, &enc_key);

    long c = 0;
    while(c < encslength)
    {
        AES_ecb_encrypt(paddedinput+c, enc_out+c, &enc_key, AES_ENCRYPT);
        c += 8;
    }

    c = 0;
    AES_set_decrypt_key(aes_key, keylength, &dec_key);
    while(c < encslength)
    {
        AES_ecb_encrypt(enc_out+c, dec_out+c, &dec_key, AES_DECRYPT);
        c += 8;
    }

    printf("original:\t");
    hex_print(aes_input, sizeof(aes_input));

    printf("encrypt:\t");
    hex_print(enc_out, sizeof(enc_out));

    printf("decrypt:\t");
    hex_print(dec_out, sizeof(dec_out));

    return 0;
}

A:
Lets say, ECB. It encrypts 64 bits at a time

AES is a 128-bit block cipher. It encrypts/decrypts 128-bit at a time. It is a standard. AES_encrypt/AES_decrypt block expects 128 bits or 16 bytes length of the input and output data.

But with the above code it doesnt encrpyt good. When I change c += 8; into c += 16; its ok then. Whats is good way of doing this? I mean, we all know that 8x8 = 64 bits so this should be correct, but it isnt, the encryption/decryption is working only when I have c += 16;

That is why it is working fine on

c+=16

Apart from this, there are few problems in your code.
unsigned char enc_out[encslength];

Please keep the size of dec_out of encslength since you are decrypting encslength bytes not inputslength in your code.
unsigned char dec_out[encslength];
memset(enc_out, 0, sizeof(enc_out));
memset(dec_out, 0, sizeof(dec_out));

AES_KEY enc_key, dec_key;
AES_set_encrypt_key(aes_key, keylength, &enc_key);

In this section, increase c by 16 as AES is 128 block cipher.
long c = 0;
while(c < encslength)
{
    AES_ecb_encrypt(paddedinput+c, enc_out+c, &enc_key, AES_ENCRYPT);
    c += 16;
}

Similar change here:
c = 0;
AES_set_decrypt_key(aes_key, keylength, &dec_key);
while(c < encslength)
{
    AES_ecb_encrypt(enc_out+c, dec_out+c, &dec_key, AES_DECRYPT);
    c += 16;
}

About other modes:

*

*CFB mode
There is no need to pad the data. Use AES_cfb128_encrypt and initialization vector (IV) along with key.

For encryption:
AES_cfb128_encrypt (paddedinput, enc_out, inputlength, &enc_key, iv, AES_ENCRYPT);

For decryption:
AES_cfb128_decrypt (enc_out, dec_out, inputlength, &enc_key, iv, AES_ENCRYPT);

*

*OFB mode
Similarly on OFB mode, there is no need to pad the data. Use AES_ofb128_encrypt and IV along with key.

For encryption:
//Initialize num to 0.
num = 0;
AES_ofb128_encrypt (paddedinput, enc_out, inputlength, &enc_key, iv, &num);

For decryption:
num = 0;
AES_ofb128_encrypt (enc_out, dec_out, inputlength, &enc_key, iv, &num);

You may need to tweak the code some bit as per your need.
Please read more about block cipher mode of operation.


text:
Q: Discrepancy in simplification For the below mentioned
simplify[(1/x)*(t/x)^(N-1)*(1-(t/x)^N)^(-2)]

and
simplify[(1/x)*(t/x)^(N-1)*(-1+(t/x)^N)^(-2)]

I am getting the same output which is
(t/x)^N/(t (-1 + (t/x)^N)^2)

How is it possible? Kindly help.
Thanks in advance.

A: The only terms that are different in your "code" are
(1-(t/x)^N)^(-2)

and
(-1+(t/x)^N)^(-2)

and these are identical too. It's because the parentheses that are raised to the power of -2 are negatives of each other. A power of something to -2 is equal to 1 over the power the same thing to 2 and, as you certainly know, x^2 is equal to (-x)^2.
Proof: just perform the exponentiation. Let B = (t/x)^N (so that I don't need to write it over and over again). The first expression:
(1 - B)^(-2) = 1 / ((1 - B)^2) = 1 / (1 - 2*B + B^2)

And the second expression:
(-1 + B)^(-2) = (B - 1)^(-2) = 1 / ((B - 1)^2) = 1 / (B^2 - 2*B + 1) = ...
... = 1 / (1 - 2*B + B^2)

Proved.
If we were to substitute back for the B then the result is
1 / ((t/x)^2N - 2*(t/x)^N + 1)


text:
Q: Defining the correct types for an HOC injecting a prop So I have a set of base components that have its prop types set as:
type SomeProps = {
  // ... arbitrary prop types
  theme: {
    wrapper: string,
    button: string,
    // these are also kind of arbitrary
  }
}

Now I have an HOC that's going to inject the theme prop so users of this newly created component don't/shouldn't have to pass a theme prop. Testing showed that the below code won't work though (the merging of types of the same field)...
type A = { foo: number };
type B = A & { foo?: number };
const x: B = { foo: 2 };

Regardless, I wrote the HOC but I'm not sure the flow types work in the scenario I described. As an additional requirement, the newly created component can still be passed a theme prop which should be merged with the injected theme. Here's the code for the HOC:
// @flow

import withProps from 'recompose/withProps';
import setDisplayName from 'recompose/setDisplayName';
import wrapDisplayName from 'recompose/wrapDisplayName';
import classnames from 'classnames';

type FunctionComponent<P> = (props: P) => ?React$Element<any>;
type ClassComponent<D, P, S> = Class<React$Component<D, P, S>>;
type Component<P> = FunctionComponent<P> | ClassComponent<any, P, any>;

type ThemeType = { [className: string]: string };
type OptionalThemePropType = {
    [prop: string]: mixed,
    theme?: ThemeType
}

function mergeTheme<T, U: T & { theme: ThemeType }>(
    injectedTheme: ThemeType
): (BaseComponent: Component<T>) => Component<U> {
    return BaseComponent => {
        const Themed: Component<U> = withProps((ownProps: OptionalThemePropType) => {
            let theme: ThemeType = injectedTheme;
            if (ownProps && ownProps.theme) {
                const ownTheme: ThemeType = ownProps.theme;
                theme = Object
                    .keys(ownTheme)
                    .filter((key: string) => !!injectedTheme[key])
                    .reduce(
                        (accum: ThemeType, key: string) => {
                            accum[key] = classnames(ownTheme[key], injectedTheme[key]);
                            return accum;
                        },
                        { ...ownTheme, ...injectedTheme }
                    );
            }
            return { theme };
        })(BaseComponent);
        setDisplayName(wrapDisplayName(BaseComponent, 'themed'))(Themed);
        return Themed;
    };
}

Is this correct?

A: The idea is to use $Diff flowtype helper to remove injected props from Component Props.
example for withNavigation of @expo/ex-navigation package
declare type FunctionComponent<P> = (props: P) => ?React$Element<any>;
  declare type ClassComponent<D, P, S> = Class<React$Component<D, P, S>>;
  declare type Component<P> = FunctionComponent<P> | ClassComponent<any, P, any>;

  declare type ExNavProps = {
    navigation: NavigationContext,
    navigator: ExNavigatorContext,
  };

  declare type WithNavigationOptions = {
    withRef: boolean,
  };

  // withNavigation should add navigator and navigation as defaultprops for WrappedComponent
  declare function withNavigation<DefaultProps, Props, State>(
    WrappedComponent: ClassComponent<DefaultProps, Props, State>,
    options?: WithNavigationOptions,
  ): ClassComponent<DefaultProps & ExNavProps, $Diff<Props, ExNavProps>, State>;

however you still need to define ExNavProps in your component, like this
type Props = {
   firstProp: string,
} & ExNavProps
export default class MyComponent extends React<void, Props, void>


text:
Q: Is it possible to automate running PDFelement using command line I am currently trying to parse some PDF with tables to formats like csv/excel so that I can then programmatically process them with python, etc.
I have found that PDFElement does a good job converting PDF to excel, but have only been doing conversions manually via the GUI.
I'm hoping to be able to automate the process of batch converting PDF to excel using a program and was wondering if anyone had any ideas on how to best achieve this.
My initial instinct was to try to run the program .exe from command prompt using some arguments. However, based on their support page, it doesn't look like this functionality is supported.
Is there a way around this? Or should I resort to some sort of automated clicking script? Thanks!

A: PDFelement cannot be used from the command line. Their software provides a GUI and there is no way to automate tasks. I've spoken with their support.


text:
Q: reject in promise undefined I tried below function use co and javascript promise test, the fulfill will success return but reject not, and catch error undefined. and the flow can't continue. why?
Error:
> at GeneratorFunctionPrototype.next (native)
    at onFulfilled (/Users/../project/app/node_modules/co/index.js:65:19)
    at runMicrotasksCallback (node.js:337:7)
    at process._tickDomainCallback (node.js:381:11)

Code:
domain.run(function() {

  var testPromise = function() {
    return new Promise(function (fulfill, reject){
      //reject('error');
      reject(new Error('message'));
    });
  };

co(function *() {
  var d = yield testPromise();
  console.log(d);
  res.send('fin');
}).catch(onerror);
function onerror(error) { console.error(error.stack); }

});
domain.on('error', function(error) { console.error(error); });

A:
catch error undefined

No. It catches the error 'error', the value you rejected with. Of course, it's not really an Error but a string, and as such it does not have a .stack property - that's why it logs undefined. Fix your code by doing
reject(new Error('…'));

See also Should a Promise.reject message be wrapped in Error?

the flow can't continue. why?

Well, because you've got an error, and thrown exceptions do have this behaviour. You'll also want to send a response in your error handler!
co(function *() {
  …
}).catch(function onerror(error) {
  console.error(error.stack);
  res.send('err');
});

Or if you intend to continue the flow at the call, put the .catch handler right there:
co(function *() {
  yield testPromise().then(function(d) {
    console.log(d);
  }).catch(function(error) {
    console.error(error.stack);
  });
  res.send('fin');
});

Alternatively, wrap your promise call in a try-catch:
co(function *() {
  try {
    var d = yield testPromise();
    console.log(d);
  } catch(error) {
    console.error(error.stack);
  }
  res.send('fin');
});


text:
Q: How can I load templates from an html file into my Angular app? I have a bunch of template html files in my Angular app, and it was getting inefficient for distribution. So I checked out grunt-angular-combine to put all my templates into one single HTML file. So now it looks like
<script type="text/ng-template" id="modules/home/profile.template.html">
<div id="template-seasons">
    This is empty! But it's the proifle template
</div></script>
<script type="text/ng-template" id="modules/home/score.template.html">
...

The trouble is, how can I "import" all of these individual templates into my app so I can refer to them from my ui-router states, ng-includess, etc..

A: Load the result file, Then you can just use it's path in templateUrl in ui-router config.
templateUrl: "modules/home/profile.template.html"

Or if you neet to use $compile somewhere, use $templateCache.get("modules/home/profile.template.html") to get the template.


text:
Q: remove newlines from a .txt file with a simple cmd command? How do I remove newlines from a .txt file with a simple cmd command?

*

*This will erase the file:
findstr "{\r\n}" %USERPROFILE%\Desktop\tt\t.txt %USERPROFILE%\Desktop\tt\t.txt > t.txt

*Whereas this will add useless information:
findstr "." %USERPROFILE%\Desktop\tt\t.txt %USERPROFILE%\Desktop\tt\t.txt > t.txt

A: You are specifying the input file twice, so you are doubling your data.
If the aim is to delete empty lines, you were not far from the right command:
findstr "." "%USERPROFILE%\Desktop\tt\t.txt" > t.txt

Just ensure that your current folder is not %USERPROFILE%\Desktop\tt,
or you will overwrite the input file.
You may alternatively specify a full path for the output file.
The following post might also help:
How to remove newlines from a text file with batch or PowerShell.
To totally remove all newlines, I used the following script:
@echo off
setlocal EnableDelayedExpansion
set row=
for /f %%x in (test.txt) do set "row=!row!%%x"
echo %row% >newfile.txt
echo %row%

Here is how running the above script works:

A: One thing you could do is to get some unix/linux/*nix commands on there.. and use the standard 'tr' command, examples all over the internet. tr -d '\r\n' < input.txt > output.txt would remove the \r character and the \n character and any \r\n sequence (or any \n\r sequence though there shouldn't be any such thing).  Cygwin has some commands.  The xxd command is good too, to see what is really in a file. Cygwin includes that.
Since an answer shows that it's possible to use findstr, that's ok..  but if I found myself having to do something really confusing looking with the cmd.exe 'for' command then i'd look for *nix style commands it'd probably have something simpler than 'for' for it, e.g. 'tr'!
Note- Some e.g. commenter ItWasn'tMe, aren't aware that you can use cygwin commands in cmd.exe outside of a cygwin shell, but you can.  Though nevertheless, the OP has commented to suggest that he is looking for a native solution, but OP should've put that in his question.

A: FOR /F "tokens=*" %i IN (t.txt) DO @echo|set /p="%i" >> t2.txt

*

*FOR /F "tokens=*" %i IN (t.txt) .. will process the txt file line by line, %i being the whole line.

*@echo|set /p="%i" will echo the line without a new line (source).

*>> t2.txt will copy all output to a new file (efectively concatenating all lines into one since all newline characters were removed, as OP asked).

Result:
C:\Users\me\Documents>type t.txt
some line
SOME OTHER LINE
>
lolwut
Some Person
SOMEBUSINESS

SomeBusiness after an empty line
Users
Line with "quotes"
Wow look at this weird characters ÎøÎñÎ[{()}]ÖοÎö neat!
C:\Users\me\Documents>FOR /F "tokens=*" %i in (t.txt) do @echo|set /p="%i" >> t2.txt

C:\Users\me\Documents>type t2.txt
some lineSOME OTHER LINE>lolwutSome PersonSOMEBUSINESSSomeBusiness after an empty lineUsersLine with "quotes"Wow look at this weird characters ÎøÎñÎ[{()}]ÖοÎö neat!
C:\Users\me\Documents>

If you need the output file to be the same as the input file, you can then move (or copy or type > or...) t2.txt over t.txt. Example of how that would look in a single .cmd file:
@ECHO OFF
FOR /F "tokens=*" %i IN (t.txt) DO @echo|set /p="%i" >> t2.txt
MOVE /Y t2.txt t.txt

A:

*

*For powershell you can use:

((Get-Content ${Env:USERPROFILE}'\Desktop\tt\t.txt' -Raw) -replace "(?m)^\s*`r`n",'').trim() | Set-Content .\t.txt

*

*Whereas this will add useless information:

*findstr "." %USERPROFILE%\Desktop\tt\t.txt %USERPROFILE%\Desktop\tt\t.txt> t.txt

In fact, this command above can do this job, but, I'm considering that this not work, and I
also suppose that your user name have space ("compound name" == "Elisha Habinsky")

*

*that make your command became look like this layout:

findstr "." c:\Users\Elisha Habinsky\Desktop\tt\t.txt c:\Users\Elisha Habinsky\Desktop\tt\t.txt

1) Use quote in "%USERPROFILE%\Desktop\tt\t.txt" and %USERPROFILE%\Desktop\tt\t.txt"> t.txt
2) Don't need to use quote in regex:"."
3) This . means any character, also space, tabs.
4) if your file have lines with only tabs in there? The lines blank is not 100% blank, so, these lines are saving to file output too!
5) Considering use a t.tmp file to do this job.
6) My suggest to you is use the code for bat in last lines code here, just copy these lines and save as file.cmd, the bat will remove all tabs in any line blank or not.

>.\t.txt findstr . "%USERPROFILE%\Desktop\tt\t.txt"

rem :: or ::

findstr . "%USERPROFILE%\Desktop\tt\t.txt"  >.\t.txt

For lines where have only tabs:

*

*For command line(one line):

for /f "delims= " %T in ('robocopy /L . . /njh /njs')do set "_tab=%T" && findstr . .\t.txt >"%temp%\t.tmp" && >.\t.txt (for /f tokens^=* %i in ('type "%temp%\t.tmp"^|find /v "%_tab%"')do @echo/%i) && del /q "%temp%\t.tmp"

*

*For batch/cmd files:

@echo off && SetLocal EnableDelayedExpansion

for /f "delims= " %%T in ('robocopy /L . . /njh /njs')do set "_tab=%%T"
findstr . "%USERPROFILE%\Desktop\tt\t.txt" >"%temp%\t.tmp"

>.\t.txt (for /f tokens^=* %%i in ('type "%temp%\t.tmp"
')do set "_line=%%~i"&& cmd /v/c echo/!_line:%_tab%=!
) && >nul del /q "%temp%\t.tmp" && endlocal
.\t.txt && exit /b || goto :eof

Sorry my limited English


text:
Q: html code not running on notepad++ I tried running my HTML code via notepad++ on chrome but does not seem to work. This code is basically an animation of circles revolving around a bigger circle. For some odd reason, my code does not run the animation. Here is my code:

I cannot find any mistakes that I might have made. Please help. Thank you.

A: You didn't add jQuery reference in your file.
Add this in your  tag

A: It's simple. You are trying to use jQuery ($) without including jQuery library.
Please insert this

Before this:


text:
Q: Use prepared statements in MySQL-PHP-Code I'm a newbie so my question is maybe a little bit strange. I'm trying to use prepared statements for the following code:
<?php
require_once(__DIR__.'/config.php');

$value = $_POST["value"];
$ort = $_GET["ort"];

$stmt = $pdo->prepare('SELECT * FROM Suchmaschine WHERE firma = :firma AND ort = :ort');
$stmt->execute(array('firma' => $value, 'ort' => $value));

foreach ($stmt as $row) {
   echo "".$row['firma']."
";
}
?>

I tried some ways, but it doesn't work.

A: Firstly this line you are missing : and a wrong variable name, should be:
$stmt->execute(array(':firma' => $value, ':ort' => $ort));

Then you are not fetching the results.
$results = $stmt->fetchAll();

foreach( $results as $row ) {
        echo "".$row['firma']."
";
}

A: The issue is on the followling line:
$stmt->execute(array('firma' => $value, 'ort' => $value));

should be changed to:
$stmt->execute(array(':firma' => $value, ':ort' => $value));

Please note the addition of the colons prepending the strings passed as the keys to the array passed to the execute statement.
See here: http://php.net/manual/en/pdostatement.execute.php


text:
Q: Python string invalid syntax This is my code:
onedata = str("& "C:\Program Files\Windows Media Player\wmplayer.exe"")
print (onedata)

Im trying to run it but it says:
    onedata = str("& "C:\Program Files\test.test")
                      ^
SyntaxError: invalid syntax

A: You closed the string before you should have. I'm guessing you want the literal " in the string, so you need this:
onedata = str("& \"C:\\Program Files\\test.test")

\" makes a literal " character. and \\ makes a literal \ character. This is so that the compiler doesn't get confused between the literal meaning of a character and its syntactic meaning.

A: You can escape the second double quotes with \. Or you can use single outer quotes:
onedata = str('& "C:\Program Files\Windows Media Player\wmplayer.exe"')

print(onedata)

& "C:\Program Files\Windows Media Player\wmplayer.exe"

A: put a back lash behind the second ( " ) to solve it

A: The answers above are excellent, but they don't mention another solution that I personally find easier than using escape characters. In Python, you can use single quotes ('') or double quotes ("") for a string, and if you want to use a double quote inside the string, you can use single quotes to denote your string. Example:
'This is " a string'

is the same as:
"This is \" a string"


text:
Q: Science fiction story or novel: humans do not leave apartments, communicate via two-way television, "McCloo" mentioned I once read a concise, printed description of a science fiction short story or novel. I never read this short story or novel.
The story's central idea: a future civilization in which humans lived in presumably windowless apartments, never left said apartments, and communicated with each other via closed-circuit two-way television. Within this society, the word "McCloo" was spoken. The people did not say "McLuhan." My guess is that the short story was written after 1964.

A: Posting a partially matching answer, "The Machine Stops" by E.M. Forster matches other than being too old (1909) and not mentioning "McCloo".

The story describes a world in which most of the human population has lost the ability to live on the surface of the Earth. Each individual now lives in isolation below ground in a standard room, with all bodily and spiritual needs met by the omnipotent, global Machine. Travel is permitted, but is unpopular and rarely necessary. Communication is made via a kind of instant messaging/video conferencing machine with which people conduct their only activity: the sharing of ideas and what passes for knowledge.
The two main characters, Vashti and her son Kuno, live on opposite sides of the world. Vashti is content with her life, which, like most inhabitants of the world, she spends producing and endlessly discussing secondhand 'ideas'. Kuno, however, is a sensualist and a rebel. He persuades a reluctant Vashti to endure the journey (and the resultant unwelcome personal interaction) to his room. There, he tells her of his disenchantment with the sanitised, mechanical world.
He confides to her that he has visited the surface of the Earth without permission, and that he saw other humans living outside the world of the Machine. However, the Machine recaptures him, and he is threatened with 'Homelessness': expulsion from the underground environment and presumed death. Vashti, however, dismisses her son's concerns as dangerous madness and returns to her part of the world.
As time passes, and Vashti continues the routine of her daily life, there are two important developments. First, the life support apparatus required to visit the outer world is abolished. Most welcome this development, as they are skeptical and fearful of first-hand experience and of those who desire it. Secondly, "Technopoly", a kind of religion, is re-established, in which the Machine is the object of worship. People forget that humans created the Machine, and treat it as a mystical entity whose needs supersede their own.
Those who do not accept the deity of the Machine are viewed as 'unmechanical' and threatened with Homelessness. The Mending Apparatus—the system charged with repairing defects that appear in the Machine proper—has also failed by this time, but concerns about this are dismissed in the context of the supposed omnipotence of the Machine itself.
During this time, Kuno is transferred to a room near Vashti's. He comes to believe that the Machine is breaking down, and tells her cryptically "The Machine stops." Vashti continues with her life, but eventually defects begin to appear in the Machine. At first, humans accept the deteriorations as the whim of the Machine, to which they are now wholly subservient, but the situation continues to deteriorate, as the knowledge of how to repair the Machine has been lost.
Finally, the Machine collapses, bringing 'civilization' down with it. Kuno comes to Vashti's ruined room. Before they perish, they realise that humanity and its connection to the natural world are what truly matter, and that it will fall to the surface-dwellers who still exist to rebuild the human race and to prevent the mistake of the Machine from being repeated.


text:
Q: Unable to access UEFI when waking up from hibernate I have a Lenovo Thinkpad (P16) and when starting normally, I have options to enter to BIOS/UEFI setup (F1) and also boot menu (F12).
I would like to have 2 different Ubuntu installations on two different internal drives, and I would like to hibernate one installation and then resume another.
The thing is, that I don't see F1 and F12 options when starting hibernated Ubuntu. I have "Quick" and "Diagnostics" Boot Mode in BIOS. If "Diagnostics" is selected, it shows F1, but it won't let me in setup or boot menu when waking up from hibernate.
Is there any option to tell Ubuntu that UEFI interrupt should be possible on startup, when resuming from hibernate?
Thanks and best regards.


text:
Q: FTP download problems with iptables -- Port 21 connection is allowed but "Network is unreachable" I'm trying to connect to an FTP site but with, e.g., wget:
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD (1) /gcrypt/gnutls ... done.
==> SIZE v3.2 ... done.
==> PASV ... couldn't connect to 217.69.76.55 port 40258: Network is unreachable

If I disable iptables, it works, so obviously that is the problem.  Yet I'm sure I have everything set up properly:
# Accept related, established...
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# ftp/http(s) clients
-A OUTPUT -p tcp -m multiport --dports 21,80,443,8080 -j ACCEPT
-A OUTPUT -p udp --dport 21 -j ACCEPT

What's wrong?

A: Iptables needs some kernel modules loaded in order for "RELATED, ESTABLISHED" to work.  If your HTTP clients are okay, you obviously have some of them.
 > lsmod | grep conntrack
 nf_conntrack_ipv4      20258  6
 nf_defrag_ipv4         12702  1 nf_conntrack_ipv4
 xt_conntrack           12760  6
 nf_conntrack           99996  2 xt_conntrack,nf_conntrack_ipv4

However, the one for ftp, nf_conntrack_ftp, is additional and, unlike a device or filesystem driver, will not be loaded automatically by the kernel.
 > modprobe nf_conntrack_ftp

Should do it.  There is not AFAIK a cross-distro method for autoloading modules at boot, but on Fedora you can add:
IPTABLES_MODULES="nf_conntrack_ftp"

to /etc/sysconfig/iptables-config.  On other systems which use systemd but do not have this file, see man modules-load.d.


text:
Q: Accessing value through material ui ListItemText component I have material ui components like:
                  <ListItemText onClick={(ev) => onAreaSelect(ev)} primary={area} />
                </ListItem>

And then:
  const onAreaSelect = (event) => {
      console.log("area seledcted??", event.target, event.target.value)
  }

event.target returns:
<span class="MuiTypography-root MuiListItemText-primary MuiTypography-body1 MuiTypography-displayBlock"> Area </span>

but event.target.value  returns:
undefined

how can I access the value?

A: *

*useRef()which will hold the value of the element you put ref field in like so:
    const areaRef = useREf(null)
    .
    .
    <ListItemText ref = {areaRef} onClick={(ev) => onAreaSelect(ev)}
   primary={area} />

*onChange() has two params : event and value so you can do something like this :
  onChange((event,value)=>onAreaSelect(event,value))