SQL UPDATE same sequence number in colB for same set of values in colA

Question: SQL UPDATE same sequence number in colB for same set of values in colA
Need either UPDATE SQL statement (preferred) or PL/SQL
// Here is script for table create
CREATE TABLE temp
(
    "COL_A" VARCHAR2(128 BYTE),
    "COL_B" NUMBER
);

// script for data load
INSERT INTO temp VALUES ('A', null);
INSERT INTO temp VALUES ('A', null);
INSERT INTO temp VALUES ('B', null);
INSERT INTO temp VALUES ('C', null);
INSERT INTO temp VALUES ('C', null);
INSERT INTO temp VALUES ('C', null);
INSERT INTO temp VALUES ('D', null);
INSERT INTO temp VALUES ('D', null);

BEFORE
-------
TEMP TABLE
-------------
COL_A, COL_B
-------------
A, null
A, null
B, null
C, null
D, null
C, null
D, null
C, null

DESIRED OUTPUT
-------------
COL_A, COL_B
-------------
A, 1
A, 1
B, 2
C, 3
D, 4
C, 3
D, 4
C, 3

For same values in COL_A, we will generate and reuse same sequence number for N number of rows, values for column B are from sequence number temp_seq
I tried several ideas, but I could not reuse same sequence number for same  values (it was generating new one).
Comment: Why is the desired output ordered differently?
Answer: merge might be another option:
SQL> merge into temp a
  2    using (select rowid rid,
  3                  dense_rank() over (order by col_a) col_b
  4           from temp
  5          ) b
  6    on (a.rowid = b.rid)
  7    when matched then update set
  8      a.col_b = b.col_b;

8 rows merged.

SQL> select * from temp;

COL_A           COL_B
---------- ----------
A                   1
A                   1
B                   2
C                   3
C                   3
C                   3
D                   4
D                   4

8 rows selected.

SQL>

Answer: You can do:
update temp t
set col_b = (
  select count(distinct col_a)
  from temp u
  where u.col_a <= t.col_a
);

Result:
 COL_A  COL_B
 ------ -----
 A      1
 A      1
 B      2
 C      3
 C      3
 C      3
 D      4
 D      4

See running example at db<>fiddle.


Python script to automate tasks with Excel

Question: First of all I am very sorry if this is a common questions, however I am still very new in the programming world, and cannot figure out the keywords for what I'm actually looking for.
Basically I have an Excel spreadsheet with data Picture of Excel Sheet - For each identifier I have a 0 or a 1. My task is to copy the number in the identifier column, paste it into a webpage from my workplace and click a button to exclude the customer from billing. Once I have done this, I will go back to the Excel spreadsheet and change the number from 0 to 1. Since there is a lot to go through, I thought this would be a fun project for me to start learning a basic script. I did not make it very far though!
import pandas as pd

Migreringer = pd.read_excel('Migreringer.xls')

ExludeBilling = Migreringer[["Exclude Billing", "Identifier"]]

IsExcludedBilling = Migreringer["Exclude Billing"] > 0

I was hoping that someone was able to give me a good idea as to how to move on from here, My idea is that it would check each row for the True/False statement from IsExcludedBilling, and then as a start copy the identifier if the statement is False and paste it into a word document or something similar to test this out? I just cannot seem to figure out how to make Python go through each row and validate the statements, and then make it copy something from a different column in the same row to a different document?
I know from experience that I am more motivated in learning with a project in mind, so that is why I've chosen to start here. Maybe I should take a couple of steps back before engaging with a project like this?
Answer: do you wan this ?
df = pd.DataFrame(
    {
        'Exclude Billing': [1,0,0,1,0],
        'Identifier': [ 41823,41835,41819,41798,41812],
    }
)
df_zero=df.loc[df['Exclude Billing']==0,:]
df_zero.to_csv('data_with_zero.csv',index=False)

Comment: That would definietly be a start, how would I go about adding the actual numbers from my sheet with this?
Comment: @SimonKianzad with df=pd.read_excel(your_files) and then you df_zero=df.loc…


Credentials are required to create a Client Twillo in codeigniter

Question: Fatal error: Uncaught Twilio\Exceptions\ConfigurationException: Credentials are required to create a Client in E:\wamp64\www\sms\src\Twilio\Base\BaseClient.php on line 70
error image
i will try this error solve iam tried. direct sid and token paste in src file
how to fix this problem and i want solution this error.
This is my code
require(__DIR__.'./src/Twilio/autoload.php');

use Twilio\Rest\Client;

$sid = getenv('xxxxxx');
$token = getenv('xxxxx');
$client = new Client($sid, $token);

// Specify the phone numbers in [E.164 format](https://www.twilio.com/docs/glossary/what-e164) (e.g., +16175551212)
// This parameter determines the destination phone number for your SMS message. Format this number with a '+' and a country code
$phoneNumber = "+91xxxx";

// This must be a Twilio phone number that you own, formatted with a '+' and country code
$twilioPurchasedNumber = "+xxxxxx";

// Send a text message
$message = $client->messages->create(
    $phoneNumber,
    [
        'from' => $twilioPurchasedNumber,
        'body' => "Hey Jenny! Good luck on the bar exam!"
    ]
);
print("Message sent successfully with sid = " . $message->sid ."\n\n");

// Print the last 10 messages
$messageList = $client->messages->read([],10);
foreach ($messageList as $msg) {
    print("ID:: ". $msg->sid . " | " . "From:: " . $msg->from . " | " . "TO:: " . $msg->to . " | "  .  " Status:: " . $msg->status . " | " . " Body:: ". $msg->body ."\n");
}

Comment: Please provide more details such as the source code and explain what you already tried to solve this problem.
Comment: Can you check my edited questions?
Comment: The code looks good now. It seems that the account sid and auth token cannot be loaded in line 5 and 6. Are you sure the environment variables are set?
You should be able to test this when you try to `print()` the `$token` and `$client`
Comment: I set two variable of values but show this error. i con't provide my sid and token so i write "xxxx"
Comment: Do you mean you entered your credentials instead of `xxx`? This code should contain name name of the environment variables which store the secret tokens. If you want to use the tokens directly in the code, you don't need to call [`getenv()`](https://www.php.net/manual/en/function.getenv.php)
Comment: Great, I covered our conversation to an answer to that it's easier to find. Feel free to mark it complete with the green checkmark button.
Answer: It seems to me the environment variables are not set properly.
This code should contain name name of the environment variables which store the secret tokens. If you want to use the tokens directly in the code, you don't need to call getenv() and just defined the strings directly.


Percentile calculation for binary voting system

Question: Consider a system like Tinder for example where users can vote yes or no to a profile (like or dislike).  If Tinder wanted to come up with an internal percentile rating of a user based only on the other users' votes of their profile (not based on how picky that particular user is), what would be a good statistical approach?
I have thought a good amount about this and I think there are two important points to consider.
1) Different users have different styles of voting.  Some users are pickier than others.  Thus, a like from a picky user should impact a profile's percentile more positively than a like from a less picky user.  The same logic goes for dislikes.
2) Votes more likely to be spam should be weighted less heavily in the percentile.  Spam can be determined by somehow analyzing a user's voting style and compare each vote they do to what everyone else is voting for a specific profile.
Beyond this I'm struggling to come up with a good algorithm to do this.
One other issue I'm thinking about is that let's say you come up with some number that represents a user's score in the system.  You can get this user's percentile by getting the ranking of that user's score among all the scores.  However, what if your system only has a small number of users?  The system I am thinking about is supposed to predict globally what the profile's percentile would be.  Thus, if there are only 5 profiles on the system and it is the top profile, this will only be the top 20th percentile. This would only be a problem when the system only has a few users, but I am wondering how to represent some idea of a percentile in this case.
Answer: I do not have the one true answer to your problem, but FWIW I think you should look into Item Response Theory (IRT). That was, off course, developed for questionnaires but there are a lot of similiarities to your situation: In a Rasch model, each item has a difficulty and each participant decides whether for his particular situation, he decides to tick yes or no. In your Tinder example, a profile has an attractiveness and the user decides, whether with his particular standards is going to click yes or no. So looking into Rasch models or more broadly IRT you will find som probabilistic methods to determine latent traits.
I am not aware, whether you will find a way to weigh answers that are likely to be spam, though, but you will find methoeds, algorithms and statistics packages to compute how picky each user is and how attractive each profile is at the same time.
As always: You cannot do some statistical methods based on very small numbers. There will always be minimal requirements for the amounts of data to draw reliable conclusions.


How to make my rock, paper, scissor run more than once

Question: below is what I have so far, I need to implement function simul() that takes as input an integer n and simulates n rounds of Rock, Paper, Scissors between players Player 1 and Player 2. Any tips would be appreciated
import random
def simul(n):

    p1 = random.choice("RPS")
    p2 = random.choice("RPS")

    if p1 == p2:
       print("Tie")
    elif (p1 == "R" and p2 == "S") or (p1 == "S" and p2 =="P") or (p1 == "P" and p2 == "R"):
       print("Player 1 wins")
    else:
       print("Player 2 wins")

Answer: import random
def simul(n):

    for i in range(n):
       p1 = random.choice("RPS")
       p2 = random.choice("RPS")

       if p1 == p2:
          print("Tie")
       elif (p1 == "R" and p2 == "S") or (p1 == "S" and p2 =="P") or (p1 == "P" and p2 == "R"):
          print("Player 1 wins")
       else:
          print("Player 2 wins")

Comment: sorry, I need to input an integer on simul(n): and run the number of times n
Comment: @Jaime2823 as the statement was unclear, i made a few assumptions. I've updated the answer.
Answer: You need recursive func. Simple solution is :
import random
def simul(n):
    if n < 1:
        return 'Finished'
    p1 = random.choice("RPS")
    p2 = random.choice("RPS")
    if p1 == p2:
       print("Tie")
    elif (p1 == "R" and p2 == "S") or (p1 == "S" and p2 =="P") or (p1 == "P" and p2 == "R"):
       print("Player 1 wins")
    else:
       print("Player 2 wins")
    simul(n-1)

n = int(input('Enter the number of rounds'))
simul(n)

Comment: Python doesn't do tail-call optimization, so this kind of recursion is not terribly efficient. In other languages, the compiler will often turn this into a loop, but in Python, you get a lot of unnecessary overhead with recursion that you can avoid using iteration instead.


how to add conditional styles?

Question: How can I insert the following:

I tried it in page.tpl.php but not worked.
Answer: Put it in html.tpl.php also it work in page.tpl.php but I think you did not clear cache , please dont forget this, clear cache after templates changes.
also you can use conditional css
this link help you
https://drupal.org/project/conditional_styles
Comment: I cleared the cache ctrl+f5 but not changed...
Comment: do you try to put it in html.tpl.php?
Comment: yes, tried that too....
Comment: would you please add that part of code in your question ?
Comment: what part? the exact code as in the question I placed in html.tpl.php in head.....
Comment: yes,that part with some line after and before
Comment: before the closing of head tag, also tried right after title tag...
Comment: But I've copied the html.tpl.php to my subtheme from the base theme...
Comment: I tried conditional-styles just now but still having no change... I think compatibility mode doesn't change in ie?
Comment: Ctrl+f5 clears the browser cache.  Did you clear Drupal's cache?
Comment:
Should be in the

You could add it as an attribute for some element with conditional comments - but it's extra ugly.

Just put ie styles in a separate file and require it in .
Comment: @RooticalV. I agree with you put it in separate file is very better solution

how to add conditional styles?


Difference between Ramsey Reset test and link test

