text:
Q: How do you make sure that a query always returns a result and sorts the results by relevance? Now I have a database set up like the following example:
id (int(11)) | name (varchar(20)) | food (varchar(20)) | fastfood (varchar(3)) | pricerange (int(11))

1            | McDonalds          | American           | Yes                   | 1
2            | Outback            | BBQ                | No                    | 2
3            | Mortons            | Steakhouse         | No                    | 3

Now I have a user form set up like the following:
<form action="index.php" method="GET" id="sheet">

    <select name="name1" id="name1">
        <option value="%">No Preference</option>
        <option value="outback">Outback</option>
        <option value="mcdonalds">McDonalds</option>
        <option value="mortons">Mortons</option>
    </select>

    <select name="food1" id="food1">
        <option value="%">No Preference</option>
        <option value="american">American</option>
        <option value="bbq">BBQ</option>
        <option value="steakhouse">Steakhouse</option>
    </select>

    <select name="fast" id="fast">
        <option value="%">No Preference</option>
        <option value="yes">Yes</option>
        <option value="no">No</option>
    </select>

    <select name="price" id="price">
        <option value="%">No Preference</option>
        <option value="1">Cheap</option>
        <option value="2">Middle Ground</option>
        <option value="3">Expensive</option>
    </select>

    <input type="submit" value="Submit" id="submit"></input>
    <input type="clear" value="Clear" id="Clear"<input>

</form>

Now when I run the following query if not all the fields match, I will get no result. How can I manipulate the query to display a result based on best match when I have ints & varchars involved?
$query = "SELECT * FROM .$usertable
             WHERE $name LIKE '$name' AND
                   $food LIKE '$food1' AND
                   $fastfood LIKE '$fast' AND
                   $pricerange LIKE '$price' ";

Fulltext search doesn't work because of the INT and 'OR' will not display the results based on the best match. Let's say the user selected 3 of the 4 options such as: BBQ | Yes | 2
Now, the best match in that case would be Outback, however because it is trying to match up fast food as well, it will return no result. And if there are even more options it gets even more complicated.
If anyone could shed some light on a solution for this problem I would be extremely appreciative.

A: First you need to parse those ints. These functions may help you:
http://php.net/manual/en/function.intval.php
http://es.php.net/manual/en/function.trim.php
Second, you may manipulate your query so the ints go like $pricerange <= $price order by $pricerange desc
(this query would give you first the items with closer pricerange starting from below. you can link it with another with closest priceranges starting from the top with a left join or put a selector to chose from above or from behind the range in case it's not matched. This is only a halfway solution but it works and many search algorithms implement something like that. If you squeeze your brain you may find something closer to what you want, linking querys with JOIN, UNION, LIMIT, etc. Check out those entries on the mysql manual)
Third, you may also use JOIN .. ON NOT NULL to add criterias to your search. Take a look at this (and, if you don't know how to use join, this)
Finally, I recomend you to get familiar with PDO. It's the best way to perform a proper database query in PHP.

A: This isn't really an issue of query syntax. The issue here is defining for your application what you consider to be a "best match". There's no straightforward best match for functions like this: you need to define it yourself. Once you do that you can work on implementing it.
As a simple example, you can define a "best match" as one where as many explicit query parameters as possible match, and int-valued parameters are as close as possible. Then you can compute a "score" for each match, and sort by that.
So suppose the search is food=BBQ, fastfood=Yes, price=2. Your query could look like this:
SELECT *,
    SUM(
        food=:food, -- if food matches, add one to score
        fastfood=:fastfood, -- if fastfood matches, add one to score
        -- finally, add 2 for an exact price match, 1 for off-by-one price match,
        -- 0 for off-by-two matches, etc
        (SELECT MAX(price)-1 from foods)-ABS(price-:price)
    ) AS score
    FROM foods ORDER BY score DESC

You can adjust how important you want each match to be by adjusting how much is added to the score. Also, you can decide if there are different "distances" between categories. E.g., maybe "Steakhouse" is more like "BBQ" than "American" is, so Steakhouse places should score higher.
This is a straightforward approach, but it can be inefficient since you need to calculate a score for each row. You can speed it up with multiple queries: first look for an exact match; if you don't find any, calculate the score for all rows that are partial matches. Only if nothing is still found fall back on a total table search.
SELECT * FROM foods WHERE food=:food AND fastfood=:fastfood AND price=:price;
-- if no matches then:
SELECT *, SUM(food=:food, fastfood=:fastfood, (SELECT MAX(price)-1 from foods)-ABS(price-:price)) AS score
WHERE food=:food OR fastfood=:fastfood OR price=:price ORDER BY score DESC

A: If you are on MySQL look and try the "match against" instruction !
And use "OR" instead of the "AND" ! (match against is the best way i think)

A: Well, the MySQL database is not really designed with that sort of thing in mind. It should give you back actually what you ask of it, not perform guesswork for you.
Unfortunately, this means you need to implement this logic in code.  Search for full match, then if that doesn't work, search for cases where certain items match.
The relevence of matches is going to be up to you as a designer.
That is not to say you can't put together a complex query to get the data you are after, you just have to build that logic (perhaps by doing UNIONS on the results of various SELECT statements).


text:
Q: add http:// to input if not present on blur For all input fields with the type of url (input[type=url]), on blur I wish to check if the value of an input contains http:// or https:// and if it does not to add http:// to the beginning of the user inputted value. Similar to the below jquery:
$('.txtUrl').blur(function(e) {
    if ($(this).val().match(/^http/) || $(this).val().match(/^https/)) {
        $.noop()
    }
    else {
        // get value from field
        var cur_val = $(this).val();
        // do with cur_val
        $(this).val('http://' + cur_val);
    }

});

How do I do this the angular way?

A: You could do the same functionality using angular directive.
Define ng-model that will take care of ng-model value.
Markup
<input type="url" my-directive ng-model="myUrl"/>

Directive
app.directive('myDirective', function() {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            var model = $parse(attrs.ngModel)
            element.on('blur', function(e) {
                var value = ctrl.$modelValue; //ngModel Value
                if (value.match(/^http/) || value.match(/^https/)) {
                    angular.noop()
                } else {
                    // assign value to $modelValue
                    model.assign(scope, 'http://' + value);
                }
            });
        }
    }
});

This could help you, Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to add administrators and managers entries into database for cakePHP 2x ACL aros and acos I'm implementing ACL in a CakePHP app that I have and I seem to be struggling with setting up ACOs. I've been following the Simple ACL Controlled Application
[https://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html] tutorial and I've set up the aros, acos and aros_acos tables using sql file.
In the documentation they said insert user,manager,group by browsing a website. Problem is when i browse for that website no such document was found there like bellow.
http://http://example.com/groups/add
Now how can i add users and administrators into database for aros and acos table using cake bake or SQL?

A: It was a silly mistake by me. Just need to use
localhost/project_name/users/add


text:
Q: Window not showing up in Window menu I am creating an OS X application with multiple windows.  The main window appears in the Window menu as expected.
I'm creating the 2nd NSWindow using initWithWindowNibName.  It appears as expected when I call showWindow.  However the window doesn't show up in the Window menu (under "Bring all to front" and the main window's name).
I tried:
[[NSApplication sharedApplication] addWindowsItem:[winController window]
                                                title:@"The Window"
                                                filename:NO];    }

I also tried:
[[winController window] setExcludedFromWindowsMenu:NO];

Neither of these seemed to help.
If you can't tell, I'm new to OS X (but I know Obj-C relatively well).

A: I figured it out.  I was creating the window in a NSResponder's init function.  Somehow it was happening too early and the sharedApplication wasn't ready yet.  When I moved the window creation into an awakeFromNib everything worked as expected.

A: The Window Programming Guide says that "This menu automatically lists windows that have a title bar and are resizable and that can become the main window".  Is there a reason that this window cannot become main, e.g., is it an NSPanel?


text:
Q: How to improve the speed while using NSURLSessionDownloadTask? I need to download some images and a video from server:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
for (int i = 0; i < _collectionArr.count; ++i) {

    NSURL *URL = [NSURL URLWithString:URL_ADDRESS(portNumber,_collectionArr[i])];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        NSLog(@"File downloaded to: %@", filePath);
        if (i == _collectionArr.count - 1) {
            [SVProgressHUD showSuccessWithStatus:@"Done"];
        }

    }];
    [downloadTask resume];
}

I found that it is so slow! The speed is about 200K/s and the time with Android is 2/3 less than iPhone.
When I download a mp4 about 4.6M, it takes 15s.
2014-11-29 13:46:35.071 testDownload[2105:47825] Begin
2014-11-29 13:46:51.740 testDownload[2105:47825] File downloaded to: file:///Users/apple/Library/Developer/CoreSimulator/Devices/259F2CB8-01FD-47C2-A38F-6100A2FF350A/data/Containers/Data/Application/71E553BC-F85D-4BFA-8937-FE9026FDF65C/Documents/VTS_01_audi.mp4

But when I using other app to download movies it can be 2M/s. Am I wrong when I use afnetworking ? How it happens and what can I do to deal with it.
Another question is that I know it's wrong to monitor the last request with  if (i == _collectionArr.count - 1){[SVProgressHUD showSuccessWithStatus:@"Done"];}  But I don't know the right answer.
Thanks for your help.

A: A couple of thoughts:

*

*The removal of the HUD when i hits count - 1 is not correct. You actually may remove it before they're all done. If you start two downloads, one huge one and one tiny one, the HUD will be dismissed when the second one finishes, but the other one might not be done yet. These run concurrently, so you have to wait until they're all done, not just when the last submitted one is done.
One way to do this is to use a dispatch group (which you enter as you submit the requests, leave in the completion block, and then add a dispatch group notification that removes the HUD).

*You're not doing anything else outside of this code that might be blocking the main thread are you? AFNetworking dispatches its completion blocks to the main queue, and if you block the main thread for anything, it will affect this performance. You could either use Instruments to identify waiting threads, or, for testing purposes only, temporarily change the completionQueue of the manager to be some custom queue of your own creation.
For example, before your for loop, do something like:
manager.completionQueue = dispatch_queue_create("com.example.app.netCompletionQueue", NULL);

