text:
Q: Read ashx jpg with .Net 4.5 My goal is to read a jpg file from a ashx Url. I would like to do this with Windows Phone 8 but I'm starting with .Net 4.5 because that might be more simple for me.
Here is an example url:
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card
If you go to this Url in IE 10 you'll see an image. How do I download the image in .Net 4.5? I have tried using:
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpg"));
string resourceAddress = "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);

HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);

byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();

and also using WebClient
string url = @"http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card";
byte[] imageData;
using (WebClient client = new WebClient())
{
    imageData = client.DownloadData(new Uri(url));
}

both of these methods return no data. How do I get the data and format it into a jpg? I am pretty new to using ashx files. I see that they are used easily in Asp.Net web sites but have not been able to find anything that allows to simply download the file. The goal is to download the jpg file and display it in a windows phone 8 application.

A: Take a look at that URL. You've URL encoded the &, so indeed there's nothing returned from
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card

this
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card

however, worked just fine for me in Windows 8 using your first code sample.
By the way, I see you set an Accept header of image/jpg, the ASHX seems to set the Content-type to image/jpeg - it does work though.


text:
Q: Channel vocoder using FFT - what to do about DC Component and Nyquist frequency? I am trying to implement a channel vocoder using the iOS Accelerate vDSP FFT algorithms. I am having trouble figuring out how to treat the DC component and Nyquist frequency.
The modulator and carrier signals are both float arrays of length n. On each, I perform a forward FFT and am returned a frequency plot (call it bin[]) of length n/2.
As per the vDSP specifications, bin[1] contains the first frequency above 0Hz, bin[2] the second, etc... bin[0] contains the DC Component in the real part and the Nyquist frequency (which would normally be in bin[n/2]) in the imaginary part. vDSP essentially packs the frequency plot into as little space as possible (the imaginary part for bin[0] and bin[n/2] should always be zero before the packing).
I split the frequency plot for both carrier and modulator into k bands. My goal is to multiply each frequency in carrier.band[x] by the total magnitude of the frequencies in modulator.band[x]. Essentially, increasing the intensity of those frequencies in the carrier that are also present in the modulator.
So if n=8 and k=2, the second band for the modulator would contain contain bin[2] and bin[3]. Simple enough to find the total magnitude, simply sum the magnitudes of each bin (for example mag[2] = sqrt( bin[2].real*bin[2]*real + bin[2].imag*bin[2]*imag )).
That works great for all bands except the first one, because the first band contains the weird bin[0] with the DC component and Nyquist frequency.
How do I handle that first bin when calculating the total magnitude of a band? Do I just assume the magnitude for the first bin is JUST the DC component by itself? Do I discard the Nyquist frequency?
Thank you to anyone who can provide some guidance! I appreciate it.

A: I suggest you ignore 0 Hz and Nyquist since they contain no useful information in the case of an audio signal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling Javascript On Someone Else's Site From Custom Browser I have a custom browser for kids that blocks a whole ton of sites, including blocking pop ups.
I would like to link to the games section of this PEEP site, but for some reason, when I copy/paste the url to the game page, it just redirects me to the home page.
I look at the source, and the onclick is set to "return gamesWin(this.href)". I see that javascript function in the source... so I would like to either:

*

*Call that from my browser to redirect the user to the games page directly

*Make a quick custom web page to redirect them to the game list

Are either of these possible? How/what should I do to achieve this?

A: It seems the Games page is checking if the visit is coming from their website -- they check for the presence of the string "peepand":
if(document.referrer.indexOf('peepand')==-1) {location.replace('../');

So, if you create a page at a location which has "peepand" somewhere in the path, or even in a query string parameter (foo.html?peepand=), a link on that page should work.
Note, however, that this can be discovered by the site admins, and they might introduce a better checking mechanism that won't be so easy to work around.


text:
Q: QT: Creating different QGraphicsItems from one slot I have some classes inherited from QGraphicsItem, I also have buttons in my interface. Right now, when I press a button, an item is created in the scene. I have such signal/slot system for all of my classes, so as a result I have a lot of slot functions that are very similar, and the only difference is in the type of objects they create. Is this a good programming practice or not, because it doesn't look like it. Is there a way to simplify this?
Armchair is a class inherited from QGraphicsItem
armchair is an object of this class
this is a code example of such slot function
void MainWindow::armchairButton_clicked()
{
    scene_preview->clear();
    armchair = new Armchair();
    scene_preview->addItem(armchair);
}

A: There is no general fixed rule for this, just the DRY principle (Don't Repeat Yourself).
In general, every button has a distinct function, so there must be some code to distinguish those.
Depending on how much code is common and how much is individual, you need to find a good balance.
In your case, you seem to only have 1 thing to change (the object type to add) and some common code for cleaning. This could be separated, e.g.
void MainWindow::replaceSceneObject(QGraphicsItem *i)
{
    scene_preview->clear();
    scene_preview->addItem(i);
}

void MainWindow::armchairButton_clicked()
{
    replaceSceneObject(new Armchair);
}

As you use manual connects, you actually don't need separate slots for this, but could use lambdas in the connect calls, e.g.:
connect(armchairButton, &QPushButton:clicked, [=]{ replaceSceneObject(new Armchair); });


text:
Q: Whats the best way to get access to SlickGrid in a meteor App I'm trying to integrate slickgrid into a meteor application. I've tried the existing atmosphere package for SlickGrid. I've also tried building my own smart-package.
Either way, I can't get the Slick namespace to show up on on the client side. I suspect that it has something to do with the way that the slickgrid code handles namespacing. They do it as follows in their slick.core.js file:
(function ($) {
  // register namespace
  $.extend(true, window, {
    "Slick": {
      "Event": Event,
      "EventData": EventData,
      "EventHandler": EventHandler,
      "Range": Range,
      "NonDataRow": NonDataItem,
      "Group": Group,
      "GroupTotals": GroupTotals,
      "EditorLock": EditorLock,

      /***
       * A global singleton editor lock.
       * @class GlobalEditorLock
       * @static
       * @constructor
       */
      "GlobalEditorLock": new EditorLock()
    }
  });

I've tried some other code snippets with that style of namespacing and it didn't seem to work. What is the right approach here? I could edit the SlickGrid files to use a different namespacing approach, but that seems rather hackish and I'd like to avoid doing it if possible.

A: Both linked packages are missing export call. If you have a global variable in your package that should be accessible from outside, you need to add the following line to your Package.on_use method:
Package.on_use(function(api) {
  ...

  api.export('SlickGrid', 'client');
  ...
});


text:
Q: how to insert bulk into the fact table in redshift I am interested in exapanding the fact tables so that they contain 2 billion rows. What do you think is the best way to do this? For example, do we take a year of data, and copy back into the same table, but change the dates for a subsequent year? What I mean is, taking 2010 data and making it 2011 data, or something like that. Thoughts?
Regards,

A: Your solution is how I've done it within Redshift for testing on large datasets, something like:
INSERT INTO factTable (factdate, columns...)
SELECT DATEADD(year, -1, factdate), columns...
FROM factTable;
Then you can run this multiple times either changing the -1 value or keeping it the same if you're happy duplicating data.
Redshift is very fast performing inserts like this, if you're doubling your dataset each time you execute the statement you'll get to a large enough table pretty quickly.


text:
Q: This Android SDK requires Android Developer Toolkit version 22.0.0 or above. Current version is 21.x.x. Hi i have a problem with my Eclipse and the SDK  (i have download and install the latest ADT Bundle for windows )
when i start my eclipse i get this problem :
This Android SDK requires Android Developer Toolkit version 22.0.0 or above. Current version is 20.0.0.
please update your SDK tools to the latest version

i have tried the option  : Help -> check for updates
But with no new update find
then i try this one :
How to Update your ADT to Latest Version

In Eclipse go to Help
Install New Software ---> Add
inside Add Repository write the Name: ADT (or whatever you want)
and Location: https://dl-ssl.google.com/android/eclipse/
after loading you should get Developer Tools and NDK Plugins
check both if you want to use the Native Developer Kit (NDK) in the future or check Developer Tool only
click Next
Finish

But i dont have the option to click next to finish  (the back , next and finish options are grey )
Then i try this method :
Go here download latest version of ADT-22.0.4.zip (*)
At Eclipse > Help > Install new software... > Uncheck Contact all update sites during install to find required software (last bottom preference) that will avoid any unwanted delays during install.
then at the same screen (top) Click Add > Archive > select downloaded ADT-X.X.X.zip > follow on screen installation steps

But had the same problem when it was to finish the installation.. no option to click ''next''
then i try this one :
Help – Install New Software in the ADT menu.
Type https://dl-ssl.google.com/android/eclipse/site.xml in "Work with:" and Enter.
You can see the "Developer Tools" item.
Select it and click Next.
Click Next one more.
Click Finish accepting the terms of the license agreements.
Click OK in the "Security Warning" window.
Let the installer restart ADT after installing the tools.

But and in this option have the same problem as above..  can click the ''next'' to finish
http://i30.photobucket.com/albums/c316/caslor_1978/diafora/atdproblem_zps0d141b7b.jpg
i check my version and it is  the latest but have the problem
http://i30.photobucket.com/albums/c316/caslor_1978/diafora/atdproblem2_zps81de6317.jpg
How can i fix this problem ? any suggestion?
Win7 / 32bit /  java SE Development kit7 update 25

A: http://developer.android.com/sdk/installing/installing-adt.html
Start Eclipse, then select

Help > Install New Software.

Click Add, in the top-right corner.
In the Add Repository dialog that appears, enter ADT Plugin for the Name and the following URL for the Location:
https://dl-ssl.google.com/android/eclipse/

Click OK.
If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
In the next window, you'll see a list of the tools to be downloaded. Click Next.
Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
When the installation completes, restart Eclipse...

A: I had the same problem last week, I tried everything, but nothing helped me.
Finally fixed it only by re-downloading ADT bundle whole again.

A: Click ADT, then About ADT. You should see your software info. Click the ADT version and then click update.
That worked for me.

A: you have to download android sdk for your computer. like 32bit or 64 bit. try re - downloading and placing the android sdk into some other folder.
and in future updates. update eclipse first and then android sdk.
Hope this helps

A: Ok this is how I solved it.
It happened to me because I had previously installed ADT ( in Feb 2012 ) , and therefore the new eclipse.exe from the newly unzipped ADT was pointing to the old SDK Manager.
So I deleted the following folders belonging to the older version:

*

*From C:\Users\*your_name*\ , delete .android and .android-sdk . I forgot the exact name of the second folder, but basically you have to delete android related stuff from there.

*Also delete .metadata from workspace. You may keep your old project folders.


text:
Q: Trouble downloading & parsing Google Trends from a JSON file I found this URL that gives you a google trends json file:
http://www.google.com/trends/fetchComponent?cid=TIMESERIES_GRAPH_0&export=3&q=javascript&geo=US
<- This trends link shows you the US search trends history for the word javascript.
I am having trouble parsing it and turning it into an object that I can use. Now I am starting to doubt it's even possible since it's not really an API but instead a raw file.
I had a friend help me build a quick test but doesn't its not working either.
End Result Goal:
I just want to be able to pull in all the data via json, have javascript parse it and print the data in the console
Here is the code
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
  <script>

    var url = 'http://www.google.com/trends/fetchComponent?cid=TIMESERIES_GRAPH_0&export=3&q=bread&cat&geo=US';

    var jsonObject;

    var google = {
      visualization : {
        Query : {
          setResponse: function(json) {
            jsonObject = json;
          }
        }
      }
    };

    console.log('Making ajax request ...');
    $.ajax({ dataType: 'text', url: url })

      // When it arrives, pull out the JSON using the function we setup on
      // line 16
      .done(function(data) {
        console.log('Data has arrived! Executing it to get the JSON from it ...');
        eval(data);
        console.log(jsonObject);
      })

      // If the request fails, print out the reason why.
      .fail(function(jqXHR, textStatus) {
        console.log("The ajax request failed: " + textStatus );
      });

  </script>
</body>

Thank you!!!
-Nico


text:
Q: Загрузка файлов через админку Добрый день, имеется модель вида
class Image(models.Model):
    image = models.ImageField(..)
    info = models.TextField(..)

т.е. обычное изображение с каким-то описанием. Заливка производится через админку. Заливать поштучно - не удобно. Можно ли как-то запилить модель и заливать через админку сразу по несколько изображений, на примере инлайнов? Желательно без подключения сторонних js-библиотек :)
A: Ну сделайте еще одну модель, типа ImageSet, в Image добавьте ForeignKey на неё, и подключив Inline, - можете заливать сразу кучу картинок.
A: Я думаю что лучше всего использовать все-таки библиотеки, т.к они написаны хорошо и имеют хорошее время выполнения!
 Вот что вам понадобится

*

*jQuery Multiple File Upload Plugin v1.31 тута (сам плагин)

*Query Form Plugin v2.18 тута (Плагин для ajax работы с формами.)

*jQuery BlockUI Plugin v2.14 тута (для ошибок)

*ну JQuery найдете сами))

Апишки довольно простые, написать не сложно)
Как и что делать дальше можно прочитать вот тута
A: Вот в этой книге "Django Разработка веб-приложений на Python", в главе - создание галереи, там подробно всё описано и там как рас применяется метод загрузки одновременно нескольких картинок.