Question: My question is simple, what is the difference between reset test and link test? My understanding of reset test is that it tests the correctness of the functional form by incorporating square, cube etc. of explanatory variables $X$. Link test on the other hand regress the dependent variable $Y$ on predicted variable $\hat{Y}$ and $\hat{Y}^2$.
In various places I have seen that reset test and link test is testing omitted variable, but I am not sure if this is true. To me they are testing whether functional form is correct or not. However, I do not see the difference between  these two. For instance, would it be enough to run only reset or would one still need to check link? If yes, why? I hope somehow these questions make some sense to somebody.
Answer: I also expected to find some discussions on the comparisons of the two tests online. I think that, if we didn't find them, it is due to the fact the Link test is not very popular. However, I try to address the issue below.
My understanding is that the main version of the Ramsey test includes powers of fitted values of $\hat{Y}$. Then there is the modified version including powers of explanatory variables $X$, as you say. My reasoning is that the Link test coincides with the Ramsey Reset test using just the squared value (the Ramsey test may also be performed using higher order polynomials), in case there is just 1 regressor; otherwise, the Ramsey test is more flexible since it includes all original regressors $(Y=\alpha+\beta_1*X_1+...+\beta_k*X_k+\hat{Y^2}+... )$, thus allowing for different parameter values as compared to the first regression, while the Link test only includes the predicted value from the previous model. Also, the Link test is more parsimonious than the Ramsey model specified using powers of regressors (if they are more than one) while at the same time taking non-additivity into account (as the "regular" Ramsey test): $\hat{Y}^2$ also includes $2*\beta_1\beta_2*XZ$, if $\hat{Y}=\beta_0+\beta_1*X+\beta_2*Z$.
Both tests evaluates the hypotesis: $E(y | x)=F(x\theta)$, thus are generical tests for functional form. In case of rejectance, it could be that we just need to allow for non-linearity and/or non-additivity using the same model, covariates and observations, but there may be many alternative explanations, for example: the link function (or, if you prefer, the dependent variable) is misspecifed, relevant variables are omitted, measurement (or classification) errors. Sometimes Ramsey and Link are presented as tests for omitted variables. I think the reason (apart from the fact the Ramsey test was originally introduced as such, as well as the Link test suggests to be a test on the link function by its very name) is that, unless such variables are available, you can't test for their inclusion directly. On the contrary, one can test for heteroskedasticity, or compare models with different link functions/outcome specification, or nested (for example: linear models vs fractional or order polynomials). Moreover, it is not a test against heteroskedasticity (where squared residuals should be used) nor, in case they are not correlated with the available predictors,  omitted variables.
For a reference to Ramsey test and possible reasons for misspecification (although in the binary setting, where also heteroskedasticity may lead to hypothesis rejection), please see:
Ramalho, E. A. and Ramalho, J. J. S. (2012), Alternative Versions of the RESET Test for Binary Response Index Models: A Comparative Study*. Oxford Bulletin of Economics and Statistics, 74: 107–130. doi:10.1111/j.1468-0084.2011.00654.x


Given some continuous function $g:\mathbb R_{+}\to \mathbb R_{-}$, and $\lambda >0$, does there exist $C^{1}$ function $\psi$ satisfying the following

Question: Given some continuous function $g:\mathbb R_{+}\to \mathbb R_{-}$, and $\lambda >0$, does there exist a $C^{1}$ $\psi$ such that
$$ g(t) =\frac{\partial}{\partial t}\psi(t)+\lambda\psi(t), \; \psi(0)=0?$$
I am rusty on ODEs but in my view, since $g$ is continuous and (trivially) locally Lipschitz continuous in the second argument (there is no second argument), and hence a unique maximal solution must exist?
I am very unsure on this. Any ideas?
Comment: Does $\Bbb R_+$ contain $0$?
Comment: @s.harp No, it does not contain zero
Answer: The ODE you are interested in is a inhomogenous linear differential equation of first order and there is no magic to it at all. Let $g : \mathbb R \to \mathbb R$ continuous (else your initial condition makes no sense). Then the solution is given by
$$\psi(x) = \biggl(\int_0^x g(t) \mathrm e^{\lambda t} \, \mathrm dt + c \biggr) \mathrm e^{-\lambda x} \qquad (x \in \mathbb R)$$
for a suitable constant $c \in \mathbb R$. Using your inital condition we observe
$c = \psi(0) = 0$. Thus, the solution is given by
$$\psi(x) = \int_0^x g(t) \mathrm e^{\lambda (t - x)} \, \mathrm dt \qquad (x \in \mathbb R).$$
Obviously, the solution is maximal but you can restrict it to $\mathbb R_+$ if that fits your application better.


Using a remote host's USB port as local USB (Linux and Windows)

Question: I have a USB device that reads data from a system and transfers them to the computer. I am wondering if it's possible to have a Linux single board PC (i.e. Raspberry Pi) to run a script and be a remote-server for my USB device and I can connect to that "remote-server"(Linux) through SSH or FTP or another protocol (over the Internet) and mount that USB port to my computer. Any software would do it, you know how terminal service connects the remote resources, and I need the same, but preferably on a Linux board.
My system is Windows 7, so I need to mount that remote-USB as a "local port" so the software thinks it's communicating locally, and it'll find the reader.
Comment: You can stop researching now - Samba won't help. It's a file/printer sharing server, not anything more general.
Comment: Have you tried Samba?
Comment: No I'll do a quick research now, thanks
Comment: Well from what I've found so far, I can use it as a bridge. It sounds like it just sends/receives data and passes to the next hop, it's not actually doing anything with the signal
Answer: There is an open source project called usbip that provides functionality to share and/or mount a remote USB device over an IP network (LAN/Internet).
There are also at least three commercial products that provide this functionality with better documentation and UI. I've included links to the commercial products at the end of this reply.
From the usbip web page:

http://usbip.sourceforge.net

To share USB devices between computers with their full functionality, USB/IP encapsulates "USB I/O messages" into TCP/IP payloads and transmits them between computers. Original USB device drivers and applications can be also used for remote USB devices without any modification of them. A computer can use remote USB devices as if they were directly attached

The usbip server process runs on Linux systems and clients are available for Linux and Windows - the project has apparently been around since 2005, and they've had a signed Windows client driver since 2011. In theory, depending on the repositories configured on your Raspberry Pi, you should be able to execute sudo aptitude install usbip to install the server-side drivers and application.
Note that if you use Ubuntu 14.10 (Utopic Unicorn) or newer, you do not need to install the usbip package: the usbip tools are part of the linux-tools-generic package, and the binaries are already available in /usr/lib/linux-tools-KERNEL-VERSION/.
A walkthrough tutorial on how to install and use usbip is available at HowToForge:

How to modify your GNU/Linux box to serve as a USB-over-IP server

The Windows client has advanced since the HowToForge tutorial and has a little more interface now instead of just a command-line tool.
Commercial USB-over-IP tools:
Fabula-Tech USB-over-Network - runs on Windows & Linux - trial available:

USB over Network

Eltima Software USB Network Gate - runs on Windows, Mac OS X, & Linux - trial available:

USB Network Gate Share USB over Ethernet for Windows

Incentives Pro/SimplyCore LLC USB Redirector - runs on Windows & Linux - apparently free for Linux server and a free Windows client is available:

USB Redirector for Linux - Share USB devices over the network on Linux
Comment: Incentives Pro/SimplyCore LLC USB Redirector - is an expectedly commercial: you can use free client to connect to paid server, or you can use paid client to connect to paid server, it is prohibited to connect by free client to free server.  ( Tested in the field and covertly documented at http://www.incentivespro.com/purchase.html )
Comment: To add to what @Arioch'The said, the Incentives Pro [purchase page](http://www.incentivespro.com/purchase.html) says "**USB Redirector Client is FREE for connecting USB devices shared by USB Redirector on Windows [1]. Commercial license must be purchased for connecting USB devices shared by USB Redirector for Linux. [2]**".  ~~~ The "USB Redirector on Windows" [1] is paid software and "USB Redirector for Linux. [2]" is free.
Comment: +1 for the incentive-pro, it just works! where the usbip just does not compile out of the box on Ubuntu 14.04
Comment: fresh ubuntu's don't have drivers for usbipd. more details: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/898003/comments/37
Comment: USB-IP project does not have signed win64 drivers, which mean their  Windows client only can be used on XP-x64 or 32-bit Windows later versions // this problem also hurt Sandboxie project for few months, but they found a sponsor who signed their Win7+ drivers for them. Sadly USB-IP did not.
Comment: Couldn't one use `netcap` to accomplish this? Cf. the question "[Converting serial port data to TCP/IP in a linux environment](https://stackoverflow.com/q/484740/1429450)."
Comment: It's really a shame that USB/IP doesn't have a Windows version for the server.
Comment: To add more, we wanted to move from Windows server to Linux server, so we asked USB Redirector vendor if they can change our Windows-Server license to equivalent Linux-server one, or better make that license universal, applicable to both Windows and Linux servers interchangeably, but sadly they refused, though promised to consider it for future versions some day


How to get WooCommerce product variation values

Question: I want to be able to list the the variation option values. For example I have a lantern that comes in 12in, 14in and 16in. I want to be able to get these values. I have been trying to use the foreach loop to get these values but I need a little help. here's my code;
function test_func(){
    global $woocommerce, $product, $post;
    // test if product is variable
    if( $product->is_type( 'variable' ) ){
        $available_variations = $product->get_available_variations();
        // var_dump($available_variations);

        foreach( $available_variations as $key => $value ){
            var_dump( $value['attributes'] ) ;
        }
    }
}

This is what is output:
array(1) { ["attribute_pa_size"]=> string(4) "12in" } array(1) { ["attribute_pa_size"]=> string(4) "14in" } array(1) { ["attribute_pa_size"]=> string(4) "16in" }

As you can see the values that I want are there, but I don't know how to get them to echo them.
Here's what I get if I var_dump() $available_variations;
" ["backorders_allowed"]=> bool(false) ["dimensions"]=> array(3) { ["length"]=> string(4) "11.8" ["width"]=> string(4) "11.8" ["height"]=> string(4) "11.8" } ["dimensions_html"]=> string(21) "11.8 x 11.8 x 11.8 in" ["display_price"]=> float(3.2) ["display_regular_price"]=> float(3.2) ["image"]=> array(18) { ["title"]=> string(11) "6712R-1.jpg" ["caption"]=> string(0) "" ["url"]=> string(59) "http://website/wp-content/uploads/2018/10/6712R-1.jpg" ["alt"]=> string(0) "" ["src"]=> string(67) "http://website/wp-content/uploads/2018/10/6712R-1-600x600.jpg" ["srcset"]=> string(445) "http://website/wp-content/uploads/2018/10/6712R-1-600x600.jpg 600w, http://website/wp-content/uploads/2018/10/6712R-1-150x150.jpg 150w, http://website/wp-content/uploads/2018/10/6712R-1-300x300.jpg 300w, http://website/wp-content/uploads/2018/10/6712R-1-768x768.jpg 768w, http://website/wp-content/uploads/2018/10/6712R-1-1024x1024.jpg 1024w, http://website/wp-content/uploads/2018/10/6712R-1-100x100.jpg 100w" ["sizes"]=> string(31) "(max-width: 600px) 100vw, 600px" ["full_src"]=> string(59) "http://website/wp-content/uploads/2018/10/6712R-1.jpg" ["full_src_w"]=> int(2000) ["full_src_h"]=> int(2000) ["gallery_thumbnail_src"]=> string(67) "http://website/wp-content/uploads/2018/10/6712R-1-100x100.jpg" ["gallery_thumbnail_src_w"]=> int(100) ["gallery_thumbnail_src_h"]=> int(100) ["thumb_src"]=> string(67) "http://website/wp-content/uploads/2018/10/6712R-1-300x300.jpg" ["thumb_src_w"]=> int(300) ["thumb_src_h"]=> int(300) ["src_w"]=> int(600) ["src_h"]=> int(600) } ["image_id"]=> string(3) "164" ["is_downloadable"]=> bool(false) ["is_in_stock"]=> bool(true) ["is_purchasable"]=> bool(true) ["is_sold_individually"]=> string(2) "no" ["is_virtual"]=> bool(false) ["max_qty"]=> int(17) ["min_qty"]=> int(1) ["price_html"]=> string(145) "
" ["sku"]=> string(5) "6712R" ["variation_description"]=> string(0) "" ["variation_id"]=> int(1462) ["variation_is_active"]=> bool(true) ["variation_is_visible"]=> bool(true) ["weight"]=> string(0) "" ["weight_html"]=> string(3) "N/A" } [1]=> array(24) { ["attributes"]=> array(1) { ["attribute_pa_size"]=> string(4) "14in" } ["availability_html"]=> string(51) "
This is just for one product, there is one for each variation, but this gives you the idea of how it works. I'm also open to trying another method to get the same results so if you know of one let me know. Thanks
Answer: You need to use a 2nd foreach loop for the product attributes:
function test_func(){
    global $woocommerce, $product, $post;
    // test if product is variable
    if( $product->is_type( 'variable' ) ){
        // Loop through available product variation data
        foreach ( $product->get_available_variations() as $key => $variation ) {
            // Loop through the product attributes for this variation
            foreach ($variation['attributes'] as $attribute => $term_slug ) {
                // Get the taxonomy slug
                $taxonmomy = str_replace( 'attribute_', '', $attribute );

                // Get the attribute label name
                $attr_label_name = wc_attribute_label( $taxonmomy );

                // Display attribute labe name
                $term_name = get_term_by( 'slug', $term_slug, $taxonmomy )->name;

                // Testing output
                echo '
' . $attr_label_name . ': ' . $term_name . '
';
            }
        }
    }
}

Comment: How could i get the product variation description, I mean the description inside the variation and not the main product description
Comment: For me, the value I need is just `$term_slug`. `$term_name` is empty.


Habilitar e desabilitar um botão de edição de formulário - com PHP

Question: Tenho a seguinte situação:
Tenho um página (ex: EDITAR.PHP) que vai ser onde será editado as informações que anteriormente foi cadastrada por um formulário (Formulário de cadastro de usuários).
A questão é, no final dessa página EDITAR.PHP, terá um botão salvar (onde será redirecionado para uma função que fará o INSERT na base). Gostaria de saber se com PHP eu conseguiria que, ao abrir essa página tivesse alguma validação pra fazer com uma consulta ao banco pois quando esse determinado usuário fosse de sexo = M, por exemplo, não habilitasse o botão SALVAR, deixando visualizar mas não salvar.
ESTÁ TRAZENDO AMBOS OS SEXOS COM O BOTÃO DESABILITADO
<?php
@ini_set('display_errors', '1');
error_reporting(E_ALL);

$id = $_GET["id"];
settype($id, "integer");

mysql_connect("localhost", "root", "");
mysql_select_db("banco");

$resultado = mysql_query("select * from tabela where id_tabela = $id");
$dados     = mysql_fetch_array($resultado);
if($dados["sexo"] == "M") {
    $checkedM   = "checked=\"checked\"";
    $checkedF   = "";
} else {
    $checkedM   = "";
    $checkedF   = "checked=\"checked\"";
}
$sqlstatus = mysql_query("select * from tabela where sexo = 'M' GROUP BY sexo");
$res = mysql_num_rows($sqlstatus);

mysql_close();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Cadastro</title>

<form id="form1" name="form1" method="post" action="salvar_edicao.php">
<input type="hidden" name="id" id="id" value="<?php echo $id;?>" />

Edição de Cadastro PHP/MYSQL

      Nome
      <input name="nome" type="text" id="nome" value="<?php echo $dados["nome"];?>" />

      Sobrenome
      <input name="sobrenome" type="text" id="sobrenome" value="<?php echo $dados["sobrenome"];?>" />

      Email
      <input name="email" type="text" id="email" value="<?php echo $dados["email"];?>" />

      Sexo
      <input name="sexo" type="radio" value="M" <?php echo $checkedM;?> />
        Masculino
        <input name="sexo" type="radio" value="F" <?php echo $checkedF;?> />
        Feminino

      <input type="submit" name="Submit" value="Gravar" <?php echo $res > 0 ? 'disabled' : '' ; ?> />	 //Com o 'disabled' na frente trás tudo desabilitado, e com ele na frente traz habilitado.

</form>

NO BANCO ESTÁ ASSIM:
Comment: Você chegou dar `print_r($dados); die();` para ver o que retorna?
Answer: Se acordo com sua consulta você pergunta se  o status é igual a 2.
Então, apenas faça uma verificação perguntando se retornou algum registro ( > 0 ). Se sim, ele mostra o botão desabilitado, disabled.
<?php

    $sqlstatus = mysql_query("select status_atividade from atividades where status_atividade = 2");

    $res = mysql_num_rows($sqlstatus);

    if($res > 0)
       <input type="submit" disabled>
    else
       <input type="submit">

?>

Comment: Ai lá no botão não precisa por nada? @DiegoSouza
Comment: Eu coloquei o `disabled`.
Comment: Eu não havia visto sua consulta toda... mudei meu código e estou verificando pelo número de linhas retornadas do seu `select`.
Comment: Testei e deu erro.  Funciona se o campo for uma Letra ao invés de um numero no status_atividade = 'M' ? @DiegoSouza
Comment: Acabei de editar o código acima conforme o teu exemplo. Vê onde pode tá errado. @DiegoSouza
Comment: Recomendo que não use mysql_* e sim mysqli_* ou PDO. Vou dar a resposta baseado que você já fez a correção.
Comment: Nomear a tabela de "tabela" é a coisa gente preguiçosa.
Answer: Ao invés de fazer
if($res > 0)
<input type="submit" disabled>

else{
<input type="submit">

Você também pode usar o operador ternario fazendo da seguinte maneira.
$res = 2; // Exemplo de resultado
<input type="submit" <?php echo $res > 0 ? 'disabled' : ''; ?> />
// Se $res for maior que 0 será exibido disabled se não, não será exibido nada.

Sua consulta pode estar retornando mais de 1 resultado, utilize da seguinte maneira.
$sqlstatus = mysql_query("select * from tabela where sexo = 'M' GROUP BY sexo");

O GROUP BY ira agrupar todos as linhas que tiverem o sexo = M
Comment: Funcionaria onde você colocou $res =  2; Eu definir uma letra, tipo 'M', ai no input como ficaria?
Comment: Coloquei assim: $sqlstatus = mysql_query("select sexo from tabela where sexo = 'M'");
$res = mysql_num_rows($sqlstatus);
$res = 'M'; E:  . Ta ficando tudo desabilitado agora. @
Rafael Acioly
Comment: @TiagoIB Tente usar dois sinais de iguais `==` ou ate mesmo 3 para verificar autenticidade `===`, mas neste caso voce esta usando  `$res` para pegar um `NUMERO (mysql_num_rows)` de linhas e não uma `string`.
Comment: @ Rafael Acioly Ajustei o código da pergunta acima, de acordo com a sua sugestão porém, está retornando ambos as opções com o botão desabilitado.
Comment: Coloquei todo o meu código de como está agora. E mesmo assim está trazendo desabilitado tanto em usuários com sexo: M ou F.
@ Rafael Acioly
Comment: @TiagoIB é claro que vai sempre ficar desabilitado, depois de usar o `$res` para pegar o numero de linhas você define ele como `2` apagando o que foi buscado no banco, apague esta linha`($res = 2)`, e dentro da condição ternaria que te passei inverta as ordens: ` 0 ? '' : 'disabled'; ?>`
Comment: @ Rafael Acioly . Apaguei e continua ficando desabilitado sempre: $sqlstatus = mysql_query("select * from tabela where sexo = 'M' GROUP BY sexo");
$res = mysql_num_rows($sqlstatus); e o botão:  0 ? 'disabled' : ''; ?>/>
Comment: Com eu disse antes, troque a ordem para ` 0 ? '' : 'disabled'; ?>` este operador ternario é basicamente um `if` super pequeno e funciona assim: `"mostre (echo)" (operacao) ($res > 0) ?  "se for verdadeiro" : "se for falso" ?>`
Comment: @ Rafael Acioly . Acabei de colocar o código todo no topo da pergunta. Fiz bem o que você disse e por algum motivo está retornando desabilitado. O tipo de dado no banco interessa?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/29273/discussion-between-rafael-acioly-and-tiagoib).
Answer:
EDITADO para satisfazer a necessidade com versão antiga sem uso de mysqli:

<?php

$params = array("M",1);

// query
$sql = "select * from tabela where sexo ='{$params[0]}' and id ={$params[1]} ";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
   $permission='';
    if(count($row)){
        if ($row[0]['status'] == 2) {
           $permission = ' disabled = "disabled"';
        }
    }
?>
<input type="submit" name="Submit" value="Gravar"<?php echo $permission ?> />

Comment: Vou fazer aqui.
Comment: Esse meu trabalho está todo como conexão Mysql, ai não vai funcionar a não ser que eu mude tudo. Teria como formatar essa função em uma maneira mais simples, de acordo com o método de conexão mais antigo? @IvanFerrer
Comment: Deu esse erro:  Parse error: syntax error, unexpected '=' in C:\wamp\www\cadastro-simples\editar.php on line 32 . @IvanFerrer
Comment: O erro é na linha do: permission=''; @IvanFerrer
Comment: Obrigado por avisar, era para ser uma variável.
Comment: Só aviso que não sei se vai dar certo, pois não tem como eu testar aqui, pois não tenho php antigo aqui, no meu servidor retorna uma mensagem de código depreciado, e para de funcionar.


Roll 2 dice. Let A = 'the first die is odd', B = 'the second die is odd', and C = 'the sum is odd'

Question: I am currently working on a probability problem. I am new to probability (just now studying it). I came across this question just working on some problems.
The question asks, are A and B independent? By intuition I would say so.
A = {1,3,5},
B = {1,3,5}
(Alternatively, I think I could also represent them as pairs with size sets of 36; the probabilities would
still be 1/2).
$P(A) = 1/2$
$P(B) = 1/2 $
However, whenever I find the $P(A \cap B)$, it does not
equal $P(A)P(B)$.
I get that $$P(A \cap B)=1/2$$ $$|A \cap B|=3,|\Omega|=6$$ where $\Omega$ is the total number of outcomes.
Thus, $$P(A \cap B)=|A \cap B|/|\Omega|=3/6=1/2$$ However, $$P(A)P(B)=1/4$$
Therefore, $$P(A \cap B)=1/2 \neq P(A)P(B)=1/4$$.
This leads to a rejection of
independence.
Have I made a mistake?
Answer: They are independent.  There are $3$ ways for each die to be odd.  Therefore there are $3^2 = 9$ ways for both dice in a pair to be odd.  There are 6 results for each die.  Therefore there are $6^2 = 36$ possible results for a pair of dice.  The probability for a pair of dice to both be odd is then
$$ P(A \cap B) = \frac{9}{36} = \frac{1}{4} = \frac{1}{2} \cdot \frac{1}{2} = P(A) P(B) $$
The mistake you made is when you wrote $|A \cap B| = 3$.  It is actually 9 (and the full space has size 36).
Comment: So I made a mistake in the intersection. I see now, thanks!
Answer: You wrote that $|A \cap B| = 3, |\Omega| = 6$. This is not correct.
$A = \{1,3,5\}, B = \{1,3,5\}$
For throw of two dice, $|\Omega| = 36$
$A \cap B$ is the event of both dice turning up odd. That is,
$A \cap B = \{1,1\}, \{1,3\}, \{1,5\}, \{3,1\}, \{3,3\}, \{3,5\}, \{5,1\}, \{5,3\}, \{5,5\}$
$|A \cap B| = 9$
$\displaystyle |\frac{A \cap B|}{|\Omega|} = \frac{9}{36} = \frac{1}{4}$
Comment: You are welcome!
Comment: I see, my omega for the intersection was off. Thanks for this!

Roll 2 dice. Let A = ‘the first die is odd’, B = ‘the second die is odd’, and C = ‘the sum is odd’


Playing sweetly vs gently in violin

Question: I am learning violin as a beginner (2.5 months), and one of the early practice pieces contain dolce and piano. The latter is more like playing quietly and gently, so it makes some intuitive sense and I think I know how to pull that off. However, I cannot seem to play "sweetly", most likely because I do not quite understand what it would entail. It's probably not just a matter of playing softer, and maybe I need to take specific care on how to change notes and position of the bow between the fingerboard and the bridge.
As this is in beginner's practice pieces, I would assume that this is not one of those "you will get it after few years" kind, though I might be wrong. Any help, conceptually and practically, would be greatly appreciated!
Answer: I think the taste metaphor does capture it quite well: while piano and dolce are both "soft" in a sense, they are so in very different ways. p is a shy, fragile kind of soft, in the way a balm mint leaf is soft. But dolce is a thick, embracing kind of soft, more like the way a custard pie is soft. As well as how it's sweet.
So, how do you play it? It's hard to explain, this is in fact one of the things that requires lots of practise to really get the feel. A couple of technical elements that can contribute to a dolce sound are

bowing sul tasto, i.e. further away from the bridge and almost over the fingerboard. This tends to allow generating a smoother, less harsh sound, if you get the pressure and speed right.
legato phrasing. In particular, avoid rythmically accenting the start of notes, but don't allow the notes to "wear thin" at the end. In fact, you can try outright delaying the note onsets – start very softly but then let the notes bloom. This isn't something you would do in a mere p passage, that should keep the phrasing as-is.
vibrato. Here I seem to disagree with Old Brixtonian – IMO dolce can come out very nicely with strong vibrato, only it must not be too hectic. Not too fast or too wide, but thick and soothing. (Whatever that's supposed to mean...)

While you're still a beginner, don't worry too much about really getting a noticeable dolce sound within a piece. More important is that you try out how different the instrument responds when you play it in certain ways, that's what will eventually give you the right sense, feeling, for such nuances.
Comment: That's a good answer. I agree with 'almost over the fingerboard,' I'm not sure about delaying the note onsets, and I disagree about thick and soothing vibrato. I feel you are veering towards the *espress.* the composer so didn't ask for! *p*, is not "a shy, fragile kind of soft": dynamics tell us only how loudly or softly to play. There's no more shyness in *p* than there is gregariousness in *f*. *Dolce*, though, does suggest a degree of fragility: not, for me, a 'thick embracing kind of soft' - Custard pies? Get outta here! - but as I said: such music is tender, simple & sometimes childlike.
Answer: piano is simply p: more quietly than mp, but not as quietly as pp.
Dolce means, as you say, 'sweetly', and I think it often suggests a degree of simplicity in the playing. The composer might have written espress. but has chosen NOT to. I think such passages should be played with little rubato and with little vibrato. Music marked dolce is tender, often simple and sometimes childlike.
Comment: I don't think "little vibrato" is commonly agreed, rather the opposite.

Playing sweetly vs gently in violin


What does asymptotically optimal mean for an algorithm?

Question: What does it mean to say that

heap sort and merge sort are asymptotically optimal comparison sorts .

I know What the Big O , Big Omega($\omega)$ and Theta($\theta$) notations are and I also know why these two sorts are called comparison sorts ? But I am not able to understand why they are called asymptotically optimal  ? Why doesn't this asymptotically optimal property also apply to quick sort ?
P.S: I had a look in this question but still I am not clear about the definition of asymptotically optimal .
Comment: Because the Landau symbols only give you asymptotic statements, that is in the limit for $n \to \infty$.
Answer: Computing a simple function that characterizes the behavior of an algorithm for any input is difficult. So upper and lower bounds are used, in addition to probabilistic methods.
The term 'asymptotic' is used because the bound is typically only valid for large $n$, as an accurate formula for small $n$ is more complicated, and not really interesting from a performance perspective.
To answer your question, you can prove that any working comparison sort takes a lower bound of $\Omega(n \lg n)$ on running time. Consequently, if you can show that a sorting algorithm (such as heapsort or merge sort) has an upper bound of $O(n \lg n)$ on running time, then in fact you have a running time of $\Theta(n \lg n)$ which is, by definition, an asymptotically tight bound for the running time (See Cormen, Leiserson & Rivest's "Introduction to Algorithms", Chapter 2, Theorem 2.1, and the section on sorting).
Quicksort has a worst-case running time of $\Theta(n^2)$, which is larger than the above bound, hence is not optimal.
Note, however, that quicksort has an average running time of $\Theta(n \lg n)$. (This, of course, assumes that all inputs of length $n$ are equally likely.)
Comment: I also have a [related question here](http://math.stackexchange.com/questions/181139/which-one-gives-better-constant-factors-between-heap-sort-and-quick-sort) . I got an answer still not clear on it yet . Can you answer that ?
Comment: I added a comment to the question. In short, I don't have a good answer.
Comment: Thanks for second paragraph which is clear enough!
Answer: It means that they can't be improved upon. It's fairly easy to prove that any comparison sort can't do better than $\Theta(n \log n)$, so any comparison sort which achieves $\Theta(n \log n)$ is asymptotically optimal.
Quick sort is $O(n^2)$ and that bound can't be tightened.
Comment: isn't quick sort also  $O(n \log n)$ on average ? Its worst case if it is run without any randomization is $O(n^2)$ though.
Comment: "Quick sort is O(n2) and that bound can't be tightened." I think you meant that that bound can be tightened further meaning can be improved upon  or am I missing something fundamental here ?
Comment: @Geek, depends on what you average over. And worst case is what's relevant unless otherwise specified.
Answer: It means the following: Let $A$ be a comparison based sorting algorithm,
and denote $T_{A}(n$) the time complexity of $A$ then $T_{A}(n)=\Omega(nlogn)$
That is, there exist a constant $c>0$ and $n_{0}$ such that for every
$n>n_{0}$ it holds that $T_{A}(n)\geq c\cdot nlogn$


How would I go about making a custom Whois look up

Question: I want to add a custom Whois look up to my site. I've looked around but haven't found much information.
Comment: Do you have any code that you have written yet? Please provide some code samples for what you have tried so that others can more easily assist you with your question.
Comment: call command line `whois` parse data
Answer: Here's a great simple PHP whois script. It's free, and just has a couple functions you can call.
http://www.phpeasycode.com/whois/
Reference
Use the following php
<?php
/*************************************************************************
php easy :: whois lookup script
==========================================================================
Author:      php easy code, www.phpeasycode.com
Web Site:    http://www.phpeasycode.com
Contact:     email@example.com
*************************************************************************/

$domain = $_GET['domain'];

// For the full list of TLDs/Whois servers see http://www.iana.org/domains/root/db/ and http://www.whois365.com/en/listtld/
$whoisservers = array(
    "ac" => "whois.nic.ac", // Ascension Island
    // ad - Andorra - no whois server assigned
    "ae" => "whois.nic.ae", // United Arab Emirates
    "aero"=>"whois.aero",
    "af" => "whois.nic.af", // Afghanistan
    "ag" => "whois.nic.ag", // Antigua And Barbuda
    "ai" => "whois.ai", // Anguilla
    "al" => "whois.ripe.net", // Albania
    "am" => "whois.amnic.net",  // Armenia
    // an - Netherlands Antilles - no whois server assigned
    // ao - Angola - no whois server assigned
    // aq - Antarctica (New Zealand) - no whois server assigned
    // ar - Argentina - no whois server assigned
    "arpa" => "whois.iana.org",
    "as" => "whois.nic.as", // American Samoa
    "asia" => "whois.nic.asia",
    "at" => "whois.nic.at", // Austria
    "au" => "whois.aunic.net", // Australia
    // aw - Aruba - no whois server assigned
    "ax" => "whois.ax", // Aland Islands
    "az" => "whois.ripe.net", // Azerbaijan
    // ba - Bosnia And Herzegovina - no whois server assigned
    // bb - Barbados - no whois server assigned
    // bd - Bangladesh - no whois server assigned
    "be" => "whois.dns.be", // Belgium
    "bg" => "whois.register.bg", // Bulgaria
    "bi" => "whois.nic.bi", // Burundi
    "biz" => "whois.biz",
    "bj" => "whois.nic.bj", // Benin
    // bm - Bermuda - no whois server assigned
    "bn" => "whois.bn", // Brunei Darussalam
    "bo" => "whois.nic.bo", // Bolivia
    "br" => "whois.registro.br", // Brazil
    "bt" => "whois.netnames.net", // Bhutan
    // bv - Bouvet Island (Norway) - no whois server assigned
    // bw - Botswana - no whois server assigned
    "by" => "whois.cctld.by", // Belarus
    "bz" => "whois.belizenic.bz", // Belize
    "ca" => "whois.cira.ca", // Canada
    "cat" => "whois.cat", // Spain
    "cc" => "whois.nic.cc", // Cocos (Keeling) Islands
    "cd" => "whois.nic.cd", // Congo, The Democratic Republic Of The
    // cf - Central African Republic - no whois server assigned
    "ch" => "whois.nic.ch", // Switzerland
    "ci" => "whois.nic.ci", // Cote d'Ivoire
    "ck" => "whois.nic.ck", // Cook Islands
    "cl" => "whois.nic.cl", // Chile
    // cm - Cameroon - no whois server assigned
    "cn" => "whois.cnnic.net.cn", // China
    "co" => "whois.nic.co", // Colombia
    "com" => "whois.verisign-grs.com",
    "coop" => "whois.nic.coop",
    // cr - Costa Rica - no whois server assigned
    // cu - Cuba - no whois server assigned
    // cv - Cape Verde - no whois server assigned
    // cw - Curacao - no whois server assigned
    "cx" => "whois.nic.cx", // Christmas Island
    // cy - Cyprus - no whois server assigned
    "cz" => "whois.nic.cz", // Czech Republic
    "de" => "whois.denic.de", // Germany
    // dj - Djibouti - no whois server assigned
    "dk" => "whois.dk-hostmaster.dk", // Denmark
    "dm" => "whois.nic.dm", // Dominica
    // do - Dominican Republic - no whois server assigned
    "dz" => "whois.nic.dz", // Algeria
    "ec" => "whois.nic.ec", // Ecuador
    "edu" => "whois.educause.edu",
    "ee" => "whois.eenet.ee", // Estonia
    "eg" => "whois.ripe.net", // Egypt
    // er - Eritrea - no whois server assigned
    "es" => "whois.nic.es", // Spain
    // et - Ethiopia - no whois server assigned
    "eu" => "whois.eu",
    "fi" => "whois.ficora.fi", // Finland
    // fj - Fiji - no whois server assigned
    // fk - Falkland Islands - no whois server assigned
    // fm - Micronesia, Federated States Of - no whois server assigned
    "fo" => "whois.nic.fo", // Faroe Islands
    "fr" => "whois.nic.fr", // France
    // ga - Gabon - no whois server assigned
    "gd" => "whois.nic.gd", // Grenada
    // ge - Georgia - no whois server assigned
    // gf - French Guiana - no whois server assigned
    "gg" => "whois.gg", // Guernsey
    // gh - Ghana - no whois server assigned
    "gi" => "whois2.afilias-grs.net", // Gibraltar
    "gl" => "whois.nic.gl", // Greenland (Denmark)
    // gm - Gambia - no whois server assigned
    // gn - Guinea - no whois server assigned
    "gov" => "whois.nic.gov",
    // gr - Greece - no whois server assigned
    // gt - Guatemala - no whois server assigned
    "gs" => "whois.nic.gs", // South Georgia And The South Sandwich Islands
    // gu - Guam - no whois server assigned
    // gw - Guinea-bissau - no whois server assigned
    "gy" => "whois.registry.gy", // Guyana
    "hk" => "whois.hkirc.hk", // Hong Kong
    // hm - Heard and McDonald Islands (Australia) - no whois server assigned
    "hn" => "whois.nic.hn", // Honduras
    "hr" => "whois.dns.hr", // Croatia
    "ht" => "whois.nic.ht", // Haiti
    "hu" => "whois.nic.hu", // Hungary
    // id - Indonesia - no whois server assigned
    "ie" => "whois.domainregistry.ie", // Ireland
    "il" => "whois.isoc.org.il", // Israel
    "im" => "whois.nic.im", // Isle of Man
    "in" => "whois.inregistry.net", // India
    "info" => "whois.afilias.net",
    "int" => "whois.iana.org",
    "io" => "whois.nic.io", // British Indian Ocean Territory
    "iq" => "whois.cmc.iq", // Iraq
    "ir" => "whois.nic.ir", // Iran, Islamic Republic Of
    "is" => "whois.isnic.is", // Iceland
    "it" => "whois.nic.it", // Italy
    "je" => "whois.je", // Jersey
    // jm - Jamaica - no whois server assigned
    // jo - Jordan - no whois server assigned
    "jobs" => "jobswhois.verisign-grs.com",
    "jp" => "whois.jprs.jp", // Japan
    "ke" => "whois.kenic.or.ke", // Kenya
    "kg" => "www.domain.kg", // Kyrgyzstan
    // kh - Cambodia - no whois server assigned
    "ki" => "whois.nic.ki", // Kiribati
    // km - Comoros - no whois server assigned
    // kn - Saint Kitts And Nevis - no whois server assigned
    // kp - Korea, Democratic People's Republic Of - no whois server assigned
    "kr" => "whois.kr", // Korea, Republic Of
    // kw - Kuwait - no whois server assigned
    // ky - Cayman Islands - no whois server assigned
    "kz" => "whois.nic.kz", // Kazakhstan
    "la" => "whois.nic.la", // Lao People's Democratic Republic
    // lb - Lebanon - no whois server assigned
    // lc - Saint Lucia - no whois server assigned
    "li" => "whois.nic.li", // Liechtenstein
    // lk - Sri Lanka - no whois server assigned
    "lt" => "whois.domreg.lt", // Lithuania
    "lu" => "whois.dns.lu", // Luxembourg
    "lv" => "whois.nic.lv", // Latvia
    "ly" => "whois.nic.ly", // Libya
    "ma" => "whois.iam.net.ma", // Morocco
    // mc - Monaco - no whois server assigned
    "md" => "whois.nic.md", // Moldova
    "me" => "whois.nic.me", // Montenegro
    "mg" => "whois.nic.mg", // Madagascar
    // mh - Marshall Islands - no whois server assigned
    "mil" => "whois.nic.mil",
    // mk - Macedonia, The Former Yugoslav Republic Of - no whois server assigned
    "ml" => "whois.dot.ml", // Mali
    // mm - Myanmar - no whois server assigned
    "mn" => "whois.nic.mn", // Mongolia
    "mo" => "whois.monic.mo", // Macao
    "mobi" => "whois.dotmobiregistry.net",
    "mp" => "whois.nic.mp", // Northern Mariana Islands
    // mq - Martinique (France) - no whois server assigned
    // mr - Mauritania - no whois server assigned
    "ms" => "whois.nic.ms", // Montserrat
    // mt - Malta - no whois server assigned
    "mu" => "whois.nic.mu", // Mauritius
    "museum" => "whois.museum",
    // mv - Maldives - no whois server assigned
    // mw - Malawi - no whois server assigned
    "mx" => "whois.mx", // Mexico
    "my" => "whois.domainregistry.my", // Malaysia
    // mz - Mozambique - no whois server assigned
    "na" => "whois.na-nic.com.na", // Namibia
    "name" => "whois.nic.name",
    "nc" => "whois.nc", // New Caledonia
    // ne - Niger - no whois server assigned
    "net" => "whois.verisign-grs.net",
    "nf" => "whois.nic.nf", // Norfolk Island
    "ng" => "whois.nic.net.ng", // Nigeria
    // ni - Nicaragua - no whois server assigned
    "nl" => "whois.domain-registry.nl", // Netherlands
    "no" => "whois.norid.no", // Norway
    // np - Nepal - no whois server assigned
    // nr - Nauru - no whois server assigned
    "nu" => "whois.nic.nu", // Niue
    "nz" => "whois.srs.net.nz", // New Zealand
    "om" => "whois.registry.om", // Oman
    "org" => "whois.pir.org",
    // pa - Panama - no whois server assigned
    "pe" => "kero.yachay.pe", // Peru
    "pf" => "whois.registry.pf", // French Polynesia
    // pg - Papua New Guinea - no whois server assigned
    // ph - Philippines - no whois server assigned
    // pk - Pakistan - no whois server assigned
    "pl" => "whois.dns.pl", // Poland
    "pm" => "whois.nic.pm", // Saint Pierre and Miquelon (France)
    // pn - Pitcairn (New Zealand) - no whois server assigned
    "post" => "whois.dotpostregistry.net",
    "pr" => "whois.nic.pr", // Puerto Rico
    "pro" => "whois.dotproregistry.net",
    // ps - Palestine, State of - no whois server assigned
    "pt" => "whois.dns.pt", // Portugal
    "pw" => "whois.nic.pw", // Palau
    // py - Paraguay - no whois server assigned
    "qa" => "whois.registry.qa", // Qatar
    "re" => "whois.nic.re", // Reunion (France)
    "ro" => "whois.rotld.ro", // Romania
    "rs" => "whois.rnids.rs", // Serbia
    "ru" => "whois.tcinet.ru", // Russian Federation
    // rw - Rwanda - no whois server assigned
    "sa" => "whois.nic.net.sa", // Saudi Arabia
    "sb" => "whois.nic.net.sb", // Solomon Islands
    "sc" => "whois2.afilias-grs.net", // Seychelles
    // sd - Sudan - no whois server assigned
    "se" => "whois.iis.se", // Sweden
    "sg" => "whois.sgnic.sg", // Singapore
    "sh" => "whois.nic.sh", // Saint Helena
    "si" => "whois.arnes.si", // Slovenia
    "sk" => "whois.sk-nic.sk", // Slovakia
    // sl - Sierra Leone - no whois server assigned
    "sm" => "whois.nic.sm", // San Marino
    "sn" => "whois.nic.sn", // Senegal
    "so" => "whois.nic.so", // Somalia
    // sr - Suriname - no whois server assigned
    "st" => "whois.nic.st", // Sao Tome And Principe
    "su" => "whois.tcinet.ru", // Russian Federation
    // sv - El Salvador - no whois server assigned
    "sx" => "whois.sx", // Sint Maarten (dutch Part)
    "sy" => "whois.tld.sy", // Syrian Arab Republic
    // sz - Swaziland - no whois server assigned
    "tc" => "whois.meridiantld.net", // Turks And Caicos Islands
    // td - Chad - no whois server assigned
    "tel" => "whois.nic.tel",
    "tf" => "whois.nic.tf", // French Southern Territories
    // tg - Togo - no whois server assigned
    "th" => "whois.thnic.co.th", // Thailand
    "tj" => "whois.nic.tj", // Tajikistan
    "tk" => "whois.dot.tk", // Tokelau
    "tl" => "whois.nic.tl", // Timor-leste
    "tm" => "whois.nic.tm", // Turkmenistan
    "tn" => "whois.ati.tn", // Tunisia
    "to" => "whois.tonic.to", // Tonga
    "tp" => "whois.nic.tl", // Timor-leste
    "tr" => "whois.nic.tr", // Turkey
    "travel" => "whois.nic.travel",
    // tt - Trinidad And Tobago - no whois server assigned
    "tv" => "tvwhois.verisign-grs.com", // Tuvalu
    "tw" => "whois.twnic.net.tw", // Taiwan
    "tz" => "whois.tznic.or.tz", // Tanzania, United Republic Of
    "ua" => "whois.ua", // Ukraine
    "ug" => "whois.co.ug", // Uganda
    "uk" => "whois.nic.uk", // United Kingdom
    "us" => "whois.nic.us", // United States
    "uy" => "whois.nic.org.uy", // Uruguay
    "uz" => "whois.cctld.uz", // Uzbekistan
    // va - Holy See (vatican City State) - no whois server assigned
    "vc" => "whois2.afilias-grs.net", // Saint Vincent And The Grenadines
    "ve" => "whois.nic.ve", // Venezuela
    "vg" => "whois.adamsnames.tc", // Virgin Islands, British
    // vi - Virgin Islands, US - no whois server assigned
    // vn - Viet Nam - no whois server assigned
    // vu - Vanuatu - no whois server assigned
    "wf" => "whois.nic.wf", // Wallis and Futuna
    "ws" => "whois.website.ws", // Samoa
    "xxx" => "whois.nic.xxx",
    // ye - Yemen - no whois server assigned
    "yt" => "whois.nic.yt", // Mayotte
    "yu" => "whois.ripe.net");

function LookupDomain($domain){
    global $whoisservers;
    $domain_parts = explode(".", $domain);
    $tld = strtolower(array_pop($domain_parts));
    $whoisserver = $whoisservers[$tld];
    if(!$whoisserver) {
        return "Error: No appropriate Whois server found for $domain domain!";
    }
    $result = QueryWhoisServer($whoisserver, $domain);
    if(!$result) {
        return "Error: No results retrieved from $whoisserver server for $domain domain!";
    }
    else {
        while(strpos($result, "Whois Server:") !== FALSE){
            preg_match("/Whois Server: (.*)/", $result, $matches);
            $secondary = $matches[1];
            if($secondary) {
                $result = QueryWhoisServer($secondary, $domain);
                $whoisserver = $secondary;
            }
        }
    }
    return "$domain domain lookup results from $whoisserver server:\n\n" . $result;
}

function LookupIP($ip) {
    $whoisservers = array(
        //"whois.afrinic.net", // Africa - returns timeout error :-(
        "whois.lacnic.net", // Latin America and Caribbean - returns data for ALL locations worldwide :-)
        "whois.apnic.net", // Asia/Pacific only
        "whois.arin.net", // North America only
        "whois.ripe.net" // Europe, Middle East and Central Asia only
    );
    $results = array();
    foreach($whoisservers as $whoisserver) {
        $result = QueryWhoisServer($whoisserver, $ip);
        if($result && !in_array($result, $results)) {
            $results[$whoisserver]= $result;
        }
    }
    $res = "RESULTS FOUND: " . count($results);
    foreach($results as $whoisserver=>$result) {
        $res .= "\n\n-------------\nLookup results for " . $ip . " from " . $whoisserver . " server:\n\n" . $result;
    }
    return $res;
}

function ValidateIP($ip) {
    $ipnums = explode(".", $ip);
    if(count($ipnums) != 4) {
        return false;
    }
    foreach($ipnums as $ipnum) {
        if(!is_numeric($ipnum) || ($ipnum > 255)) {
            return false;
        }
    }
    return $ip;
}

function ValidateDomain($domain) {
    if(!preg_match("/^([-a-z0-9]{2,100})\.([a-z\.]{2,8})$/i", $domain)) {
        return false;
    }
    return $domain;
}

function QueryWhoisServer($whoisserver, $domain) {
    $port = 43;
    $timeout = 10;
    $fp = @fsockopen($whoisserver, $port, $errno, $errstr, $timeout) or die("Socket Error " . $errno . " - " . $errstr);
    //if($whoisserver == "whois.verisign-grs.com") $domain = "=".$domain; // whois.verisign-grs.com requires the equals sign ("=") or it returns any result containing the searched string.
    fputs($fp, $domain . "\r\n");
    $out = "";
    while(!feof($fp)){
        $out .= fgets($fp);
    }
    fclose($fp);

    $res = "";
    if((strpos(strtolower($out), "error") === FALSE) && (strpos(strtolower($out), "not allocated") === FALSE)) {
        $rows = explode("\n", $out);
        foreach($rows as $row) {
            $row = trim($row);
            if(($row != '') && ($row{0} != '#') && ($row{0} != '%')) {
                $res .= $row."\n";
            }
        }
    }
    return $res;
}
?>

<title>Whois Lookup Script</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<form action="<?=$_SERVER['PHP_SELF'];?>">

Domain/IP Address: <input type="text" name="domain" id="domain" value="<?=$domain;?>"> <input type="submit" value="Lookup">

</form>
<?
if($domain) {
    $domain = trim($domain);
    if(substr(strtolower($domain), 0, 7) == "http://") $domain = substr($domain, 7);
    if(substr(strtolower($domain), 0, 4) == "www.") $domain = substr($domain, 4);
    if(ValidateIP($domain)) {
        $result = LookupIP($domain);
    }
    elseif(ValidateDomain($domain)) {
        $result = LookupDomain($domain);
    }
    else die("Invalid Input!");
    echo "
\n" . $result . "\n
\n";
}
?>

and call the php in the page where you are going to implement

Upload whois.php file on your server and open in your browser:    http://www.yourdomain.com/whois.php
Enter the domain name (only the name itself, without http://www) or    IP address you want to get whois data.
View results online.

Hope it is useful
Comment: @Dagon - I have added code snippet ..i hope you would review the downvote


Difference between Time delayed neural networks and Recurrent neural networks

Question: I would like to use a Neural Network to predict financial time series. I come from an IT background and have some knowledge of Neural Networks and I have been reading about these:

TDNN
RNN

I have been searching for R packages for them and I only found one for RNN, the RSNNS package which has elman and jordan implementations which are RNN.
So, are Recurrent Neural Networks useful to use with (financial) time series? Since they (quote from the wikipedia link on RNN cited before):

At each time step, the input is propagated in a standard feed-forward fashion, and then a learning rule is applied. The fixed back connections result in the context units always maintaining a copy of the previous values of the hidden units (since they propagate over the connections before the learning rule is applied). Thus the network can maintain a sort of state, allowing it to perform such tasks as sequence-prediction that are beyond the power of a standard multilayer perceptron.

aren't in practice the same as Time Delay Neural Networks? If not, which are the differences with Time Delay Neural Networks? Are both suitable to use with Time Series or which one is more suitable?
Thanks beforehand!
Answer: I have never worked with recurrent networks, but from what I know, in practice, some RNN and TDNN can be used for the same purpose that you want: Predict time series values. However, they work different.
It is possible with TDNN:

Predict process' values
Find a relationship between two processes.

Some RNN, like NARX also allow you to do that, and it is also used to predict financial time series, usually better than TDNN.
A TDNN looks more like a feedforward network, because time aspect is only inserted through its inputs, unlike NARX that also needs the predicted/real future value as input. This characteristic makes TDNN less robust than NARX for predicting values, but requires less processing and is easier to train.
If you are trying to find a relationship between a process $X(t)$ and a process $Y(t)$, NARX requires you to have past values of $Y$, while TDNN does not.
I recommend reading Simon Haykin's Neural Networks: A Comprehensive Foundation (2nd Edition) and this FAQ. There are lots of neural networks architectures and variations. Sometimes they have many names or there is no consensus about their classification.
Comment: Thanks for your answer Mario, but I can't access the FAQ you posted, it seems the link is broken. Could you repost it?
Comment: I couldn't find another link for it, so I am reposting the same: [ftp://ftp.sas.com/pub/neural/FAQ.html](ftp://ftp.sas.com/pub/neural/FAQ.html)
I could access it with Firefox, Safari and Chrome. Let me know if it helps you.
Answer: TDNNs is a simple way to represent a mapping between past and present values. The delays in the TDNN remain constant throughout the training procedure and are estimated before by using trial and error along with some heuristics. It, however, may be the case that these fixed delays do not capture the actual temporal locations of the time dependencies. On the other hand, the "memory" feature of the RNN structures can capture this information by learning these dependencies. The problem with RNNs is that they are impractical to use when trained with traditional techniques (e.g Backpropagation through time) for learning long term dependencies. This problem arises from the so-called "vanishing/exploding" gradient which basically means that as we propagate the error signals backwards through the networks structure they tend to vanish or explode. More advanced recurrent structures (eg LSTM) have properties that mitigate this problem and can learn long term dependencies and are particularly suited for learning sequential data.


Is there a reason combining SELECT TOP with OPTION (FAST N) would change the execution plan?

Question: This is an example of a query I looked at recently:
SELECT TOP 10 id, name
FROM example_table WITH(NOLOCK)
INNER JOIN example_table2 WITH(NOLOCK)
    ON example_table.x = example_table2.id
OPTION (FAST 10)

Assuming the rest of this somewhat unusual query stays the same...is there any reason why adding OPTION (FAST N) would cause a query already using TOP to go any faster, or run any differently? If so, why?
Comment: Technically, it could speed your results, although I doubt that it would in such a simple query. In a somewhat more complex query, though, it could change the process flow so the first N records of joined tables are returned more quickly. I've never compared the query plans of TOP vs FAST queries, though, so I can't claim to know for sure. Only testing will tell.  I'm voting to not close, because the dba question asks how something works generally, whereas this one asks what would happen in a specific case. The general answer may be insufficient to answer the special case.
Comment: I'm voting to close, as I think that your question has already been asked and answered on dba.stackexchange  https://dba.stackexchange.com/questions/135455/what-does-option-fast-in-select-statement-do
Comment: @DeanOC that question covers pretty well how `OPTION (FAST N)` affects the execution plan by itself, but it's typically used in a query where you would want to retrieve more than N records -- I'm looking for some understanding of whether it has some impact beyond what TOP would already have.
Answer: See first of all OPTION (FAST N) retrieve first N rows faster then  the query continues execution and produces its full result set.
Even if you don't mention FAST N hint, Sql Query return first N rows fast where N depend upon query to query and execution plan.
for Example suppose,
SELECT  id, name
FROM example_table WITH(NOLOCK)
INNER JOIN example_table2 WITH(NOLOCK)
    ON example_table.x = example_table2.id

Suppose this query return 8000 rows and first 50 row are return faster
If I mention Top N and OPTION (FAST N) both in same query and in another window I just mention TOP N where N<=50 or N<=100 (roughly)
Then both perform same. Check The XML query plan.
If I Use value of N >=3000 then query with Top N and OPTION (FAST N) perform poorer than TOP N alone.
Though GUI execution plan is same ,you can see the difference in XML query plan.
I notice that QueryHash,CompileTime and CompileCPU were different.CompileTime and CompileCPU  are higher in query with both Top N and OPTION (FAST N)
You do similar experiment.


Como passar parâmetros e pegá-los com $state.go do angular?

Question: Tenho o seguinte código no controller
app.controller('loginCtrl', ['$scope', '$stateParams', '$http', '$cordovaSQLite', '$window', '$state',

function ($scope, $stateParams, $http, $cordovaSQLite, $window, $state) {

$scope.clienteId = null;
$scope.clienteNome = null;
$scope.clienteEmail = null;

$scope.profId = null;
$scope.profNome = null;
$scope.profEmail = null;

$scope.logar = function(usuario){

    $scope.error = null;
    $scope.errors = {};

    $http.post("http://vigilantescomunitarios.com/serviapp/api_gustavo/login.php", usuario).success(function(response){
        //console.log(response);
        if(response == '' || response == [] || response == 'null'){
            $scope.msgErro = "E-mail ou senha inválido";
            return;

        }else if(typeof(Storage) !== "undefined") {

            var prof = response.e_profissional;
            var id = response.idusuario;
            var nome = response.nome;
            var email = response.email;

            if(prof == 1){
                $scope.profNome = nome;
                $scope.profEmail = email;
                $scope.profId = id;
                console.log($scope.profNome);

                $state.go('menuProfissional', { "nome": nome, "email": email, "id": id });
            }else{
                $scope.clienteId = id;
                $scope.clienteNome = nome;
                $scope.clienteEmail = email;
                console.log($scope.clienteNome);

                $state.go('menuCliente');
            }
        }

        })

     }

}])

E o controller onde vou pegar eles
app.controller('menuProfissionalCtrl', ['$scope', '$stateParams', 'stateParams', function ($scope, $stateParams, stateParams) {

$state.params.nome;
console.log($state.params.nome);

}])

Porém, o que aparece no console é "NaN"
O que tenho que corrigir para pegar o nome, email e id?
Comment: Onde está definida sua rota `menuProfissional`?
Comment: .state('menuProfissional', {
    url: '/menuProfissional/:nome/:email/:id',
    templateUrl: 'templates/menuProfissional.html',
    controller: 'menuProfissionalCtrl'
  })
Comment: Para pegar o valor você só precisa usar `$stateParams.nome` dentro do seu controller. Testa pra ver se te atende
Answer: Para pegar o valor você deve usar o service $stateParams que irá conter o valor que foi passado pelo $state.go. Por exemplo, no menuProfissionalCtrl:
...
console.log($stateParams.nome);
...

Dica: Este link contém um manual de boas práticas que facilita a manutenção e criação de código usando o Angular 1.x.
Comment: Consegui.Obrigado.


InvalidClassCastException in .jar after using proguard

Question: I am using eclipse to develop an android app. When I press Run(the green triangle), the app works fine. But , I enabled proguard, and the app crashes. I am using the default proguard-android.txt which is present in sdk/tools/proguard.
I have a jar called Software.jar , which has a few classes. One of them (Data) is a serializable class.(with serialversionUID=112358L). This is (probably) the part that causes the error.
This is the error log(i dont know why, but it is showing in yellow as a warning):

07-22 15:29:46.429: W/System.err(2051): java.io.InvalidClassException:
  software.Data; Incompatible class (SUID): software.Data: static final
  long serialVersionUID =112358L; but expected software.Data: static
  final long serialVersionUID =-4551990835091843772L; 07-22
  15:29:46.433: W/System.err(2051):     at
  java.io.ObjectInputStream.verifyAndInit(ObjectInputStream.java:2380)
  07-22 15:29:46.433: W/System.err(2051):   at
  java.io.ObjectInputStream.readNewClassDesc(ObjectInputStream.java:1662)
  07-22 15:29:46.437: W/System.err(2051):   at
  java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:683)
  07-22 15:29:46.437: W/System.err(2051):   at
  java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:1803)
  07-22 15:29:46.441: W/System.err(2051):   at
  java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:787)
  07-22 15:29:46.441: W/System.err(2051):   at
  java.io.ObjectInputStream.readObject(ObjectInputStream.java:2003)
  07-22 15:29:46.441: W/System.err(2051):   at
  java.io.ObjectInputStream.readObject(ObjectInputStream.java:1960)
  07-22 15:29:46.445: W/System.err(2051):   at
  java.util.ArrayList.readObject(ArrayList.java:657) 07-22 15:29:46.445:
  W/System.err(2051):   at java.lang.reflect.Method.invokeNative(Native
  Method) 07-22 15:29:46.449: W/System.err(2051):   at
  java.lang.reflect.Method.invoke(Method.java:511) 07-22 15:29:46.449:
  W/System.err(2051):   at
  java.io.ObjectInputStream.readObjectForClass(ObjectInputStream.java:1354)
  07-22 15:29:46.449: W/System.err(2051):   at
  java.io.ObjectInputStream.readHierarchy(ObjectInputStream.java:1266)
  07-22 15:29:46.453: W/System.err(2051):   at
  java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:1855)
  07-22 15:29:46.453: W/System.err(2051):   at
  java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:787)
  07-22 15:29:46.457: W/System.err(2051):   at
  java.io.ObjectInputStream.readObject(ObjectInputStream.java:2003)
  07-22 15:29:46.457: W/System.err(2051):   at
  java.io.ObjectInputStream.readObject(ObjectInputStream.java:1960)
  07-22 15:29:46.457: W/System.err(2051):   at
  com.mainpackage.FullGenPhysics.a(Unknown Source) 07-22 15:29:46.457:
  W/System.err(2051):   at com.mainpackage.de.run(Unknown Source)