That would take main thread blocking out of the equation (though this strikes me as unlikely unless you're doing something extraordinary in the main thread). Once you confirm this is not the issue, though, comment out that line, because you really do want to use the main thread for your completion blocks.

*Once you confirm the perf problem is not result on main thread contention issue, I'd suggest doing some benchmarking of alternative techniques (e.g. your own NSURLSession, etc.). This could help diagnose whether the problem is AFNetworking, rather than something like simulator vs device performance, caching, etc. Frankly, I find it unlikely that AFNetworking is, itself, the problem, though.


text:
Q: How to deploy our app which is running on parcel bundler In my recent project, I have made an animated website using gsap and parcel-bundler. When I want to run it, I will type parcel index.html or npm run dev and it will start a server on port 1234, making it accessible at http://localhost:1234/.
Can anyone tell me how to deploy it to netlify or Heroku?
My package.json file looks like this
{
   "name":"expportfolio",
   "version":"1.0.0",
   "description":"",
   "main":"app.js",
   "scripts":{
      "dev":"parcel index.html",
      "build":"parcel build index.html"
   },
   "author":"",
   "license":"ISC",
   "devDependencies":{
      "cssnano":"^4.1.10",
      "sass":"^1.26.7"
   },
   "dependencies":{
      "@dogstudio/highway":"^2.2.1",
      "gsap":"^3.3.0"
   }
}

Terminal:

Web:

A: There must be a command in parcel that will build your project. You can upload your project to netlify and then add this command to its Build Settings console and it'll use that command to build your application. You can define a lot of other stuff there too.
If this project is on github, you can just add your github account to netlify and directly transfer it over there.
ref: https://docs.netlify.com/configure-builds/get-started/#basic-build-settings

A: just use this command on the terminal on your project file: npx parcel build src/index.html. where src is the folder where index.html is and you will get a build on dist folder. Directly deploy it on netlify or any other platform easily.

A: Try this command from the docs: parcel build index.html


text:
Q: System.Data.OleDb.OleDbException: Unspecified error I'm Totally new in ASP.net and currently working on a CRM application. This project uses .mdb files as backend but I am getting the following runtime error:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:

System.Data.OleDb.OleDbException:
  Unspecified error
       Stack Trace:
[OleDbException (0x80004005):
  Unspecified error]
  EmployeeManager.isUser(String strUID,
  String strPswd) in
  d:\hosting\nitindia\App_Code\EmployeeManager.vb:481
  Employees.BtnSubmit_Click(Object
  sender, EventArgs e) in
  d:\hosting\nitindia\Employees.aspx.vb:35
  System.Web.UI.WebControls.Button.OnClick(EventArgs
  e) +111
  System.Web.UI.WebControls.Button.RaisePostBackEvent(String
  eventArgument) +110
  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
  eventArgument) +10
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
  sourceControl, String eventArgument)
  +13    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection
  postData) +36
  System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint) +1565

The above error occurs only when we upload these pages & test online. When running on localhost the error is not being raised.
What is the cause of this issue, and solution?

A:
System.Data.OleDb.OleDbException: Unspecified error

This error mostly belongs to permission error, for this error we have mutiple solutions as per situation

*

*Put the impersonate=false in web.config file.

*If you want to put the impersonate = true in that case you need to provide the read/write permission to impersonate user on "C:\Documents and Settings\server name\ASPNET" folder or through process monitor utility you can check which file don't have sufficient permission.

*If you have windows server 2008 then you will not found the ASPNET folder and still want impersonate=true then you need to change the configuration in IIS 7.5/7.0.
Go to IIS -> select your application pool -> Advanced Setting -> Process Model ->Identity=ApplicationPoolIdentity
Go to IIS -> select your application pool -> Advanced Setting -> Load User Profile = False
See here for more details.

A: Both of these conditions may cause this (rather unhelpfully named) error to occur:

*

*The ASPNET account not having permissions to open the file.

*The database file is locked by another user.

A: for answer finders :
try to look into https://learn.microsoft.com/en-us/iis/application-frameworks/running-classic-asp-applications-on-iis-7-and-iis-8/using-classic-asp-with-microsoft-access-databases-on-iis#using-process-monitor-to-gather-more-information  and set Permissions on the Temporary Folders
PS in my case it was impersonate user who does not have access to current user temp folder C:\Users\`Username`\AppData\Local\Temp\


text:
Q: Am I unwise to power a low-draw cooling fan off my router's USB port? tl;dr: I want to run a 120mm case fan (drawing 0.05A) off my router's USB port, and don't know whether to be concerned about running a DC motor off a sensitive box full of radios.
The CPU in my (ASUS RT-AC3200) Wi-Fi router has a tendency to self-report temps of 70°C and higher when working hard.
Because of my (admittedly potentially unfounded) concern about that temp, and because I like to tinker, I tried sitting the router atop a garden-variety 120mm case fan (marked 12V 0.16A), which I fed just 5V to keep it slow and quiet.
The router temp soon dropped to 57°C, which I like much better.
My cheapo meter tells me the fan draws 0.05A when fed 5.33V.
Given the installation of the router, it would be quite handy to power this fan off the router's USB port.
Though I don't know the USB port's specs, a current draw of 0.05A doesn't strike me as troubling--I know it will fundamentally "work."
What does give me pause, though, is putting a motor on the power bus of a box of sensitive radios, for fear of generating problematic electrical noise or causing other woes.
Should I avoid this? Or am I being paranoid?

A: All USB hosts must however be able to provide 100mA by default, so in terms of current you should have no issues.
However, fans are inductive and could produce back-EMF when the power switches off. This is basically a high voltage spike that will feed back into the USB port. Depending on how well protected the port is, this shouldn't be an issue. I would personally place a diode in anti-parallel with the fan (anode to GND). This will add some additional protection.
Another potential issue is that if the fan stalls, you may get a current surge as a result because the fan is basically just a DC motor, and current could rise rapidly under stall condition. This is likely not an issue with higher quality fans. Placing something like a 15Ω resistor in series between the 5V and the fan will limit the maximum current that can be drawn in the event of a stall. It will cause ~0.5V drop under normal conditions, but this shouldn't be an issue for the fan.
As a final point, the fan will generate electrical noise. I would personally place something like a 10μF capacitor across the USB +5V/GND pins. This in combination with the 15Ω resistor will act as a low pass filter, limiting the amount of noise that gets back into the device from the motor.
Something like this should suffice:

simulate this circuit – Schematic created using CircuitLab

Investigation - Akasa AK-183-L2B 12V 120mm Fan
So I though I would do a quick investigation with a branded (£8) fan, to see if my points about noise and filtering, quote "... are unfounded" (@AliChen)
So here is my PSU. I'm loading it with a ~33mA pure resistive load, which is an equivalent current draw to the fan:

Not bad I think you would agree. Regulating nicely, with ~40mV ripple/noise.
Now lets connect the fan. The fan draws roughly 33mA from the PSU, and is spinning happily.

There are now period spikes pulsing up to ~5.5V, with a large amount of ripple and noise (~200mVpp). I personally don't want that anywhere near a USB port.
Now lets put a capacitor across it:

Not bad, filters out a lot of the mess.
Now with a series resistor as well, same circuit as in the main answer above (minus the diode). I'm probing on the power supply side.

Even better. The spikes are cleaned up to ~70mVpp, and the noise is pretty clean.
As another point of interest, this particular fan draws about 55mA in a stall condition, so not too bad.

A: The ASUS RT-AC3200 gigabit router has USB 2.0 and USB 3.0 ports. As a self-powered device, the ports should be expected to deliver no less than 500 mA of current from USB2 port, and 900 mA from USB3 port. This is in accord with Section 7.2.1 of USB 2.0 specifications, which reads in part: "Systems that obtain operating power externally, either AC or DC, must supply at least five unit loads to each port." Therefore it should be of no concern to take 50 mA out of any of these ports.
Then, modern PC case fans are built on brushless technology, with a driver IC that uses magneto-sensitive index sensors, and then pulses internal stator windings accordingly to make the fan's blades to spin. A typical motor driver IC application is:

Due to massive deployment of fans in PC industry and associated potential liabilities from mechanical failures, the technology has developed fairly sophisticated methods to prevent electrical problems. The controllers (and internal boards) in PC fans have all sorts of protection against EMI, temperature, stalls, etc. The ICs would usually shut itself down if the rotor blades are not spinning.
Many manufacturers guarantee a 12-V fan operating range from 6 to 18 V, example is here.

Therefore operating a 12-V fan at 5 V is not far away from main specifications, and is frequently used in "silent PC" designs by DIYers. It is however advisable to check if the particular fan has any margins in this mode. This can be checked either using a variable benchtop power supply and dropping the voltage until the fan no longer starts, or just stalling the blade and making sure that the spin starts "happily", softly speaking.
Further, a USB port is required to have a sizable bypass capacitor on each USB host port. An example of the bypass from design guidance is shown below

Furthermore, in case of several USB ports, design recommendations are to use separate bypass caps on each port, and de-couple them from main power source with inductive filters,

This technique is required to avoid so-called "droop" effect, when a hot plug of a device in one port might cause power interruption for a device working in another port. Without this de-coupling a USB host would fail USB-IF certification. Therefore, any possible interference on power at one port is unlikely to penetrate internals of USB host and disrupt USB or any radio functionality.
In conclusion, just plug your fan into any of USB ports of your router, and, if it spins "happily", don't worry much.


text:
Q: Query about derivation for the grand partition function for an ideal fermi gas I am having trouble understanding the following derivation:

I am having a bit of trouble understanding what it means to sum over all states.
So this is how I am interpreting the above.
We have a gas of $N$ particles in different states $n_1, n_2, n_3,...$ with energies $Ɛ_1, Ɛ_2, Ɛ_3,...$ etc.
In the above derivation $E$ is just the total energy, given by $$\sum_{i=1}^{i=\infty} {n_iƐ_i}, $$
and $N$ is just the sum of the occupancies $n_1 + n_2 + n_3 + ...$.
My issue might be more with the mathematical notation than the physics but when we have a sum like the one above, the different terms in the sum are given by the indice $i$, i.e $$\sum_{i=1}^{i=\infty} {n_iƐ_i} ,$$ = $n_1Ɛ_1 + n_2Ɛ_2 + n_3Ɛ_3 +...$.
What are the different terms in the sum given by line 2 in the above derivation?
I can't even write the second term in the above sum as I don't see what the summing indice is.
Secondly, I don't understand what the logic is going from line 3 to line 4 is.
If someone understands the above derivation can you please explain it.