Качайте книгу и за 10 минут разберётесь с первоисточника.


text:
Q: Should annotation based JPA Entity Manager be closed? I have used annotation for using Entity Manager instead of using EntityManagerFactory.
@PersistenceContext
EntityManager entityManager;

I searched a lot regd the closing of entityManager. But in most places the EntityManager is being used
EntityManager em = EMF.get().createEntityManager();

And Im not sure how the closing varies for annotation based.
Do we use it just like we use normal jdbc connection?
Eg:
Connection conn=DataBaseConnection.getConnection();
PreparedStatement stmt;
ResultSet result;
stmt=conn.prepareStatement("SELECT * from table WHERE id = ?  ");
stmt.setString(1,id);
result=stmt.executeQuery();
conn.close();

So, do we need to add a begin tran to the entityManager, commit it and then close it for each method we use? or will the annotation take care of it all?
public class someClass{
    public someMethod1(){
     //use entityManager - do I need to close it for each method?
    }
    public someMethod2(){
     //use entityManager
    }
}

Or am I getting this entirely wrong?
Please advice.


text:
Q: Persisting objects after AJAX calls in Node.js How can objects that are created during an AJAX request persist so that it can be used by subsequent AJAX calls?
I have tried using the debugger to see if my variables exist after a call to my route function and they seemed to be destroyed each time after the call ends.
Any suggestions or examples?

A: First of global variables are bad. I think what you are looking for is called sessions. Using web framework express this is achieved without any pain.
package.json
{
  "name": "hello-world",
  "description": "hello world test app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "3.x"
  }
}

app.js
var express = require('express');
var app = express();
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser('keyboard cat'));
app.use(express.cookieSession());

app.get('/count', function (req, res) {
    if (req.session.count === undefined) {
        req.session.count = 1;
    } else {
        req.session.count += 1;
    }

    res.send('Number of times you visited this page: ' + req.session.count);
});

app.get('/reset', function (req, res) {
    req.session = null;

    res.send('session has been reset');
});

app.listen(3000, '127.0.0.1');
console.log('Listening on port 3000');

After you have created the file package.json you can install express issuing npm install. Then running program is as simple as node app.js. The route htttp://localhost:3000/counter counts how many times you have visited that page. Even after you have shutdown server. The route http://localhost:3000/reset is used to reset the counter.

A: What I was looking for was the global object.
To use foo between different modules and router calls, I declared global.foo and used that object.
http://nodejs.org/api/globals.html


text:
Q: Unable to get copy text into clipboard I am using this for copying text into clipboard..
http://www.steamdev.com/zclip/

I have tried like this, but I am unable to get the copied text into clipboard..
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>

<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/jquery.zclip.js"></script>

<script>

    $(document).ready(function(){

        $('textarea#showthis').zclip({
            path:'js/ZeroClipboard.swf',
            copy:function(){return $('#showthis').val();}
        });

    });

    function myfunc2()
    {
         var selectedobj=document.getElementById('showthis');

        if(selectedobj.className=='hide')
        {  //check if classname is hide
            selectedobj.style.display = "block";
            selectedobj.readOnly=true;
            selectedobj.className ='show';
         } else {
            selectedobj.style.display = "none";
            selectedobj.className ='hide';
         }
    }
</script>
 </head>

 <body>
   <label onclick="myfunc2()">Click here</label>
   <textarea id="showthis" style="display:none" class="hide"  readonly>hi, how are you?</textarea>
 </body>
</html>

Please tell me what went wrong! (I am not aware of javascript and jquery stuff!)

A:  function myfunc2() {
   if($('#showthis').css('display') == 'none'){
    $('#showthis').show().removeClass('hide').addClass('show');
  }else{
    $('#showthis').hide().removeClass('show').addClass('hide');
  }
 }


text:
Q: using ifdef and ifndef directives to include header files Please excuse my basic question and poor programming knowledge.
I have an implementation that I need to use in many of my projects. But the included header files are different for different projects.
Say I have spi.h header file to be used in projecta.c and projectb.c. But a particular include (definitions.h) is not required in projectb.c then how do I make this include project specific?
I have seen that is done through #ifdef and #ifndef and directives. But can someone please help me understand how is it done.
Thank you

A:
Say I have spi.h header file to be used in projecta.c and projectb.c. But a particular include (definitions.h) is not required in projectb.c then how do I make this include project specific?

Like this:
// projecta.c
#include "spi.h"
#include "definitions.h"

// projectb.c
#include "spi.h"

There's no need for ifdef directive.

A: You can include a certain header depending on an #ifdef like that:
#ifdef INCL_DEFINITIONS
#   include "definitions.h"
#endif

The in the project where you need definitions.h you have to add -DINCL_DEFINITONS to the compiler parameters

A:
I have seen that is done through #ifdef and #ifndef and directives.

It can be done through #ifdef and #ifndef directives or #if directives.
The key part of this is you need some way to define preprocessor macros based on what project is being built. A common way this is done is:

*

*Each project has its own build settings.

*Those build settings include options to pass to the compiler.

*The compiler has options to define preprocessor symbols.

For example, with GCC and Clang, you can use -Dsymbol to cause symbol to be defined (with no replacement tokens; it is defined, but the definition is empty) or -Dsymbol=replacement to cause it to be defined with the indicated replacement.
Once you have this, there are choices about how to use it. One choice is for a symbol to be defined if a feature should be included and undefined if not. Then you would have directives such as:
#if defined FeatureX
    #include "HeaderForFeatureX.h"
#endif

Another choice is for a symbol to be defined to be 1 if the feature should be included and 0 if not. Then you would have:
#if FeatureX
        #include "HeaderForFeatureX.h"
#endif

Historically, some people used the first choice and some people used the second. Because of this, it is common to write your settings and code to cover both of them. When defining a symbol with a compiler option, we will both define it (satisfying the first method) and define it to be 1 (satisfying the second method), as with -DFeatureX=1. When testing it, we will test with with #if defined FeatureX because that is true if either choice is used, whereas #if FeatureX is true only if FeatureX is defined to be 1, not just defined with empty replacement tokens.
(In a #if directive, if a token that could be a preprocessor macro name is not a defined preprocessor macro name, it is replaced with 0. So, if FeatureX is not defined, #if FeatureX becomes #if 0.)
A third choice is to define a symbol to have different values according to the features chosen. For example, we could define ProductLevel to be 10, 20, or 30, and then use directives such as:
#if 10 <= ProductLevel
    #include "Level10Features.h"
    #if 20 <= ProductLevel
        #include "Level20Features.h"
        #if 30 <= ProductLevel
            #include "Level30Features.h"
        #endif
    #endif
#endif


text:
Q: Delete only folders using windows batch I have one folder XYZ. In XYZ I have multiple folders and Files.
D:/XYZ/Myfolder1/a1.csv
D:/XYZ/Myfolder2/
D:/XYZ/Myfolder3/
D:/XYZ/aaa.csv
D:/XYZ/bbb.sql
I want to delete folders and every content of that from XYZ
Like Myfolder1,Myfolder2,Myfolder3
but not aaa.csv and bbb.sql
How can I write batch for this.

A: CD c:\windows
For /f "delims=" %A in ('dir c:\windows /b /ad') Do Echo %A [RD %A /s /q deletes the folder %A]

See For /?, dir /?, rd /?, and cd /?.


text:
Q: table with multiple multicolumn I am struggling to get the distribution for table with multiple columns per rows right.
My LaTeX code is:
\documentclass{book}
\begin{document}

\begin{table}[]
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
\multicolumn{7}{|c|}{0} & \multicolumn{7}{c|}{1}\\ \hline
\multicolumn{7}{|c|}{Negative} & \multicolumn{7}{c|}{Positive}\\ \hline
\multicolumn{4}{|c|}{-1} & \multicolumn{6}{c|}{0} & \multicolumn{4}{c|}{1} \\ \hline
\multicolumn{4}{|c|}{Negative} & \multicolumn{6}{c|}{Neutral} & \multicolumn{4}{c|}{Positive} \\ \hline
\multicolumn{2}{|c|}{1} & \multicolumn{3}{c|}{2} & \multicolumn{4}{c|}{3} & \multicolumn{3}{c|}{4} & \multicolumn{2}{c|}{5} \\ \hline
\multicolumn{2}{|c|}{\begin{tabular}[c]{@{}c@{}}Strongly\\ Negative\end{tabular}} & \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Weakly\\ Negative\end{tabular}} & \multicolumn{4}{c|}{Neutral} & \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Weakly\\ Positive\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Strongly\\ Positive\end{tabular}} \\ \hline
\begin{tabular}[c]{@{}c@{}}Very\\ Negative\end{tabular} & \multicolumn{2}{c|}{Negative} & \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Mostly\\ Negative\end{tabular}} & \multicolumn{2}{c|}{Neutral} & \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Mostly \\ Positive\end{tabular}} & \multicolumn{2}{c|}{Positive} & \begin{tabular}[c]{@{}c@{}}Strongly \\ Positive\end{tabular} \\ \hline