and these are the red lines(tag error)

07-22 15:29:46.465: E/AndroidRuntime(2051): FATAL EXCEPTION:
  Thread-161 07-22 15:29:46.465: E/AndroidRuntime(2051):
  java.lang.NullPointerException 07-22 15:29:46.465:
  E/AndroidRuntime(2051):   at software.Gen_Phy.a(Unknown Source) 07-22
  15:29:46.465: E/AndroidRuntime(2051):     at software.Gen_Phy.a(Unknown
  Source) 07-22 15:29:46.465: E/AndroidRuntime(2051):   at
  software.Gen_Phy.(Unknown Source) 07-22 15:29:46.465:
  E/AndroidRuntime(2051):   at com.mainpackage.FullGenPhysics.a(Unknown
  Source) 07-22 15:29:46.465: E/AndroidRuntime(2051):   at
  com.mainpackage.de.run(Unknown Source) 07-22 15:29:46.465:
  W/ActivityManager(333):   Force finishing activity
  com.mainpackage/.FullGenPhysics 07-22 15:29:46.525:
  E/SocketStream(112): readFully was waiting for 403440 bytes, got 49152
  07-22 15:29:46.525: E/SocketStream(112): readFully was waiting for
  354288 bytes, got 16384  07-22 15:29:46.529: E/SocketStream(112):
  readFully was waiting for 337904 bytes, got 1624  07-22 15:29:46.529:
  E/SocketStream(112): readFully was waiting for 336280 bytes, got 49152
  07-22 15:29:46.533: E/SocketStream(112): readFully was waiting for
  287128 bytes, got 16384  07-22 15:29:46.533: E/SocketStream(112):
  readFully was waiting for 270744 bytes, got 1624  07-22 15:29:46.537:
  E/SocketStream(112): readFully was waiting for 269120 bytes, got 49152
  07-22 15:29:46.537: E/SocketStream(112): readFully was waiting for
  219968 bytes, got 16384  07-22 15:29:46.537: E/SocketStream(112):
  readFully was waiting for 203584 bytes, got 1624  07-22 15:29:46.541:
  E/SocketStream(112): readFully was waiting for 201960 bytes, got 49152
  07-22 15:29:46.541: E/SocketStream(112): readFully was waiting for
  152808 bytes, got 16384  07-22 15:29:46.541: E/SocketStream(112):
  readFully was waiting for 136424 bytes, got 1624  07-22 15:29:46.545:
  E/SocketStream(112): readFully was waiting for 134800 bytes, got 49152
  07-22 15:29:46.545: E/SocketStream(112): readFully was waiting for
  85648 bytes, got 16384  07-22 15:29:46.549: E/SocketStream(112):
  readFully was waiting for 69264 bytes, got 1624  07-22 15:29:46.549:
  E/SocketStream(112): readFully was waiting for 67640 bytes, got 49152
  07-22 15:29:46.549: E/SocketStream(112): readFully was waiting for
  18488 bytes, got 16384