A: The index $i$ in $n_i$ and $\epsilon_i$ refers to the label of the one-particle states. I.e., the Hamiltonian $\hat H_N$ of the non-interacting gas of $N$ particles is written as a sum of $N$ one-particle Hamiltonian $\hat h_{\alpha}$:
$$
\hat H_N= \sum_{\alpha=1}^N \hat h_{\alpha}
$$
and the eigenstates of $\hat h_{\alpha}$ are the states $\left| i\right>$ such that
$$
\hat h_{\alpha}\left| i\right>=\epsilon_i \left| i\right>.
$$
In general, the number of the one-particle states is infinite ($i=1, \dots, \infty$).
$N$-particle states are obtained as symmetrized or anti-symmetrized tensor products of $N$ of such one-particle states. The corresponding $N$-particle energy, $E_N$, is just the sum of the one particle energy for each state, each multiplied by the number of particles which are in that state  (the occupation numbers $n_i$):
$$
E_N= \sum_{i=1}^{\infty} n_i \epsilon_i,
$$
with the constraint $\sum_{i=1}^{\infty} n_i=N$. Therefore, one could say that a single $N$_particle state is uniquely identified by the infinite set of occupation numbers $\left\{ n_i \right\}$, or equivalently by the ordered sequence $(n_1,n_2,n_3,\dots)$, always with the constraint $\sum_{i=1} n_i=N$.
Now, let's go to grand-canonical statistical mechanics. Your starting expression is a possible way to slightly simplify the derivation, by starting immediately with a sum ove all the states, without any constraint on the number of particles. It is a way to get almost immediately the correct final result for the gran-canonical partition function.
It could be interesting and probably pedagogically more useful to start with the expression for the gran canonical partition function, written as:
$$
\mathcal{Z} = \sum_{N=0}^{\infty} e^{\beta \mu N} Q_N ~~~~~~~~~~~[1]
$$
where $Q_N$ is the canonical partition function for a system of $N$ particles.
$$
Q_N=\sum_{\left\{ n_i \right\}; \sum_{i=1} n_i=N   } e^{-\beta E_N(\left\{ n_i \right\})}.
$$
The constraint $ \sum_{i=1} n_i=N $ can be absorbed into a Konecker's delta, in order to rewrite $Q_N$ as an unconstrained the sum over all possible values of the occupation numbers:
$$
Q_N=\sum_{\left\{ n_i \right\}  } e^{-\beta E_N(\left\{ n_i \right\})}\delta_{N,\sum_{i=1} n_i}~~~~~~~~~~[2]
$$.
Using this expression [2], the gran canonical partition function [1] can be rewritten as:
$$
\mathcal{Z} = \sum_{N=0}^{\infty} e^{\beta \mu N}\sum_{\left\{ n_i \right\}  } e^{-\beta E_N(\left\{ n_i \right\})}\delta_{N,\sum_{i=1} n_i}=
\sum_{N=0}^{\infty} \sum_{\left\{ n_i \right\}  } e^{\beta \mu N}e^{-\beta E_N(\left\{ n_i \right\})}\delta_{N,\sum_{i=1} n_i}=
\sum_{N=0}^{\infty} \sum_{\left\{ n_i \right\}  } e^{\beta \mu \sum_{i=1}^N n_i}e^{-\beta E_N(\left\{ n_i \right\})}\delta_{N,\sum_{i=1} n_i}=
\sum_{N=0}^{\infty} \sum_{\left\{ n_i \right\}  } e^{-\beta \sum_{i=1}^{\infty} n_i (\epsilon_i-\mu)}\delta_{N,\sum_{i=1} n_i}
$$
In the last formula, it is possible to invert the order of summation, leaving an external, unconstrained sum over all the possible choices of occupation numbers, while the sum over $N$ of the Kronecker's delta, for each choice of of the occupation numbers $\left\{ n_i \right\} $, is equal to $1$ (only one value of $N$ is equal to $\sum_i n_i $ ).
Therefore, we have arrived to the unconstrained sum over the occupation numbers.
Its explicit meaning is
$$
\sum_{\left\{ n_i \right\}  }=\sum_{n_1}\sum_{n_2}\sum_{n_3}\dots.
$$
So that, if each term in the sum is factorized [1] gets factorized as
$$
\left(\sum_{n_1} e^{-\beta n_1 (\epsilon_1-\mu)}\right)\left(\sum_{n_2} e^{-\beta n_2 (\epsilon_2-\mu)}\right)\left(\sum_{n_3} e^{-\beta n_3 (\epsilon_3-\mu)}\right)\dots.
$$
At this point the exact calculation depends on the statistics (two values of each occupation number for fermions, infinite values for bosons), but it is straightforward.


text:
Q: Is access token required even when publish_stream is granted? I am a newbie to facebook opengraph and creating facebook applications. I have developed an app in facebook and going by the opengraph tutorial I have inserted the necessary meta tags. Testing the app privately, "publish_stream" permission have been granted. Is it necessary to obtain user access token even if publish_stream permission has been granted by the user? How can one obtain user token?
function Visit_Link()
{
    $config = array();
    $config['appId'] = 'APP ID';
    $config['secret'] = 'APP SECRET';

    $facebook = new Facebook($config);
    $response = $facebook->api(
    'me/namespace:action',
    'POST',
    array(
            'website' => "WEBSITE",

        )
        );

    print_r($response);
}

The error displayed is Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in
P.S I am using fb php sdk

A: yes you do need the access token, a long lived one preferably (which last for 60 days). If you are testing your app with the graph api explorer token, you will always need a new one after 30 min or so, because it short-lived. Use this to login your user, because it will always return a long lived access token which you can store in the DB for offline-access (which facebook deprecated and introduced the long lived access tokens).


text:
Q: How could i make a mirrored (sync) hard link copy of files from different folders on windows? I'm trying to create hard link entries from a folders content into another folder, but synced in such a way that any files deleted from one (or the target) will be deleted from the other.
There is one caveat tough and is that the source folder is comprised of way too many sub-folders, with the files nested in then; My aim are said files mirrored into a single folder.
im used to link shell extension and its smart mirror is exactly what im looking for, however it can only target folders (not their contents), which would mirror all the sub-folders inside which im trying to get rid of...
Sadly no other symlinks will do for me. To give some context the files are part of an 'database' that is generated by an app as directories, and it creates a folder for every single file (every folder contain the main file and a sidecar, .json) and it's huge.
I want to access those files in a practical manner with a number of other applications - none of which handled symbolic links well, but work fine with hard links.
Given the sizes involved and my available space a mirrored copy is out of the question - so my hopes are with hard links.
Any ideas how may I achieve this? Any software that can make this?


text:
Q: Proof of Leibniz series expansion for $\pi$
It can be shown that for positive integer values of $n$,
  $$1+2(\cos x + \cos 2x + \cos 3x + \dots + \cos nx) = \frac{\sin(n+\frac{1}{2})x}{\sin(x/2)},\quad\text{Do NOT prove this}$$
  (i) Show that:
  $$\int_0^{\pi/2}\frac{\sin(n+\frac{1}{2})x}{\sin(x/2)}\mathrm{d}x = \frac{\pi}{2}+2(1-\frac{1}{3}+\frac{1}{5}-\dots+\frac{1}{n}\sin(\frac{n\pi}{2}))$$
  (ii) Show that:
  $$\left\lvert\int_{\pi/2}^{\pi}\frac{\sin(n+\frac{1}{2})x}{\sin(x/2)}\mathrm{d}x\right\rvert\leq\frac{1}{2n+1}\left(2\sqrt{2}+\int_{\pi/2}^{\pi}\frac{\cos(x/2)}{\sin^2(x/2)}\mathrm{d}x\right)$$
  (iii) Hence, show that as $n\to\infty$:
  $$\int_0^{\pi/2}\frac{\sin(n+1/2)x}{\sin(x/2)}\mathrm{d}x \to \pi$$

Does anyone have a website or a link to the solution for the Leibniz Series expansion for $\pi$ that has all this trigonometry things in it? (Simple solution as I am in Year 12) Most of the online solutions for Leibniz Series use geometric series or something like that.
Anyone part i was very simple, as you just use the expansion in the question and then you can easily integrate to get the required result.
However, not sure what to do for part ii. I tried integration right hand side as $\cot(x/2)\csc(x/2)$ which gives $-2\csc(x/2)$ but I'm not sure if that approach is correct and how I am able to prove the inequality part. Also because the limits have switched so I am slightly confused.


text:
Q: Как правильно сделать отношение между такими таблицами в SQL?
*

*Есть таблица пользователей (User).

*Есть таблица товаров (Product).

*Есть таблица групп пользователей (UsersGroup).

Всего две группы: Пользователь и продавец. Отношение между User и UserGroup - многие ко многим (один пользователь может входить во много групп, каждая группа может иметь много пользователей).
Пользователь, что относится к группе "продавец", может создать товар. Все могут покупать.
Суть:
Как правильно сделать отношение между пользователем, чтобы иметь возможность получать созданные товары пользователем и купленные товары этим пользователем (актуально для роли продавца).
Я думаю, для продавца внешний ключ:
FOREIGN KEY (sellerId) REFERENCES User(id)

А для тех, кто покупает - JUNCTION таблицу UserProducts?
Как решить этот вопрос правильно?


text:
Q: How to generate array of size M that only contains elements from provided list? What am I trying to achieve?

*

*I am trying to generate array of size M, but elements of that array can only be ones that can be find within of provided list.

My Python code:
import random
def generisanjevol1(nekalista):
 return random.choice(nekalista)

listaslova=['A','B','C','D','E']

for x in range(4):
 lista=[generisanjevol1(listaslova)]

print(lista)

Output:
['E']

As shown, in the output that I am getting there's only one element and not 4 (I expected to be 4, because of for loop)
Example of wanted Output:
['B', 'E', 'A', 'C']

Deeper explanation of what I am trying to achieve:
I have 1 array of 5 strings and I am trying to pass that array into function (generisanjevol1) and there I should generate array of size M (generated by random.choice() function but that array should be generated only from these 5 strings which are in array (listaslova) )
Can anyone help me how to do that exactly and how can I save multiple 'data' into one array ?
Thanks

A: If I understand you correctly, you want to generate array of size M that has elements only from supplied list. You can use random.choices() with k= parameter:
import random

M = 4

def generisanjevol1(nekalista, m):
    return random.choices(nekalista, k=m)

listaslova=['A','B','C','D','E']

lista=generisanjevol1(listaslova, M)
print(lista)

Prints (for example):
['A', 'E', 'C', 'E']


text:
Q: Left Join not returning Null or Non-matching values I want to return all values from PF_OUTPUT where the token ID equals "AdmissionInfo" as well as the matching results from PF_RESULTS just for PAT_SEQ = 105566168.
I've looked at some other questions and I have included the null statement within the Left join where clause, however it still is just returning matching values.
    SELECT CCDEV.PF_OUTPUT.TOKEN_NAME,
  CCDEV.PF_OUTPUT.DISPLAY_SEQ,
  CCDEV.PF_OUTPUT.RES_SEQ,
  CCDEV.PF_OUTPUT.LABEL_SEQ,
  CCDEV.PF_OUTPUT.DISPLAY_RESULT_NAME,
  CCDEV.PF_OUTPUT.OUTPUT_RESULT_NAME,
  CCDEV.PF_OUTPUT.OUTPUT_FIELD_NAME,
  PF_RESULTS.PERFORM_DDT,
  PF_RESULTS.CHART_DDT,
  PF_RESULTS.STAFF_SEQ,
  PF_RESULTS.RESULT_VALUE,
  PF_RESULTS.STATUS,
  PF_RESULTS.PF_RESULTS_SEQ,
  PF_RESULTS.PAT_SEQ,
  PF_RESULTS.PF_RESULT_SEQ,
  PF_RESULTS.RECORD_VERSION,
  PF_RESULTS.LABEL_SEQ AS LABEL_SEQ1
FROM CCDEV.PF_OUTPUT
LEFT JOIN PF_RESULTS
ON CCDEV.PF_OUTPUT.LABEL_SEQ      = PF_RESULTS.LABEL_SEQ
AND CCDEV.PF_OUTPUT.RES_SEQ       = PF_RESULTS.RES_SEQ
WHERE (CCDEV.PF_OUTPUT.TOKEN_NAME = 'AdmissionInfo'
AND PF_RESULTS.PAT_SEQ            = 105566168)
OR (CCDEV.PF_OUTPUT.TOKEN_NAME    = 'AdmissionInfo'
AND PF_RESULTS.PAT_SEQ           IS NULL)
ORDER BY CCDEV.PF_OUTPUT.TOKEN_NAME,
  CCDEV.PF_OUTPUT.DISPLAY_SEQ