\end{tabular}
\end{table}

\end{document}

This coding results in this:

But I actually want this:

A: Here's a solution that uses a tabularx environment to (a) assure that the table fits inside the width of the text block, (b) assure that the 7 cells in the bottom row have equal widths, and (c) allow automatic line wrapping within the cells.
As in David Carlisle's answer, the tabularx env. is set up to have not 7 but 14 underlying columns. Each visible cell in the bottom row actually spans 2 underlying columns. The contents of the visible cells must be entered in \mc (or \md) wrappers, to indicate how many underlying columns they should span.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tabularx}
\renewcommand\tabularxcolumn[1]{m{#1}}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcommand\newhsize[1]{\hsize= \dimexpr #1\hsize
                    +#1\tabcolsep+#1\tabcolsep-2\tabcolsep
                    +#1\arrayrulewidth-\arrayrulewidth  \relax}
\newcommand{\mc}[2]{\multicolumn{#1}{ >{\newhsize{#1}}C|}{#2}}
\newcommand{\md}[2]{\multicolumn{#1}{|>{\newhsize{#1}}C|}{#2}} % for first col. in row

\begin{document}
\setlength\tabcolsep{3pt}      % default: 6pt
\setlength\extrarowheight{2pt} % for a more open "look"

\noindent
\begin{tabularx}{\textwidth}{|*{14}{C|}}
\hline
\md{7}{0} & \mc{7}{1} \\ \hline

\md{7}{Negative} & \mc{7}{Positive}\\ \hline

\md{5}{$-1$} & \mc{4}{0} & \mc{5}{1}\\ \hline

\md{5}{Negative} & \mc{4}{Neutral} & \mc{5}{Positive} \\ \hline

\md{3}{1} & \mc{2}{2} & \mc{4}{3} & \mc{2}{4} & \mc{3}{5}\\ \hline

\md{3}{Strongly Negative} & \mc{2}{Weakly Negative} & \mc{4}{Neutral} &
\mc{2}{Weakly Positive} & \mc{3}{Strongly Positive}\\ \hline

\md{2}{Very Positive} & \mc{2}{Positive} & \mc{2}{Mostly Positive} & \mc{2}{Neutral} &
\mc{2}{Mostly Negative} &  \mc{2}{Negative} & \mc{2}{Strongly Negative} \\ \hline
\end{tabularx}
\end{document}

A: In it's lowest level \halign table column assignment Tex does a "simplification" that if there is a cell boundary that is spanned on every row it is essentially removed from the internal structure.
So here you want to ensure that you really have 14 effective columns so you can have a final last row with every cell present and no spans, this would normally force extra visible vertical space and vertical rules so i used \omit primitive to prevent the addition of the rules and the \strut that latex normally adds to a row.

\documentclass{article}

\addtolength\textwidth{2pt}
\begin{document}

\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
\multicolumn{7}{|c|}{0} & \multicolumn{7}{c|}{1} \\ \hline
\multicolumn{7}{|c|}{Negative} & \multicolumn{7}{c|}{Positive}\\ \hline
\multicolumn{4}{|c|}{-1} & \multicolumn{6}{c|}{0} & \multicolumn{4}{c|}{1}  \\\hline
\multicolumn{4}{|c|}{Negative}& \multicolumn{6}{c|}{Neutral}& \multicolumn{4}{c|}{Positive}\\ \hline
\multicolumn{2}{|c|}{1}& \multicolumn{3}{c|}{2}& \multicolumn{4}{c|}{3} & \multicolumn{3}{c|}{4} & \multicolumn{2}{c|}{5}\\ \hline
\multicolumn{2}{|c|}{\begin{tabular}[c]{@{}c@{}}Strongly\\ Negative\end{tabular}} & \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Weakly\\ Negative\end{tabular}}& \multicolumn{4}{c|}{Neutral}& \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Weakly\\ Positive\end{tabular}}& \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Strongly\\ positive\end{tabular}} \\ \hline
\begin{tabular}[c]{@{}c@{}}Very\\ Positive\end{tabular}& \multicolumn{2}{c|}{Positiv}& \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Mostly\\ Positive\end{tabular}} & \multicolumn{2}{c|}{Neutral} & \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Mostly \\ Negative\end{tabular}} & \multicolumn{2}{c|}{Negative}& \begin{tabular}[c]{@{}c@{}}Strongly \\ Negative\end{tabular}\\ \hline
\omit&\omit&\omit&\omit&\omit&\omit&\omit&\omit&\omit&\omit&\omit&\omit&\omit&\omit
\end{tabular}

\end{document}

I left the table content as unrelated to the question but numbers should be in math mode, $-1$ is not -1, I would also use \setlength\extrarowheight{2pt} to keep the \hline away from the cell content.


text:
Q: silverstripe upload tiff and convert to jpeg i´m working on a image database build with silverstripe framework. It needs to be able to upload large tiff files and they should be converted to jpeg. is there a build in function to do that, or do I have to use a library for that?
Regards,
Florian

A: SilverStripe doesn't have built-in image conversion utilities, just a GD class which mainly handles resizing of existing images (in gif/jpg/png).
ImageMagick supports conversion of TIFFs (see supported formats). I'm sure you can find PHP wrapper libraries for it (doesn't have to be specific to SilverStripe), or use the commandline tool directly via exec().
Other than that, we have the UploadField class to handle uploads. It uses the jQuery fileupload plugin, which supports larger files (although server timeouts and PHP config play a role here as well). You might want to look into chunked uploads.


text:
Q: Remove unicode from string I'm trying to remove special character from Arabic String using it's Unicode which I got from this link:
https://www.fileformat.info/info/unicode/char/0640/index.htm
This is my code:
TATWEEL = u"\u0640"
text = 'الســلام عليكــم'

text.replace(TATWEEL, '')
print(text)

But I tried it and doesn't work (it prints the same string without removing the character)
This is the special character 'ــ'

I'm using Python3

A: The replace method of strings does not change the string it is called on; it returns a new string with the specified character replaced.
This code does what you want:
TATWEEL = u"\u0640"
text = 'الســلام عليكــم'

text2 = text.replace(TATWEEL, '')
print(text2)

To get the exact result you expected, use this:
text = text.replace(TATWEEL, '')
print(text)

A: If text may contain multiple unicode elements then you should go for regex as below:
import re
TATWEEL = u"\u0640"
text = 'الســلام عليكــم'

unicode_removed_text = re.sub(TATWEEL, '', text)


text:
Q: calculating duration of 1 cycle I'm working on RGBGenerator, I want to calculate how many seconds it needs to do 1 cycle;
Forumla:
ticks it needs for 1 cycle * speed / 1000 = seconds
ticks it needs for 1 cycle * speed / 1000 / 60 = minutes

But it calculates it wrong; example:
If it needs 1791 ticks and the speed is 10ms/tick it needs 17.9 seconds (18 seconds). When I start a countdown it takes longer then 18seconds to do one cycle.
Calculate how many ticks it needs:
var r = settings.startR, g = settings.startG, b = settings.startB, range = settings.range, states = [], tick = 0;
states.push(Math.max(Math.abs((r - range)), Math.abs((g - range)), Math.abs((b- range))));
for(var i = 0; i < 6; i++) {
    states.push((states[i]+1) + range);
}

Calculating seconds/minutes:
$( "#cycleSeconds" ).html("1 cycle = " + ((states[6]*speed/1000) >= 60 ? Math.round((states[6]*speed/1000/60)) + " minutes" : Math.round((states[6]*speed/1000)) + " seconds"));

Live demo (you need to set the speed input to the left and press start)
Does somebody know why it calculates it wrong, and how to fix it?

A: For more accurate drawing use window.requestAnimationFrame instead of setTimeout.
You actually do something like this:

*

*paint

*wait for some time

*goto 2

You probably didn't count the time which is spent to paint & other calculations. That is why the duration is more than tick * count.
Just in case: Performance.now() will help you to measure execution time quite accurately.


text:
Q: I am trying to redirect to another page after X seconds, but I get this error I am trying to set up an exam page for my friend Neil. The user clicks on a link 'First Year exam' or 'Second Year exam' and goes to a login page. If the login is successful, and the time is right, the exam opens
I use this to make the exam page available at a certain time:
<?php
$time = date('Y:F:d:G:i');
echo 'the time now is ' . $time . '
';
// the page is only available between 10 and 11
if(date('G') < 10 or  date('G') > 10  )  {
    include 'jsclock.html';
   exit();
    }
?>

Works OK!
Now I would like to use PHP to open jsclock.html at 11 o'clock. I tried this at the top of the exam page:
echo "Welcome to the exam page
";
echo "we will redirect to the jsclock.html webpage in 30 seconds";

// The function will redirect to jsclock.html in 30 seconds
header("refresh: 30; url = jsclock.html");
exit();

But I get this message:

Welcome to the exam page we will redirect to the jsclock.html webpage
  in 30 seconds Warning: Cannot modify header information - headers
  already sent by (output started at
  /var/www/html/Neil_Exam/FirstYear/19BEsW13.html.php:4) in
  /var/www/html/Neil_Exam/FirstYear/19BEsW13.html.php on line 7

The login.php will direct the user to the exam page if the login is successful:
//validate inputted password with $user password
                if(password_verify($password, $user['password'])){
                    //action after a successful login
                    //for now just message a successful login
                    $_SESSION['success'] = 'User verification successful';
                    //header('location: 19BEsW13.html.php');
                    include '19BEsW13.html.php';
                    exit();

The login part also works well!
I do not use

'header('location: '19BEsW13.html.php');'

in  login.php because I keep getting weird errors when I use