The funny thing is, that I have a system.out in one of the classes of software.jar. That is getting printed.
I have tried adding -libraryjars C:\Users\Harsh\git\marks++\Marks++\Software.jar as well as
-keep  class Software.**

to the already mentioned .txt file
Where am I going wrong ?
EDIT

07-22 16:10:54.957: W/System.err(2233): java.lang.ClassNotFoundException: software.Data
07-22 16:10:54.961: W/System.err(2233):   at java.lang.Class.classForName(Native Method)
07-22 16:10:54.961: W/System.err(2233):   at java.lang.Class.forName(Class.java:217)
07-22 16:10:54.965: W/System.err(2233):   at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:2301)
07-22 16:10:54.965: W/System.err(2233):   at java.io.ObjectInputStream.readNewClassDesc(ObjectInputStream.java:1660)
07-22 16:10:54.965: W/System.err(2233):   at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:683)
07-22 16:10:54.969: W/System.err(2233):   at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:1803)
07-22 16:10:54.969: W/System.err(2233):   at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:787)
07-22 16:10:54.973: W/System.err(2233):   at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2003)
07-22 16:10:54.973: W/System.err(2233):   at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1960)
07-22 16:10:54.973: W/System.err(2233):   at java.util.ArrayList.readObject(ArrayList.java:657)
07-22 16:10:54.973: W/System.err(2233):   at java.lang.reflect.Method.invokeNative(Native Method)
07-22 16:10:54.977: W/System.err(2233):   at java.lang.reflect.Method.invoke(Method.java:511)
07-22 16:10:54.977: W/System.err(2233):   at java.io.ObjectInputStream.readObjectForClass(ObjectInputStream.java:1354)
07-22 16:10:54.977: W/System.err(2233):   at java.io.ObjectInputStream.readHierarchy(ObjectInputStream.java:1266)
07-22 16:10:54.977: W/System.err(2233):   at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:1855)
07-22 16:10:54.977: W/System.err(2233):   at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:787)
07-22 16:10:54.977: W/System.err(2233):   at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2003)
07-22 16:10:54.977: W/System.err(2233):   at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1960)
07-22 16:10:54.977: W/System.err(2233):   at com.mainpackage.FullGenPhysics.a(Unknown Source)
07-22 16:10:54.977: W/System.err(2233):   at com.mainpackage.de.run(Unknown Source)
07-22 16:10:54.981: W/System.err(2233): Caused by: java.lang.NoClassDefFoundError: software/Data
07-22 16:10:54.981: W/System.err(2233):   ... 20 more
07-22 16:10:54.981: W/System.err(2233): Caused by: java.lang.ClassNotFoundException: software.Data
07-22 16:10:54.981: W/System.err(2233):   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
07-22 16:10:54.981: W/System.err(2233):   at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
07-22 16:10:54.981: W/System.err(2233):   at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
07-22 16:10:54.985: W/System.err(2233):   ... 20 more