A: Move PF_RESULTS.PAT_SEQ            = 105566168 line from your where condition to your ON clause of the join.
    SELECT CCDEV.PF_OUTPUT.TOKEN_NAME,
  CCDEV.PF_OUTPUT.DISPLAY_SEQ,
  CCDEV.PF_OUTPUT.RES_SEQ,
  CCDEV.PF_OUTPUT.LABEL_SEQ,
  CCDEV.PF_OUTPUT.DISPLAY_RESULT_NAME,
  CCDEV.PF_OUTPUT.OUTPUT_RESULT_NAME,
  CCDEV.PF_OUTPUT.OUTPUT_FIELD_NAME,
  PF_RESULTS.PERFORM_DDT,
  PF_RESULTS.CHART_DDT,
  PF_RESULTS.STAFF_SEQ,
  PF_RESULTS.RESULT_VALUE,
  PF_RESULTS.STATUS,
  PF_RESULTS.PF_RESULTS_SEQ,
  PF_RESULTS.PAT_SEQ,
  PF_RESULTS.PF_RESULT_SEQ,
  PF_RESULTS.RECORD_VERSION,
  PF_RESULTS.LABEL_SEQ AS LABEL_SEQ1
FROM CCDEV.PF_OUTPUT
LEFT JOIN PF_RESULTS
ON CCDEV.PF_OUTPUT.LABEL_SEQ      = PF_RESULTS.LABEL_SEQ

   AND CCDEV.PF_OUTPUT.RES_SEQ       = PF_RESULTS.RES_SEQ

 AND PF_RESULTS.PAT_SEQ            = 105566168

    WHERE (CCDEV.PF_OUTPUT.TOKEN_NAME = 'AdmissionInfo')
    OR (CCDEV.PF_OUTPUT.TOKEN_NAME    = 'AdmissionInfo'
    AND PF_RESULTS.PAT_SEQ           IS NULL)
    ORDER BY CCDEV.PF_OUTPUT.TOKEN_NAME,
      CCDEV.PF_OUTPUT.DISPLAY_SEQ

When you include a column from the RIGHT table of your LEFT join you essentially eliminate the LEFT join and make it an inner join.  Unless you are saying where RIGHTTable.column IS NULL.

A: It looks like you're using the left-joined table in the where clause. This effectively makes it an inner join since any record that doesn't exist wil always yield false.
Unless of course the check in the where clause includes an 'is null' check.
You should move the PF_RESULTS.PAT_SEQ = 105566168 check to the on clause of the left join to fix this.


text:
Q: R: How to assign a value in a dataframe column based in rows selected by some criteria? I have a dataframe like:
> head(bedfile)
                        chr start   end                        fam    class_subclass Jval_at_closing step strand    code            family
1 1.1000_SRR13070663.317319   582   665      LINE__rnd-6_family-16     LINE/I-Jockey               2    3      R    LINE   rnd-6_family-16
2 1.1000_SRR13070663.317319 20701 20804    LINE__rnd-5_family-6279           LINE/L2               3    2      F    LINE rnd-5_family-6279
3 1.1001_SRR13070663.317930  1023  1117     DNA__rnd-5_family-1403 DNA/TcMar-Mariner               2    3      R     DNA rnd-5_family-1403
4 1.1001_SRR13070663.317930  1139  1196 Unknown__rnd-5_family-4199           Unknown               3    3      F Unknown rnd-5_family-4199
5 1.1001_SRR13070663.317930  1199  1282 Unknown__rnd-5_family-6039           Unknown               4    3      R Unknown rnd-5_family-6039
6 1.1001_SRR13070663.317930  1317  1384 Unknown__rnd-6_family-2340           Unknown               5    3      F Unknown rnd-6_family-2340

and another one:
> head(CODE)
      V1 V2 V3  V4 V5
1   rDNA  F  S 500  3
2   rDNA  R  s 500  3
3 CL0015  F  O 300  3
4 CL0015  R  o 300  3
5 CL0076  F  P 300  3
6 CL0076  R  p 300  3

I would like to create a new column in the first one, and assign different values to selected rows based on criteria, using a nested for loop that creates the criteria:
    for (i in unique(CODE$V1)) {
        for (j in unique(CODE$V2)) {
                bedfile[bedfile$code == i & bedfile$strand == j,]$codification <- CODE[CODE$V1 == i & CODE$V2 == j,]$V3}}

The idea is that a particular value from one dataframe to be assigned to all rows that match these criteria in bedfile, but the actual code does not work. The problem is in the assignation line, since the following statement does not work either:
bedfile[bedfile$code == "LTR" & bedfile$strand == "+",]$codification <- "some_string"

Can anyone help me? I think that it may be also a way more efficient way for do that than with a nested for loop, but I don't know how
Thank you


text:
Q: Can vimgrep be used with lookaround assertions? I'm trying automate some text operations on a large JavaScript project, and wish to jump to the matches using vimgrep, which I'll follow with various macro invocations.
My target lines look like this:
getText("foo", 1)

But, not like this:
getText("foo")
getText("foo", [1])