header('location ..

anywhere, so I use include statements.
Any tips on how to overcome this error please??
I could use javascript. I was told that it is 'trivial' to alter a webpage to change javascript settings. (Although I have no idea how!!) So I thought it is better to use php if I can.

A: You cannot echo or output anything before using header().  Check out the documentation:  https://www.php.net/manual/en/function.header.php

A: Like @Adam Winter said you cannot use header() if in your code you already echo or output some data.
If you still want to redirect the user you can use Javascript to do so like that :
echo '';


text:
Q: Value Error : invalid literal for int() with base 10: '' I'm new in Python and I don't know why I'm getting this error sometimes.
This is the code:
import random
sorteio = []
urna = open("urna.txt")

y = 1
while y <= 50:
    sort = int(random.random() * 392)
    print sort
    while sort > 0:
        x = urna.readline()
        sort = sort - 1
    print x
    sorteio = sorteio + [int(x)]
    y = y + 1
print sorteio

Where urna.txt is a file on this format:
1156
459
277
166
638
885
482
879
33
559

I'll be grateful if anyone knows why this error appears and how to fix it.

A: Upon attempting to read past the end of the file, you're getting an empty string '' which cannot be converted to an int.
>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

to satisfy the requirement of selecting 50 random lines from the text value, if I understand your problem correctly:
import random

with open("urna.txt") as urna:
    sorteio = [int(line) for line in urna] # all lines of the file as ints

selection = random.sample(sorteio, 50)

print selection

A: .readline() returns an empty string when you come to the end of the file, and that is not a valid number.
Test for it:
if x.strip():  # not empty apart from whitespace
    sorteio = sorteio + [int(x)]

You appear to beappending to a list; lists have a method for that:
sorteio.append(int(x))

If you want to get a random sample from your file, there are better methods. One is to read all values, then use random.sample(), or you can pick values as you read the file line by line all the while adjusting the likelihood the next line is part of the sample.  See a previous answer of mine for a more in-depth discussion on that subject.


text:
Q: Definition of chaos for maps I'm looking for a mathematical precise definition of chaos for maps as I don't find that much information on it on the web.

A: I studied at least two ways of defining chaos on real-valued maps during my Chaos class. The first looks at the orbit. (Chaos: An Introduction to Dynamical Systems - Authors: Alligood, Kathleen T., Sauer, Tim, Yorke, James).
CHAOTIC ORBITS
Let $f$ be a map of the real line R andlet {$x_1,x_2,...$} be a bounded orbit of $f$. The orbit is chaotic if:
1) {$x_1,x_2,...$} is not assymptotically periodic;
2) the Lyapunov expoent $h(x_1)$ is greater than zero.
CHAOTIC MAPS
The other way of defining chaos for maps is looking at the map itself. Here we have an invariant set $I$ such that $f:I\to I$.
We say the map is chaotic if
1) periodic points are dense in $I$;
2) there is an dense orbit in $I$;
3) there is sensitive dependense to initial conditions.
Check out Yorke's book for more details and definitions used here you don't get (for example Lyapunov expoent).

A: The book Chaotic Dynamics on Nonlinear Systems by S. Neil Rasband is an accessible introduction to the theory,techniques and applications of chaos.


text:
Q: Is there anyway to get the current object in has_permission method while calling DetailView in Django CBV I have a DetailView where I want to restrict the access to the payment based on the user project assignment related to this payment.
I have the following code working just fine. Just wondering if there is a cleaner way to retrieve self.object within the has_permission instead of getting the object using the PK directly.
class PaymentDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView):
    model = Payment
    template_name = "finance/payments/details.html"
    context_object_name = "payment"

    def has_permission(self):
        payment = Payment.objects.get(pk=self.kwargs.get("pk"))
        # Check permission here based on the current user project assignment
        if condition:
            return True
        return False

I understand that has_permission is part of PermissionRequiredMixin and not the DetailView and this might not be possible but I wonder if there is a better way to test this object-based permission.
Note: the logic is a bit complicated and might not be as easy as a simple query (in fact it is actually based on the user role, project assignment, the time of assignment compared to the payment date, payment type.....)
Thanks

A: follow the documentation on how to create custom permissions.
your custom permission should look like this:
from rest_framework.permissions import BasePermission, SAFE_METHODS

class CustomPermission(BasePermission):

    def has_permission(self, request, view):
      .......

within has_permission you can do this:
from rest_framework.permissions import BasePermission, SAFE_METHODS

class CustomPermission(BasePermission):

    def has_permission(self, request, view):
        id = view.kwargs.get('pk', None)

This would return you the id that was passed in the url, you can then get the object


text:
Q: ¿Como agregar una nueva linea en un DataGridView con Doble Click C#? Quisiera agregar una nueva linea en un DataGridView, dando doble click.
Pero no he logrado que agregue la nueva linea.
Para esto utilizo el evento:
private void Partes_MouseDoubleClick(object sender, MouseEventArgs e)
{ }

Partes es el nombre de mi DataGridView en el código.

public partial class Form1 : Form
{
    DataTable datos = new DataTable();
    public string datos = "";
    public string descripcion = "";
    public string material = "";
    public string SN = "";
    public Form1()
    {
        InitializeComponent();
        crearDatatable();
        this.Controls.Add(dataGridView1);
        InitializeDataGridView();
    }
    private void InitializeDataGridView()
    {
        try
        {
            //DataGridView1.DataSource="";
            dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.Rows.Add();

        }
        catch (InvalidCastException)
        {
            MessageBox.Show("Error al iniciarGrid");
        }
    }
    public bool crearDatatable()
    {
        dataGridView1.Columns[0].HeaderText = "Datos";
        dataGridView1.Columns[1].HeaderText = "Descripcion";
        dataGridView1.Columns[2].HeaderText = "Material";
        dataGridView1.Columns[3].HeaderText = "Numero de Serie";

        return true;
    }
    //estos datos se mandan a un xml.
    private void getData(int e)
    {
        datos = dataGridView1.Rows[e].Cells[0].Value.ToString();
        descripcion = dataGridView1.Rows[e].Cells[1].ToString();
        material = dataGridView1.Rows[e].Cells[2].ToString();
        SN = dataGridView1.Rows[e].Cells[3].ToString();
        return;

    }
    private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        InitializeDataGridView();
    }
    protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
    {

        if (keyData == Keys.Enter)
        {
            dataGridView1.Rows.Add();
            dataGridView1.CurrentCell = dataGridView1.CurrentRow.Cells[0];
        }
        if (dataGridView1.CurrentCell.ColumnIndex == 4)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
    private void Partes_MouseDoubleClick(object sender, MouseEventArgs e)
    {

    }
}

A: Pero como estas llenando el datagrid?
Suponiendo que estas utilizando un Datatable para llenar el Datagrid
arias así
private void Partes_MouseDoubleClick(object sender, MouseEventArgs e)
{
    //agregas fila
    DataTable dt = NombreTuDataTable;
    DataRow row= dt.NewRow();
    dt.Rows.Add(row);

    //cargas los datos
    dataGridView1.DataSource = dt;

}

NombreTuDataTable es el nombre del Datatable con el Cual llenas tu DataGrid.
En mi blog tengo un articulo donde agrego una nueva fila para sumar los datos de una columna
SUMAR COLUMNAS DATAGRIDVIEW USANDO LINQ

A: Te recomiendo que uses los eventos del DataGridView.
Si lo que quieres es que cuando hagas doble click en el area gris del DataGridView por ejemplo(entre otros muchos eventos doble click)

Usa este evento:
private void DataGridView1_DoubleClick(object sender, EventArgs e)
{
    dataGridView1.Rows.Insert(0);
}


text:
Q: Finding the angle between unit vectors A vector $\vec{v}$ is called a unit vector if $\|\vec{v}\| = 1$.
Let $\vec{a},\vec{b}$, and $\vec{c}$ be unit vectors, such that $\vec{a} + \vec{b} + \vec{c} = \vec{0}$. Show that the angle between any two of these vectors is $120^\circ$. I have
$$ \vec{a} \cdot \vec{b} + \vec{a} \cdot \vec{c} = -1 $$
$$ \vec{a} \cdot \vec{b} + \vec{b} \cdot \vec{c} = -1 $$
$$ \vec{a} \cdot \vec{c} + \vec{b} \cdot \vec{c}= -1 $$
What should I do next?

A: I will continue on your approach:
$$ \vec{a} \cdot \vec{b} + \vec{a} \cdot \vec{c} = -1 $$
$$ \vec{a} \cdot \vec{b} + \vec{b} \cdot \vec{c} = -1 $$
$$ \vec{a} \cdot \vec{c} + \vec{b} \cdot \vec{c}= -1 $$
If we subtract 2nd and 3rd equations we will have:
$$\vec{a} \cdot \vec{b} - \vec{a} \cdot \vec{c} = 0,$$
Now we can add this new equation with your 1st equation:
$$\vec{a} \cdot \vec{b} + \vec{a} \cdot \vec{c} = -1,$$
we will have:
$$2\vec{a} \cdot \vec{b} = -1.$$
I believe it is easy now to conclude the angle between vectors $\vec{a}$ and $\vec{b}$. Similar approach will result with other angles...

A: Hints:

*

*Solve the system of linear equations to get the values of $a.b$, $b.c$, and $a.c$.

*The angle between $a$ and $b$ is $\cos^{-1}(a.b)$


text:
Q: Save .master file I have a couple of master pages that I have downloaded into the _catalogs/masterpage/ folder, but when I try to copy any .master file using Windows Expolrer, I get the following error message: "Could not find this item. This is no longer located in..."
I can open and edit them in SharePoint Designer, but having to open each one .master file and copy pasting to my backup folder is going to take a while, because I have a few master pages.

A: Just select Send To -> Download a copy from the ECB menu in the MasterPage Gallery.
Or, try checking out the MasterPage then copying from Windows Explorer, it might let you do it then.


text:
Q: AttributeError: module 'MyLib' has no attribute 'add' I'm not too sure why i keep getting the error "AttributeError: module 'MyLib' has no attribute 'add'" since it looks to me like I have already defined "add" in my MyLib file. I definitely am likely missing something obvious but was hoping to get some assistance on it.
import MyLib
while True:
  lowrange = input("Enter your Lower range --> ")
  highrange = input("Enter your Higher range --> ")
  try: #Exception to catch inputs that are not numbers on range.
    lowrange = float(lowrange)
    highrange = float(highrange)
  except Exception:
    print ("Please enter a number")
    continue

  #limit input
  while True:
    num1 = input("Enter first number --> ")
    try:#Catch inputs that are not numbers for calculations.
      num1 = float(num1)
    except Exception:
      print ("Please enter a number")
      continue
    if lowrange > num1 or highrange < num1:#Range limit
       print ("Input number not in defined range. Please check the numbers and try again.")
    else:
      break
  while True:
    num2 = input("Enter second number --> ")
    try:#Catch inputs that are not numbers for calculations.
      num2 = float(num2)
    except Exception:
      print ("Please enter a number")
      continue
    if lowrange > num2 or highrange < num2:#Range limit
       print ("Input number not in defined range. Please check the numbers and try again.")
    else:
      prob1 = str(input("Enter a problem in the following format, Num1,Num2,operator.(+,-,*,/)"))
      break

# Results
  print (num1, "+", num2, "=", MyLib.add(num1, num2))
  print (num1, "-", num2, "=", MyLib.sub(num1, num2))
  print (num1, "*", num2, "=", MyLib.mult(num1, num2))
  print (num1, "/", num2, "=", MyLib.div(num1, num2))
  print("The answer to your problem is ", Mylib.scalc(prob1))
  ans=input(' Do you want to preform another calculation? Enter "y" to continue.')
  if (ans=="y"):
     continue
  else:
     print("Thanks for using my calculator")
     break