Answer: It seems after going through proguard your serializable class's serialVersionUID is getting changed. You need to change the configuration of proguard to include:
-keepclassmembers class software.Data {
    static final long serialVersionUID;

}

As described Here
Comment: i am getting classnotfoundexception now
Comment: Please post stacktrace
Answer: I found a working solution after a bit of experimenting.
This is what I used:
-libraryjars Software.jar
-keep  class software.**{
*;

}


Close the last accordion item when clicked on it in react-accessible-accordion

Question: I have a basic FAQ component in React. My problem is when I open an accordion item, I cannot close it again when I click on it. The only way I can close the accordion is to click another question. But I also want to close it when I clicked on the question. Here is my code:
import React from "react";
import {
  Accordion,
  AccordionItem,
  AccordionItemHeading,
  AccordionItemButton,
  AccordionItemPanel,
} from "react-accessible-accordion";

import "react-accessible-accordion/dist/fancy-example.css";

export default function FAQ() {
  return (
    <>
      <Accordion>
        <AccordionItem>
          <AccordionItemHeading>
            <AccordionItemButton>Question 1</AccordionItemButton>
          </AccordionItemHeading>
          <AccordionItemPanel>

              Exercitation in fugiat est ut ad ea cupidatat ut in cupidatat
              occaecat ut occaecat consequat est minim minim esse tempor laborum
              consequat esse adipisicing eu reprehenderit enim.

          </AccordionItemPanel>
        </AccordionItem>
        <AccordionItem>
          <AccordionItemHeading>
            <AccordionItemButton>Question 2</AccordionItemButton>
          </AccordionItemHeading>
          <AccordionItemPanel>

              Exercitation in fugiat est ut ad ea cupidatat ut in cupidatat
              occaecat ut occaecat consequat est minim minim esse tempor laborum
              consequat esse adipisicing eu reprehenderit enim.

          </AccordionItemPanel>
        </AccordionItem>
      </Accordion>
    </>
  );
}