I only want to match usages of getText that have more than one parameter, which is not enclosed in an array.
This search query (/), which uses a negative look-ahead, seems to work:
getText(.*",\(.*[\)\@!

But, running this regular expression with vimgrep:
:vimgrep /getText(.*",\(.*[\)\@!/ project/src/**/*.js

...fails with this message:
E682: Invalid search pattern or delimiter

I suspect that the look-ahead part of my regex is the cause, as the error goes away when I remove it.
Is there a way to utilize lookaround assertions with vimgrep?

A: :vimgrep loads each searched file into a Vim buffer and then applies Vim's regular expression search to it. So, unlike external tools as 'grepprg' / :grep, you can use the full Vim regular expression syntax here.
As @Matt already commented, the E682 is caused by failing to escape the [. When you use the expression in a regular / search, Vim just treats the [ as a literal character, as the collection isn't properly closed - your search works as expected.
In :vimgrep, the {pattern} has to be enclosed by /.../ delimiters, however. Apparently the parser continues to look for the ending /, but cannot find it as the not-yet closed [ collection keeps consuming characters, and this causes the error. This inconsistency isn't nice, and it obviously made you stumble, but it's not necessarily wrong. Now you know :-)
Just properly escape the [ character as \[, and it'll work:
:vimgrep /getText(.*",\(.*\[\)\@!/ project/src/**/*.js

There are special regexp atoms (\v and \V) that change the amount of escaping; some people like to use them (to avoid excessive escaping, or for better readability) - I mostly find the necessary shift in interpretation distracting.

A: @IngoKarkat answered your question directly. However, :vimgrep can be slow on large projects so it would be good to have an alternative if the need arises.
:grep and 'grepprg'
Vim's :grep is similar to :vimgrep except it uses an external program (like grep) to do the searching. You can even set 'grepprg' to a different tool like: ripgrep, the silver searcher, or git-grep. Using these tools can often speed up searching considerably.
set grepprg=rg\ --vimgrep

However, each tool uses their own regex syntax and may not provide positive/negative look-ahead/behind assertions. One way to do this is to search for all the criteria with :grep and then filter out the unwanted results via :Cfilter.
:grep -t js 'getText' project/src/

:Cfilter
:Cfilter /{pat}/ will allow you to filter the quickfix results with a pattern. This pattern will use Vim's regex syntax so you can use your assertions as you normally would.
:Cfilter /getText(.*",\(.*\[\)\@!/

You can use ! to negate the filter, e.g.  :Cfilter! /{pat}/, then entries not matching {pat} are used.
Note: :Cfilter is an optional package and you will need to do :packadd cfilter to load the plugin.
More help
For more help see:
:h :grep
:h 'grepprg'
:h :Cfilter


text:
Q: excel 2007 vba: how to refer to HPageBreaks I'm trying to write a macro which can look into the list of horizontal page breaks that a worksheet keeps, and it seems like HPageBreaks should be exactly that.  I can add or remove page breaks from it, but I can't seem to isolate the collection itself to look at its contents.  Even adding a watch and looking at ActiveSheet.HPageBreaks just brings up a generic looking object with a count field equal to 0 regardless of existing page breaks.
I'm really confused about this now.  Is there any way to look into the existing page breaks within a sheet?  A listing of what rows they occur on/between would be great.

A: This should get you started:
Sub testing()
    MsgBox "There are " & ActiveSheet.HPageBreaks.Count & " pagebreaks."
    For Each pb In ActiveSheet.HPageBreaks
        MsgBox "a page break lies between rows " & pb.Location.Row - 1 _
            & " and " & pb.Location.Row
    Next
End Sub

Here are some (rather scanty) references.:
http://msdn.microsoft.com/en-us/library/aa661442(office.10).aspx
http://msdn.microsoft.com/en-us/library/aa206426(office.10).aspx


text:
Q: @media min and max both or just one For example, use both

@media (min-width: 768px) and (max-width: 992px){...}
@media (max-width: 768px) {...}
or just

@media (max-width: 992px) {...}
@media (max-width: 768px) {...}
What's more efficient? I want browser performance!
To width less then 768px in the second case the browser will apply the style two times until get the correct one?

A: Use this one
@media (min-width: 768px) and (max-width: 992px){...}
@media (min-width: 480px) and (max-width: 767px) {...}

In this way browser not apply same css two times and you can easily use css with different property in different devices size.
Sometimes browser don't overwrite the css in different device media query then you use !important in css.
Example
@media (min-width: 768px) and (max-width: 992px){
 .nav{max-width:900px;}
}
@media (min-width: 480px) and (max-width: 767px){
 .nav{max-width:700px !important;}
 // only use important if browser not apply this property in this device size
}


text:
Q: cut/copy file with it's related file/folders like html I've a binary file with "dat" suffix and a json file which contains information about that file. Is there any way to cut/copy json file whenever .dat file cut/copied? (As you know .html file has a folder which contains it's css and gifs, ... when we copy the file, the folder also will be copied.)
my platform is windows 7.


text:
Q: Display filled form fields in a div as the question specifies I want the filled form entries to display somewhere below the form.
I have tried to build a string based on each input value. But on hitting submit button nothing shows up and it just scrolls to the top of the page.

$(function() {

  var $name = $("#name");
  var $email = $("#email");
  var $password = $("#password");
  var $mobile = $("#mobile");
  var $textarea = $("#textarea");
  var $filledHtml = "";

  $("form span").hide();

  function isEmailValid() {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test($email.val());
  }

  function isPasswordValid() {
    return $password.val().length > 8;
  }

  function isMobileValid() {
    return $mobile.val().length === 10;
  }

  function canSubmit() {
    return isPasswordValid() && isEmailValid() && isMobileValid();
  }

  function passwordEvent() {

    if (isPasswordValid()) {

      $password.next().hide();
      $filledHtml += $password.val() + "
";
    } else {

      $password.next().show();
    }
  }

  function emailEvent() {

    if (isEmailValid()) {

      $email.next().hide();
      $filledHtml += $email.val() + "
";
    } else {

      $email.next().show();
    }
  }

  function mobileEvent() {

    if (isMobileValid()) {

      $mobile.next().hide();
      $filledHtml += $mobile.val() + "
 ";
    } else {

      $mobile.next().show();
    }
  }

  function enableSubmitEvent() {

    $("#submit").prop("disabled", !canSubmit());

  }

  $email.focus(emailEvent).keyup(emailEvent).keyup(enableSubmitEvent);

  $password.focus(passwordEvent).keyup(passwordEvent).keyup(enableSubmitEvent);

  $mobile.focus(mobileEvent).keyup(mobileEvent).keyup(enableSubmitEvent);

  enableSubmitEvent();

  $("#submit").click(function() {
    $filledHtml += $textarea.val();
    $('#filled-data').html(filledHtml).addClass('small');
  });

});
html,
body,
div,
span,
applet,
object,
iframe,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}
body {
  line-height: 1;
  font-family: 'Maven Pro', sans-serif;
  font-size: 14px;
}
ol,
ul {
  list-style: none;
}
blockquote,
q {
  quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
a:hover {
  text-decoration: none;
  cursor: pointer;
}
/* ------------------------------------------------------------Reset Ends----------------------------------------------------------------------------------- */

#orders-mobile {
  display: none;
}
.group:after {
  content: '';
  clear: both;
  display: table;
}
.btn-login {
  background: #fc9816;
  border-radius: 4px;
}
.btn-demo {
  background: #fc9816;
  border-radius: 0;
  padding: 10px 15px;
  font-size: 1.7em;
  color: #fff;
  display: inline-block;
  width: 270px;
  text-align: center;
}
.caption {
  padding-bottom: 30px;
}
.caption h1 {
  text-transform: uppercase;
}
header,
footer {
  background: #E9F1F4;
}
footer {
  padding: 10px;
}
footer a {
  color: #5e5e5e;
}
footer .blue {
  color: rgb(62, 138, 213);
}
footer .orange {
  color: orange;
}
footer h3 {
  margin: 0.5em 0;
}
section {
  text-align: center;
  padding: 40px;
  padding-top: 0px;
}
.media p,
.media-heading {
  text-align: left;
}
.sec-title {
  margin: 1.2em 0;
  color: rgb(62, 138, 213);
}
.subtitle {
  margin-bottom: 40px;
}
.media-heading {
  color: rgb(62, 138, 213);
}
section#orders,
section#orders-mobile {
  background: #E9F1F4;
  min-height: 700px;
}
.mobile {
  background: url('images/mobile.png') no-repeat;
  width: 370px;
  margin: 0 auto 30px;
  position: relative;
  height: 600px;
  margin-top: 40px;
}
.mobile > img {
  height: 418px;
  width: 239px;
  position: absolute;
  top: 59px;
  left: 39px;
}
.marketplace-tabs span.glyphicon {
  font-size: 4em;
}
.marketplace-tabs .nav-tabs a {
  font-size: 1.5em;
  color: #5e5e5e;
}
.nav-tabs>li.active>a,
.nav-tabs>li.active>a:focus,
.nav-tabs>li.active>a:hover {
  color: rgb(62, 138, 213);
  background: transparent;
  border: 0px;
}
.nav-tabs>li>a:hover {
  border-color: transparent;
  background: transparent;
  color: rgb(62, 138, 213);
}
.nav-tabs>li {
  padding: 0 35px;
}
#orders-below {
  background: rgb(62, 138, 213);
  color: #fff;
}
#orders-below .sec-title,
#orders-below a {
  color: #fff;
}
#orders-below .glyphicon {
  font-size: 3em;
}
.form-control {
  border-radius: 0;
  padding: 8px 12px !important;
}
.form-control:not(textarea) {
  height: 39px !important;
}
form #submit {
  margin-top: 50px !important;
  font-size: 1.2em !important;
  text-transform: uppercase;
  border-radius: 0;
  background: rgb(62, 138, 213);
  color: #fff;
}
form #submit:hover {
  border: 1px solid rgb(62, 138, 213);
  color: rgb(62, 138, 213);
  background: transparent;
  font-weight: bold;
}
form span {
  border-radius: 5px;
  display: block;
  font-size: 1em;
  text-align: center;
  position: absolute;
  background: rgb(62, 138, 213);
  left: 103%;
  top: 5px;
  width: auto;
  padding: 7px 10px;
  color: #fff;
  z-index: 9999;
}
form span:after {
  right: 100%;
  top: 50%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-color: rgba(136, 183, 213, 0);
  border-right-color: #2F558E;
  border-width: 8px;
  margin-top: -8px;
}
@media only screen and (min-width: 768px) {
  h1 {
    font-size: 4em;
    margin: 2em 0;
  }
  h2 {
    font-size: 3.5em;
    margin: 1.7em 0;
  }
  h3 {
    font-size: 3em;
    margin: 1.5em 0;
  }
  h4 {
    font-size: 2.4em;
    margin: 1.2em 0;
  }
  h5 {
    font-size: 2em;
    margin: 1em 0;
  }
  h6 {
    font-size: 1.4em;
    margin: 0.7em 0;
  }
  p {
    font-size: 1.2em;
    margin: 1.4em 0;
  }
  header {
    background: url('images/header.jpg') no-repeat;
    background-size: cover;
    min-height: 700px;
    position: relative;
  }
  .navbar {
    border: 0;
    border-bottom: 1px solid #BEBEBE;
    border-radius: 0px;
  }
  .navbar-default {
    background-color: transparent;
  }
  .navbar-default {
    padding: 10px 0;
  }
  .navbar-default .navbar-brand {
    color: #fff;
    font-size: 2em;
  }
  .navbar-nav li > a {
    color: #fff !important;
    background: transparent;
    font-size: 1.2em;
  }
  .navbar-nav li > a:hover {
    color: #5e5e5e !important;
  }
  .navbar-default .navbar-nav>.active>a,
  .navbar-default .navbar-nav>.active>a:focus,
  .navbar-default .navbar-nav>.active>a:hover {
    color: #fff;
    background-color: transparent;
  }
  .btn-login {
    background: #fc9816;
    border-radius: 4px;
  }
  .navbar-nav>li>a {
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .navbar-default .navbar-toggle .icon-bar {
    background-color: #fff;
  }
  .navbar-default .navbar-toggle:focus,
  .navbar-default .navbar-toggle:hover {
    background: transparent;
  }
  .caption h1 {
    font-size: 4em;
  }
  .caption {
    color: #fff;
    width: 50%;
    height: 50%;
    margin: auto;
    position: absolute;
    top: 71px;
    left: 0;
    bottom: 0;
    right: 0;
  }
  .centered {
    margin-top: 14%;
    text-align: center;
  }
  .caption p,
  .caption .btn-demo {
    margin-top: 30px;
  }
  section#orders {
    position: relative;
  }
  section#orders .position-mobile {
    position: absolute;
    top: 70px;
    right: -450px;
    width: 346px;
  }
}
@media only screen and (min-width: 768px) and (max-width: 1280px) {
  .marketplace-tabs span.glyphicon {
    font-size: 1.5em;
  }
  section {
    padding: 10px !important;
  }
  .nav-tabs > li {
    padding: 0px;
  }
  .marketplace-tabs .nav-tabs a {
    font-size: 1.2em;
  }
  section#orders .col-sm-7 {
    padding: 0px;
  }
}
@media only screen and (min-width: 768px) and (max-width: 1425px) {
  h1 {
    font-size: 3em;
    margin: 1em 0;
  }
  h2 {
    font-size: 2.5em;
    margin: 0.7em 0;
  }
  h3 {
    font-size: 2em;
    margin: 0.5em 0;
  }
  h4 {
    font-size: 1.4em;
    margin: 0.3em 0;
  }
  h5 {
    font-size: 1.2em;
    margin: 0.2em 0;
  }
  h6 {
    font-size: 1.1em;
    margin: 0.2em 0;
  }
  p {
    font-size: 1.2em;
    margin: 0.4em 0;
  }
  .caption {
    width: 100%;
    height: auto;
  }
  header {
    min-height: 600px;
  }
  section {
    padding: 10px;
  }
}
@media only screen and (max-width: 767px) {
  section {
    padding: 15px 10px;
  }
  .pull-right {
    float: none !important;
  }
  #orders {
    display: none;
  }
  .navbar-default .navbar-nav>li>a {
    text-align: center;
  }
  header,
  header .caption {
    position: static;
    width: 100%;
    display: block;
    height: auto;
    text-align: center;
  }
  #orders-mobile {
    display: block;
    height: auto;
    min-height: auto;
  }
  form #submit {
    width: 100%;
    display: block;
    float: none;
  }
  .col-sm-3,
  .col-sm-4 {
    margin-bottom: 30px;
  }
  #orders-below .col-sm-4 a {} .marketplace-tabs-nulled .items a {
    font-size: 1.5em;
    margin-bottom: 20px;
    display: block;
  }
  .marketplace-tabs-nulled .items span {
    padding-bottom: 15px;
    font-size: 2.3em;
  }
}

Blah marketplace to run world's best Retail

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae dui et orci dapibus auctor a ac augue.

      <form action="" method="post">

            <input type="text" class="form-control" id="name" placeholder="Full Name">

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

            <input type="password" class="form-control" id="password" placeholder="Password">
            Enter a password longer than 8 characters

            <input type="number" class="form-control" id="mobile" placeholder="Mobile no...">
            Invalid

            <textarea id="textarea" class="form-control" rows="4" placeholder="Enter details..."></textarea>

          <button type="submit" id="submit" class="btn btn-info text-center pull-right">Submit</button>
      </form>

A: When you press the submit button, it does display, but at the same time, posts to the page. So the page technically gets refreshed. So add return false or e.preventDefault() so that it doesn't post it or refresh the page:
$("#submit").click(function(){
    $filledHtml += $textarea.val();
    $('#filled-data').html(filledHtml).addClass('small');
    return false;
});

And later you can use $.post() or $.get() to submit your form data and show it to your screen.
The other error is, that you have filledHtml not equal to $filledHtml. Forgot a dollar sign:
$("#submit").click(function() {
  $filledHtml += $textarea.val();
  debugger;
  $('#filled-data').html($filledHtml).addClass('small');
  //---------------------^ Add dollar here.
  return false;
});


text:
Q: Añadir espacios de tabulacion en CKEditor 5 Estoy tratando de añadir a CKEitor 5 la funcionalidad del boton TAB, es decir, agregar 4 espacios al precionar el tabulador.
buscando lo unico que encontre fue el codigo que ven aqui abajo

