Select em atributo String usando Split e LINQ?

Question: Eu tenho a seguinte string "1,2,3,4,5,6,7,8,9,10," que quero fazer um Split em um Select para buscar no banco de dados se o número 9 esta inserido em um campo que recebe strings de números. Quero fazer isso usando o LINQ do C# sem ter que usar foreach ou algo semelhante.
Como fazer isso ?
Estou tentando assim
public class SequenciaNumero {
     public string Numeros {get;set;}
}

SequenciaNumero sn = new SequenciaNumero();
sn.Numeros = "1,2,3,4,";

SequenciaNumero sn1 = new SequenciaNumero();
sn1.Numeros = "5,6,7,8,9,10,"

context.SequenciasNumeros.Add(sn, sn1);
context.SaveChanges();

//pesquisar numeros a partir de uma string de numeros
string _pesquisaNumeros = "10,11,12,15,"

//teste de split no LINQ
context.SequenciasNumeros
       .Select(x => x.Numeros.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries))
       .Where(x => _pesquisaNumeros.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries)
       .Any(y => y.Equals(x)));

//erro
Exception thrown: 'System.NotSupportedException' in EntityFramework.dll

No meu teste, estou tentando pesquisar a partir de uma string de numeros buscando os numeros que existem em comum no banco em strings. No caso, retornaria apenas o numero 10 que deveria ser encontrado q esta em _pesquisaNumeros
Comment: qual versão do Entity Framework? e também qual banco de dados?
Comment: @novic EF 6.4 e Mysql
Comment: então não vai funcionar porque ele não consegue traduzir isso para SQL, o que você pode fazer é na memória, mas, ai tem o custo do desempenho... não sei se vale a pena
Answer: Resolvido.
var _myNum = context.SequenciasNumeros
                                    .AsEnumerable()
                                    .SelectMany(x => x.Numeros.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                                    .Intersect(_pesquisaNumeros.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                                    .ToArray();


Equal vertical spacing in linear layout not working

Question: Running the below code in ANDROID studio is not giving me the desired result: Please help? I would like the 3 TextViews to be equally spaced out vertically in the screen of the device.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="Debanshu"
    android:textSize="24sp"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:text="Chakraborty"
    android:textSize="24sp"
    android:layout_weight="1" />

<TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:text="Voltas"
        android:textSize="24sp"
        android:layout_weight="1"/>

</LinearLayout>

Comment: . Thanks to all. Working now. Have just started learning.
Comment: With a screenshot would be easier to get what's wrong.
Answer: I believe you want this (added gravity just for the fun of it):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="Debanshu"
    android:gravity="center"
    android:textSize="24sp"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:text="Chakraborty"
    android:textSize="24sp"
    android:gravity="center"
    android:layout_weight="1" />

<TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:text="Voltas"
        android:textSize="24sp"
        android:gravity="center"
        android:layout_weight="1"/>

</LinearLayout>

Answer: As you LinearLayout height equal to wrap_content its working but as height wrapping view you are not getting desired view
try below making LinearLayout height equal to match_parent
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Debanshu"
        android:textSize="24sp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:text="Chakraborty"
        android:textSize="24sp"
        android:layout_weight="1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:text="Voltas"
        android:textSize="24sp"
        android:layout_weight="1"/>

</LinearLayout>

Answer: you can try this its work for me
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Debanshu"
    android:background="#ffa905"
    android:textSize="24sp"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Chakraborty"
    android:textSize="24sp"
    android:background="#ffffff"
    android:layout_weight="1" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Voltas"
    android:textSize="24sp"
    android:background="#008000"
    android:layout_weight="1"/>

enjoy!!!


Where is my iframe in the published web application/sidebar?

Question: I've been running into various errors when trying to control the window in DOM of my published web app and addon sidebar.

window.location returns a vague  unknown url like n-rysutduudd.google-usercontent.com instead of my published web app url script.google.com/[SCRIPT_ID]/exec

Attempts to redirect my published web-app to a new url fails
window.location.href=www.google.com

Forms in web app, when submitted  redirects to blank page.

After researching, I figured  this is due to the web content being served in a iframe. The documentation doesn't show much except that the webapp is sandboxed in a iframe.
Relevant documentation I've researched:

https://developers.google.com/apps-script/migration/iframe
https://developers.google.com/apps-script/guides/html/restrictions

Some of the relevant questions I've looked into:

window.location.href = window.location.href returning a blank page
Google script web app goes blank page after submit
How to stop redirected URL from being masked?

My specific question is: Where exactly is my iframe window in the published web app or my add on sidebar?
Answer:               PUBLISHED WEB APP
+---------------------------------------------+
|              script.google.com              |
|                                             |<------- [#0] window.top The top frame
|                                             |
|     +---------------------------------+     |
|     |     *.googleusercontent.com     |<----+-------- [#1] Outer Sandboxed Iframe
|     |         sandboxFrame            |     |
|     |    +-----------------------+    |     |
|     |    |        /blank         |    |     |
|     |    |    userHtmlFrame      |    |     |
|     |    |                       |    |     |
|     |    |     Where the html    |<---+-----+-------- [#2] Inner Sandboxed Iframe
|     |    |    file you created   |    |     |
|     |    |       is loaded       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    +-----------------------+    |     |
|     |                                 |     |
|     |                                 |     |
|     +---------------------------------+     |
|                                             |
|                                             |
|                                             |
+---------------------------------------------+

You're right. Most of the errors are due to  the iframe sandboxing done by Google. To answer your question,

Your window is located in a iframe with id: userHtmlFrame with  it's src set to /blank.

This frame is nested inside another frame with src: *.googleusercontent.com and id sandboxFrame.

Finally, The sandboxFrame is nested inside the main frame: script.google.com

Notes:

window in your  published app refers to the inner most frame.

This inner most frame has it's own cookies, storage and most other attributes unique to a window.

Unfortunately, this inner frame cannot be navigated elsewhere.

All window navigation must be done on the outermost frame: script.google.com.  This is why the documentation asks you to set base or anchor's target to the top frame.

Forms  without action are submitted to the inner frame /blank. Therefore, you're redirected to a blank page. The documentation states,

With IFRAME mode however HTML forms are allowed to submit, and if a form element has no action attribute specified it will submit to a blank page. Worse, the inner iframe will redirect to the blank page before the onclick handler has a chance to finish.

The solution is to add JavaScript code to your page that prevents the form elements from actually submitting, so that the click handlers have time to function

The origin of your iframe userHtmlFrame is inherited from sandboxFrame and set to *.googleusercontent.com. For all intents and purposes(cors, whitelisting origins, fetch requests), this is the  effective origin.

The sandboxFrame currently has the following  feature policy: allow

accelerometer *; ambient-light-sensor *; autoplay *; camera *; encrypted-media *; fullscreen *; geolocation *; gyroscope *; magnetometer *; microphone *; midi *; payment *; picture-in-picture *; speaker *; usb *; vibrate *; vr *

Currently, It has the following sandbox attributes, which limit what you can  do to other frames:

allow-downloads allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation

The outer windows/other windows can be  referenced using window.top or window.parent or window.opener from the inner frame. But, There are multiple restrictions imposed due to same origin policy. Cross origin access is limited mostly. Of particular note would be the window.postMessage, which allows communication between frames.

            SIDEBAR/MODAL DIALOG
+---------------------------------------------+
|              docs.google.com                |
|  +--------------------------------------+   |<------- [#0] window.top The top frame
|  |      /macros/.../iframedAppPanel     |<--+-------- [#1] Frame1 Same origin
|  |  +---------------------------------+ |   |
|  |  |     *.googleusercontent.com     |<|---+-------- [#2] Outer Sandboxed Iframe
|  |  |         sandboxFrame            | |   |
|  |  |    +-----------------------+    | |   |
|  |  |    |        /blank         |    | |   |
|  |  |    |    userHtmlFrame      |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |     Where the html    |<---+-|---+-------- [#3] Inner Sandboxed Iframe
|  |  |    |    file you created   |    | |   |
|  |  |    |       is loaded       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    +-----------------------+    | |   |
|  |  |                                 | |   |
|  |  |                                 | |   |
|  |  +---------------------------------+ |   |
|  |                                      |   |
|  +--------------------------------------+   |
|                                             |
+---------------------------------------------+

All the above notes for web app stands true also for webcontent published using HtmlService in sidebar or modal dialogs. However,

There is a extra nested layer of iframe here.
The allow-top-navigation is  missing from the sandbox attributes. Therefore, It is not possible to change/navigate the top frame(docs.google.com) here.

Changelog:

Sep 1, 2021: allow-top-navigation is removed and allow-top-navigation-by-user-activation is added instead. Security  for the end user is increased at the cost of convenience for the developers.


Manage Microsoft Server upgrades across multiple machines

Question: How do admins typically manage server upgrades across multiple servers?  It seems like Microsoft is always coming out with upgrades that require the server to be rebooted, but we have a half dozen production servers, and every time one is rebooted users are stuck without access.  How do most small-medium shops handle this situation?
Answer:
Install updates after hours

or

Schedule downtime with your users.

Beyond that it's finding what tool(s) will make your update process the most efficient so that you minimize the impact of downtime.
WSUS is an option for the Windows environment.  Other patch management solutions are available as well.  These will not handle many third party products, however.  With those you are limited to their patching mechanism.


How to compute $\int^1_0\sqrt{\ln(1/x)}dx$

Question:
$$\int^1_0\sqrt{\ln(1/x)}dx$$

How does one integrate the above by making use of a double integral, the only thing I could do is simplify $\ln(1/x)$ into $-\ln(x)$ which does not help much. How does one attack problems of such style?
Answer: We want $$I = \int_0^1 \sqrt{-\ln(x)} dx$$ The first thing is to get rid of this relatively ugly integrand. Let us do the most obvious substitution i.e. let $-\ln(x) = t^2$ i.e. $x = \exp(-t^2)$.
This gives us $dx = -2t \exp(-t^2) dt$. Hence, we get that $$I = \int_{\infty}^{0} t (-2t \exp(-t^2)) dt = 2 \int_0^{\infty} t^2 \exp(-t^2) dt$$ Now you should be able to evaluate this integral using the fact that
$$\int_0^{\infty} \exp(- \alpha t^2) dt = \dfrac{\sqrt{\pi}}{2 \sqrt{\alpha}}$$
Look here for various proofs for the result stated in the above line.
EDIT
You could rewrite your $I$ as $$I = \int_0^1 \int_0^{-\ln(x)} \dfrac{dt dx}{2 \sqrt{t}} = \int_0^{\infty} \int_{0}^{\exp(-t)} \dfrac{dx dt}{2 \sqrt{t}} = \int_0^{\infty} \dfrac{\exp(-t)}{2 \sqrt{t}} dt = \dfrac{\sqrt{\pi}}2$$
In general, any substitution/change of variable can be interpreted (or) made into an appropriate double integral.
Comment: Thanks! that method works. However, the question specifically required a method that uses the double integral more directly (although evaluating the gaussian does employ using a double integral + change of variable). Is it possible to apply double integration directly?


"Exact" probability from Normal distribution

Question: I have a small problem. Lets say I have a system that emits random distances from a certain point in space, its a real number from a normal distribution with mean = 0 and a set variance I know (lets say its 1 for this example). Note that distance of -x and x are the same, so practical distribution is like a "folded" bell starting at 0 with densities being double at every x>0.
My problem is that I am now analyzing a stream of those distances and I need to determine the probability that the system would emit that value. Say, I need to know what the probability is that system emits 1.23.
I know how to calculate P(X < dist), its CDF(dist) - CDF(-dist), but I have no idea how to work with a single point. Do I have to use some fixed ε environment e.g. 2*(CDF(x+ε)-CDF(x-ε))?
Answer: The probability of any single value from a continuous distribution is zero. This is what makes a continuous distribution different from a discrete distribution. The normal distribution is a continuous distribution and hence the probability of getting exactly 1.23 is zero. Further, the probability of getting either 1.23 or -1.23 is also zeo. Said differently, the set $\{-1.23;1.23 \}$ has measure zero (the probability that any of its values are produced by a normal is zero). The set of rational numbers has also measure zero. Depending on what you are interested in, a way might be to work with intervals which seems to be what you have suggested. You might also consider the probabilities of distances greater than a certain value.
If however you are interested in estimating the parameters of your normal distribution, then the likelihoodfunction might be what you are interested in. Assuming that the system creates distances independently (each distance is drawn independently from other distances) and according to the same folded normal distribution, then this likelihoodfunction is given by the product of the densities of each distance. This however isn't equal to the probability of the observed distances.
Comment: problem is I dont know which states led to the formation of emitter, but I know for a fact its there at certain location and emitting at certain gaussian density. What I have is a series of these emitters in n-dim hyperspace,  and I have a vector that was emitted, I need to figure out which of the emitters is the most likely source (thats what I don't know). The only way to do that is to compare the probabilities that each emitter generated that vector and choose the one most probable.
Comment: Then you can compare the (log)likelihoods (not the probability) of each vector as indicated in my answer. For hypothesis testing log-likelihood ratio tests could be appropriate.
Comment: Yeah, in the end, the likelihood function saved the day. I will try with the log approach.


jQuery plugin on multiple elements executes asynchronously

Question: EDIT - Js fiddle link to script file - http://jsfiddle.net/r4uH3/
EDIT 2 RE ACCEPTED ANSWER Although question already closed, thought I would add some detail on why I accepted the answer below.
Also see this re why original code didn't work - How do I return the response from an asynchronous call? - it's points re AJAX are not literally related, but the explanation of asynchronicity is important to understand.
Fabrício Matté's answer works perfectly for me, although I adapted it slightly:
(function($){
    // some pre-iteration stuff here

    // iteration vars
    var elementIndex = 0;
    var collectionLength = this.size();
    var ts = this;

    // THIS IS THE KEY BIT AS PER ACCEPTED ANSWER
    // RATHER THAN USING THE NORMAL "this.each"
    (function initLoop(){

        // check if got to last element
        if (elementIndex < collectionLength){

            // DO STUFF, WHATEVER, AS LONG AS YOU DON'T EXPECT
            // ASYNCHRONOUS FUNCTIONS LIKE AJAX / TIMERS NOT TO, WELL, EXECUTE ASYNCHRONOUSLY UNLESS YOU HANDLE THEM PROPERLY!!

            // AND FINALLY - GO TO NEXT ELEMENT IN COLLECTION
            initLoop();
        };

    })());
})(jQuery);

The other thing that helped, although not exactly related, was using global and element-specific variables stored using jQuery(el).data(); rather than using window.VARIABLENAME or MyNamespace.VARIABLE_NAME. Eg:
// outside of iteration
jQuery(window).data("GLOBAL_STUFF", { /* add properties here and set them later*/ });
var globalData = jQuery(window).data("GLOBAL_STUFF");

// inside iteration
jQuery(currentElement).data("ELEMENT_DATA", { /* add properties here and set them later*/ });
var elementData = jQuery(window).data("ELEMENT_DATA");

// then set props like so (obviously get, similarly..)
globalData.someArrayOfSomething.push(something);
elementData.someBooleanValue = true;

Again, thanks to Fabrício.

I have written a jQuery plugin that, like most, can be executed on multiple (i.e. a collection of) elements.
in the this.each(function(i,el){ }); part of the function, I create a new instance of another object type (nothing to do with jQuery) and call its "Init" method.
I expect, with the .each loop, that it will loop to the next instance after the init method has been fully executed.
I am not using any async (AJAX / timers) anywhere.
I am using callbacks always on anything like "jQuery.fadeIn" or similar.

THE PROBLEM
The Init methods are called virtually in parallel. They do not complete their execution before the next one is called.
Can anybody advise of any known issues? Is there something I'm missing from the above "theory"?
Using jQuery 2.0.
Comment: Not enough data. If you're dealing with async code, you should at least post a [SSCCE](http://sscce.org/). Without code we can do nothing but advise to adapt your object's `init` function to take a callback parameter or return a deferred instance.
Comment: @LiverpoolsNumber9 The fact is javascript executes synchronously (with a few exceptions). If you are seeing otherwise, that means you are using one of the methods that are an exception to that rule, such as a setTimeout or an ajax request. We can't see your code, therefore there isn't much we can do to help you figure out why you are seeing otherwise.
Comment: @FabrícioMatté I appreciate that but the amount of code is enormous. The init method is fairly long too. It does already take a callback. Also, could you explain what you mean by "return a deferred instance"?
Comment: If you just want to know what code is being run in what order, that's what the browser's JavaScript debugger is for.
Comment: Hence I suggested a [SSCCE](http://sscce.org/). `=]` Well yes, take a look at [`$.Deferred`](http://api.jquery.com/jQuery.Deferred/) - basically you create a `Deferred` instance inside `init` and return it so your caller can bind `done` handlers to it. Of course you will have to resolve the deferred somewhere after `init` has finished.
Comment: Just use a bog standard for loop, if you want it to be synchronous. Not very pretty though. .each is asynchronous for a reason. Mainly so that the UI thread doesn't become unresponsive. jQuery is doing best practise. Your anonymous function is being called asynchronously.
Comment: @FabrícioMatté about to put a js fiddle link up...
Comment: @twilson Are you saying that `.each` is asynchronous? Sorry to disappoint but it is a completely synchronous method. What is async is the function that OP calls from inside of `.each`.
Comment: @twilson he's right. That's why I'm tearing my hair out!!
Comment: @KevinB I'm not I promise!! See js fiddle link!
Comment: Ah, sorry i didn't see the fiddle.
Comment: Where within that fiddle do we need to look to see the loop you are performing that's supposed to be synchronous? The commented out section? or the `$.fn.jrte` method
Comment: @KevinB At the end. The actual jQuery "plugin" function.
Comment: Oh wait I've found the `Init` function. Though it looks like quite a stack of callbacks. You may be able to resolve a deferred or run a callback inside the last callback in that stack, though it is hard to say whether it will work without an example that executes.
Comment: Is the problem you are seeing them all fade in at the same time? or what. Based on the current code, i would expect them all to fade-in at  the same time.
Answer: Try replacing your for loop with:
var i = 0,
    l = window.JRTE_INSTANCES.length;
(function initloop() {
    if (i < l) window.JRTE_INSTANCES[i].Init(initloop);
    i++;
}());

This will start the init loop by calling window.JRTE_INSTANCES[0].Init. The initloop passed as callback will execute again when the Init concludes, starting another Init with the next i and so forth until it has iterated over all instances.
Here's a more practical async demo using a very similar structure as the above: Fiddle
Comment: Looks correct; the problem in code seems to be that startEditor contains async code (namely, jQuery.fadeIn). So with the code in the original fiddle, all the Init calls get made before even the first fadeIn completes. Making the next Init call inside the callback to the previous one sounds like what the OP wants.
Comment: @FabrícioMatté ok thanks. Have updated above, hope it's a bit more helpful now!!
Comment: I didn't test it but I believe the logic is correct. Should work as long as the callback system in place suffices.
Comment: @dancek Yes, I noticed that when Kevin commented in the question too. You explained it better though, thanks for the addition. `=]`
Comment: @dancek but I'm waiting for the fade to finish executing?
Comment: @FabrícioMatté thanks so much for taking the time to answer. Late here but will look in the morning :)
Comment: I'll add that this code seems a bit smelly to me; I'd rather make it: `(function initloop(n) { ... .Init(function() {initloop(n+1)}); }(0));`. Though this might be a matter of taste (the inline function is ugly, too).
Comment: @dancek Yeah, personal taste. I find lexical scope easier to read than traditional recursion as yours, but both have the same effect. `=]`
Comment: @FabrícioMatté Have accepted as answer (even though post closed) as you are correct in everthing you say. I have to say I'm a little disappointed that the question has been closed as, upon further investigation, and with your help, I've found out what the issue was. However, I won't share it here now. Shame really, could've been really helpful to somebody in the future which, after all, is what this site is about.
Comment: @LiverpoolsNumber9 Yes, you can't remove a close vote once you've cast it (which I've cast before your updated question with fiddle), though I believe you can still edit the question to include the data. `=]` I'll cast a reopen vote nevertheless, but in case you want to edit the question, I'd suggest adding the `Init` method's code too so it doesn't end up closed as Too Localized after it is re-opened.
Comment: @FabrícioMatté Ok thanks. Your "closure" / "recursive" type solution is perfect by the way! Would never have thought of that in a million years! But still don't understand why "this.each" flies through the collection without completing the "init" function! Ah well..
Comment: @LiverpoolsNumber9 As `Init` is asynchronous, `.each()` will call all `Init`s without waiting for these to finish. Here's another popular better explained async code explanation: http://stackoverflow.com/q/14220321/1331430


Máscara e Validação de Campo para Celular

Question: Poderiam me ajudar com essa validação? O campo "txtTelCel" deverá ter o formato ####-####, onde # é um dígito numérico e, caso não esteja nesse formato, deverá aparecer um aviso informando o usuário.
Obs.: sem usar jQuery.
Telefone Celular:

    <input type="text" id="txtTelCel" name="txtTelCel" size="50" maxlength="8">

Comment: Já tentou usar o https://igorescobar.github.io/jQuery-Mask-Plugin/ ?
Comment: preciso que seja em JavaScript
Answer: Mude o atributo maxlenght para 9 e use está função no onblur.
 function validarTel() {
    var tel = document.getElementById('txtTelCel').value;
    var pattern = /^\d{4}-\d{4}$/;

    if(!pattern.test(tel))
        alert('Número de telefone inválido!');
 }


Strip Links in Strings

Question: I'm trying to create a strict chat filter for those that choose the strict version. I would like to block all URLs except a few whitelisted ones (youtube, prntscr, facebook, etc) to prevent people from sending porn, IP grabbers, virus downloads, etc.
I know I could do this with a few extra lines of code, however is there a way to do this using a regular expression? I would like to have it check if the string contains a URL but the URL is not a whitelisted one (youtube.com for example).
I'm looking to implement this in both Python and PHP, but I only need the regex since I know how to simply use regular expressions in both languages.
Thanks
Edit: to be clear - this is for a strict mode on a chat system. The messages a user sends could be anything from "Hello" to "http://unsafelink.com go there!!"
Answer: Check the snippet below
$message = array(
  "Dude I saw her on youtube",
  "I just opened an account on youtuber.com",
  "I'm watching an amazing prank, check this out youtube.com/gfsddfh784",
  "Dude, isn't this girl forbidden.com/hot-chick/123 Mery from our school?",
  "Take a look google.com?search=how%20to%20hack%20a%20wireless",
  "Ask someone on stackoverflow.com :p",
  "I found this great snippet on stackoverflow!",
  "He's all day on xxx.net"
  );

$url = '/(((https?:\/\/)?www)?\.?[a-z0-9]+\.[a-z0-9]+[a-z0-9\-\/?&#%=]+)/';
$whitelist = "/\b(youtube|stackoverflow|google|twitter|facebook|prntscr)\b/";

// check messages like this
foreach ($message as &$line){
  if(preg_match($url, $line, $match)){
    echo $match[0] , preg_match($whitelist, $match[0]) ? " -> Safe" : " -> Unsafe" , '
';
  }
}

echo "
";

// or like this
foreach ($message as &$line){
  if(preg_match($url, $line, $match) && !preg_match($whitelist, $match[0])){
    echo $match[0]  . " -> Unsafe" . '
';
  }
}

Output:
youtuber.com -> Unsafe
youtube.com/gfsddfh784 -> Safe
forbidden.com/hot-chick/123 -> Unsafe
google.com?search=how%20to%20hack%20a%20wireless -> Safe
stackoverflow.com -> Safe
xxx.net -> Unsafe
------------------------------------------------------------
youtuber.com -> Unsafe
forbidden.com/hot-chick/123 -> Unsafe
xxx.net -> Unsafe

Comment: And to validate the URL in PHP use filter_var: http://php.net/manual/en/function.filter-var.php
Comment: The string may not always contain a URL though. This is for a strict mode on a chat system. A random message could be "Hello" for example
Comment: Thanks! This is just what I was looking for. No idea why I never thought of doing it this way, but luckily you did. Thanks!

Strip Links in Strings


How to share my linux folder with mac mini over nfs

Question: I tried to mount using following command after exporting the folder in linux source machine ( NFS server)  .
sudo mount -t nfs -o resvport,rw 192.168.12.10:/home/pavunkumar  /private/nfs

It is mounted successfully in my mac mini. I could see using mount -v
192.168.12.10:/home/pavunkumar on /private/nfs (nfs)

But, when I tried to get into that directory , I am getting error as follows
Mac-mini-5:~ pavunkumar$ cd /private/nfs/
-bash: cd: /private/nfs/: Permission denied
Mac-mini-5:~ pavunkumar$

When I check the permission, it is in following mode
drwx------  101 1014  _lpoperator  16384 Aug 27 16:12 nfs

Do I need to change permission explicitly for each time ?
Comment: Check the permissions.
Comment: Updated the question.
Answer: You have different uids for the users on the Linux and the MacOS machine, so you run into issues with the permissions.
Either change the users to have the same ID (or use something like NIS or LDAP as backend) or set the permission of the shared directory to allow access for everyone.
Comment: +1 , Yes I got it now. Why down vote for me ?


How to make a numeric textField in Drupal WebForm?

Question: Can anyone suggest how to make a numeric only textfield in WebForm for a mobile number field?
Answer: You can use the Webform validation module to create such validation.
Answer: The following features of the Webform Validation module will help you
The following validation rules are currently included:
Numeric values (optionally specify min and / or max value)
Minimum length
Maximum length
Minimum number of words
Maximum number of words


Push new value to inner array with Lithium and MongoDB

Question: I have a structure like this:
<code>[_id] => MongoId Object (
    [$id] => 4e91bcb40b7aab256c000000
)
[campaigns] => Array (
    [0] => Array (
        [campaign_id] => 4e91bcd10b7aab2b6c000000
        [refer_code] => AjZCJR
        [owner] => 1
        [campaign_name] => Test Campaign
        [users] => Array (
        )
    )
    [1] => Array (
        [campaign_id] => 4e9210600b7aab276c000000
        [refer_code] => FQIMJd
        [owner] => 1
        [campaign_name] => New Test Campaign
        [users] => Array (
        )
    )
)
</code>
I would like to be able to update the campaigns array with new fields and update the existing fields, on the match of the ID.
Currently I am trying to do the following:
<code>$data = array('campaign_name'=>'changed', 'new_field'=>'its new');
User::update(array('$push'=>array('campaigns.$'=>$data)),array('campaigns.campaign_id'=>$campaign_id));
</code>
However that is not working - I'm using the positional operator in order to try and match the array to the condition statement, as without it, it just creates a new array within the campaigns array.
I understand I am probably using it wrong, as I presume it should be used by doing
<code>'campaigns.$.campaign_name'=>'changed'
</code>
However I don't want to be limited to specifying it each time, and was wondering the best way to do this type of update without using a for loop and adding each piece of data (which I'm currently doing as follows:)
<code>$data = array();
foreach($this->request->data as $key=>$value) {
    $data['campaigns.$.'.$key] = $value;
}
User::update($data,array('campaigns.campaign_id'=>$campaign_id));
</code>
If someone could let me know the 'proper' way to do this, that would be great!
Thanks :)
Dan
Answer: Just update:
<code>$co = array(
        '$pull' => array('campaigns.1" => array('campaign_name' => 'changed'' ) )
);

$p->update(array("_id" => new MongoId( $MongoID  )), $co);
</code>
Comment: Would the 'campaigns.1' only update the first item in the array though? As opposed to the array item that matches the query?
Comment: Item with index 1  eq  campaigns.2 campaigns.3 campaigns.4 etc


How to append \line into RTF using RichTextBox control

Question: When using the Microsoft RichTextBox control it is possible to add new lines like this...
richtextbox.AppendText(System.Environment.NewLine); // appends \r\n

However, if you now view the generated rtf the \r\n characters are converted to \par not \line
How do I insert a \line control code into the generated RTF?
What does't work:
Token Replacement
Hacks like inserting a token at the end of the string and then replacing it after the fact, so something like this:
string text = "my text";
text = text.Replace("||" "|"); // replace any '|' chars with a double '||' so they aren't confused in the output.
text = text.Replace("\r\n", "_|0|_"); // replace \r\n with a placeholder of |0|

richtextbox.AppendText(text);

string rtf = richtextbox.Rtf;
rtf.Replace("_|0|_", "\\line"); // replace placeholder with \line
rtf.Replace("||", "|"); // set back any || chars to |

This almost worked, it breaks down if you have to support right to left text as the right to left control sequence always ends up in the middle of the placeholder.
Sending Key Messages
public void AppendNewLine()
{
    Keys[] keys = new Keys[] {Keys.Shift, Keys.Return};
    SendKeys(keys);
}

private void SendKeys(Keys[] keys)
{
    foreach(Keys key in keys)
    {
        SendKeyDown(key);
    }
}

private void SendKeyDown(Keys key)
{
    user32.SendMessage(this.Handle, Messages.WM_KEYDOWN, (int)key, 0);
}

private void SendKeyUp(Keys key)
{
    user32.SendMessage(this.Handle, Messages.WM_KEYUP, (int)key, 0);
}

This also ends up being converted to a \par
Is there a way to post a messaged directly to the msftedit control to insert a control character?
I am totally stumped, any ideas guys? Thanks for your help!
Comment: you had 1 side-mistake: on first stage, you replaced two `||` into one, instead you needed reversely.
Answer: Adding a Unicode "Line Separator" (U+2028) does work as far as my testing showed:
private void Form_Load(object sender, EventArgs e)
{
    richText.AppendText("Hello, World!\u2028");
    richText.AppendText("Hello, World!\u2028");
    string rtf = richText.Rtf;
    richText.AppendText(rtf);
}

When I run the program, I get:
Hello, World!
Hello, World!
{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fnil\fcharset0 Courier New;}}
{\colortbl ;\red255\green255\blue255;}
\viewkind4\uc1\pard\cf1\f0\fs17 Hello, World!\line Hello, World!\line\par
}

It did add \line instead of \par.
Comment: A note, though, mono's RichTextBox emulation is rather broken and, among other imcompatibilities, doesn't understand the line separator. It appears as a box character in the text.
Comment: This worked like a charm for me, it allowed me to remove the horrible hack we had in place. Our customers will thank you!
Comment: did not work for me . a '?' appeared on the file
Comment: if you're editing the RTF Raw code, why not just replace/add the '\line' tag to the code?
Answer: Since you want to use a different RTF code, I think you may need to forget about the simplistic AppendText() method and manipulate the .Rtf property of your RichTextBox directly instead. Here is a sample (tested) to demonstrate:
RichTextBox rtb = new RichTextBox();
//this just gets the textbox to populate its Rtf property... may not be necessary in typical usage
rtb.AppendText("blah");
rtb.Clear();

string rtf = rtb.Rtf;

//exclude the final } and anything after it so we can use Append instead of Insert
StringBuilder richText = new StringBuilder(rtf, 0, rtf.LastIndexOf('}'), rtf.Length /* this capacity should be selected for the specific application */);

for (int i = 0; i < 5; i++)
{
    string lineText = "example text" + i;
    richText.Append(lineText);
    //add a \line and CRLF to separate this line of text from the next one
    richText.AppendLine(@"\line");
}

//Add back the final } and newline
richText.AppendLine("}");

System.Diagnostics.Debug.WriteLine("Original RTF data:");
System.Diagnostics.Debug.WriteLine(rtf);

System.Diagnostics.Debug.WriteLine("New Data:");
System.Diagnostics.Debug.WriteLine(richText.ToString());

//Write the RTF data back into the RichTextBox.
//WARNING - .NET will reformat the data to its liking at this point, removing
//any unused colors from the color table and simplifying/standardizing the RTF.
rtb.Rtf = richText.ToString();

//Print out the resulting Rtf data after .NET (potentially) reformats it
System.Diagnostics.Debug.WriteLine("Resulting Data:");
System.Diagnostics.Debug.WriteLine(rtb.Rtf);

Output:
Original RTF data:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17\par
}

New RTF Data:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17\par
example text0\line
example text1\line
example text2\line
example text3\line
example text4\line
}

Resulting RTF Data:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17\par
example text0\line example text1\line example text2\line example text3\line example text4\par
}
Answer: if you are using paragraphs to write to richtextbox you can use the LineBreak() same code shown below
Paragraph myParagraph = new Paragraph();
FlowDocument myFlowDocument = new FlowDocument();

// Add some Bold text to the paragraph
myParagraph.Inlines.Add(new Bold(new Run(@"Test Description:")));
myParagraph.Inlines.Add(new LineBreak()); // to add a new line use LineBreak()
myParagraph.Inlines.Add(new Run("my text"));
myFlowDocument.Blocks.Add(myParagraph);
myrichtextboxcontrolid.Document = myFlowDocument;

Hope this helps!
Comment: it`s perfect solution


Using pathauto for taxonomy pages

Question: I'm using pathauto on a D8 site successfully for pattern type Content using a pattern like this:
[node:content-type]/[node:title]

But I'm not having any luck at all when trying to use it for pattern type Taxonomy term using a pattern like this:
[term:vocabulary]/[term:name]

I just keep getting /taxonomy/term/123 instead of /taxonomyname/taxonomyterm
I have searched and searched and every article I find only covers the tokens for Content, not Taxonomy. I did find one youtube video that covered it in D7 and the pattern was identical to mine, yet his worked but mine doesn't. I've cleared caches and even tried bulk generate to no avail. But Taxonomy (list) pages don't create aliases though, so I'm wondering if that has something to do with it.
Answer: OK, I figured this out, and the funny thing is, I had it right from the start. The pattern I used above is correct (what I wanted). The only problem I created for myself was, I created the taxonomy terms before I created the pattern for it, so all those terms needed to have aliases generated for them. Hint: bulk generate
When I generate new terms now, I see at the bottom of the form there is a checkbox (default is checked) to Generate automatic URL alias. And that does in fact create a new alias because I tested it.
If you find yourself in the same position, go to /admin/config/search/path/update_bulk and select the Taxonomy term checkbox, and then the Generate a URL alias for un-aliased paths only radio button. Alternatively, you can check the Regenerate URL aliases for all paths if you think you have some existing alias that may be wrong to changes you've made to taxonomy.
Answer: Have you actually tried to visit /taxonomyname/taxonomyterm?
The /taxonomy/term/123 isn't actually a taxonomy page, it is a Views showing content tagged with the term from the URL. It's a separate thing.
What do you expect to see on that page? Just the term name and description? That should work with the Pathauto as you have set it up.
If you want to see the content, like that Views page, you can use the Taxonomy term Views, Duplicate it and disable the original just for future reference, and modify the Contextual filters and Path to your preference.
You will need to add the Relationship to the term so you could use the Taxonomy: Name Contextual filter to get the term name in the URL.
You can also set up aliases for the default Taxonomy term Views so they use names, but I think it would have to be done manually, and isn't at all elegant/smart solution. It make more sense to set up the Views as you intend it to be used.
Comment: prkos, thank you for the assit, here's more info...

Visiting `/taxonomyname/taxonomyterm` just returns a 404 error, even though I agree it should at least return the term name and description.

I want it to work just like the Taxonomy view, which I didn't realize existed and explains why no one covers it in pathauto tutorials. However, if I can find that youtube video where someone did it in D7, I'll share that.

Manually setting up aliases is way too much work, I'll try the view method you described and follow up with how I make out. Thanks again, Rick
Comment: Here's an interesting note, I disabled the default Taxonomy view without duplicating it to test what would happen if there was no view at all, and while I got no list of matching items, I still got a blank page with the term name and the URL is `/taxonomy/term/7` so there is more to the URL than just what is configured in the view.
Comment: I'm not having much luck using Views, which may be due to not setting up the Contextual filters and Relationships correctly. There are a lot of configuration options and I tried a few things based on prior knowledge of Views, and I have been able to get results to return on the page, but the URL hasn't changed at all, even though I have tried a few things in the Page settings / Path section of the View. It  seems to me that pathauto should be able to override the URL path of the default View anyway, so this (to me) seems like overkill to achieve friendly URLs from taxonomy pages.
Comment: Can you post your Pathauto taxonomy configuration? It's not a blank page if it's showing the term name. It would probably show any fields associated with that term. You need to have the path start with something solid, some word, before you can add contextual values to it, so in the end it will be `/someword/taxonomyname/taxonomyterm`. You have to have two Contextual filters, both working, one for Vocabulary, the other for term name, then you change your Path setting to `/someword/%/%`, each % is one contextual value. Search for taxonomy term name as contextual in views for detailed steps.

Using pathauto for taxonomy pages


Use logical equivalences to prove that ( ∧ ) → q is a tautology

Question: Use logical equivalences to prove that ( ∧ ) → q is a tautology
I have no idea how to start this, is this not a given?
Answer: $$ (p \land q) \rightarrow q $$
Definition of Material Conditional:
$$ \neg(p \land q) \lor q $$
De Morgan's Law:
$$ \neg p \lor \neg q \lor q $$
By the Law of Negation, since either $ q $ or $ \neg q$ must be true, the statement is always true; it is a tautology.


R: What is the distance function equivalent for this formula?

Question: Hi I'm using an R package that calculates distance with this formula here,
<code>as.dist(1 - cor(df, use = "pa"))
</code>
However I cannot seem to find an equivalent dist function from this.  I tried
"euclidean", "manhattan", or "minkowski".  thanks!
Comment: If you view each object as a direction in $\mathbb{R}^n,$ this is the metric on the unit sphere $S^{n-1}$ inherited from the Euclidean space $\mathbb{R}^n$ by inclusion.
Answer: By default cor will compute the Pearson correlation coefficient. Subtracted from $1$ this is know as the Pearson Distance.
Comment: thank you this makes sense.  Is there an advantage of running an hierarchical clustering with pearson distance vs something more standard like euclidean?
Comment: You're just measuring correlation so I would assume the clustering algorithm would only be concerned with how data relates, as opposed to where it physically lies.


Dante server Pam authentication does not work

Question: So I configured Dante 1.4.2 (compiled it from source on Debian 8.7 which runs on MS Azure) and followed their official configuration guide to run my SOCKS5 server. I created a firewall rule to accept incoming connection on port 1080 tcp. I used Mozilla Firefox to connect to it. It works fine when there is no authentication. However, I cannot connect when I set socksmethod: pam.username. I'm also quite sure that Dante was compiled with pam support (build: libwrap mon-data mon-disconnect pam preload sess2)
This is my /etc/sockd.conf
#logging
errorlog: /home/toto/Logs/sockd.errlog
logoutput: /home/toto/Logs/sockd.log
#debug: 1

# The listening network interface or address.
internal: eth0 port = 1080

# The proxying network interface or address.
external: eth0

#server identities (not needed on solaris)
user.privileged: root
user.notprivileged: nobody
#user.libwrap: libwrap

#reverse dns lookup
#srchost: nodnsmismatch

# client-rules determine who can connect to the internal interface.
# The default of "none" permits anonymous access.
clientmethod: none

# socks-rules determine what is proxied through the external interface.
# The default of "none" permits anonymous access.
socksmethod: pam.username

#standard client rule, accept all clients
client pass {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        log: connect disconnect error
        socksmethod: pam.username
}

#outgoing traffic, requiring pam.username authentication, as specified
#in the global socksmethod.
socks pass {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        command: bind connect udpassociate
        log: connect disconnect error
        socksmethod: pam.username
}

Socks does not seems to bind to my internal address. The log file says: failed to bind internal addresses: Address already in use The internal address is behind an NAT so that could be the problem.
If I remove bind from config it starts but throws the message: block(1): tcp/accept ]: 126.96.36.199.9069 10.0.0.6.1080: error after reading 3 bytes in 0 seconds: client offered no acceptable authentication method , these log entries continue (each with different address) until I end the server process.
Also my /etc/pam.d/sockd
account    required     pam_nologin.so
session    required     pam_loginuid.so
session    optional     pam_keyinit.so force revoke
session    required     pam_limits.so

Thank You!
Answer: I would check if you are sending your username and password when connecting.
client offered no acceptable authentication method

it seems nothing was sent by the client.
Answer: It turns out to be a client issue, i.e Firefox does not know how to authenticate SOCKS5 properly. Better use a browser extension


Workaround for subfunction defined in exec() inside of a function

Question: I am writing a function that needs to contain a subfunction in order to run the curve_fit function from the scipy.optimize module. The issue is that the number of variables that goes into the subfunction (let's call it fitFunc) depends on how many columns are in the dataframe input into the main function. Below is my code:
def function(mod_data):
    import numpy as np
    i = 0
    ps = len(mod_data.columns) - 7
    temp = '(xdat[0]**b)'

    while i != (ps-1):
        dummypy = '(xdat[' + str(i+1) + ']'
        temp = temp + '+' + dummypy + '**b)'
        i += 1

    xdat = mod_data.iloc[:,7:].values
    xdat = np.transpose(xdat)
    ydat = mod_data.iloc[:,1].values

    form = 'def fitFunc(xdat, a, b): return (a/ps) * (%s)' % temp
    exec(form)
    result = curve_fit(fitFunc, xdat, ydat,
                       p0 = np.array([100000,.75]))
    return result

Above mod_data is the dataframe that contains the variables for the modeling process. form should be the following character string if xdat has two or three rows respectively:
# xdat has 2 rows
form = 'def fitFunc(xdat, a, b): return (a/ps) * ((xdat[0]**b)+(xdat[1]**b))'

# xdat has 3 rows
form = 'def fitFunc(xdat, a, b): return (a/ps) * ((xdat[0]**b)+(xdat[1]**b)+(xdat[2]**b))'

I realize that I could just define the function, but the issue is that I don't know how many variables will actually be in the dataframe before it's entered into the function, so I run through the final columns in order to find that number, then write have the code write the function for me depending on how many variables there will be.
I know from this previous question that exec doesn't work when there are subfunctions in the function: Why doesn't exec work in a function with a subfunction? . So my goal here is to find another way to define the fitFunc subfunction depending on how many variables xdat will have from the mod_data dataframe. Thanks in advance for any advice.
Answer: There's no need to create the function dynamically and use exec. Just iterate over xdat.
def fitFunc(xdat, a, b):
    return (a/ps) * sum(x**b for x in xdat)


Elixir Phoenix ecto.create fail

Question: i am following along with the Phoenix Up & Running guide at https://phoenixframework.readme.io/docs/up-and-running
and when I try to use ecto to create a database (Postgresql) I get the following error
mix ecto.create

17:55:35.631 [error] GenServer #PID<0.215.0> terminating
** (RuntimeError) Connect raised a CaseClauseError error. The exception details are hidden, as they may contain sensitive data such
as database credentials.

    (postgrex 0.12.2) lib/postgrex/utils.ex:40: Postgrex.Utils.parse_version/1
    (postgrex 0.12.2) lib/postgrex/protocol.ex:497: Postgrex.Protocol.bootstrap_send/4
    (postgrex 0.12.2) lib/postgrex/protocol.ex:353: Postgrex.Protocol.handshake/2
    (db_connection 1.1.3) lib/db_connection/connection.ex:135: DBConnection.Connection.connect/2
    (connection 1.0.4) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib 3.11.2) proc_lib.erl:249: :proc_lib.init_p_do_apply/3

Last message: nil

State: Postgrex.Protocol

** (Mix) The database for HelloPhoenix.Repo couldn't be created: an exception was raised:
    ** (RuntimeError) Connect raised a CaseClauseError error. The exception details are hidden, as they may contain sensitive data such
as database credentials.

        (postgrex 0.12.2) lib/postgrex/utils.ex:40: Postgrex.Utils.parse_version/1
        (postgrex 0.12.2) lib/postgrex/protocol.ex:497: Postgrex.Protocol.bootstrap_send/4
        (postgrex 0.12.2) lib/postgrex/protocol.ex:353: Postgrex.Protocol.handshake/2
        (db_connection 1.1.3) lib/db_connection/connection.ex:135: DBConnection.Connection.connect/2
        (connection 1.0.4) lib/connection.ex:622: Connection.enter_connect/5
        (stdlib 3.11.2) proc_lib.erl:249: :proc_lib.init_p_do_apply/3

The only suggestions I found was to update Postgrex.  I ran mix deps.update postgrex and this did not fix it.
Finally I checked config/dev.exs and username/password are set to "postgres".  I used PgAdmin3 to confirm this is a valid login.
So at this point I am stuck.
Ubuntu 19.10
postgres (PostgreSQL) 11.7 (Ubuntu 11.7-0ubuntu0.19.10.1)
 installed from Ubuntu repo via apt-get

Answer: What are the versions of
Postgress and postgrex ?
postgrex supports PostgreSQL 8.4, 9.0-9.6, and later (hstore is not supported on 8.4)
Comment: postgres (PostgreSQL) 11.7 (Ubuntu 11.7-0ubuntu0.19.10.1)

Elixir Phoenix ecto.create fail


What is the exact Juniper and Cisco router per-packet balancing hash algorithm?

Question: Due to JunOS and Cisco documentation there is ability to configure hashing algorithm choosing one of the next-hop from the several multiple equal-cost paths. There is information about fields that could be used to compute target hash - it could be l3 (including src and dst ips) or l4 (including ports) but there is no any information how exactly (crc, xor, and+xor, etc) this hash sum computed. Is there any standard of this behaviour or this is a proprietary and brand/model dependent?
Answer: Here's a document that explains the algorithm for a Cisco 3750, 4500 and 6500.  It's too long to quote here.


A question on gradients: $f$ must assume equal value at two points

Question: If $\nabla f(x,y,z)$ is always parallel to $x i+y j+z k$, show that $f$ must assume equal values at the points $(0,0,a)$ and $(0,0,-a)$.
Comment: Done. Any question?
Comment: Please share your solution.
Answer: We have $$\nabla f(x, y , z) = \lambda(xi + yj + zk)$$
Equating the $z$-components gives $$\frac{\partial{f}}{\partial{z}} = \lambda z \\ \Rightarrow f(x, y, z) = \frac{\lambda z^2}{2} + g(x, y)$$ where $g(x, y)$ is some arbitrary function. By  this formula, we obtain $$f(0, 0, a) = \frac{\lambda a^2}{2} + g(0,0) \\ f(0,0,-a) = \frac{\lambda a^2}{2} + g(0,0)$$ which proves the given assertion.


Como personalizar Form gerado pelo CRUD do Symfony?

Question: Estou alterando o template do Symfony para que o CRUD já tenha o formato que eu preciso, consegui alterar quase tudo, mas agora tinha a necessidade de alterar o form, para editar as classes de css e outros elementos com div e etc... para ficar de acordo com o layout que eu quero, os Controllers e as views do twig (edit.html.twig.twig, index.html.twig.twig, new.html.twig.twig, show.html.twig.twig e inclusive os actions.html.twig.twig e record_actions.html.twig) estão ok, mas para fazer o form eu vejo que há chamadas no código do twig para uma função form. Eu gostaria de saber onde eu posso mudar o template desse form, pois eu quero alterar o layout dele. Abaixo é um trecho do código do new.html.twig.twig.
{% block extends %}
    {{ "{% extends '::form.html.twig' %}" }} {% endblock extends %} {% block body %}
    {{ "{% block body -%}" }}

                {{ entity }} creation

                {{ '{{ form(form) }}' }}

                {% set hide_edit, hide_delete = true, true %}
                {% include 'crud/views/others/record_actions.html.twig.twig' %}

    {{ "{% endblock %}" }} {% endblock body %}

Onde eu encontro o template que gerar o conteúdo de {{ form(form) }} e como personaliza-lo?
No edit.html.twig.twig ele cria o botão delete pelo seguinte comando:
{% if ('delete' in actions) and (not hide_delete) %}
        {{ '{{ form(delete_form) }}' }}
    {% endif %}

Só que adiciona algumas DIVs que eu quero remover, e deixar apenas o form e o button.
O trecho de código do edit que gera o botão delete produz a seguinte saída após renderizado o html:
<form name="form" method="post" action="/sbcorp/web/app_dev.php/city/2"><input type="hidden" name="_method" value="DELETE">

<button type="submit" id="form_submit" name="form[submit]" class="btn btn-group">Delete</button>
<input type="hidden" id="form__token" name="form[_token]" value="cpQYW2u5jQ9eH-Ux7VOeKQMtERVno_T4h3Olshaw9js">
</form>

Quero deixar apenas o form, os input hidden e o button
O local onde estou modificando o template da view está sendo mostrando conforme imagem abaixo. Já alterei todo o skeleton\crud\view e skeleton\crud\action
Comment: Não recomendo alterar a base do sistema. Acredito que tenha uma maneira de extender em forma de macro essas funções, como no framework laravel, por exemplo. Caso atualize as dependências(composer update) todas essas alterações serão perdidas ou quem sabe, até tenham que ser ajustadas também.
Comment: @Lucas sua sugestão é válida, havia pensado nesse problema, a questão foi que eu não consegui encontrar uma outra solução em um primeiro momento e precisava criar um protótipo, os links que encontrei na internet me levaram inicialmente a essa solução, mas estou aberto a qualquer sugestão para melhorar isso. Até porque, realmente, se eu tiver que atualizar o componente minha implementação vai para o espaço, contudo nesse primeiro momento (enquanto não tenho uma solução melhor) é um risco aceitável e como ainda estou aprendendo a mexer, o conhecimento aqui também vai ser valido.
Answer: Não é necessário alterar os arquivos do framework. Para customizar a forma como os elementos de formulários são renderizados, é necessário copiar os arquivos dos templates para dentro dos arquivos da sua aplicação.
Leia esse artigo da documentação para saber mais a respeito:
http://symfony.com/doc/current/cookbook/form/form_customization.html
Comment: Vou ler novamente e testar, sabe se é possível trabalhar com o skeleton da mesma forma, jogando para uma pasta e mandando buscar o modelo nele?
Comment: Sim, é exatamente essa a ideia. Já fiz muito isso adaptando templates para o Twitter Bootstrap.


1046: type was not found not a compile-time constant: NewsItem

Question: i'm having trouble this errors keep comeup :
1046: type was not found not a compile-time constant: NewsItem
1108: call to a possibly undefined
my actions is :
var newsContainer:Sprite = new Sprite;
addChild(newsContainer);

var newsArray:Array = new Array( );

for(var k:Number=0;k<0;k++) {

    var newsItem:NewsItem = new NewsItem;

    newsArray.push(newsItem);
    newsContainer.addChild(newsItem);

}

Answer: You need to import the NewsItem class.
An import statement follows the structure:
import path.path.Class

Where the path begins from the location of the .fla file. For example, if you have a folder compile in the same directory as your .fla and it contains a class MyClass, the import statement would be:
import compile.MyClass;

Comment: shall i replace the Class with my class name
Comment: ^^^^^ ?!! shall i replace the Class with my class name


How versatile is logistic regression?

Question: Amazon ML (Amazon Machine Learning) is offered by Amazon as a general purpose supervised classification service. They don't even bother to mention what algorithms are being used, they just use the generic term "ML models".
From their Key Concepts page:

An ML model is a mathematical model that generates predictions by finding patterns in your data. Amazon ML supports three types of ML models: binary classification, multiclass classification and regression.

Upon digging deeper, they state in their FAQ:

Amazon Machine Learning currently uses an industry-standard logistic regression algorithm to generate models.

Based on this, one would assume that logistic regression can pull off anything that an SVM, an RF or a Neural Net can. Is that the case?
Isn't logistic regression limited to linearly separable models? Isn't it just a special case of Neural Net (i.e. one layer perceptron) ?
And is it really an "industry standard", and is it really so versatile that Amazon would favor it over something more complex ?
Comment: Maybe they mean they do GLMs, which can do regression, and with the right family/link binary classification (logistic regression), and multiple logistic regressions can be used to do multi class regression. They don't claim that they can "pull off" anything a Neural Net can do. (SVM's, in my opinion, are overrated, and have no probabilistic interpretation, so no great loss there.)
Comment: @Wayne it's true that they don't make the explicit claim. But their product description clearly indicates that is supposed to be a one-stop shop for all of your supervised classification needs. And if they're using GLM's, why not say so? "industry-standard logistic regression" are their words not mine.
Comment: My guess would be that many non-statisticians have heard of Logistic Regression, while few have heard of GLMs. Or maybe they wrote the Key Concepts and FAQ were written at different times by different folks and don't quite match up.
Comment: For classification, Kernel SVMs have the advantage of the possibility of sparseness, and SVMs are also applicable in regression, with epsilon-insensitive losses. Also, ordinary SVMs are $\ell_2$-regularized. I guess a $\ell_2$-regularized Kernel Logistic Regression could be a good alternative.
Answer: That AML uses logistic regression for all cases, if true, is somewhat surprising to me, since logistic regression is not generally the most powerful classification tool. Perhaps AML uses it because training the logistic regression model would require much less of Amazon's resources than, say, training a boosted decision tree -- though as a customer, processing power is what I'd think I was paying Amazon for.
If they are indeed using only logistic regression, they are possibly using augmented versions for increased performance. For instance, they could conceivably be training a GAM with the logistic loss function, to account for nonlinear relationships via smoothing splines, or modeling interactions through some automated procedure.

How versatile is logistic regression?


Testing browsers (Firefox, Chrome, IE) and HSTS

Question: I am trying to do some testing with HSTS and so I setup a new Apache instance, configured it with a server cert (not self-signed), and configured it to send the HSTS header, and then am trying testing using Firefox, Chrome, and IE.
However, so far, it seems like I am only able to see the HSTS functionality (changing the end URL to an HTTPS URL when I point the browser to a non-HTTPS URL) with only Firefox.
When I do the same tests, using either Chrome or IE, when I point the browser to the non-HTTPS URL, the browser just displays the response page...
FYI, based on some searches, I have tried going to an HTTPS URL first, and then trying to point the browser to a non-HTTPS URL.... in this case, the browser just shows the non-HTTPS page.
Is there something additional that I need to do to IE and Chrome to get them to exhibit the HSTS functionality?
Thanks,
Jim
Comment: With Chrome you should be able see the status of HSTS cache by typing `chrome://net-internals/#hsts` into the address bar and searching for your domain. Are you using a real domain? Do you get a green padlock or an HTTPS error? Chrome doesn't cache details if you skip past cert errors.
Answer: I figured out my problem.  It appears that in order for the HSTS to work when using Chrome and IE, the server certificate MUST have a Subject Alternative Name (SAN) with the server name/FQDN, in addition to the FQDN in the certificate Subject.
I was able to modify and use one of the scripts in this thread:
https://serverfault.com/questions/845766/generating-a-self-signed-cert-with-openssl-that-works-in-chrome-58
to make a new CA-signed server certificate with a SAN, and now the HSTS works with Firefox, Chrome and IE (most of the solutions on that page were for self-signed server certs, but I was able to adapt one of them to use with my own (test) CA cert).


How can I disable a region at with the context module at all pages but the  (home page)

Question: How can I disable a region at with the context module at all pages but the  (home page).
I've been trying to disable a region on all pages, except the , without having to write all the paths.
I can't make the wildcards * ~ work on the <front> page.
In the condition field, I've tried to put alot of different combos i cant show here, because my post is deemed spam:
Imagine me using * ~ wildcards in front and in back of all the ways you can write the front page path: eks.  http//www.domain.com/
same goes for <front> with all the different combos.
Which one is supposed to work? Hope you get the idea.
Thanks!
Best Regards Elias
Answer: Set ~<front> in path. This will exclude only the front page.
I just tried it and it works properly.


SQL query for updating column with values from a local variable

Question: How can I update my SQL Table column with the value that is stored in a local variable.
In my program I have taken value from the HTML page using the following statement:
String idd=request.getParameter("id");
String report=request.getParameter("rprt");

So now I have to update the value of report in my database table named "ptest" and I am using the following query:
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("update ptest set result = @reprt where patient_id=
@idd");

out.println("Successfully Entered");

But the value is not being stored in the database instead NULL is being stored.
I have already seen this question and got no help.
Question
Please ignore my mistakes if any in this question as I am new to MYSQL.
Comment: idd is used to get the value of patient_id from the html page and reprt is used to get the report from the html page
Comment: Please learn how to use prepared statements
Comment: @MarkRotteveel I think he started doing that by asking the question
Comment: @markg Learning is better done by following a good tutorial or book, than by asking questions like this.
Answer: You can use prepared statements in java.
setString or setInt can set different data types into your prepared statements.
The parameter 1, 2 are basically the positions of the question mark. setString(1,report) means that it would set the string report in the 1st question mark in your query.
Hope this code helps you in achieving what you want.
String query = "update ptest set result = ? where patient_id = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);

preparedStatement.setString(1, report);
preparedStatement.setString(2, idd);

preparedStatement.executeUpdate();

Comment: `PreparedStatment preparedStatement` should be `PreparedStatement preparedStatement` (Typo in the type declaration)
Comment: how to use this statement as it is showing the following error

    PreparedStatment cannot be resolved to a type
Comment: @PiyushAgarwal please tell what is the error you are getting so I can cater the answer more correctly.
Comment: @FarhanQasim The error: Can not issue data manipulation statements with executeQuery()
Comment: @PiyushAgarwal yes I have already edited it and used executeUpdate. sorry for the mistakes, but it would work correctly now.
Answer: In JDBC, you use ? as placeholders for where you want to inject values into a statement.
So you should do something like this ...
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
PreparedStatement st= con.prepareCall("update ptest set result = ? where patient_id=
?");

///now set the params in order
st.setString(1, report);
st.setString(2, idd);
//then execute
st.executeUpdate();

Doing a string concat with the values is dangerous due to sql injection possibilities, so I typically make statement text static and final, and also if your value has a ' in it that could blow up your sql syntax etc. Also, notice the use of executeUpdate rather than query.
Hope this helps
Comment: there is an error :

The method createStatement() in the type Connection is not applicable for the arguments (String)
Comment: oops, forgot to change to prepareCall, I changed it so it should be ok now


Excel: getting cells content to generate Google maps Url

Question: I have followed this tutorial:
http://m.youtube.com/watch?v=Xnp2B0JBD_Y&desktop_uri=%2Fwatch%3Fv%3DXnp2B0JBD_Y
and now I have a google map in my excel stylesheet with a formula like this:
="http://maps.google.com/maps?saddr="&B1&"&addr="&B2&"&daddr="B3""
B1 contains Madrid
B2 contains Barcelona
B3 contains Sevilla
It plots ok the markers in the map.
Now I would like to select the cells with the mouse (B1, B8, B14, B17...or from B1 to B25) and generate the formula. Is that possible?
Answer: You can use an input prompt and then concatenate the response.  Here is how to get a range from a user:
On Error Resume Next
    Application.DisplayAlerts = False
        Set rRange = Application.InputBox(Prompt:= _
            "Please select cells with your mouse.", _
                Title:="SPECIFY RANGE", Type:=8)
On Error GoTo 0
    Application.DisplayAlerts = True

    If rRange Is Nothing Then
        Exit Sub
    End If

URL = "http://maps.google.com/maps?s"

For Each cell In rRange
   URL = URL & "addr=""&" & cell.Address & "&""&"
Next

URL = Left(URL, Len(URL) - 1)

Range("C1").FormulaLocal = URL

Output in C1 looks like this:
http://maps.google.com/maps?saddr="&$B$1&"&addr="&$B$2&"&addr="&$B$3&"

Comment: I've updated the last part of the code to string together your addresses better.


How can I read a wav file and replace bits in it?

Question: I've just started learning Java and I'm working on an audio steganography project in Java (i.e. hiding a text file in a wav file).
For that I store a text and wav file in two files. Now I want to read them in bytes and replace random bits of the wav file with text file bits.
How can i read the files in bytes? (I've tried using InputStream). Is it possible to replace random bits in wav file with bits of text file? Are there any functions for it?
Once I've read the files (both text and wav file), how can I edit (and replace) the bytes of wav file?
This is the the First screen, when user hits on HIDE button, the next screen opens up.
<code>public class OptionScreen extends javax.swing.JFrame {

    /** Creates new form OptionScreen */
    public OptionScreen() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        hide = new javax.swing.JButton();
        unhide = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        hide.setText("Hide");
        hide.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hideActionPerformed(evt);
            }
        });

        unhide.setText("UnHide");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addComponent(hide, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(94, 94, 94)
                .addComponent(unhide, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(81, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(109, 109, 109)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hide, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(unhide, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(101, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void hideActionPerformed(java.awt.event.ActionEvent evt) {
        second s=new second();
        s.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new OptionScreen().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton hide;
    private javax.swing.JButton unhide;
    // End of variables declaration
}

import java.io.DataInputStream;
import java.io.File;
import java.io.File.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

public class second extends javax.swing.JFrame {
private File afile;     // put at bottom of class
private File tfile;
    /** Creates new form second */
    public second() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        text = new javax.swing.JButton();
        audio = new javax.swing.JButton();
        tname = new javax.swing.JLabel();
        aname = new javax.swing.JLabel();
        begin = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        text.setText("TEXT FILE");
        text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textActionPerformed(evt);
            }
        });

        audio.setText("AUDIO FILE");
        audio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                audioActionPerformed(evt);
            }
        });

        begin.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        begin.setText("BEGIN");
        begin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                beginActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(text, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(audio, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(tname, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(26, 26, 26)
                                .addComponent(aname, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(270, 270, 270)
                        .addComponent(begin, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(101, 101, 101)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(text)
                    .addComponent(tname, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(audio)
                    .addComponent(aname, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(begin, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void textActionPerformed(java.awt.event.ActionEvent evt) {
        JFileChooser opentext=new JFileChooser();
        opentext.showOpenDialog(this);
        int returnVal = opentext.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        tfile = opentext.getSelectedFile();
        String tfname=tfile.getName();
        tname.setText(tfname);
        // ... code that loads the contents of the file in the text area

    }

    }

    private void audioActionPerformed(java.awt.event.ActionEvent evt) {
        JFileChooser openaudio=new JFileChooser();
        openaudio.showOpenDialog(this);
        int returnVal = openaudio.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        afile = openaudio.getSelectedFile();
        aname.setText(afile.getName());
        // ... code that loads the contents of the file in the text area
    }
    }

    private void beginActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            InputStream fint = new FileInputStream(tfile);

            byte []bt=new byte[(int)afile.length()];
            InputStream fina = new FileInputStream(afile);
            int offset = 0;
            int numRead = 0;
            //
            try {

                System.out.println(new DataInputStream(fint).readByte());
            } catch (IOException ex) {
                Logger.getLogger(second.class.getName()).log(Level.SEVERE, null, ex);
            }
            //
            System.out.println(bt);

//////////////////////////////////////////////////////////////////

            FileOutputStream outs=new FileOutputStream(new File("C:\\Documents and Settings\\Administrator\\My Documents\\My Music\\Secret.wav"));
        } catch (FileNotFoundException ex) {

        }

        //end of try catch
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new second().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel aname;
    private javax.swing.JButton audio;
    private javax.swing.JButton begin;
    private javax.swing.JButton text;
    private javax.swing.JLabel tname;
    // End of variables declaration
}
</code>
Answer: You have 2 ways: (1) read your file into byte array, than manipulate it in memory and then write it back to disk. (2) use RandomAccessFile that allows you manipulating file directly on disk.
Comment: To the computer a file is a file, it's all just data. So yes, you can use it to access the wav
Comment: using RandomAccessFile can i access the wav file too? and is it then possible to replace its bytes?
Comment: Keep in mind a wav file is composed of 16 bit values not 8 bit values.
Comment: @Angel O'Sphere: Or 32-bit, etc., depending on the metadata in the wav header.
Comment: Strictly speaking, no. There is no 32 bit WAV format, except you condisder Windows only special formats. On a CD it will always be 16 bit. However I did not know that there are meanwhile variations from the "standard" wav format. Thanx for pointing that out.


Colorir uma região do gráfico

Question: Gostaria de colorir apenas a região dentro do circulo, mas não estou conseguindo. O programa e a imagem são:
theta <- seq(0, 2 * pi, length = 200)
r = exp(1i*theta)

fx=function(r) {
 x = r-1
return (x) }

xi = fx(r)
plot(xi)

Comment: Vê se ajuda: http://stackoverflow.com/questions/12794596/how-fill-part-of-a-circle-using-ggplot2
Comment: Ainda não está dando certo!
Comment: A pergunta diz respeito a colorir algum círculo com determinado centro e raio no R ou quer colorir a parte interna da figura gerada pela função fx?
Comment: Colorir apenas a parte interna da figura gerada pela função fx! Para uma outra função, meu interesse vai ser colorir a parte externa do circulo.
Answer: Considero que a melhor maneira de resolver este problema, dada esta resposta ao meu comentário acima, é fazer um polígono com os valores da função em vez de tentar fazer um círculo. Segue o código para isso:
theta <- seq(0, 2 * pi, length = 200)
r     <- exp(1i*theta)

fx <- function(r) {
    x = r-1
    return (x)
}

xi <- fx(r)

plot(xi)
polygon(Re(xi), Im(xi), col="cyan")

Note que simplesmente construí um polígono com as partes reais e imaginárias do resultado obtido pela função.

Colorir uma região do gráfico


HTML: Automatic generated date and time

Question: I'm trying to implement a time stamp on a tomcat server page. It should always show the current time and date whenever I trigger a button.
Right now I'm using this:

It is a auto-generated time and date view I just found in the web. It is working fine, except the problem that it is always visible and not only when clicking on the button.
HTML-File:

    Dev. Tool

<h:form enctype="multipart/form-data">

        <f:facet name="header">
            <h:outputText value="WorkON Dev. Quality Check Tool" style="font-size:16px" />
            <h:outputLink value="https://inside-wiki.bosch.com/confluence/display/woco/18.0+Dev.+tool+according+to+Dev.+guideline"
                target="_blank">

                <h:graphicImage id="helpIcon" value="/imgs/help.png" style="margin-left:10px" />

            </h:outputLink>

        </f:facet>

            <h:outputText value="                           " />
                <h:outputText value="Validation result :" style="font-weight: bold" />

                    <h:outputText id="valiCodePass" value="#{_item.code}" />

                    <h:outputText value="#{_item.result.flag} : #{_item.result.content}" rendered="#{_item.result.content != null}" />
                    <h:outputText value="#{_item.result.flag}" rendered="#{_item.result.content == null}" />

                    <h:outputText id="valiCodeFail" value="#{_item.code}" />

                    <h:outputText value="#{_item.result.flag} : #{_item.result.content}" />

                    <h:outputText id="valiCodeWarn" value="#{_item.code}" />

                    <h:outputText value="#{_item.result.flag} : #{_item.result.content}" />

            <h:outputText value="Project details :" style="font-weight: bold;" />

                <h:outputText value="Project name (in source)" />
                <h:outputText value="#{validator.project.name}" />

                <h:outputText value="Project key" />
                <h:outputText value="#{validator.project.key}" />

                <h:outputText value="Language available" />
                <h:outputText value="#{validator.project.lanInfo}" />

                <h:outputText value="Interface | configed -> used" />
                <h:outputText value="#{validator.project.itfInfo}" />

                <h:outputText value="Interface | web service | used" />
                <h:outputText value="#{validator.project.itConfig.wfIterfaces.size()}" />

                <h:outputText value="Interface | old excel | used" />
                <h:outputText value="#{validator.project.itConfig.excelIterfaces.size()}" />

                <h:outputText value="Interface | database | used" />
                <h:outputText value="#{validator.project.itConfig.dbIterfaces.size()}" />

                <h:outputText value="Workflow | configured | used" />
                <h:outputText value="" rendered="#{validator.project.configuredWfs.size() == null}" />
                <h:outputText value="#{validator.project.configuredWfs.size()} -> #{validator.project.usedWfs.size()}"
                    rendered="#{validator.project.configuredWfs.size() != null}" />

                <h:outputText value="Escalation | used" />
                <h:outputText value="#{validator.project.escalationConfig.escalationItems.size()}" />

                <h:outputText value="Unused custom field amount" />
                <h:outputText value="#{validator.project.unusedCustomField}" />

                <h:outputText value="Lines of javascript" />
                <h:outputText value="#{validator.project.getJavaLines()}" />

                <h:outputText value="Lines of velocityscript" />
                <h:outputText value="#{validator.project.getVelocityLines()}" />

                <h:outputText value="Amount of used user picker" />
                <h:outputText value="#{validator.project.getUserPicker()}" />

                <h:outputText value="IssueType | configed -> used" />
                <h:outputText value="#{validator.project.getIssueTypeInfo()}" />

                <h:outputText value="IssueType list" />
                <h:outputText value="#{validator.project.getIssueType()}" />

                <h:outputText value="Used Non-standard status" />
                <h:outputText value="#{validator.project.getStatus()}" />

                <h:outputText value="Used Non-standard resolution" />
                <h:outputText value="#{validator.project.getLangPropertiesNames()}" />

                <h:outputText value="Amount of used parallel approval lines // Amount of used sequential approval lines" />
                <h:outputText value="#{validator.project.getParallelApprovalLines()} // #{validator.project.getSequentialApprovalLines()}"
                rendered="#{validator.project.getParallelApprovalLines() != null}" />

        <f:facet name="footer">

                <h:outputText value="Innovated and developed by CI/AFR-CN  V1.4" style="color:grey" />

        </f:facet>

</h:form>

    <f:facet name="start">

    </f:facet>

    <f:facet name="complete">
        <h:outputText value="" />
    </f:facet>

If you know how to show the date/time when clicking a button, please respond.
Thanks in advance!
Comment: Are you open to use some JS?
Comment: already write some code down, i could help you implement that for example look at this im working right now i get the current date and displaying on my mother language (spanish) and playing with dates http://majestic-wave-16-154974.sae1.nitrousbox.com/ i can help you if you want, make some github repo PD: the code below it very basic and i know it look boring its just an example :p
Answer: If you are open to use JS code try this
You can use an script tag like this

and html tag like this
calling js code

and it will get you the current date, also if you want to improve better performance and languages on you web page i suggest you to use
moment.js
Try to use some JS code to show dates, etc i would be a nice behavior on whatever you are doing
Comment: I already found this JS on "http://www.w3schools.com/js/js_dates.asp".
But it is as the frame above always visible.
Comment: ok so baa my bad i don't get you point i will edit my answer wait
Comment: This is an alternative way to create the date itself. Personally, I think this is a little better than using an iFrame, however you must combine this with my answer regarding adding a button & jquery to make it show/hide. The problem of showing/hiding is not caused by the fact that this is an iFrame.
Comment: @Etjana That methode works fine for me, could you please also tell me how to hide the date and time? I only want to display it when this code is used.
``

Right now, the date appears when I load/reload the page.
Thanks in advance.
Answer: I think it would be helpful if you could please provide a little more info (perhaps the full .html for the page?), however here's my best guess:
An iFrame is basically a window into another page - in your case, the free.timeanddate page. However, to make this iFrame hide or show, you'd need javascript or jquery in order to change the iFrame's visibility. Here's a link to a JSFiddle to help you out: http://jsfiddle.net/KingOfTheNerds/dd8cy97p/
An example of the jquery is:
$( "button" ).click(function() {
  $( "p" ).slideToggle( "slow" );
});

Comment: Hey, I'm a beginner in HTML and JS. Can in write both, the script and the html code into my .html?

    `
`
Comment: @Julian - this is almost correct. You need to also add a button to your html. Here's another jfiddle example: http://jsfiddle.net/KingOfTheNerds/adaq974z/

You also need to add jQuery to the page in the html head. You can get the code for this from Google's CDN: https://developers.google.com/speed/libraries/devguide#jquery
Comment: @Julian - did this work for you? If so, can you please mark the question as answered by clicking the check mark next to the answer you want to accept. Thanks!
Comment: I have already implemented a button. When I add your jQuery to my code the button is not visible anymore. But I want the button to be always visible and only the time hidden. I will post you my current HTML code.
Comment: `
Tool

`
Comment: `

`
Comment: @Julian - I don't have a way of testing the fileUpload class from a Tomcat/JSF application, however I found this StackOverflow article that suggests you should assign an id to that tag, and then reference the ID from your jQuery: http://stackoverflow.com/questions/18439699/primefaces-file-upload-drop-file-outside-of-pfileupload-anywhere-in-the-page

Also - the code in your original post does not contain the iFrame at all. Perhaps you can update your original post to contain some code that follows the MCVE guidelines found here: http://stackoverflow.com/help/mcve

I hope this helps!

HTML: Automatic generated date and time


Deploy simple Java Web Application on Appfog

Question: I started using appfog ( http://www.appfog.com/ ) and I haven't found any resources explaining how to deploy a simple Java Web application. I tried extracting a .war file I have and then updating the app but I got no luck.
Cheers
Answer: Deploying Java Web Application on AppFog is pretty easy once you see an example. Here is some documentation: https://docs.appfog.com/languages/java
Step 1) Build a war file and cd into the directory with the war file in it (usually cd target)
Step 2) af push
You do not want to extract the war file, you just need to be in the same directory as the war file.
Hope this helps! Best of luck! There is a great and vibrant community of AppFog Java users in the google group as well: https://groups.google.com/forum/#!forum/appfog-users


Entity custom displays

Question: Is there a way to create multiple displays for an existing entity?
The node has already Full content, Teaser, RSS, Search index, Search result display types. I was wondering if I can add more to these or to any other entity.
Thanks :)
Answer: I think this is the answer I was looking for:
<code>function hook_entity_info_alter(&$entity_info) {
  $entity_info['entity_type']['view modes']['custom mode'] = array(
    'label' => t('Custom view mode'),
    'custom settings' => FALSE
  );
}
</code>
Answer: You can use display suite module. this is your answer
Comment: I think `hook_entity_info_alter(&$entity_info)` is what I was looking for. I just need it so I can invoke it from code later on.

Entity custom displays


Any chance to recover formatted hard drive LVM to ext3

Question: I am a big fool. But i believe this could be the event for every serious linux administrator. I Accidentally formatted my hard drive from LVM to Ext3. I tried some of the recovery tools. I can see around 13 GB recovery from 500+ GB contents. I learnt from this mistake. But data is really important for me.
Even what recovery software is offering me to recover has no correct file names. They are random file names. So obviously all source code has no use to recover in that state. Because there is no link suppose to be there in this random state.
I can see all data is there. mkfs.ext3 re-write the blocks. I don't know if there is any hope i could recover everything in the same stage. But whatever recovered should be in exact format.
Please help me if you can suggest me any open/commercial solution to recover whatever possible.
I learnt lesson from this mistake.
Comment: No i do not. That's why i am considering my self as a fool. :(
Comment: So, no backups, eh?
Answer: I did something similar quite a while back, except it was ext3 and overwritten by lvm3.
I updated my partition table with fdisk to reflect an ext3 partition without rewriting the actual blocks. I was able to recover the vast majority of my files after I did that. Something similar might do the trick for you.
Comment: Actually i ran mkfs.ext3 instead of fdisk. And that really makes me worry about things.
Answer: There's a possibility that if you boot a CD like RIP (Rescue is Possible) and run Testdisk (Google for more information) that you may recover data from the partition. I've had pretty good luck with salvaging information using it and it's free. You might find it on other discs as well like Ubuntu or Knoppix, you'd have to look.
Also...you're not using that computer, yes? Every time you write or alter anything on the drive you could be rendering more data irrecoverable.
Next...you need a backup system. If it's important, you never keep only one copy.
If the data is very important, you might want to consider FIRST getting another hard drive, booting an external disc (like the previously mentioned RIP) and making a complete image of the drive before ANY attempt to extract data. That way you can recover back to a known-good state if something goes wrong. Use a utility to clone the disk at the block level like dd; not something that will just copy at the file level so you'll have a 500 gig image.
Comment: you are right. I learnt from my mistake and i did what i should before. I buy new 1TB disk and made a snapshot using "dd" of 1TB. now i have snapshot of best known disk state.
Comment: testdisk does not work for me. I got nothing from the deep search. I found some data recovery tools which are commercial. I tried their demo version. One software is showing me 13+ GB contents which is out of format (strange folder names and file names). So that's why i though, i should do lil more research to make any decision. This time i must have to be very careful about what i left. (At least recovery tool showing me something).


How to understand boxplot skewness

Question: I have a boxplot that is drawn and the whiskers are the same length but the median is closer to the upper quartile than the middle.
Would this be considered skewed or symmetrical?
Comment: Can you post an image of the plot? Also, the data or a summary of it (mean, median, sd, skewness, etc) would help.
Comment: Also, how large is the sample size? And how much closer?
Answer: Note that this asymmetry in the box of a boxplot is related to a measure of skewness called the quartile skewness (Also see here)
In small samples from symmetric distributions the median may frequently be much closer to one hinge (effectively, quartile) than the other.
Even very "nicely" behaved unimodal distributions like the normal can have this boxplot-asymmetry happen. If the sample size is 10, then the median will be 63% or more of the way toward the nearest quartile half the time (i.e. the absolute quartile skewness will half the time exceed 0.26). That is, for sampling from a normal with $n=10$, this is a typical (i.e. median) amount of asymmetry in the box:

(since 25% it will be at least this far up, and 25% of the time it would be equally as far below the midhinge point)
At n=9 it's 67% for samples from a normal distribution. [Equivalently the absolute value of the quartile skewness will exceed 1/3 half the time.]
If the population distribution is non-normal but still symmetric, a typical boxplot might be much more asymmetric (one symmetric example I just came up with had the median-line position about 92.5% of the way toward the nearest quartile at least half the time at n=10).
Which is to say, in small samples, we have to be very cautious about interpreting asymmetry in the boxplot as implying asymmetry of the population from which the sample was drawn.
For a given distribution, as $n$ increases, such a large deviation from symmetry  becomes less likely and then we may feel somewhat safer in calling it asymmetric (e.g. for normal samples at n=100 the typical split of the box is 45-55), but even at large samples there would still be symmetric distributions that tended to have very asymmetric-looking boxes (they won't be unimodal, though -- but you generally won't be able to tell that from the boxplot either).

How to understand boxplot skewness


How to create database diagrams in SQL Server 2008 express?

Question: I am using SQL Server 2008 express version but don't know how to generate database diagrams. When I click the Database Diagrams, it give me an error diagram tell me "Database diagram support objects cannot be installed because this database does no thave a valide owner. ...." I follow its instruction and cannot find anything wrong. Anybody can help me about this?
Anybody can recommend a free database design tool I can use with SQL Server to create ER diagram for our existing database?
Answer: You need to change the compatibility level and set authorisation:
Database diagram support objects cannot be installed
Comment: how to escape character '\' in the login replacement of the SQL