Answer: You need to provide a boolean prop allowZeroExpanded to the Accordion.
 <Accordion allowZeroExpanded>
...
 </Accordion>

It will let you close the last one which would otherwise remain always opened. See this official demo.
Comment: worked for my requirements, thanks.
Comment: this is basically what the OP has already isn't it , he wants a toggling kind of mechanism
Answer: this is how I would go about doing this :
const [FAQS, setFAQS] = useState([
    {
      title:"Question 1",
      answer:`Exercitation in fugiat est ut ad ea cupidatat ut in cupidatat
       occaecat ut occaecat consequat est minim minim esse tempor laborum
       consequat esse adipisicing eu reprehenderit enim.`,
       expanded:false
    },
    {
      title:"Question 2",
      answer:`Exercitation in fugiat est ut ad ea cupidatat ut in cupidatat
      occaecat ut occaecat consequat est minim minim esse tempor laborum
      consequat esse adipisicing eu reprehenderit enim..`,
      expanded:true
    },
  ])

  const setExpand=(index)=>e=>{
     let temp=[...FAQS]
     temp[index].expanded= !temp[index].expanded
     setFAQS(temp)
  }

  return (
    <Accordion allowZeroExpanded={true}  >
        {
          FAQS.map((FAQ,index)=><AccordionItem onClick={setExpand(index)} dangerouslySetExpanded={FAQ.expanded} key={FAQ.title} >
            <AccordionItemHeading>
              <AccordionItemButton  >{FAQ.title}</AccordionItemButton>
            </AccordionItemHeading>
            <AccordionItemPanel>

              {FAQ.answer}

            </AccordionItemPanel>
          </AccordionItem>)
        }
    </Accordion>
  );


Solving $xy'+y=x^{k}$

Question:
Find a solution to:
  $$xy'+y=x^{k}$$
  Where $k>0$, and on the assumption that the transforms of $f$ and $f'$ exist.