ClassicEditor
    .create(document.querySelector('#editor'))
    .then(editor => {
       editor.editing.view.document.on( 'keydown', function(e){

              if ( e.keyCode == 9 ) {
                  e.preventDefault();
                  this.value+="    ";
              }
       });
       myEditor = editor;
    })
    .catch(error => {
        console.error(error);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js"></script>
<textarea id="editor"></textarea>

No estando conforme, ya que me cambia el focus,  probe lo siguiente, tratando de tomar el objeto editor (que en fin de cuentas es el editor creado por la libreria)

ClassicEditor
    .create(document.querySelector('#editor'))
    .then(editor => {
       $(editor).on( 'keydown', function(e){
              if ( e.keyCode == 9 ) {
                  console.log( 'AAAAAA!!' );
                  e.preventDefault();
                  this.value += "    ";
              }
       });

       myEditor = editor;
    })
    .catch(error => {
        console.error(error);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js"></script>
<textarea id="editor"></textarea>

pero como ven, al precionar el TAB sigue cambiando el focus.
otro tentativo fue el siguiente, tratando de tomarlo gracias a las clases que utiliza CKEditor (clases tomadas de la ventana de desarrollo):

ClassicEditor
    .create(document.querySelector('#editor'))
    .then(editor => {
       $(".ck.ck-content.ck-editor__editable.ck-rounded-corners.ck-blurred.ck-editor__editable_inline").on( 'keydown', function(e){

              if ( e.keyCode == 9 ) {
                  editor.setData(editor.getData()+"    ");
                  e.preventDefault();
              }
       });
       myEditor = editor;
    })
    .catch(error => {
        console.error(error);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js"></script>
<textarea id="editor"></textarea>

en este caso directamente no hace nada mientras que si trato de alcanzar el textarea :

ClassicEditor
    .create(document.querySelector('#editor'))
    .then(editor => {
       $("#editor").on( 'keydown', function(e){

              if ( e.keyCode == 9 ) {
                  e.preventDefault();
                  this.value+="    ";
              }
       });

       myEditor = editor;
    })
    .catch(error => {
        console.error(error);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js"></script>
<textarea id="editor"></textarea>

me sigue cambiando el focus.
alguien tendria alguna idea de como podria hacer ?

A: Encontre la solucion!
hay que utilizar la propriedad .keystrokes.set() a la cual hay que pasar como parametro :keyName y callback en mi caso : editor.keystrokes.set("tab", (data, cancel) => {...}).
para agregar el texto hay que utilizar el metodo change del modelo : editor.model.change ( writer => {...})
ahi instanciamos un writer, y le decimos que queremos añadir como testo plano '    ', eso se hace de la siguiente manera : writer.insertText("    ", editor.model.document.selection.getFirstPosition())
ahi lo que estamos haciendo es :

*

*le decimos que insertar en este caso '    ' (4 espacios)

*donde lo queremos insertar ? en este caso agarramos nuevamente el modelo, y le decimos que tome la primera posision de la seleccion que hemos echo al interno del documento.

y el cancel() toma la funcion de e.preventDefault, es este caso es nativo osea que evita conflictos con otras partes de codigo.
PD: para probar el codigo escribir algo al interno del documento, en caso contrario el puntador queda al inicio aunque añada la indentacion

ClassicEditor
      .create(document.querySelector('#editor'))
      .then(editor => {
          editor.keystrokes.set( 'Tab', ( data, cancel ) => {
             editor.model.change( writer => {
                  writer.insertText("    ", editor.model.document.selection.getFirstPosition())
             });
             cancel();
           });
        myEditor = editor;
     })
     .catch(error => {
          console.error(error);
     });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js"></script>
<textarea id="editor"></textarea>

espero que sea de ayuda para alguien mas !


text:
Q: Question about Convolution terminology (analog to mean, variance, skewness, kurtosis,...) In probability theory we have mean, variance, skewness, kurtosis and etc. Can we use the same terms for a convolution (kernel) that sums to 1?
For example, can we say a $1$-D convolution kernel $[3/2,-2,3/2]$ has mean $0$ and $\sigma= 3$?
I'm wondering what basic results generalize from probability distributions to convolutions, or if there are any references that people would recommend (background: math and phy undergrad and grad.). Thanks!

A: If you work with non-negative kernels, then after the normalization, you can treat it as a distribution of a delta-signal after one convolution step. So it's natural to talk about statistics of such distribution. Important:  it's not the values statistics, it's position statistics assuming the values are probabilities. So if you have a kernel $[0.25, 0.5, 0.25]$ and assume the positions are $[-1,0,1]$, then the mean and sigma are
$$m=-1\times0.25 +0\times 0.5+1\times0.25 = 0\\
\sigma=(-1)^2\times0.25+0^2\times0.5+1^2\times0.25=0.5$$
However, if you want to treat the numbers in the kernel as a set and calculate statistics over those, it makes little sense.


text:
Q: What is Kendall Tau's co-efficient and Pearson co-efficient I came across these two terms in a paper about Natural Language Processing.
So I looked both of them up on the net and couldn't understand a thing.
So far I think their a method of comparing two quantities that have some kind of relationship with each other.Their used to determine how strong that relationship is but I don't quite understand how they work.
Could someone explain this like I'm 5?

A: Kendall Tau and Pearson product moment are two (among many) correlation measures that quantify how closely one variable "tracks" another.
If you get the concept of an outlier, data points that are far from most other points, then the question arises as to how to weigh the outliers.
Pearson correlation weighs the outliers quadratically: outliers are relatively important.
Kendall Tau is called a "robust" correlation because it's based on just looking at rank-order as opposed to metric information and weighs outliers far less.
What's the difference? Think of a bicycle race. If only the order in which racers finish matters, rather than the clock-times (ie, metric) then it doesn't matter how far apart the racers are spaced - hence the winner could win by 1 second an hour (ie, outlier) - but the rank orders will stay the same.
The above example is just for the sake of understanding - there is no actual correlation with anything (you'd have to introduce another variable, maybe the degree of doping?)
There are many different ways to correlate data (some, like mutual information, quite abstract), each having its own limitations but how they weigh the data is a key distinction among them.
Let me add since you mention NLP, that one measure of document distance is via vector space models where correlations between words reflect how close documents match, see for example Rehurek "Scalability of semantic analysis...", 2011.


text:
Q: How to use osmfilter to drop features with non-empty values on a key? I know one can use --drop="key=value" option with osmfilter to filter out OSM features for which key has a value of value.
For example, I can use
osmfilter input.o5m --drop="service=parking_aisle" --drop="service=driveway"  -o=output.o5m

to drop out service roads with the service tag and parking_aisle or driveway values.
How can drop all features for which the service have a non-empty value?
I tried --drop="service=", and it seems to drop features with an empty service tag too.
Any official documentation on how to do this?


text:
Q: Is that possible to create APEX application which access two databases simultaneously? I'm trying to extend an existing Apex app: connection to another database is required. Would it be possible?
Or at least start Apex on one database and connect to another.
This is for Oracle 12c and Apex 5.2

A: Database link is the best option if you want to access directly to the other database using queries, but if you want to get the information in JSON from one or two tables you can use ORDS to public a web service.


text:
Q: Incorrect mapping URL of SAPUI5 app on Fiori Launchpad I have two SAPUI5 apps and they both are working well, but there is a problem with them on Fiori launchpad. The initially opened app gets the correct url to our rest service (.json), but after I click the Home button and go to the second app the url gets put together incorrectly, because the resource-path of the second App still contains the folder of the initial App.
1. .../app1folder/app1resource
2. .../app1folder/app2resource

Correct would be:
2. .../app2folder/app2resource

The resources we use are created as destinations in the SAP HANA Cloud Platform Cockpit>Connectivity>Destinations
Neo-app.json
{
      "path": "/app1resource",
      "target": {
        "type": "destination",
        "name": "app1"
      },
      "description": "app1 API"
    }

How can I manually change the "appfolder"-directory (app1folder, app2folder)? Or is it automatically created by the fiori launchpad and unaccessible?
My application is built from scratch and not generated and maybe there's a common mistake.
Thank you.

A: Problem:
Both apps had the same id and as a result the launchpad couldn't load the applicationfiles into the scope.
Solution:
I changed the app id and all related references in the controllers, modules... .


text:
Q: Google Sheets. What's the formula for counting but checks conditions first? I don't know if my question is correct but basically, I have a Google Form that accepts two inputs from these questions:

*

*Text - Name

*Integer - How many newspapers did you sell today?

With this, I have linked a Google Sheet for this Form, and every input of the employees, adds another entry to the sheet. The employees answers the form every day.
Form Responses 1
+-----------+--------------+-----------------------------------------+
| Timestamp |     Name     | How many newspapers did you sell today? |
+-----------+--------------+-----------------------------------------+
|  June 11  | Kristine     | 12                                      |
+-----------+--------------+-----------------------------------------+
|  June 11  | Jeffrey      | 11                                      |
+-----------+--------------+-----------------------------------------+
|  June 12  | Kristine     | 5                                       |
+-----------+--------------+-----------------------------------------+
|  June 12  | Jeffrey      | 9                                       |
+-----------+--------------+-----------------------------------------+

In the same Sheet, I made another sheet called "Tracker" that tracks the number of newspapers sold for each individual (Just think Jeffrey and Kristine are the only ones who are selling the newspapers).
Tracker
+--------------+-----------------+
|     Name     | Newspaper Count |
+--------------+-----------------+
| Kristine     | 17              |
+--------------+-----------------+
| Jeffrey      | 20              |
+--------------+-----------------+

What should be the formula for the newspaper count? I've tried brute-forcing it by using this formula for each individual (this example is for Kristine):
IF('Form Responses 1'!B2 = "Kristine", 'Form Responses 1'!C2, 0) +
IF('Form Responses 1'!B3 = "Kristine", 'Form Responses 1'!C3, 0) +
IF('Form Responses 1'!B4 = "Kristine", 'Form Responses 1'!C4, 0) +
IF('Form Responses 1'!B5 = "Kristine", 'Form Responses 1'!C5, 0) ...

But when another entry is added, somehow the formula also changes. The cells move like this:
IF('Form Responses 1'!B2 = "Kristine", 'Form Responses 1'!C2, 0) +
IF('Form Responses 1'!B3 = "Kristine", 'Form Responses 1'!C3, 0) +

IF('Form Responses 1'!B6 = "Kristine", 'Form Responses 1'!C6, 0) +
IF('Form Responses 1'!B7 = "Kristine", 'Form Responses 1'!C7, 0) ...

So what should be the proper formula to solve this problem?

A: I found the solution, I used this:
QUERY('Form Responses 1'!B2:C,"SELECT SUM(C) WHERE B = 'Kristine'")
QUERY('Form Responses 1'!B2:C,"SELECT SUM(C) WHERE B = 'Jeffrey'")


text:
Q: Press any key to continue According to Microsoft's documentation, read-host lets the user type some input, and then press enter to continue. Not exactly the correct behavior if you want to have "Press any key to continue". (Wait... where's the Any key?!)
Is there a way to accomplish this? Something like read-char?
I've tried searching for "single character input" and "powershell input" to see if I could find a list of all ways to get input without much luck. And several Stack Overflow questions that looked hopeful use read-host which doesn't actually work for "press any key..." functionality.

A: I've created a little Powershell function to emulate MSDOS pause.  This handles whether running Powershell ISE or non ISE.  (ReadKey does not work in powershell ISE).  When running Powershell ISE, this function opens a Windows MessageBox.  This can sometimes be confusing, because the MessageBox does not always come to the forefront.  Anyway, here it goes:
Usage:
pause "Press any key to continue"
Function definition:
Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Yellow
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

A: Check out the ReadKey() method on the System.Console .NET class. I think that will do what you're looking for.
http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx
Example:
Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

A: Here is what I use.
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');


text:
Q: Spark Streaming - java.lang.NoSuchMethodError Error I am trying to access the streaming tweets from Spark Streaming.
This is the software configuration.

Ubuntu 14.04.2 LTS

scala -version

Scala code runner version 2.11.7 -- Copyright 2002-2013, LAMP/EPFL

spark-submit --version

Spark version 1.6.0

Following is the code.
object PrintTweets
{
 def main(args: Array[String]) {

  // Configure Twitter credentials using twitter.txt
  setupTwitter()

  // Set up a Spark streaming context named "PrintTweets" that runs locally using
  // all CPU cores and one-second batches of data
  val ssc = new StreamingContext("local[*]", "PrintTweets", Seconds(1))

  // Get rid of log spam (should be called after the context is set up)
  setupLogging()

  // Create a DStream from Twitter using our streaming context
  val tweets = TwitterUtils.createStream(ssc, None)

  // Now extract the text of each status update into RDD's using map()
  val statuses = tweets.map(status => status.getText())

  // Print out the first ten
  statuses.print()

  // Kick it all off
  ssc.start()
  ssc.awaitTermination()
 }
}

Utilities.scala
object Utilities {
/** Makes sure only ERROR messages get logged to avoid log spam. */
def setupLogging() = {
  import org.apache.log4j.{Level, Logger}
  val rootLogger = Logger.getRootLogger()
  rootLogger.setLevel(Level.ERROR)
}

/** Configures Twitter service credentials using twiter.txt in the   main workspace directory */
def setupTwitter() = {
  import scala.io.Source

  for (line <- Source.fromFile("./data/twitter.txt").getLines) {
   val fields = line.split(" ")
   if (fields.length == 2) {
    System.setProperty("twitter4j.oauth." + fields(0), fields(1))
   }
 }

}
}
Issues:
Since it needs the twitter4j library, i have added
twitter4j-core-4.0.4, twitter4j-stream-4.0.4 in eclipse build path as external jars.
Then i ran the program, it didnt throw any error. But the tweets not appearing in console. It were empty.
So i see some forums and downgraded twitter4j to 3.0.3. Also in Eclipse i chosen Scala 2.10 Library container in Build Path window.
After that i got java.lang.NoSuchMethodError run-time error.
16/05/14 11:46:01 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
java.lang.NoSuchMethodError:    twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at    org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at   org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:148)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:130)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:575)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:565)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:1992)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:1992)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:213)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

Please help me to resolve this. Initially i have installed spark by built using Scala 2.11. Is that the problem. Do i need uninstall everything and re-install Scala 2.10, then Spark pre-compiled package.
Or apart from Scala 2.11, do i need to have Scala 2.10 in my system?

A: The above exception seems to be caused by the incompatibility of spark version 1.6.0 and twitter4j 3.0.3 version.
twitter4j.TwitterStream which is being passed in the onStart method of org.apache.spark.streaming.twitter.TwitterReceiver, has method addListener which takes instance of twitter4j.StreamListener.
twitter4j 3.0.3 version has no method twitter4j.TwitterStream.addListener(StreamListener), instead it has few other addListener methods, which take the subclass of StreamListener.
twitter4j 4.0.4 version has the desired method, so that's why no error comes with this library. So changing to twitter4j 3.0.3 version will not solve the problem.
Problem is somewhere else.

A: In my case.
I had spark java project.
I cleaned pom file and start adding in order. First resolved spark related errors, then spark launcher, next on ward based on bigger library.
Note I was using cdh6.2.0 environment


text:
Q: Scrapyng AngularJS with Selenium in Python in Chrome headless mode I want to crawl information from a webpage which is made with angularjs.
My problem is, that if I crawl the page in "--headless" mode I do not receive my target element. Without "--headless" everything works fine.
May somebody can explain or point a link what are the differences to "--headless"?
I red http://allselenium.info/wait-for-elements-python-selenium-webdriver/ . What else could be the matter?
Thank you for any hints.
EDIT:
It also doesn't work with wait conditions in headless mode

A: Here is a solution that worked for me after some research, reading:
https://github.com/GoogleChrome/puppeteer/issues/665
https://intoli.com/blog/making-chrome-headless-undetectable/
The headless request is detected, so one has to set arguments hiding headless mode:
options.add_argument('--headless')
options.add_argument('--lang=de-DE')
options.add_argument('--user-agent="Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36"')

options.add_argument("window-size=1920x1080")


text:
Q: Storing SMS received through Twilio in a database I'm building a website that allows people to receive SMS messages online through Twilio.
I was planning on receiving the data through Twilio and then storing it in a database. Here is the quick example database schema that I came up with to handle this:
CREATE TABLE InboundSMS(
   MessageSid            TEXT,
   SmsSid                TEXT,
   AccountSid            TEXT,
   MessagingServiceSid   TEXT,
   From                  TEXT,
   To                    TEXT,
   Body                  TEXT,
   NumMedia              TEXT
);

But as I was reading the documentation I saw the below regarding MessageSid.

A 34 character unique identifier for the message. May be used to later
  retrieve this message from the REST API.

This lead me to question do I even need to store the received SMS messages in my own database? Can I just leave them stored on Twilio and retrieve them using the API?
What is the suggest thing to do here? How long are they kept for on Twilio?

A: Twilio developer evangelist here.
You could absolutely use Twilio as the store for these messages. We don't delete SMS messages so you can always look them up.
However, it depends on how you want to access the messages in your application. You can filter the list of SMS messages in various ways, but that might not apply to how you want to use them. There are also performance benefits to storing your messages inside your own database where you can access them with a connected database driver rather than over HTTP.
If you do want to keep them, you could very well use the MessageSid as the key field on your database table to match the way that Twilio stores the message.
Also, note that the MessageSid and SmsSid are equal. SmsSid is just a legacy value kept for backwards compatibility with an older version of the API.
Let me know if this helps at all.

A: Twillio will store your messages indefinitely until you delete them, however they do charge for storage.

Twilio bills for storage on a monthly basis. The first 5GB per month
  is stored free of charge, additional storage is charged at 20¢ per GB
  per month.

If you want to save a few bucks, better store them locally and delete them from Twilio upon inserting into local storage. It's probably going to be quicker to retrieve them from a local database anyway.
Makes sense that the Twilio employee would suggest you store remotely so they can make a few bucks :P
https://www.twilio.com/help/faq/sms


text:
Q: Cannot build project 'Simplify' with gradle I am trying to build the project 'Simplify' from github (https://github.com/CalebFenton/simplify). I have downloaded the files and ran the command in command prompt:
gradle build

But the build fails with the following error:
FAILURE:Build failed with an exception
*What went wrong:
>Could not resolve all dependencies for configuration ':demoapp:compile'
Required by org.cf:demoapp:1.0.0
>Could not resolve org.skf4j:slf4j-nop:1.7.7
>Could not get resource 'https://repo1.maven.org/maven2/org/slf4j/slf4j-nop/1.7.7/slf4j-nop-1.7.7.pom'
>Failure inintializing default system SSL context

....etc
What am I doing wrong?
I have internet connected during the build. I am using Java SE 8u74 and gradle 2.10.
P.S- When I tried to run the gradle wrapper by the command:
gradlew fatjar

It gives many errors.


text:
Q: $resource Callback not Being Invoked Angular I have a method which makes a call to Angular's $resource.  I am trying to test the return value of this method. This method should be simple enough to test.
Method Code
getCountries(): returnTypeObject {
        var countries = this.$resource(
            this.apiEndpoint.baseUrl,
            {
                'get': {
                    method: 'GET', isArray: false
                }
            });
        return countries;
    }

Unit Test
describe('module', (): void => {

    beforeEach((): void => {
        angular.mock.module('ngResource');
    });

    describe('getCountries...', (): void => {

        it("should...", inject(
            ['Builder', (Builder: IBuilder): void => {
                Builder.getCountries().get(
                    (value: any) => {
                        console.log(value);
                    }, (error: any) => {
                        console.log(error);
                    });
            }]));
    });

});

Now in the above code when I run my test the none of the callbacks ever get called.  Neither "value" nor "error" ever get printed.  I've been looking for a solution for quite a while now but haven't been able to find anything.
Keep in mind that I do not want to mock $resource, instead I want to test what is returned by getCountries().get() and then I want to use the callbacks to test the return value.


text:
Q: Nginx with Oracle I'm having the following problem, configured my nginx with gem passenger for my ruby-on-rails application using Oracle database (instant client), the principle is configured everything correctly, but when I access the address of my server, the following error occurs:
ERROR: ActiveRecord oracle_enhanced adapter could not load ruby-oci8 library. Please install ruby-oci8 gem. (LoadError)
.
.
.

My gem ruby-oci8 is installed, when I run on rails server, it works normally.
My gemfile:
gem 'rails', '3.2.15'
gem 'ruby-oci8', '~> 2.1.0'
gem 'activerecord-oracle_enhanced-adapter', '~> 1.4.0'

On Red Hat Enterprise Linux 6
Any tips?

A: I found an old server with configuration close to yours:
gem 'rails', '~> 3.2.0'
gem 'ruby-oci8', '~> 2.1.0'
gem 'activerecord-oracle_enhanced-adapter', '~> 1.4.0'

It's Ubuntu 12.04, Apache, and Passenger.
Virtual host config looks like this:
LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.33/buildout/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.33
PassengerDefaultRuby /usr/local/bin/ruby

<VirtualHost *:80>
    DocumentRoot /...path.../public
    <Directory /...path.../public>
        Allow from all
        Options -MultiViews
    </Directory>
</VirtualHost>


text:
Q: Count Distinct Visits per user and grouping them SELECT user_id,
SUM(DISTINCT CASE
WHEN click_date BETWEEN '2020-08-01' AND '2020-07-25'
THEN 1 ELSE NULL
END) total_visits_0to8_days,
SUM(DISTINCT CASE
WHEN click_date BETWEEN '2020-07-26' AND  '2020-07-18'
THEN 1 ELSE NULL
END) total_visits_8to14_days,
SUM(DISTINCT CASE
WHEN click_date BETWEEN '2020-07-19' AND  '2020-07-02'
THEN 1 ELSE NULL
END) total_visits_14to30_days,
SUM(DISTINCT CASE
WHEN click_date BETWEEN '2020-07-03' AND  '2020-06-02'
THEN 1 ELSE NULL
END) total_visits_30to60_days,
SUM(DISTINCT CASE
WHEN click_date BETWEEN '2020-06-02' AND  '2020-05-01'
THEN 1 ELSE NULL
END) total_visits_60to90_days
FROM my_table
GROUP BY user_id
My query is returning NULL for all the groups where as I want an aggregate of visit counts per user
DESIRED OUTPUT:
Sum of times each user id visited withing established time windows.
I am using COUNT DISTINCT in order to count each date only once so there should not be in total more than 93 visits per user from May 1st to Aug.1st if that makes sense? Thank you

A: When you use BETWEEN a AND b you must make sure that a is <= than b, otherwise BETWEEN always returns FALSE and this is what happens in your code.
So reverse the dates in all cases.
Also use COUNT() instead of SUM() if you want to count the distinct dates:
SELECT user_id,
  COUNT(DISTINCT CASE WHEN click_date BETWEEN '2020-07-25' AND '2020-08-01' THEN click_date END) total_visits_0to8_days,
  COUNT(DISTINCT CASE WHEN click_date BETWEEN '2020-07-18' AND '2020-07-26' THEN click_date END) total_visits_8to14_days,
  COUNT(DISTINCT CASE WHEN click_date BETWEEN '2020-07-02' AND '2020-07-19' THEN click_date END) total_visits_14to30_days,
  COUNT(DISTINCT CASE WHEN click_date BETWEEN '2020-06-02' AND '2020-07-03' THEN click_date END) total_visits_30to60_days,
  COUNT(DISTINCT CASE WHEN click_date BETWEEN '2020-05-01' AND '2020-06-02' THEN click_date END) total_visits_60to90_days
FROM my_table
GROUP BY user_id

A: you should use date conversion for'click_date'
is date . for oracle sample below
also notice first variable '2020-07-25' should be less than second '2020-08-01', yours is reverse.
click_date BETWEEN TO_DATE ('2020-07-25', 'yyyy/mm/dd')
               AND TO_DATE ('2020-08-01', 'yyyy/mm/dd');


text:
Q: Raster attribute table not showing up after exporting from R I exported a categorical raster from R and loaded it into ArcMap to visualize it. However, the attribute table is greyed out.
Code In R:
I first tell R that the values are factors by ratifying it.
lulc_1985.resam <- ratify(lulc_1985.resam)
rat1985 <- data.frame(
  ID= 1:11,
  LandCover = c("Deciduous","Cropland", "Settlement","Mixed Forest",
                "Scrubland","Barren Land","Wetlands","Plantations",
                "Coastal","Grassland","Evergreen")
)
levels(lulc_1985.resam)<- rat1985

The output of the above:
> lulc_1985.resam
class       : RasterLayer
dimensions  : 203, 192, 38976  (nrow, ncol, ncell)
resolution  : 1000, 1000  (x, y)
extent      : 628560.6, 820560.6, 1084984, 1287984  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=43 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names       : layer
values      : 1, 11  (min, max)
attributes  :
       ID LandCover
 from:  1 Deciduous
 to  : 11 Evergreen

As you can see above, the attributes exist here. Now I export the same out of R:
writeRaster(lulc_1985.resam,"E:\\lulc_1985.tif", format="GTiff")

The raster is now visualized in ArcMap, where the attribute table is greyed out.

How do I retrieve this attribute table?
The exported .tif is just 13kb in size.


text:
Q: Mapstruct: from a list of OM to list of entity (parent/child relationship) and viceversa I need to map a List into List in this following way (and viceversa)
One MyOM (the parent) can have a list of MyOM inside (the children). A child can't have children. A parent can have no children.
MyEntity has a field "parent" of type MyEntity.
How can I use Mapstruct in order to build these list of objects correctly?
thanks a lot
my classes
class MyOM {
    private String label;
    private Set<MyOM> children;
}

class MyEntity {
    private String label;
    private MyEntity parent;
}

json example of list of OM
[
    {
        "label": "parent",
        "children": [
            {
            "label": "child_1",
            "children": []
            },
            {
            "label": "child_2",
            "children": []
            }
        ]
    },
    {
        "label": "noParent_1",
        "children": []
    },
    {
        "label": "noParent_2",
        "children": []
    }
]

The interface is:
@Mapper(config = ServiceMapperConfig.class)
public interface IMyObjectMapper {

    MyOM map(MyEntity entity);

    List<MyOM> mapEntities(List<MyEntity> entities);

    MyEntity map(MyOM om);

    List<MyEntity> mapOMs(List<MyOM> dtos);

}


text:
Q: Oracle MAF : ListView displaying all data when setEntity sets empty ResultList? I am displaying list of data based on the query result in MAF along with A-Team persistence accelerator, below is the sample code which i'm using when some action button has been clicked,
ClassMappingDescriptor descriptor = ClassMappingDescriptor.getInstance(PojoClass.class);
DBPersistenceManager pm= getLocalPersistenceManager();

try {
   StringBuffer sql = pm.getSqlSelectFromPart(descriptor);
   sql.append(" WHERE ACTIVE_FLAG='YES'");
   sql = pm.constructOrderByClause(sql, descriptor);
   ResultSet set = pm.executeSqlSelect(sql.toString(), new ArrayList());
   List ResultList = pm.createEntitiesFromResultSet(set, (List) descriptor.getAttributeMappingsDirect());
   System.out.println("ResultList size : " +ResultList.size())
   setEntityList(ResultList);
} catch (Exception exp) {
   System.out.println("Exception : " + exp);
}

If ResultList size returns any value then it is working as expected, But when ever ResultList size returns 0 then listView showing all data of the particular associated pojo class table. In this case, actually non of the record should be displayed.
Any help would be appreciated, please comment below if you need any more details regarding this.


text:
Q: Dimension of affine variety $V(f+g)$ in terms of the dimensions of $V(f)$ and $V(g)$ Suppose I have two affine varieties over $\mathbb{C}$, say $V_1 = V(f_1, f_2)$ and $V_2 = V(g_1, g_2)$. Is there anything we can say about
the dimension of $V(f_1 + g_1, f_2 + g_2 )$ in terms of the dimensions of $V_1$ and $V_2$? Thank you very much!

A: Let $V(f) = V(f_1, \dots, f_m)$, $V(g) = V(g_1, \dots, g_m)$, and $V(f + g) = V(f_1 + g_1, \dots, f_m + g_m)$.
If $x \in V(f)\cap V(g)$, then $f_1(x) = \dots = f_m(x) = g_1(x) = \dots = g_m(x) = 0$ so for every $i$,
$$(f_i + g_i)(x) = f_i(x) + g_i(x) = 0 + 0 = 0$$
and hence $x \in V(f + g)$. Therefore $V(f)\cap V(g) \subseteq V(f+g)$ so
$$\dim V(f + g) \geq \dim(V(f)\cap V(g)).$$
This inequality is far from optimal in general. For example, take $f_1 = \dots = f_m = 1$ and $g_1 = \dots = g_m = -1$ on $\mathbb{C}^n$, then $V(f + g) = V(0, \dots, 0) = \mathbb{C}^n$ and $V(f) = V(g) = \emptyset$. The corresponding inequality $$n = \dim \mathbb{C}^n \geq \dim\emptyset = 0$$ is not that helpful.


text:
Q: Stuck on Python "KeyError: " in BFS code of a water jug scenario Intended Function of code: Takes a user input for the volume of 3 jars(1-9) and output the volumes with one of the jars containing the target length. jars can be Emptied/Filled a jar, or poured from one jar to another until one is empty or full.
With the code I have, i'm stuck on a key exception error .
Target length is 4 for this case
Code:
`
class Graph:

    class GraphNode:
        def __init__(self, jar1 = 0, jar2 = 0, jar3 = 0, color = "white", pi = None):
            self.jar1 = jar1
            self.jar2 = jar2
            self.jar3 = jar3
            self.color = color
            self.pi = pi

        def __repr__(self):
            return str(self)

    def __init__(self, jl1 = 0, jl2 = 0, jl3 = 0, target = 0):
        self.jl1 = jl1
        self.jl2 = jl2
        self.jl3 = jl3
        self.target = target
        self.V = {}
        for x in range(jl1 + 1):
            for y in range(jl2 + 1):
                for z in range(jl3 + 1):
                    node = Graph.GraphNode(x, y, z, "white", None)
                    self.V[node] = None

    def isFound(self, a: GraphNode) -> bool:
        if self.target in [a.jar1, a.jar2, a.jar3]:
            return True
        return False
        pass

    def isAdjacent(self, a: GraphNode, b: GraphNode) -> bool:
        if self.V[a]==b:
            return True
        return False
        pass

    def BFS(self) -> [] :
        start = Graph.GraphNode(0, 0, 0, "white")
        queue=[]
        queue.append(start)
        while len(queue)>0:
            u=queue.pop(0)
            for v in self.V:
                if self.isAdjacent(u,v):
                    if v.color =="white":
                        v.color == "gray"
                        v.pi=u
                        if self.isFound(v):
                            output=[]
                            while v.pi is not None:
                                output.insert(0,v)
                                v=v.pi
                                return output
                            else:
                                queue.append(v)
            u.color="black"
        return []

#######################################################
j1 = input("Size of first jar: ")
j2 = input("Size of second jar: ")
j3 = input("Size of third jar: ")
t = input("Size of target: ")

jar1 = int(j1)
jar2 = int(j2)
jar3 = int(j3)
target = int(t)

graph1 = Graph(jar1, jar2, jar3, target)
output = graph1.BFS()

print(output)

`
**Error: **
line 37, in isAdjacent
    if self.V[a]==b:
KeyError: <exception str() failed>

A: Strange but when I first ran this in the IPython interpreter I got a different exception:
... :35, in Graph.isAdjacent(self, a, b)
     34 def isAdjacent(self, a: GraphNode, b: GraphNode) -> bool:
---> 35     if self.V[a]==b:
     36         return True
     37     return False

<class 'str'>: (<class 'RecursionError'>, RecursionError('maximum recursion depth exceeded while getting the str of an object'))

When I run it as a script or in the normal interpreter I do get the same one you had:
... line 35, in isAdjacent
    if self.V[a]==b:
KeyError: <exception str() failed>

I'm not sure what this means so I ran the debugger and got this:
  File "/Users/.../stackoverflow/bfs1.py", line 1, in <module>
    class Graph:
  File "/Users/.../stackoverflow/bfs1.py", line 47, in BFS
    if self.isAdjacent(u,v):
  File "/Users/.../stackoverflow/bfs1.py", line 35, in isAdjacent
    if self.V[a]==b:
KeyError: <unprintable KeyError object>
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /Users/.../stackoverflow/bfs1.py(35)isAdjacent()
-> if self.V[a]==b:
(Pdb) type(a)
<class '__main__.Graph.GraphNode'>
(Pdb) str(a)
*** RecursionError: maximum recursion depth exceeded while calling a Python object

So it does seem like a maximum recursion error.  (The error message you originally got is not very helpful).  But the words <unprintable KeyError object> are a clue.  It looks like it was not able to display the KeyError exception...
The culprit is this line in your class definition:
        def __repr__(self):
            return str(self)

What were you trying to do here?
The __repr__ function is called when the class is asked to produce a string representation of itself.  But yours calls the string function on the instance of the class so it will call itself!  So I think you actually generated a second exception while the debugger was trying to display the first!!!.
I replaced these lines with
        def __repr__(self):
            return f"GraphNode({self.jar1}, {self.jar2}, {self.jar3}, {self.color}, {self.pi})"

and I don't get the exception now:
Size of first jar: 1
Size of second jar: 3
Size of third jar: 6
Size of target: 4
Traceback (most recent call last):
  File "/Users/.../stackoverflow/bfs1.py", line 77, in <module>
    output = graph1.BFS()
  File "/Users/.../stackoverflow/bfs1.py", line 45, in BFS
    if self.isAdjacent(u,v):
  File "/Users/.../stackoverflow/bfs1.py", line 33, in isAdjacent
    if self.V[a]==b:
KeyError: GraphNode(0, 0, 0, white, None)

This exception is easier to interpret. Now it's over to you to figure out why this GraphNode was not found in the keys of self.V!