This is the code for the MyLib function where we were supposed to "1) Move all the functions into Mylib.py
2) Use import to include Mylib into the code
3) Test the code and make sure that the prior code is still working
4) Add the following function into Mylib"
#Define the main program function
def main():
    #Define input function
    def float_input(msg):
        while True:
            try:
                return float(input(msg))
            except ValueError:
                print("You must enter a valid number.")
            else:
                break
    #Declare variables
    lowrange=float_input("What is your low range?")
    highrange=float_input("What is your high range?")
    num1=float_input ("What is your first number?")
    num2=float_input ("What is your second number?")

    #Defining the calculations
    def add (num1, num2):
        sum = (num1 + num2)
        print ("The result of", num1, "+", num2, "=", sum)
    def sub (num1, num2):
        diff = num1 - num2
        print ("The result of", num1, "-", num2, "=", diff)
    def muilt (num1, num2):
        prod = num1 * num2
        print ("The result of", num1, "*", num2, "=", prod)
    def div (num1, num2):
        if num2 ==0:
            print ("You cannot divide by 0")
        else:
            quot = num1 / num2
            print ("The result of", num1, "/", num2, "=", quot)
    #if/else
    if num1 < lowrange or num1 > highrange or num2 < lowrange or num2 > highrange:
        print ("The input values are outside ranges, please check the numbers and try again!")
    else:
        #Calling the calcs
        add(num1, num2)
        sub(num1, num2)
        mult(num1, num2)
        div(num1, num2)
        print("Thanks for using my calculator")

    def scalc(p1):
        astring = p1.split(",")
        print(astring)
        num1 = float(astring[0])
        num2 =  float(astring[1])
        if astring[2]=="+":
            add(num1,num2)
        elif astring[2] =="-":
            sub(num1, num2)
        elif astring[2] == "*":
            mult(num1, num2)
        elif astring [2] == "/":
            div(num1,num2)
        return value

    p1 = input ("Enter two numbers and an operator seperated by a comma: ")
    scalc(p1)

A: Assuming it should be all functional, the add function is not part of MyLib but a function called main. Thus, when you call MyLib, it does not know about add. It only knows about main. You have nested functions within functions. What you should do is remove the tab indentation so that add, sub, multi, etc. is not indented much like main. However, that will not work entirely because below your div function, you have uses of variables set in main.
There are two ways to fix this. Belhadjer Samir suggested a functional approach. I would suggest an object-oriented approach. Specifically, what you probably want is a class called MyLib (def main() -> class MyLib. You will then want to import it as: from mylib import MyLib (i.e. rename the file from MyLib.py to mylib.py - see below for why). You will want to initialize it somewhere in your other code (ml = MyLib()).
Then you can use the add, subtract methods.
Note: PEP8 rules say to use lower case for modules (mylib for mylib.py) and classes as CamelCase (e.g., MyLib).

A: you have to import you module like this :
from MyLib import main as MyLib

this is because all your code in Mylib is in main function


text:
Q: Type error, cannot read property 'match' of undefined i got stuck in the Javascript code below, I don't know what's the problem.
the code is always showing"Type error, cannot read property 'match' of undefined",
Here IS THE CODE:
function keepletteronly(str) {
     str=str.toLowerCase();//Make the string to lower case
     arr=str.split("");    //This way I make an array out of the string
     arr1=[]; //make an new array
for (i=1; i<=arr.length;i++){
    if (arr[i].match(/[a-z]/)!=null) {  //This is where the problem is
        arr1.push(arr[i]); //retain only the letters and append to the arr1
    }
}
newstring=arr1.join;
return newstring;

}

keepletteronly("1eye");

A: The index of a JS array starts from zero.
You should change your for sentence to
for ( i = 0; i < arr.length; i += 1) {

Moreover, another sentence is also incorrect:
newstring=arr1.join;

it should be
newstring=arr1.join('');

or simply produce the resultant string without arr1, like:
newstring='';
...
newstring+=arr[i];

A: Arrays in Javascript are base 0, meaning the first item is at index 0. Imagine you have three items in an array, the length property will say 3 and the three items will occupy indices 0, 1 and 2.
In your for loop, you start at index 1 (i=1;), meaning the loop will skip the first item (at index 0) and then you iterate while i is lower or equal to the length of the array. The length of the array is 3, but because of base 0, the last item in the array is at index 2. So in the last iteration of your for loop, you try to access index 3 of the array, which is undefined.
So, what you need to do is to change your for loop expressions to look like this:
(i = 0; i < arr.length; i++)

This way you will properly iterate over 0, 1 and 2 instead of 1, 2 and 3


text:
Q: MFC: How to i convert DWORD and BYTE to LPCTSTR in order to display in MessageBox I'm using VS2005 with "using Unicode Character Set" option
typedef unsigned char       BYTE;
typedef unsigned long       DWORD;

BYTE       m_bGeraet[0xFF];
DWORD      m_dwAdresse[0xFF];

How do i make the code work?
MessageBox (m_bGeraet[0], _T("Display Content"));
MessageBox (m_dwAdresse[0], _T("Display Content"));

A: It looks like you might need some help with the C language itself, and I recommend you find a beginner's book on C that is not about Windows programming.
MessageBox() only displays C-style strings which are arrays of type char which contain a character with ASCII value 0.  This zero character is the NUL character, and such strings are said to be "NUL-terminated" or "Zero-terminated."  Only the characters prior to the NUL are displayed when the string is printed, or copied when the string is concatenated.  However, if there is no NUL character in the array, then the string is not properly terminated and an attempt to display it could lead to a crash, or to "garbage" being displayed, as in: "Can I have a beer?#BT&I10)aaX?.

The szTitle and szText arguments to MessageBox() expect char * which are pointers to this type of string.
If you attempt to pass a BYTE instead of a char *, the value of the BYTE will be mistakenly treated as an address.  MessageBox() will attempt to access memory at the value "specified" by the BYTE and an Access Violation will occur.
One solution to this problem is to allocate a buffer of type char and use snprintf_s to transcribe your data values to string representations.
For example:

char output_buffer[1024];
snprintf_s(output_buffer, dimensionof(output_buffer), "Geraet = 0x%02X", m_bGeraet[i]);
  MessageBox(hwnd_parent, output_buffer, "Message from me:", MB_OK);

Would display a MessageBox with a message reading something like "Geraet = 0x35".

A: If it's essential that BYTE is 1-byte then you have to (optionally) convert your byte strings to wide strings using mbstowcs.

A: //easy way for bytes is to do this

CString sTemp;

sTemp.Format("my byte = %d", bySomeVal);

MessageBox(sTemp);

//for a DWORD try

sTemp.Format("Dword is %lu", dwSomeVal);

MessageBox(sTemp);

if you using MessageBox, i would suggest soetming like AfxMessageBox...


text:
Q: AttributeError: module 'Kurtosis' has no attribute 'Kurtosis_c' I am trying to build a sink block with FFT and Kurtosis capability using gr_modtool.
The code itself can be compiled without error.
But when I run the flow graph in GRC, it produces following error message.
Generating: '/home/nomo/gr-Kurtosis/kurtosis.py'

Executing: /usr/bin/python3 -u /home/nomo/gr-Kurtosis/kurtosis.py

Traceback (most recent call last):
  File "/home/nomo/gr-Kurtosis/kurtosis.py", line 134, in <module>
    main()
  File "/home/nomo/gr-Kurtosis/kurtosis.py", line 112, in main
    tb = top_block_cls()
  File "/home/nomo/gr-Kurtosis/kurtosis.py", line 81, in __init__
    self.Kurtosis_Kurtosis_c_0 = Kurtosis.Kurtosis_c(1024)
AttributeError: module 'Kurtosis' has no attribute 'Kurtosis_c'

Below is the implmentation source file:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <gnuradio/io_signature.h>
#include "Kurtosis_c_impl.h"

namespace gr {
  namespace Kurtosis {

    Kurtosis_c::sptr
    Kurtosis_c::make(int fftsize)
    {
      return gnuradio::get_initial_sptr
        (new Kurtosis_c_impl(fftsize));
    }

    /*
     * The private constructor
     */
    Kurtosis_c_impl::Kurtosis_c_impl(int fftsize)
      : gr::sync_block("Kurtosis_c",
              gr::io_signature::make(1, 1, sizeof(gr_complex)),
              gr::io_signature::make(0, 0, 0)),
              d_N(fftsize)
    {
      d_input = (fftw_complex*)fftw_malloc(sizeof(gr_complex) * d_N);
      K = (fftw_complex*)fftw_malloc(sizeof(gr_complex) * d_N);
      d_plan = fftw_plan_dft_1d(d_N, d_input, d_input, FFTW_BACKWARD, FFTW_ESTIMATE);
    }

    /*
     * Our virtual destructor.
     */
    Kurtosis_c_impl::~Kurtosis_c_impl()
    {
    }

    int
    Kurtosis_c_impl::work(int noutput_items,
        gr_vector_const_void_star &input_items,
        gr_vector_void_star &output_items)
    {
      const gr_complex *in = (const gr_complex*) input_items[0];

      for(int i = 0; i < noutput_items; i++)
      {
        d_input[i][0] = in[i].real();
        d_input[i][1] = in[i].imag();
      }

      fftw_execute(d_plan);

      for(int i = 0; i < noutput_items ;i++)
      {
        S1[i][0] = S1[i][0] + d_input[i][0];
        S1[i][1] = S1[i][1] + d_input[i][1];

        S2[i][0] = S2[i][0] + d_input[i][0] * d_input[i][0];
        S2[i][1] = S2[i][1] + d_input[i][1] * d_input[i][1];

        S3[i][0] = S3[i][0] + d_input[i][0] * d_input[i][0] * d_input[i][0];
        S3[i][1] = S3[i][1] + d_input[i][1] * d_input[i][1] * d_input[i][1];

        S4[i][0] = S4[i][0] + d_input[i][0] * d_input[i][0] * d_input[i][0] * d_input[i][0];
        S4[i][1] = S4[i][1] + d_input[i][1] * d_input[i][1] * d_input[i][1] * d_input[i][1];

        dc[i][0] = dc[i][0] + 1;
        dc[i][1] = dc[i][1] + 1;
      }

      for(int i = 0; i < noutput_items; i++)
      {
        Myu1[i][0] = S1[i][0] / dc[i][0];
        Myu1[i][1] = S1[i][1] / dc[i][1];

        Myu2[i][0] = S2[i][0] / dc[i][0];
        Myu2[i][1] = S2[i][1] / dc[i][1];

        Myu3[i][0] = S3[i][0] / dc[i][0];
        Myu3[i][1] = S3[i][1] / dc[i][1];

        Myu4[i][0] = S4[i][0] / dc[i][0];
        Myu4[i][1] = S4[i][1] / dc[i][1];
      }

      for(int i = 0; i < noutput_items; i++)
      {
        K[i][0] = (Myu4[i][0] - 4 * Myu3[i][0] * Myu1[i][0] + 6 * Myu2[i][0] * Myu1[i][0]
                   * Myu1[i][0] - 3 * Myu1[i][0] * Myu1[i][0] * Myu1[i][0] * Myu1[i][0]) /
                    ((Myu2[i][0] - Myu1[i][0] * Myu1[i][0]) * (Myu2[i][0] - Myu1[i][0]
                      * Myu1[i][0]));

        K[i][1] = (Myu4[i][1] - 4 * Myu3[i][1] * Myu1[i][1] + 6 * Myu2[i][1] * Myu1[i][1]
                   * Myu1[i][1] - 3 * Myu1[i][1] * Myu1[i][1] * Myu1[i][1] * Myu1[i][1]) /
                    ((Myu2[i][1] - Myu1[i][1] * Myu1[i][1]) * (Myu2[i][1] - Myu1[i][1]
                      * Myu1[i][1]));
      }

      // Tell runtime system how many output items we produced.
      return noutput_items;
    }

  } /* namespace Kurtosis1 */
} /* namespace gr */

The implementation header file is as below:
#ifndef INCLUDED_KURTOSIS1_KURTOSIS_C1_IMPL_H
#define INCLUDED_KURTOSIS1_KURTOSIS_C1_IMPL_H

#include <Kurtosis/Kurtosis_c.h>
#include <fftw3.h>

namespace gr {
  namespace Kurtosis {

    class Kurtosis_c_impl : public Kurtosis_c
    {
     private:
       int d_N;

       fftw_complex *K;
       fftw_complex *S1;
       fftw_complex *S2;
       fftw_complex *S3;
       fftw_complex *S4;
       fftw_complex *Myu1;
       fftw_complex *Myu2;
       fftw_complex *Myu3;
       fftw_complex *Myu4;
       fftw_complex *dc;

       fftw_complex *d_input;
       fftw_plan     d_plan;

     public:
      Kurtosis_c_impl(int fftsize);
      ~Kurtosis_c_impl();

      // Where all the action really happens
      int work(
              int noutput_items,
              gr_vector_const_void_star &input_items,
              gr_vector_void_star &output_items
      );
    };

  } // namespace Kurtosis1
} // namespace gr

#endif /* INCLUDED_KURTOSIS1_KURTOSIS_C1_IMPL_H */

The following python code is generated when a flow graph is run in GRC
from distutils.version import StrictVersion

if __name__ == '__main__':
    import ctypes
    import sys
    if sys.platform.startswith('linux'):
        try:
            x11 = ctypes.cdll.LoadLibrary('libX11.so')
            x11.XInitThreads()
        except:
            print("Warning: failed to XInitThreads()")

from gnuradio import blocks
import pmt
from gnuradio import gr
from gnuradio.filter import firdes
import sys
import signal
from PyQt5 import Qt
from argparse import ArgumentParser
from gnuradio.eng_arg import eng_float, intx
from gnuradio import eng_notation
import Kurtosis
from gnuradio import qtgui

class kurtosis(gr.top_block, Qt.QWidget):

    def __init__(self):
        gr.top_block.__init__(self, "Not titled yet")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Not titled yet")
        qtgui.util.check_set_qss()
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "kurtosis")

        try:
            if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
                self.restoreGeometry(self.settings.value("geometry").toByteArray())
            else:
                self.restoreGeometry(self.settings.value("geometry"))
        except:
            pass

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 32000

        ##################################################
        # Blocks
        ##################################################
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex*1, samp_rate,True)
        self.blocks_file_source_0 = blocks.file_source(gr.sizeof_gr_complex*1, '/home/nomo/gr-Kurtosis/b200_220215_0718_30_40_6000_TEST.dat', True, 0, 0)
        self.blocks_file_source_0.set_begin_tag(pmt.PMT_NIL)
        self.Kurtosis_Kurtosis_c_0 = Kurtosis.Kurtosis_c(1024)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.blocks_file_source_0, 0), (self.blocks_throttle_0, 0))
        self.connect((self.blocks_throttle_0, 0), (self.Kurtosis_Kurtosis_c_0, 0))

    def closeEvent(self, event):
        self.settings = Qt.QSettings("GNU Radio", "kurtosis")
        self.settings.setValue("geometry", self.saveGeometry())
        event.accept()

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.blocks_throttle_0.set_sample_rate(self.samp_rate)