I understand that we can take the Laplace of all of the terms and then find the inverse Laplace transform to get a solution for $y$.
I am unsure of how to find the Laplace of the first term.
Can someone show me how its done? It has to be using Laplace transforms !
Answer: Note that
$$
(xy(x))'=xy'(x)+y(x)
$$
so that your differential equation can be solved by one simple integration.
Comment: How would i solve this question using Laplace transforms to be more specific ?
Answer: Hint: you can use the fact that
$$\mathcal{L}\{f'(t)\} = s\mathcal{L}\{f(t)\}-f(0)$$
and
$$\mathcal{L}\{tf(t)\} = -\frac{d}{ds}\mathcal{L}\{f(t)\}$$
to get that
$$\mathcal{L}\{tf'(t)\} = -\frac{d}{ds}\mathcal{L}\{f'(t)\} = -\frac{d}{ds}\big(s\mathcal{L}\{f(t)\}-f(0)\big) = - \mathcal{L}\{f(t)\} - s\frac{d}{ds}\mathcal{L}\{f(t)\}$$
but you really don't need to resort to Laplace in this case.

Solving $xy'+y=x^{k}$


Scrolling in chrome shears text and elements

Question: the testing version of a portfolio site I'm working on started behaving strangely in the past few days. This might or might not be a problem related to drupal itself, but I've never come across this on a non-drupal project.
http://beta.mattgrossdesign.com/about
On my Win7 machine, Chrome 36, scrolling the page causes all the fixed position elements to be rendered in multiple places or sheared off.
Image Reference: https://i.stack.imgur.com/dSvjq.jpg
Firefox & IE aren't having problems, any ideas?
Thanks a bunch
Answer: Try to add <code>-webkit-transform: translateZ(0);</code> to your fixed elements.
Comment: I tried to inject this through Chrome and everything works fine. You are missing something.
Comment: Caching in pre-production will be the death of me.

You sir take the cake.


PHP-FPM save sessions in memcached

Question: I'm trying to switch my session_handler to memcached,
I'm not sure if it worked, it does not look like it did.
vi /etc/php5/fpm/php.ini

session.save_handler = memcached
session.save_path = unix://run/memcached/memcached.sock

/etc/init.d/php5-fpm restart

After hitting my blog a few times, I should have a key in the memcached, shouldn't I?
nc -U /run/memcached/memcached.sock

giant:~# nc -U /run/memcached/memcached.sock
stats items
END
stats slabs
STAT active_slabs 0
STAT total_malloced 0
END

phpinfo():
session.gc_probability  0   0
session.hash_bits_per_character 5   5
session.hash_function   0   0
session.name    PHPSESSID   PHPSESSID
session.referer_check   no value    no value
session.save_handler    memcache    memcache
session.save_path   unix://run/memcached/memcached.sock unix://run/memcached/memcached.sock
session.serialize_handler   php php
session.upload_progress.cleanup On  On
session.upload_progress.enabled On  On
session.upload_progress.freq    1%  1%
session.upload_progress.min_freq    1   1
session.upload_progress.name    PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix  upload_progress_    upload_progress_
session.use_cookies On  On
session.use_only_cookies    On  On
session.use_trans_sid   0   0

Can someone lead me to the correct configuration please?
Comment: i wouldn't call memcaches lru alg a garbage collector. it's more like taking out the trash only if the dustbin is completely full as compared to when it starts to smell.
Comment: If You do not plan to run memcached in cluster, then I suggest to store sessions in ram (tmpfs). usually `/dev/shm`
Comment: @DanFromGermany: as opposed to no gc'ing at all when storing sessions in memcached. btw: there is an internal gc-mechanism, the cronjob was introduced for more security on multiuser systems, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=267720
Comment: @r_3 memcached does gc using TTL. I use HHVM now which deals yet differently with sessions.
Comment: @Guntis that's a great idea too. But I don't like the session garbage collection via cronjobs in php.
Answer: Did not work:
session.save_path = unix://run/memcached/memcached.sock

Did work:
session.save_path = "/run/memcached/memcached.sock"

Quotes added, protocol removed
Comment: Memcached is secured through the network layer or when you deploy it via unix socket, no other server can access it.
Comment: for `TCP`, use following: `session.save_path='tcp://127.0.0.1:11211, tcp://192.168.1.2:11211'`
Comment: Guys, is it actually secure to do that? Memcached doesn't have any auth in front of it.

PHP-FPM save sessions in memcached


When binding data in D3, what does the index represent?

Question: I was a bit surprised when I saw the value of the index passed to the data binding function of step 3 in the following example:
1) Create two wrapper divs with a data array bound to each
2) Create two "sub-divs" within each of the wrappers, with an array bound to each
3) Append p elements to each "sub-div"
Because of the way the elements are nested, I expected to see indexes of 0,1 passed to the data binding function in step 3. Instead, I see indexes of 0,1,2,3.

var data = d3.select("#data");
var idx = d3.select("#indexes");

//---- STEP 1
//create two divs with [1, 4] and [7, 10] bound
var dbox = data.selectAll("tbody").data([[1, 4], [7, 10]]);
dbox.enter().append("div").text(function(d,i){return "Group " + i });
dbox.exit().remove();
dbox.style({"clear":"both","padding":"5px","border":"1px solid #dddddd","overflow":"hidden","margin-bottom":"10px"});

//---- STEP 2
//create sub-divs
var tr = dbox.selectAll("div").data(function(d,i){
  return d.map(function(d,i,a){ return [d, d+1, d+2]; }); //return an array of arrays [[x,y,z], [a,b,c]]
});
tr.enter().append("div").text(function(d,i){return "Index " + i});
tr.exit().remove();
tr.style({"clear":"both","overflow":"hidden","padding":"2px","border":"1px dotted #dddddd","margin-top":"5px"});

//---- STEP 3
//add text (and record indexes in the "INDEXES" section)
//since the tr selection is grouped--with two "tr" divs per "dbox", I expected to see indexes of 0,1 only, instead I see 0, 1, 2, 3.
var td = tr.selectAll("p").data(function(d,i){
  idx.append("p").text(i); //track the indexes
  return d;
})
td.enter().append("p");
td.exit().remove();
td.text(function(d,i){return d}).style({});

INDEXES

Comment: Well there are 2*2 parent groups, so altogether 4.
Comment: No, the indices refer to the parent groups (i.e. are "global" in your case). I guess it makes more sense because there's only one call to `.data()`.
Comment: Aren't the parent groups the members of the "tr" selection (in the above example)? If so, I'd still expect indexes of 0,1. I updated the example to illustrate.
Answer: selectAll simply promotes all of the elements in the selection to parent nodes (ignoring group structure) and applies the provided selector to each of the new parent nodes in turn to form new groups on them.  After this, there is no references in the selection to the previous parent nodes, that state is lost.
tr.selectAll("p") promotes all of the divs in tr (2x2 = 4 of them) to parent nodes and forms an enter selection based on the data bound to them.  So there a 4 groups (one for each div in tr) with 3 members each (the first dimension of the data bound on the parent divs is of length 3).  References to the previous parent nodes are discarded.
if values in selection.data(values) is a function, then it's d argument is the data bound on the group parent and i is the group index.
If values is not a function then the same data is bound to each group.
Answer: I think the confusion here is that when operating on selections using methods like .attr() or .style(), the index passed to a function argument represents the index of the element within its parent group.
When binding data using the .data() method, the index passed to a function argument represents the index of the parent element. This is what Lars is getting at in his comments.
I suppose this makes sense because D3 selections use a fixed two-level hierarchy (though it sounds like this may change in the future). So when you bind new data, the hierarchy of the selection changes. I.e. the parent elements are no longer nested in the selection.
Here's a clarifying example:

var L1 = d3.select("div#boxes");
L1.append("p").text("Level 1");

var L2 = L1.selectAll("div").data([1,2]);
L2.enter().append("div");

L2.append("p").text(function(d,i){return "Level 2"})

var L3 = L2.selectAll("div").data(function(d,i){
    return [i,i];
});
L3.enter().append("div");
L3.append("p").text(function(d,i){return "Level 3 - Index during data binding: "+d+". Index after appended: "+i+"." })

var L4 = L3.selectAll("div").data(function(d,i){
    return [i,i];
});
L4.enter().append("div");
L4.append("p").text(function(d,i){return "Level 4 - Index during data binding: " +d+". Index after appended: "+i+"."})
div{
    padding:5px;
    margin:5px;
    border:1px solid #555555;
}

p{
    font-family:Arial, Helvetica, sans-serif;
    font-size:13px;
}

#indexes p{
    float:left;
    margin-left:5px;
}
}

Comment: True, I was thinking in terms of my example which traversed the full extent of the DOM. I edited my answer to reflect this.
Comment: You said "When binding data using the .data() method, the index passed to a function argument represents the index of the parent element *within the entire DOM*."   Not sure what you mean there, d3 is only aware of what's in the selection, it's not aware of the entire DOM.
Comment: I still have some problems with your prose... 1) `selection.data()` can receive two arguments which are function: _`values`_ and _`key`_ so it's not absolutely clear which function argument you are talking about. 2) "the index passed to a function argument represents the index of the parent element." I suggest that it's difficult to explain this without directly mentioning the d3 _group_ concept.  "The index passed to the _value_  argument function is the group index" would be clearer. There are other indecis that could be applied to the parent element, e.g. It's DOM context.


How to offer Views as options in a Content-Type field

Question: I would like to add a field to a content type (Events) that gives several views (Certificates of Completion) as options.  Thus, when creating an Event the admin can select which certificate will be associated with this Event.
I'm hoping there is a module for this, but as you might imagine Google can't figure out exactly what I'm asking when my query is predominantly filled with generic drupal terms like "Content Type", "Field", and "Views".
Any recommendations will be greatly appreciated.
Answer: You could create a taxonomy for that content type and assign values to it like "Certificates of Completion", etc. Here is the Link for the taxonomy docs.
Comment: I currently have a View with one display per certificate.  Each display has a different background image and different coordinates for where the date and attendee's name should appear.  If I use a Taxonomy for the certificates then I face the same problem.  How to I translate from "Content-Type has Taxonomy" to "use this View Display"?  Which is basically the original problem, how to use a Content-Type Field to select a View Display.  It just shifts from Content-Type Field to Taxonomy, or am I missing something?
Answer: The closer module I can think of is the View reference module.

Defines a field type View reference which creates a relationship to a Views display and allows the view to be displayed as the content of the field.
This module is modeled on the Node reference module, and usage is similar.
Additionally, you may enter arguments for each view by a delimiter separated list with support for PHP generated arguments.


Reloading partition step to create another set of threads

Question: I have huge list of reports loaded into chunk partition step. Each reports will be further processed to generate individual report. But if I load 50k of reports in the partition step, which overloads the server and it gets much slow. Instead of that I would prefer, partition step to load 3k of report list, process it and then load another 3k reports on parition step.. continue the same until 50k reports get processed.
<code>    <step id="genReport" next="fileTransfer">
        <chunk  item-count="1000">
            <reader ref="Reader" >
            </reader>
            <writer
                ref="Writer" >
            </writer>
        </chunk>
      <partition>
            <mapper ref="Mapper">
                <properties >
                    <property name="threadCount" value="#{jobProperties['threadCount']}"/>
                    <property name="threadNumber" value="#{partitionPlan['threadNumber']}"/>
                </properties>
            </mapper>
      </partition>
    </step>
</code>
<code>public PartitionPlan mapPartitions() {
        PartitionPlanImpl partitionPlan = new PartitionPlanImpl();
        int numberOfPartitions = //dao call to load the reports count
        partitionPlan.setThreads(getThreadCount());
        partitionPlan.setPartitions(numberOfPartitions); //This numberOfPartitions is comes from the database, huge size like 20k to 40k
        Properties[] props = new Properties[numberOfPartitions];

        for (int idx = 0; idx < numberOfPartitions; idx++) {
            Properties threadProperties = new Properties();
            threadProperties.setProperty("threadNumber", idx + "");
            GAHReportListData gahRptListData = gahReportListManager.getPageToProcess(); //Data pulled from PriorityBlockingQueue
            String dynSqlId = gahRptListData.getDynSqlId();

            threadProperties.setProperty("sqlId", dynSqlId);
            threadProperties.setProperty("outFile", fileName);

            props[idx] = threadProperties;
        }
        partitionPlan.setPartitionProperties(props);
        return partitionPlan;
    }
</code>
Once 3k reports of data processed by partition mapper, Then it has to check for the next available list. If its available the partition should be reset with next set of 3k reports to process.
Comment: If I understood this right, you're launching 50,000 partitions this way.  I'd suggest launching some fixed number of partitions (maybe match however many threads you decide on) and give each partition a list of reports to process through (a list of sqlIds I guess).  All you're doing by having all these partitions is creating a lot of Java objects to manage it all.  It isn't going to run any faster than the number of threads you have working through the list of reports.  Not really an answer...just an opinion.
Comment: Each sqlid's needs to be processed separately. So passing list to a thread may not be right-way in my case. Is there anyway to reset partition Mapper ? when the created partition is over, go ahead and create another partition mapper for the same step
Answer: There's no way to reset the partition.  When all the partitions defined by the partitionMapper are done, the step is over.  You could have a second partitioned step that's just like the first one I guess (and a third, and a fourth) until you get through everything.  That's messy.  And you can't loop back in JSL and re-execute the same step again.
You could have a split/flow that ran multiples of these steps concurrently, but you can't dynamically set how many flows.  That's in the JSL.  And you'd end up with more concurrency that your environment could probably handle.
I assume your chunk reader/processor/writer are iterating through the results of the one SQLid that is assigned to the partition now.  To do a list of sqlids I guess you'd need a way to tell when one was finished and the next one started within the same chunk loop.  The reader could probably manage the list and would know when the transitions happened.  You'd probably need a signal to the writer that a chunk end was the end of one report and it should move onto the next one.  You'd probably want a custom checkpoint algorithm for that so you could be sure to checkpoint at the end of a report rather than hope you hit a checkpoint when each sqlid ran out of records to process.
I'm putting this in as an answer instead of another comment because it seems the answer to the question asked here is 'no'.  The rest is just discussion about possible alternative approaches.