def main(top_block_cls=kurtosis, options=None):

    if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
        Qt.QApplication.setGraphicsSystem(style)
    qapp = Qt.QApplication(sys.argv)

    tb = top_block_cls()
    tb.start()
    tb.show()

    def sig_handler(sig=None, frame=None):
        Qt.QApplication.quit()

    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGTERM, sig_handler)

    timer = Qt.QTimer()
    timer.start(500)
    timer.timeout.connect(lambda: None)

    def quitting():
        tb.stop()
        tb.wait()
    qapp.aboutToQuit.connect(quitting)
    qapp.exec_()

if __name__ == '__main__':
    main()

Question:
How to solve this error?
Thank you in advance for any guidance you may be able to provide.

A: There are two probable reasons:

*

*You don't have swig installed on your system and the python binding does not get generated.

#include <fftw3.h>

*You don't link all external libraries - fftw3 in your case.

Open your top-level CMakeLists.txt and add
find_package(FFTW3)

then open lib/CMakeLists.txt and add fftw3::fftw3 to target_link_libraries list, something like
target_link_libraries(gnuradio-Kurtosis PUBLIC
  gnuradio::gnuradio-runtime fftw3::fftw3
)

One more thing is to improve the error handling - open python/__init__.py and change ImportError to ModuleNotFoundError
After all these changes you need to reinstall your OOT module.


text:
Q: What does ||= mean? I have a protected method in my application contoller
def current_user
  @current_user ||= User.find_by_id(session[:user_id])
end

I was wondering what ||= means?
I've been trying to search and find out, but to no avail.

A: ||= is a ruby idiom. It means if @current_user is nil (or false) then try to find it by id and assign it to @current_user, otherwise do nothing.
See these related questions.

A: This is part of Ruby.
If @current_user is nil or false, it will be set to User.find_by_id(session[:user_id])

A: Basically, a ||= b means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby), it is similar to a = b unless a, except it will always evaluate to the final value of a (whereas a = b unless a would result in nil if a was true-ish).

A: Notice the parallels with a += b, which is equivalent to a = a + b.
So a ||= b is equivalent to a = a || b.  As others have mentioned, this is the same as a = b unless a.

A: In ruby 'a ||= b' is called "or - equal" operator. It is a short way of saying if a has a boolean value of true(if it is neither false or nil) it has the value of a. If not it has the value of b.

A:
Basically, a ||= b means assign b to a if a is null or undefined or
  false (i.e. false-ish value in ruby), it is a shortcut to a = b unless
  a.
share|edit answered Sep 26 '11 at 14:48
Romain 6,9711330

In addition to this answer here`s an example -
arr = nil || []
arr0 ||= []

arr <=> arr0    *#=> 0*

This means arr expression and arr0 expression are equal.
Hope this helps to understand better ||= operator.


text:
Q: Non-squared PNG images as background image issue in IE8 In my website (it's just for test), I added a background-image as logo just beside heading in #title. It is working fine in Chrome and firefox but not in IE8.
When I tried adding jpg format images as logo instead, It is working fine in IE8. and then I tried using a squared png image which was also worked.
Then I realized that IE8 is not working if I use Non-squared images as shown below:

Anyway to make it work in IE8?

A: The problem is because IE8 doesn't support the CSS background-size property.
If you want to support IE8 and you want to use a background image, you'll need to supply an image that actually fits into the space you're giving it, rather than asking the browser to scale it for you.
The alternative is to have it as a foreground image in an <img> tag instead of a background image. That will allow it to be scaled.

A: It is working. You just think it's not.
Background-size is not supported in IE 8 (http://caniuse.com/#search=background-size) ;
Therefor, it's using it with the size that the image is (800x800). You are seeing the image. It's just that you're seeing the top-left corner of the image, which happens to be transparent.

Wanna see what I mean? Open up your favorite modern browser, open up your inspector tools, and remove the background-sizing property. "Where'd the image go?" It's still there. Now, make the logo div much bigger: 800x800 in fact. The image is back. You've basically emulated how IE8 is displaying the image (not the resizing the div part).
Since you know the size you want your logo to be, simply use an image that is the proper size and you won't actually need to background-size property.


text:
Q: Android capture and use image not working I've written code in Android to capture an image and then use that image as follows:
private static Intent i;
final static int cons = 0;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
public void takePicture()
{
    i= new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //Open camera
    startActivityForResult(i, cons);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Log.d("Testing if condition", "Test"); //This code does not execute
            Bundle ext = data.getExtras();
            Log.d("Upload image", ext.toString());
            sendForUpload(data); // function to upload file to server
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }
    }
}

This code lets me take a photo and it saves to the SD card. However, I'm not sure if the file is sent to the sendForUpload function where I've handled getting the path and uploading the file. In fact nothing inside the  if (resultCode == RESULT_OK) block works. How do I use the image captured from this activity?

A: Well, you have a few problems.
First, you are calling startActivityForResult(i, cons);. cons is 0. You are trying to compare 0 with CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE. Since CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE is 100, that will not work.
Second, you are calling data.getExtras().toString() (split over two Java statements). I would expect this to return a value like android.os.Bundle@34334143. If that is what you want to upload, fine. I am guessing that you want to upload the image. Since you did not include EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE Intent, you get a Bitmap of the thumbnail image taken by the camera via data.getParcelableExtra("data").
Third, you are making inappropriate assumptions:

This code lets me take a photo and it saves to the SD card.

There is no requirement for the camera app to save the image anywhere, let alone to removable storage. In fact, I would argue that this is a bug in your camera app. That is not surprising, as ACTION_IMAGE_CAPTURE implementations have bugs.

where I've handled getting the path and uploading the file

There is no path. You did not include EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE Intent, and so all you get back is the thumbnail Bitmap.

A: I'm using this to put the image in a ImageView:
Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

You can use bitmap or uri objects for upload or show your picture..
Hope it helps you.


text:
Q: Why can't I output a path when in rails console? I tried doing this when in rails console:
puts about_home_index_path
It gave me an erorr, why is that? should it work?

A: It was answered here: Rails: how do you access RESTful helpers?
You should use:

puts app.about_home_index_path


text:
Q: Unity OnMouseOver is offset to where my mouse actually is I am making a game in Unity and I want to detect when the mouse is over a square on a 2D UI. I want to use OnMouseEnter and OnMouseExit as triggers (or any other way if this is the wrong method) to make the square change color when mouse hovers over it.
Problem
The detection seems to be working fine, but it is offset to where my mouse is. The square changes color a good bit before the mouse actually enters. In the picture below the red dot is where the mouse was when the top green square changed from grey to green.

What I've tried
Right now I just have a simple Monobehaviour script which looks something like this:
public class Node : MonoBehaviour, IDropHandler
{

    [HideInInspector] private Color32 canPlaceColor = new Color32(159, 255, 159, 255);

    private void OnMouseEnter()
    {
        gameObject.GetComponent<Image>().color = canPlaceColor;
    }
}

I tried changing my Canvas scaling from Scale with screen size to Constant pixel but there is still an offset. Also tried changing camera to orthogonally which also did nothing.
Question
What is going on, why is there an offset to when OnMouseEnter detects the mouse over? Is there a better method of doing this?


text:
Q: How to install ear in local web sphere (automatically) I am looking for automatic Ear deployment for WAS6 application. Is there any default scripts provided by WAS6? If Yes, Please provide me script names and please explain me, how to use that. It would be great help for me.
If there is no default scripts available to deploy ear, How to proceed to write script.
Please do needful.
Thanks in Advance

A: WebSphere Application Server provides a scripting tool, wsadmin, that may be used for automating the deployment of applications. See this Info Center document for more details.
AdminApp.install('/ears/application1.ear', '[-cluster cluster1]')

Also, for more general help in writing scripts using wsadmin, here are some other helpful resources:

*

*WebSphere Application Server V6.1: System Management and Configuration: Administration with Scripting (Chapter 5)

*WebSphere Application Server V6.1 InfoCenter: Wsadmin tool


text:
Q: AWS SDK Lex PostText Error: TruncatingBigNumber can not be converted to an String I've been using AWS SDK (PHP) LexRuntimeService for a while and this is a sudden error that occurs for seemingly random cases.
PostText Args are set like this, depending on user input and data:
(
[botAlias] => xxxxx
[botName] => xxxxxxx
[inputText] => book a ride
[userId] => xxxxxxxxxxxxxx
[requestAttributes] => Array
    (
        [userID] => xxxxxxxxxxxxxx
        [userInput] => book a ride
        [passenger_first_name] => xxxxxxxx
        [passenger_last_name] => xxxxxx
        [passenger_email] => xxxx@xxxxxxxxx.com
        [channel] => facebook
        [chatbot_session_id] => xx
    )
)

These PostText Args should be what determines this error, but I cannot find any difference between working Args and erroring Args. When the SDK errors, this is what I get:

Aws\LexRuntimeService\Exception\LexRuntimeServiceException:
Error executing \"PostText\" on \"https://runtime.lex.us-east-1.amazonaws.com/bot/xxxxxxx/alias/xxxxxx/user/xxxxxxxxxxxxxx/text\";
AWS HTTP error: Client error: POST https:\/\/runtime.lex.us-east-1.amazonaws.com\/bot\/xxxxx\/alias\/xxxxx\/user\/xxxxxxxxxxxx\/text
resulted in a 400 Bad Request response:\n{\"Message\":\"class com.amazon.coral.value.json.numbers.TruncatingBigNumber can not be converted to an String\"}\n SerializationException (client): - {\"Message\":\"class com.amazon.coral.value.json.numbers.TruncatingBigNumber can not be converted to an String\"} in /var/www/html/yt074/thirdparty/aws/Aws/WrappedHttpHandler.php on line 193
\n

I've tried setting each of the Args to strings like this:
$requestAttributes["userID"] = (string) $userData['userID'];

But the error still occurs. Any suggestions/explanations for what might cause this error?


text:
Q: How do I position one image above the other in notty when using a linux subsystem in Windows 10? I want to use Notty, so I have been looking at the "basics" repo.
So I download basics_wow.ml:
open Notty
open Notty_unix

(*
 * ocamlbuild -pkg notty -pkg notty.unix basics_wow.native
 *)
let () =
let wow = I.string A.(fg lightred) "Wow!" in
I.(wow <-> (void 2 0 <|> wow))
|> Notty_unix.eol
|> Notty_unix.output_image

I put this into my terminal: ocamlbuild -pkg notty -pkg notty.unix basics_wow.native.
Then I try to run it: ./basics_wow.native
But instead of getting Wow! above Wow! I get this:

How do I get Wow! above Wow! ?

A: This currently does not seem to be possible. See this issue


text:
Q: Applying data mining techniques on Firebase Can i perform data mining techniques on a Firebase's Database?
I want to classify data that i will get from the user and come with some results from it for my Android graduation project.
The project core is Data mining, so is Firebase friendly for this?

A: The Firebase Realtime Database API is optimized for synchronizing data between large numbers of users. It is not ideally suited for data mining, which typically requires different access patterns to the data.
Note that it's quite possible and common to combine the Firebase Realtime Database with other data storage solutions to server all needs of an app. Many developers combine Firebase with BigQuery, using the latter for their data analysis. That way your users/app can write straight to the Firebase Database (or Cloud Firestore). You'll e.g. use Cloud Functions to pass that data onto BigQuery, where you do the analysis on it. Any analysis result you'll write back to the Firebase Database, where clients can read them. With this approach Firebase functions as a proxy between your (mobile) clients and your custom cloud infrastructure.


text:
Q: How to write the probability distribution function for this? A point Y is first selected from the interval (0,1)
Then a point X is selected from the interval (Y,1)
What is the probability distribution function of X?
I thought it should be f(x) = 1/(1-Y), but it seems wrong because then if Y=1, f(x)=undefined, while it should actually be zero...
What am I doing wrong?

A: The joint distribution of $X$ and $Y$  is uniform on the triangle with corners $(0,0)$, $(1,0)$, and $(1,1)$.
The joint density is $2$ in that triangle, and $0$ elsewhere. To find the density function of $X$, "integrate out" $y$. For $0\lt x\lt 1$, we get $f_X(x)=2x$.


text:
Q: ng-repeat filter not working with quotes When I add a filter using an input type text on my ng-repeat.
<input type="text" ng-model="inputSearch" />

    {{ item.value }}

if my object contain a value like foo's bar and I type in my input foo's bar it won't find anything.
I read that angular allow you to add another single quote like this foo'' bar to escape the quote.. but there is another way ?
I don't want to add treatment on my object.
thanks.

A: I think your problem with in {{item.value}} just use  {{item}} it will work.
 <input type="text" ng-model="inputSearch" />

   {{ item}}


text:
Q: A Number State of Light through a dielectric If a number state |1> picks up a factor of  $e^{-i\phi}$ on going through a certain medium, what factor will a number state |N> pick up? Will it be $e^{-iN\phi}$ or $e^{-i\phi}$ or something else? And what is the justification? Thanks.

A: As long as it is a linear optical medium - which is typically the case up to good accuracy - it will act as $a^\dagger\to e^{-i\phi} a^\dagger$ on the creation operators (i.e. in Heisenberg picture). Thus, it acts as
$$
|n\rangle =\tfrac{1}{\sqrt{n!}}(a^\dagger)^n|0\rangle \ \to\
\tfrac{1}{\sqrt{n!}}(e^{-i\phi}a^\dagger)^n|0\rangle=e^{-in\phi}|n\rangle\ .
$$


text:
Q: Amortized Analysis of Algorithms I am currently reading amortized analysis. I am not able to fully understand how it is different from normal analysis we perform to calculate average or worst case behaviour of algorithms. Can someone explain it with an example of sorting or something ?

A: average - a probabilistic analysis, the average is in relation to all of the possible inputs, it is an estimate of the likely run time of the algorithm.
amortized - non probabilistic analysis, calculated in relation to a batch of calls to the algorithm.
example - dynamic sized stack:
say we define a stack of some size, and whenever we use up the space,  we allocate twice the old size, and copy the elements into the new location.
overall our costs are:

*

*O(1) per insertion \ deletion

*O(n) per insertion ( allocation and copying ) when the stack is full
so now we ask, how much time would n insertions take?
one might say O(n^2), however we don't pay O(n) for every insertion.
so we are being pessimistic, the correct answer is O(n) time for n insertions, lets see why:
lets say we start with array size = 1.
ignoring copying we would pay O(n) per n insertions.
now, we do a full copy only when the stack has these number of elements:
1,2,4,8,...,n/2,n
for each of these sizes we do a copy and alloc, so to sum the cost we get:
const*(1+2+4+8+...+n/4+n/2+n) = const*(n+n/2+n/4+...+8+4+2+1) <= const*n(1+1/2+1/4+1/8+...)
where (1+1/2+1/4+1/8+...) = 2
so we pay O(n) for all of the copying + O(n) for the actual n insertions
O(n) worst case for n operation -> O(1) amortized per one operation.

A: Amortized analysis gives the average performance (over time) of each operation in
the  worst  case.
In  a  sequence  of  operations  the  worst  case  does  not  occur  often  in  each operation  -  some  operations  may be  cheap,  some  may be  expensive   Therefore,  a  traditional worst-case per operation analysis can give overly pessimistic bound. For example, in a dynamic array only some inserts take a linear time, though others - a constant time.
When  different  inserts  take  different  times,  how  can  we  accurately  calculate  the  total time? The amortized approach is going to assign an "artificial cost" to each operation in the sequence, called the amortized cost of an operation.  It requires that the total real cost of the sequence should be bounded by the total of the amortized costs of all the operations.
Note, there is sometimes flexibility in the assignment of amortized costs.
Three methods are used in amortized analysis

*

*Aggregate Method (or brute force)

*Accounting Method (or the banker's method)

*Potential Method (or the physicist's method)

For instance assume we're sorting an array in which all the keys are distinct (since this is the slowest case, and takes the same amount of time as when they are not, if we don't do anything special with keys that equal the pivot).
Quicksort  chooses a random pivot. The pivot is equally likely to be the smallest key,
the second smallest, the third smallest, ..., or the largest. For each key, the
probability is 1/n. Let T(n) be a random variable equal to the running time of quicksort on
n distinct keys. Suppose quicksort picks the ith smallest key as the pivot. Then we run quicksort recursively on a list of length i − 1 and on a list of
length n − i. It takes O(n) time to partition and concatenate the lists–let's
say at most n dollars–so the running time is

Here i is a random variable that can be any number from 1 (pivot is the
smallest key) to n (pivot is largest key), each chosen with probability 1/n,
so

This equation is called a recurrence.  The base cases for the recurrence are T(0) = 1 and T(1) = 1. This means that sorting a list of length zero or one takes at most one dollar (unit of time).
So when you solve:

The expression 1 + 8j log_2 j might be an overestimate, but it doesn't
matter. The important point is that this proves that E[T(n)] is in O(n log n).
In other words, the expected running time of quicksort is in O(n log n).
Also there's a subtle but important difference between amortized running time
and expected running time. Quicksort with random pivots takes O(n log n) expected running time, but its worst-case running time is in Θ(n^2). This means that there is a small
possibility that quicksort will cost (n^2) dollars, but the probability that this
will happen approaches zero as n grows large.

Quicksort O(n log n) expected time
  Quickselect Θ(n) expected time

For a numeric example:

The Comparison Based Sorting Lower Bound is:

Finally you can find more information about quicksort average case analysis here


text:
Q: css hover an background-repeat is not working I have completed play popup youtube video. Now i am struggling in hover an image part. I need , when an hover an image, it should show play button with opacity.
So that I tried:
.youTubeVideo:hover {
    opacity:0.5;
    background-color:#ffffff;
}
.videoThum:hover{
    background-image:url('playbutton.png');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
}

Now, when an hover, opacity only working, image didn't show. But if i remove no-repeat, it shows play button.
Live example on the jsFiddle

A: Add this to your CSS:
Live example with your code.
.videoThum:hover{
    background-image:url('http://www.californiagrinders.com/images/playbutton.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: top center;
}


text:
Q: Access complete bound value of a textbox in attached property With an attached property, I want to de-/increase the value of a textbox by that value when hitting Key.Up or Key.Down.
I defined the following property:
public static readonly DependencyProperty SmallFloatIncrementProperty = DependencyProperty.RegisterAttached(
      "SmallFloatIncrement",
      typeof(double),
      typeof(InputService),
      new UIPropertyMetadata(0.1));

    public static double GetSmallFloatIncrement(DependencyObject d)
    {
        return (double)d.GetValue(SmallFloatIncrementProperty);
    }

    public static void SetSmallFloatIncrement(DependencyObject d, double value)
    {
        d.SetValue(SmallFloatIncrementProperty, value);
    }

I have also registered for PreviewKeyDown on my TextBox and handle it like this:
    if(e.Key == Key.Up)
    {
      IncrementOrDecrementValue((DependencyObject)sender, true);
    }
    else if (e.Key == Key.Down)
    {
      IncrementOrDecrementValue((DependencyObject)sender, false);
    }

...
    private static void IncrementOrDecrementValue(DependencyObject sender, bool doIncrement)
    {
        if (sender is TextBox)
        {
          TextBox tb = (TextBox)sender;
          var increment = GetSmallFloatIncrement((DependencyObject)sender);

          var text = tb.Text;
          double textBoxValue = 0.0;
          if (!string.IsNullOrEmpty(text))
          {
             try{
               textBoxValue = Convert.ToDouble(text, FormatProvider);
             }
             catch (FormatException)   { }
          }

          tb.Text = Convert.ToString((doIncrement) ? textBoxValue + increment : textBoxValue - increment, FormatProvider);
          ValidateResult(sender);
        }
    }

I run into propblems when retrieving the value of the textbox. If for example the bound property is 1.234 but there is a StringFormat = N1 defined in the binding, the call tb.Text delivers 1.2 instead of the entire value. But I need to increment the original value by the specified amount (the value must be a multiple of the increment). Is there a way to retrieve the complete bound value of the textbox?
Thanks for your help!

A: Essentially you don't want to change the textbox's value, you want to alter the view-model's value by the keys. Therefore the correct solution is to bind this behavior directly to the view-model.
So, here's the attached property holding the value itself.
public static double GetSmallFloatIncrement(DependencyObject obj)
{
    return (double)obj.GetValue(SmallFloatIncrementProperty);
}

public static void SetSmallFloatIncrement(DependencyObject obj, double value)
{
    obj.SetValue(SmallFloatIncrementProperty, value);
}

public static readonly DependencyProperty SmallFloatIncrementProperty =
    DependencyProperty.RegisterAttached("SmallFloatIncrement", typeof(double), typeof(TextBoxExtensions),
        new PropertyMetadata(0.0));

Another attached property to implement this functionality and toggle it on/off:
public static bool GetSmallFloatIncrementOn(DependencyObject obj)
{
    return (bool)obj.GetValue(SmallFloatIncrementOnProperty);
}

public static void SetSmallFloatIncrementOn(DependencyObject obj, bool value)
{
    obj.SetValue(SmallFloatIncrementOnProperty, value);
}

public static readonly DependencyProperty SmallFloatIncrementOnProperty =
    DependencyProperty.RegisterAttached("SmallFloatIncrementOn", typeof(bool), typeof(TextBoxExtensions),
        new PropertyMetadata(false, OnSmallFloatIncrementOn));

static void OnSmallFloatIncrementOn(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var textBox = (TextBox)d;

    void OnKeyDown(object sender, KeyEventArgs keyArgs)
    {
        if (keyArgs.Key == Key.Up)
            IncrementOrDecrementValue(textBox, .01);
        else if (keyArgs.Key == Key.Down)
            IncrementOrDecrementValue(textBox, -.01);
    }

    if ((bool)e.NewValue)
        textBox.PreviewKeyDown += OnKeyDown;
    else
        textBox.PreviewKeyDown -= OnKeyDown;
}

The function to increment gets simple now:
static void IncrementOrDecrementValue(TextBox textBox, double inc)
{
    var cur = GetSmallFloatIncrement(textBox);
    SetSmallFloatIncrement(textBox, cur + inc);
}

And now we can use it:
<TextBox Text="{Binding VMValue, StringFormat=F1}"
             local:TextBoxExtensions.SmallFloatIncrement="{Binding VMValue, Mode=TwoWay}"
             local:TextBoxExtensions.SmallFloatIncrementOn="True"/>

Note: with these increment and string format values you'll have to push the key 10 times until you see a value change in the TextBox. But this is something you can adjust to your taste.


text:
Q: problem in select into query Why m i getting error incorrect syntax near the keyword  IN in the following query?
select * into persons_backup IN 'HRMS.mdb' from persons

Thank you

A: Assuming SQL Server (based on your previous question) you would need
select *
into persons_backup
from HRMS.mdb.persons

or
select *
into HRMS.mdb.persons_backup
from persons

dependant upon what you are trying to do exactly. See SELECT ... INTO syntax here

A: Assuming you want to add all rows from persons into another table persons_backup:
Insert into persons_backup select * from persons;

Depending on the RDBMS you use, you might have to put () around the select.


text:
Q: Empty model in z3 z3py snippet:
x = Int('x')

s = Solver()
s.add(x <= x)
print s.check()
print s.model()
print s.model().sexpr()

http://rise4fun.com/Z3Py/mfPU
Output:
sat
[]

Any value of x would do but z3 returns empty model.
Does a missing free variable x in the model indicates that any integer value is a valid model?

A: Yes, in Z3, if a constant (such as x) does not appear in the model, then it is a "don't care". That is, any value of x will satisfy the formula. When evaluating the value of a constant, we can enable "model completion". That is, Z3 will use an arbitrary interpretation for "don't care" symbols. Here is an example http://rise4fun.com/Z3Py/bvVO
x = Int('x')
s = Solver()
s.add(x <= x)
print s.check()
m = s.model()
print m.evaluate(x)
print m.evaluate(x, model_completion=True)
print m


text:
Q: Use Prerender.io on one.com server with AngularJS For my AngularJS app I try to use the service of Prerender.io on a server by one.com. The webserver used is Apache.
I already tried to use the following .htaccess file (compare https://gist.github.com/thoop/8072354)
# Change YOUR_TOKEN to your prerender token and uncomment that line if you want to cache urls and view crawl stats
# Change http://example.com (at the end of the last RewriteRule) to your website url

<IfModule mod_headers.c>
    RequestHeader set X-Prerender-Token "YOUR_TOKEN"
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    # If requested resource exists as a file or directory
    # (REQUEST_FILENAME is only relative in virtualhost context, so not usable)
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    # Go to it as is
    RewriteRule ^ - [L]

    RewriteCond %{HTTP_USER_AGENT} baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora\ link\ preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator [NC,OR]
    RewriteCond %{QUERY_STRING} _escaped_fragment_

    # Only proxy the request to Prerender if it's a request for HTML
    RewriteRule ^(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent|\.ttf|\.woff))(.*) http://service.prerender.io/http://%{HTTP_HOST}/$2 [P,L]

    # If non existent
    # Accept everything on index.html
    RewriteRule ^ /index.html [L]
</IfModule>

I tried to use Google Webmaster Tools (Fetch as Google) to check if it works. Unfortunately, the website that the Google bot is fetching is not the one that is prefetched by Prerender.io.
It might be, that the P flag in the RewriteRule is not executed. But I am not quite sure about that.

A: Fetch as Google has a known issue where it doesn't check for the escaped fragment protocol. The actual Googlebot does not have this issue and checks for the meta fragment tag and adds the escaped fragment parameter.
For either #! URLs or HTML5 push state URLs you still need to append ?_escaped_fragment_= manually.
Here's an answer from Google on that: https://productforums.google.com/forum/#!topic/webmasters/YaOZrKGYrGA
If you have a #! URL like
http://www.example.com/#!/user/1
then you'll want to have Fetch as Google fetch this URL
http://www.example.com/?_escaped_fragment_=/user/1
If you have a non #! URL like
http://www.example.com/user/1
then you'll want to have Fetch as Google fetch this URL
http://www.example.com/user/1?_escaped_fragment_=
Feel free to email me at todd@prerender.io if you're still seeing issues!


text:
Q: How do I solve $x=1.1^x$? Is it possible? I'm trying to find the intersection of $y=x$ and $y=1.1^x$. I've tried logging both sides and doing every log law on it, but can't figure it out. I know these equations intersect twice thanks to desmos. Using desmos, when I set y=nx, where n is a big number, because the point of intersection is off-screen, I have to scroll a lot. Plus, I'm just curious how to solve this equation, $x=1.1^x$. Also, would the solving process be similar for $x=1.1^{(x-1)}$.

A: There is a famous function called the Lambert W function which one of the applications deals with solving equations of the slightly more general form $$a^x = kx + m$$
Maybe you can use the derivation in the article to solve your problem?

A: Well... an approximate solution is $x = 38.229\ldots$, which I got by experimentation.
I knew that experimentation would work because letting
$$
f(x) = x
$$
and
$$
g(x) = 1.1^x
$$
I was able to check that $f(2) > g(2)$, but $f(50) < g(50)$ by direct computation, and because both are continuous, I could tell that there must be a number $a \in [2, 50]$ with $f(a) = g(a)$.
In fact, there's a really easy way, in a situation like this, to find the value of $a$ to any degree of accuracy you like: you let $h(x) = f(x) - g(x)$, and now you know that $h(2)$ and $h(50)$ have opposite signs.
You pick the midpoint, $26$, and evaluate $h(26)$. One of three things happens:

*

*$h$ at the midpoint is exactly $0$, and you stop, delighted!

*$h$, at the midpoint, has the opposite sign from $h(2)$

*$h$, at the midpoint, has the opposite sign from $h(50)$
In cases 2 and 3, you replace one of the endpoints with the midpoint so that the signs of $h$ at the two ends are still opposite, and go back to the "pick the midpoint" step and repeat.
This rapidly converges towards a number $a$ with $h(a) = 0$, so that $f(a) = g(a)$.
By "rapidly", I mean that in binary notation, you get an extra bit per iteration. That's not blindingly fast, but it's not bad.
This works because your two functions are continuous, and the Intermediate Value Theorem applies.
If you're hoping for some algebraic trick to let you express the value you're looking for in terms of something "known," my best guess is that someone will tell you it's all about the Lambert $W$ function...whose value you still have to compute numerically.

A: Your equation can be written in the form
$$x=e^{ax}$$ or
$$a=\frac{\log x}x.$$
The function on the right increases from $-\infty$, peaks at $(e,e^{-1})$ then decreases to $0$.
Hence, for $a<0$, there is a single real solution, smaller than $1$, for $0<a<e^{-1}$ there are two of them (one in $(1,e)$ and the other above $e$), and none for $a>e^{-1}$.