text:
Q: Why does Firefox screw up my contenteditable element's text and placeholder? I have a program where you can drag widgets around. It is well on chrome, but Firefox screws up the text and removes the placeholder text when I type and delete the text. What could be causing this?
Chrome:

Firefox:
.
Here is my HTML code:

 draggable && moveDown(e)">

{{note.body}}

A: As per your comment saying that <textarea> is an improvement, but you want to prevent the textarea from being activated/focused/selectable until the user clicks on the element, use a script to toggle HTMLTextAreaElement.readonly when the container is clicked and re-set it on HTMLTextAreaElement.blur. In Vanilla JS it would be like this:

 draggable && moveDown(e)">

        <textarea class="note-body" readonly="readonly" placeholder="Write something">{{note.body}}</textarea>


text:
Q: Looping Through Subdirectories and Running a Command in Each I have a set of repositories sorted into directories based on their VCS (Git, Mercurial, SVN). With Subversion I was able to run svn update * in the parent directory and it would loop through each directory and update each repository as expected. That's not the case for Git or Mercurial.
I would like to come up with a bash script that I can run to do exactly that, loop through directories and either git pull or hg pull in each. I just don't have much bash scripting experience.

A: If you have GNU Parallel http:// www.gnu.org/software/parallel/ installed you can do this:
cd ~/projects/git/; ls | parallel 'cd {} && git pull'

This will run in parallel so if some of the git servers' network connection are slow this may speed up things.
Watch the intro video for GNU Parallel to learn more:
http://www.youtube.com/watch?v=OpaiGYxkSuQ

A: This should work
find . -maxdepth 1 -type d -name '.git' -exec sh -c 'cd "{}" && pwd && git pull' \;

A: If you need it to be recursive:
find . -type d -name .git -exec sh -c "cd \"{}\"/../ && pwd && git pull" \;

This will descend into all the directories under the current one, and perform a git pull on those subdirectories that have a .git directory (you can limit it with -maxdepth).

A: To do it without using find but forloop
for dir in ~/projects/git/*/*/; do (cd "$dir" && git pull); done

A: for dir in ~/projects/git/*; do (cd "$dir" && git pull); done

redpajama_set_name: RedPajamaStackExchange


text:
Q: Question on basic probability from Maths In Focus textbook A set of cards is numbered 1 to 20 and three are selected. Find the probability of selecting
a) all three 10's
b) no 10's
c) at least one 10.
I have solved part a) by stating that
P(one 10)= 1/20, and therefore
P(3 10's)= (1/20 x 1/20 x 1/20)
= 1/8000
To approach a question like b), I would usually draw a tree diagram and add all the possible results that give the desired outcome (I.e. No 10's). However, this  would take an extremely long time to do. Is there a more efficient way to solve b)?
Also, I understand that the answer to b) is required to answer c), which would be solved by showing that
P( at least one 10) = 1- P(No 10's)
Thank you.

A: a) is correct.
b) No 10s is equivalent to picking one of the other 19 cards. The probability of this once is $\frac{19}{20}$, and the answer is $\left( \frac{19}{20} \right)^3$
c) As you pointed out, the answer is 1 - b)
To figure out if you've understood what's happening, try doing part b) if the cards are drawn without replacement - i.e. if the first draw was 4, then 4 cannot be drawn again.


text:
Q: Nested IF field in Word VBA I'm trying to create a word addin that adds complex IF Statement Creation, from a list of possible mergefields.
Complex is
{ IF { = OR ( { COMPARE { MERGEFIELD Field_1 } <= "Value" }, { COMPARE { MERGEFIELD Field_2 } >= "Value" } ) } = 1 "True Instructions" "False Instructions" }
Im trying to do this all in VBA, but im having issues with my Complex if, as I cant get the "}" to end in the right locations.
If I use the terminator "Selection.EndKey Unit:=wdLine" in any other location besides the end, it creates a mess and putts all the } at that line.
Here is my Code:
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:="IF "

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
    Selection.TypeText Text:=" = " & JointOperator1 & " ( "

'FIRST ARG
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
    Selection.TypeText Text:="COMPARE "

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False, Text:="MERGEFIELD " & FirstArg1

    Selection.TypeText Text:=" "
    Selection.TypeText Text:=ComparisonType1
    Selection.TypeText Text:=" "
    Selection.TypeText Text:=Chr(34) & SecondArg1 & Chr(34)

Selection.TypeText Text:=", "

'SECOND ARG
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
    Selection.TypeText Text:="COMPARE "

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False, Text:="MERGEFIELD " & FirstArg2

    Selection.TypeText Text:=" "
    Selection.TypeText Text:=ComparisonType2
    Selection.TypeText Text:=" "
    Selection.TypeText Text:=Chr(34) & SecondArg2 & Chr(34)

Selection.TypeText Text:=" ) "

Selection.TypeText Text:=" = 1 "

Selection.TypeText Text:=vbCrLf & " " & Chr(34)

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:=strTempIfTrue

Selection.TypeText Text:=Chr(34) & " " & vbCrLf
Selection.TypeText Text:=" " & Chr(34)

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:=strTempIfFalse

Selection.TypeText Text:=Chr(34)
Selection.EndKey Unit:=wdLine
Selection.TypeParagraph

And this is what I get when generating the "Complex if"
{IF { = AND ( {COMPARE{MERGEFIELD FHB} = "T", { COMPARE {MERGEFIELD BLAH} = "F") = 1 "If True text" "If False Text"}}}}

But it should be this:
{IF { = AND ( {COMPARE{MERGEFIELD FHB} = "T" **}** , { COMPARE {MERGEFIELD BLAH} = "F" **}** ) **}**  = 1 "If True text" "If False Text"}

If someone could shed some light on this matter, where am I going wrong.
Or If there is a way of forcing the location of the Ending }, that would be great
I'm very new to VBA (I'm a C++ Programmer)

A: So I found a solution to my problem.
I used the word macro recorder(View>Macros>Record Macro...) to record me entering the complex if statement, then viewed the macro, by pressing Alt + F11 and selecting macros, and I simply replaced some strings with my variables.
and that has fixed the issues.
Hopefully this will be helpful for someone else, saving them hours of head scratching.
I had no Idea that you could record these actions to be reviewed later. You learn something new every day.
This is what the recording looked like.
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:="IF "
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:=" = AND ("
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:=" COMPARE "
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:="MERGEFIELD FHB"
Selection.MoveRight Unit:=wdCharacter, Count:=2
Selection.TypeText Text:=" = """""
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="T"
Selection.MoveRight Unit:=wdCharacter, Count:=3
Selection.TypeText Text:=", "
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:="COMPARE "
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:="MERGEFIELD Other"
Selection.MoveRight Unit:=wdCharacter, Count:=2
Selection.TypeText Text:=" <> """""
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="T"
Selection.MoveRight Unit:=wdCharacter, Count:=3
Selection.TypeText Text:=")"
Selection.MoveRight Unit:=wdCharacter, Count:=2
Selection.TypeText Text:=" = 1 """""
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="IfTrue"
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.TypeText Text:=" """""
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="IfFalse"


text:
Q: Loading resources from html5 filesystem api I am writing a chrome extension that dynamically writes some html pages and their resources to the file system. I have most things working but I just noticed that when I try to open one of the pages by navigating to the filesystem:chrome-extension://... url that I obtain via the fileentry.getURL() method, the page opens, but chrome does not fetch any of the associated resources: stylesheets, images etc. Any ideas why this might be? Are there some security flags I need to get this working? I am i going about this all wrong?
(One thing that may be relevant is that the resources are identified by relative urls. But I know they are correct relative to the file because if i manually resolve them and browse to the URLs I can fetch them.)

A: The page you include that uses the relative URLs doesn't understand the HTML5 filesystem's mapping. If you change the URLs to point to what the fileentry.getURL() calls give you, then this should work.
There's currently a bug that allows relative URLs in resources to be used like you're trying to do: http://crbug.com/89271


text:
Q: How to redirect to page after allowing permission in Facebook I'm trying to redirect the user to a page after he allows to share basic info with my site. I use the following code:
function render_fbconnect_button() {

return '

    ';
}

This code displays a connect button when user is not logged in. If the user is already logged in and clicks on it, it displays permission for basic info.
I want to redirect the user to abc.php page when he allows the permission.

A: In your FB.Connect.requireSession() function,
if (confirm('Are you willing to share information?')) {
   location.href='abc.php';
}


text:
Q: PostgreSQL full backups script not working I'd like to use backup script that is provided in (my scripts are the same as in given link, only configuration changed):
http://wiki.postgresql.org/wiki/Automated_Backup_on_Linux
In pg_backup.config
I added:
BACKUP_USER = myusername (that has postgresql superuser access)
HOST = localhost
USERNAME = myusername (that has postgresql superuser access)

Update full pg_backup.config:
##############################
## POSTGRESQL BACKUP CONFIG ##
##############################

# Optional system user to run backups as.  If the user the script is running as doesn't match this
# the script terminates.  Leave blank to skip check.
BACKUP_USER=myusername

# Optional hostname to adhere to pg_hba policies.  Will default to "localhost" if none specified.
HOSTNAME=localhost

# Optional username to connect to database as.  Will default to "postgres" if none specified.
USERNAME=myusername

# This dir will be created if it doesn't exist.  This must be writable by the user the script is
# running as.
BACKUP_DIR=/home/myusername/openerp/7.0/backup

# List of strings to match against in database name, separated by space or comma, for which we only
# wish to keep a backup of the schema, not the data. Any database names which contain any of these
# values will be considered candidates. (e.g. "system_log" will match "dev_system_log_2010-01")
SCHEMA_ONLY_LIST=""

# Will produce a custom-format backup if set to "yes"
ENABLE_CUSTOM_BACKUPS=no

# Will produce a gzipped plain-format backup if set to "yes"
ENABLE_PLAIN_BACKUPS=yes

#### SETTINGS FOR ROTATED BACKUPS ####

# Which day to take the weekly backup from (1-7 = Monday-Sunday)
DAY_OF_WEEK_TO_KEEP=5

# Number of days to keep daily backups
DAYS_TO_KEEP=7

# How many weeks to keep weekly backups
WEEKS_TO_KEEP=5

But when I try to run pg_backup.sh with command:
bash pg_backup.sh

I get this error message:
Performing full backups
--------------------------------------------

psql: FATAL:  no pg_hba.conf entry for host "shows my external IP", user "postgres", database "postgres", SSL on
FATAL:  no pg_hba.conf entry for host "shows my external ip", user "postgres", database "postgres", SSL off

All database backups complete!

Also it prints out that all databases are complete, but it does not do any backups.
When I try this command manually:
pg_dump -Fp -h "localhost" -U "myusername" "mydatabase" | gzip > /home/myusername/openerp/7.0/backup/"mydatabase".sql.gz;

Then it does backup perfectly!
So the question is why does it give such wierd error?
First it uses my external ip, when it should use localhost, second it connects with postgres user (or at least it shows like that), when it should connect with myusername, and thirdly, script misses some error checks, because it prints that all databases were successfully backed up, when in reality nothing was backed up at all.
Also looking in script looks like it should use everything properly as provided in pg_backup.config, but it does not..


text:
Q: Cannot evaluate tensor using eval() error I am following the code written in the tutorial here.
I have followed exactly each line, but I am receiving the following error.
Following is the error, followed by my code.

ValueError: Cannot evaluate tensor using eval(): No default session
  is registered. Use with sess.as_default() or pass an explicit
  session to eval(session=sess)

X = tf.placeholder(tf.float32, [None, n_timesteps, n_inputs])

basic_cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons)

outputs, states = tf.nn.dynamic_rnn(basic_cell, X, dtype=tf.float32)

init = tf.global_variables_initializer()
# #with tf.Session() as sess:
sess = tf.Session()

with sess.as_default():
    init.run()
    sess.run(tf.global_variables_initializer())
    outputs_val = outputs.eval(feed_dict={X: X_batch})

print(states.eval(feed_dict={X: X_batch}))

A: You have to have an active session for the print line. Bring it under the with sess.as_default() as shown below.
Use the following
> with sess.as_default():
>     init.run()
>     sess.run(tf.global_variables_initializer())
>     outputs_val = outputs.eval(feed_dict={X: X_batch})
>     print(states.eval(feed_dict={X: X_batch}))


text:
Q: Hive: how to select from specfic sub-partiton For example, create a table in hive.
CREATE TABLE t_data_daily(
    imp_date BIGINT,
    sp STRING,
    datax STRING
)
PARTITION BY LIST( imp_date )
SUBPARTITION BY LIST( sp )(
    SUBPARTITION sp_1 VALUES IN ( 'sp_1' ),
    SUBPARTITION sp_2 VALUES IN ( 'sp_2' ),
    SUBPARTITION sp_3 VALUES IN ( 'sp_3' )
)
(
    PARTITION p_20191030 VALUES IN ( 20191030 ),
    PARTITION p_20191101 VALUES IN ( 20191101 ),
    PARTITION p_20191122 VALUES IN ( 20191122 )
)

select data with specific partition:
select * from t_data_daily partition (p_20191030) x limit 100

How to select data from specific partition and sub-partition?
Except the following:
select * from t_data_daily partition (p_20191030) x where sp = 'sp_1' limit 100


text:
Q: Type mismatch. The return type 'Void' of best-match method on type is not compatible with the 'Result' argument supplied to InvokeMethod Getting Error while Invoking Workflow Activity in WCF Services
Type mismatch. The return type 'Void' of best-match method 'Mailsend' on type 'BusinessClass' is not compatible with the 'Result' argument supplied to InvokeMethod 'JobNotification', which expects return values of type 'String'.

A: It solved while defining Activity inArugment type of all the associated parameters.


text:
Q: Unknown Ψ variable in JFET's drain current equation This question considers unipolar transistor, that is JFET.
I really didn't find any other formula than this one which applies only for linear/ohmic/triode region of JFET U/I characteristic.
What is the variables marked as "Ψ" (psi) in the next equation (underlined with green colour)?

The unknown variable can be also seen here:

A: I think, if you rearrange the following formula you should get your formula: -

The web page that shows this formula state that: -

Vi is the Schottky diode potential barrier

Vi appears to be the psi constant in your equation.


text:
Q: How to Determine The Partition Size in an Apache Spark Dataframe I have been using an excellent answer to a question posted on SE here to determine the number of partitions, and the distribution of partitions across a dataframe
Need to Know Partitioning Details in Dataframe Spark
Can someone help me expand on answers to determine the partition size of dataframe?
Thanks

A: Tuning the partition size is inevitably, linked to tuning the number of partitions. There're at least 3 factors to consider in this scope:
Level of parallelism
A "good" high level of parallelism is important, so you may want to have a big number of partitions, resulting in a small partition size.
However, there is an upper bound of the number due to the following 3rd point - distribution overhead. Nevertheless, it's still ranked priority #1, so let's say if you have to make a mistake, start with the side of high level of parallelism.
Generally, it's recommended 2 to 4 tasks per core.

*

*Spark doc:

In general, we recommend 2-3 tasks per CPU core in your cluster.

*

*The book Spark in action (author Petar Zecevi´c) writes (page 74):

We recommend using three to four times more partitions than there are cores in your cluster

Memory fitting
If partition size is very large (e.g. > 1 GB), you may have issues such as garbage collection, out of memory error, etc., especially when there's shuffle operation, as per Spark doc:

Sometimes, you will get an OutOfMemoryError, not because your RDDs don't fit in memory, but because the working set of one of your tasks, such as one of the reduce tasks in groupByKey, was too large. Spark's shuffle operations (sortByKey, groupByKey, reduceByKey, join, etc) build a hash table within each task to perform the grouping, which can often be large...

Hence here comes another pros of big number of partitions (or, small partition size).
Distribution overhead
Distributed computing comes with overhead, so you can't go to an extreme either. If each task takes less than 100ms to execute, the application might have remarkable overhead due to:

*

*data fetches, disk seeks

*data movement, tasks distributing

*task state tracking

, in which case you may lower the level of parallelism and increase partition size a bit.
Take-away
Empirically, people usually try with 100-1000MB per partition, so why not start with that? And remember that the number may need to re-tuned along the time..


text:
Q: Integrating R outputs in bsplus functions I consider bsplus package as relevant when developing dynamic webs. I use R Markdown in Rstudio.
However, I find particularly tricky the way to integrate bsplus functions with R outputs.
Let's see an example with the bs_accordion function, using mtcars dataset
head <- head(mtcars)
tail <- tail(mtcars)

bs_accordion(id ="Data: mtcars") %>%
  bs_append(title = "Head of mtcars", content = head) %>%
  bs_append(title = "Tail of mtcars", content = tail)

I would like to display R outputs in the accordion function, displaying the data frames head and tail.
Now, it only displays the first numerical row in the head.
Is there any possibility to include R code within the content attribute in the bsplus functions?
In this way we could be able to display R results in a dynamic way.

A: This should work for your example. You have to create a datatable somehow, just including it wont render it as a table.
Note: I changed the id of the accordion to Data-mtcars. Using a whitespace, ":" or ";" will disable the collapsing.
library(shiny)
library(bsplus)
library(DT)

ui <- fluidPage(
  bs_accordion(id ="Data-mtcars") %>%
    bs_set_opts(panel_type = "primary", use_heading_link = T) %>%
    bs_append(title = "Head of mtcars", content = DT::dataTableOutput("table1")) %>%

    bs_set_opts(panel_type = "primary", use_heading_link = T) %>%
    bs_append(title = "Tail of mtcars", content = DT::dataTableOutput("table2"))
)

server <- function(input, output) {

  output$table1 <- DT::renderDataTable({
    head
  })
  output$table2 <- DT::renderDataTable({
    tail
  })
}

shinyApp(ui, server)


text:
Q: How to fetch special char with five digits no in oracle? I am trying to fetch :with five digits no values in oracle.
my data look this format.
this :years 2016 only department :12345
aign:BR-PESP-THELIMITED-:30510
:thiss and :years 2016 only department :12345
travel visa :34322 LLL001

i am using this query

substring(check1,regexp_instr(check1,':'),6)

my current o/p:
years
BR-PE
thiss
34322

my expected o/p
12345
30510
12345
34322

A: If you want to return the five digits after a colon:
select regexp_substr(check1, ':([0-9]{5})', 1, 1)


text:
Q: using sdl in an iphone app I am thinking of using SDL in an iPhone app. Can it be done without any major problems on an app which uses iOS 4.2 or iOS 4.3 SDKs?
Appreciate any pointers.

A: As I know, the SDL framework for iPhone isn't mature yet. But I've never tried to use it on iPhone because I found a better 2D engine, before try SDL, which is Cocos2D.
Is you're planning to port an old project on iPhone, I only can tell you to try...
But if you're planning to work on a new project with SDL because you're more familiar with SDL than others engine. I think you should go on Cocos2D.
Anyway it's my point of view, hope this help you to choose what is best.
Regards, kl94


text:
Q: How to fetch data from multiple tables using Join and where clause I have written a simple symfony controller where I have two table known as specialtyarea and physician.
this is the basic structure of the table
specialtyarea
-----------------
id | name       |
-----------------
1  | dentist    |
2  | physician  |

Physician table is related to specialtyarea as shown:
Physician
--------------------
id | name | specfk |
--------------------
1  | John  | 1     |
2  | Doe   | 2     |
3  | Ann   | 2     |

I am trying to fetch all the physician where specialty area is 2
This is my snippet of code
public function getAllPhysicianAction($specId)
{
     $id = $this->getDoctrine()->getRepository('Bundle:SpecArea')
        ->find($specId); //assuming that this returns all the id from the specialty table

    $allPhysician = $id->getPhysician()->...   //kind of lost here
}

How can I retrieve all the records from the physician table using the specialty Id?

A: Use the findBy() method of the "physician" repository:
(You didn't post your actual entities so I'm guessing the field/entity names.)
$spec = $this->getDoctrine()->getRepository('Bundle:SpecArea')->find($specId);

$physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $spec]);

You can also use $specId ID directly instead of fetching the entire entity from database:
    $physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $specId]);

See: Working with Objects - Querying - By Simple Conditions

A: I believe that you can just call findBy on your physician repository.
/**
 * @Route("/physicians/{specId}", name="getAllPhysician")
 */
public function getAllPhysicianAction($specId)
{
    $allPhysician = $this->getDoctrine()
    //call the repository of your physician table
    ->getRepository('Bundle:physician')
    ->findBy(['specfk' => $specId]);

    var_dump($allPhysician);
}


text:
Q: AS3 constructor has no method with the same name as the class I was reading ActionScript 3.0 Abstract Factory Design Pattern: Multiple Products and Factories, and I have the following,
private var busFactory:AbFactory;
busFactory=new BusinessFactory();

Both in BusinessFactory.as and in AbFactory.as there is no method with the same name as the class, only createProductA and createProductB. So, how could busFactory call the constructor with new BusinessFactory ?

A: The default constructors for both AbFactory and BusinessFactory (which the article shows inherits from AbFactory) are created by the compiler.
If you start to pass arguments to the BusinessFactory() constructor, the compiler will complain about an unexpected argument count. That's when you need to write the constructor yourself. But passing nothing means the default can be used.

A: Also the reason that you could set a AbFactory to a BusinessFactory means that they share the same heritage.


text:
Q: Magento 2.3 Configuration Product Show No Associated Products After Migration I tried to migrate producs from magento 1.9.3 to magento 2.3, everything is okay until I check the configurable product. Then I found associated product on the configurable product is null but the simple product is already migrated like this below screenshot:

So how I can migrated the links of configurable with associated product too. If someone already have same issue and solved it, please advise.
update :
here is my catalog_product_super_link table it the relation data has been migrated, but it not applied on the website product

A: Finally, I've already solve this issue, it because there is one of the attribute which used on configurable not imported successfully, as in my website variant product from configurable is by size and color when I see the color attribute table, the color not migrated successfully and it show nothing on table catalog_product_entity_int for attribute color data, so I try to copy the table data for attribute color from table catalog_product_entity_int in magento 1 database to magento 2 table. and it works, all my configurable products now show the variant.
Maybe this is not best answer, since it can be caused by some problem when migrated database from magento 1 to magento 2 but, especially for my this case I hope it will help someone who get same issue with me.

A: My solution for this problem:
I had problem only with color attribute. In my case (and i think in most cases) the problem was, because color attribute is not in default attribute set. And after migration it wasn't assigned to any attribute set. The solution was to assign color attribute to default attribute set in Magento2 before running the migration and then everything went correct.

A: You need to check in the catalog_product_super_link table whether there is a link between the configurable products and the associated products


text:
Q: Free Linked-List In C Hi I need help freeing my Linked List in C. When I run this code I get a seg fault 11. Everything up to the freeing works perfectly. Thank you for your help!
#include <stdio.h>
#include <stdlib.h>

struct node{
    int x;
    struct node *next;
};

int main(void){
    struct node *root, *next;

    root = malloc(sizeof(struct node));
    root -> x = 0;
    root -> next = NULL;

    next = root;

    for (int i = 0; i <=10; i++){
        next -> next = malloc(sizeof(struct node));
        next -> x = i;
        next = next -> next;
    }

    next = root;

    for (int j = 0; j <= 10; j ++){
        printf("%i", next -> x);
        next = next -> next;
    }
        next = root;

    while(next != NULL){
        next = root;
        root = root -> next;
        free(next);
    }
    free(root);
}

A: The original code has a few issues:
1) The while(next != NULL) loop tries to use already freed node.
2) The loop already takes care of the releasing root (next = root;) so there is no need to release root separately.
3) In order for while loop to work properly the tail/head of the list has to be properly NULL terminated. (I have added that termination in the first for loop)
4) Second loop is supposed to print all x values. It did not. The counter was short by one number.
The improved variation of the program is presented below. Please check the program output as well.
#include <stdio.h>
#include <stdlib.h>

struct node{
    int x;
    struct node *next;
};

int main(void){
    struct node *root, *next, *to_free;

    root = malloc(sizeof(struct node));                   // 1 malloc

    root->x = 777;
    root->next = NULL;

    printf("allocating memory for root. root->x = %i\n\n", root-> x);

    next = root; // next points to "head" (root)

    for (int i = 0; i <= 10; i++){
        next->next = malloc(sizeof(struct node));      // 11 mallocs

        printf("allocating memory for next. next->x = %i\n", i+1 );

        next->next->x = i+1;                           //

        next = next->next;
        next->next = NULL;                             // list termination is needed!
    }
    printf("\n");

    next = root; // next points to "head" (root)

    for (int j = 0; j <= 11; j ++){                   // 12 nodes has to be printed!
        printf("Printing x = %i\n", next->x);
        next = next->next;
    }
    printf("\n");

    next = root;   //  next points to "head" (root)

    while(next != NULL)
    {
        to_free = next;         // we will free `next` as `to_free` soon

        next = next->next;      // move to the next node

        printf("deallocating node with x = %i\n", to_free->x);

       free(to_free);          // now free the remembered `next`
    }
 return 0;
}

Output:
allocating memory for root. root->x = 777

allocating memory for next. next->x = 1
allocating memory for next. next->x = 2
allocating memory for next. next->x = 3
allocating memory for next. next->x = 4
allocating memory for next. next->x = 5
allocating memory for next. next->x = 6
allocating memory for next. next->x = 7
allocating memory for next. next->x = 8
allocating memory for next. next->x = 9
allocating memory for next. next->x = 10
allocating memory for next. next->x = 11

Printing x = 777
Printing x = 1
Printing x = 2
Printing x = 3
Printing x = 4
Printing x = 5
Printing x = 6
Printing x = 7
Printing x = 8
Printing x = 9
Printing x = 10
Printing x = 11

deallocating node with x = 777
deallocating node with x = 1
deallocating node with x = 2
deallocating node with x = 3
deallocating node with x = 4
deallocating node with x = 5
deallocating node with x = 6
deallocating node with x = 7
deallocating node with x = 8
deallocating node with x = 9
deallocating node with x = 10
deallocating node with x = 11

A: Your loop to free the nodes checks to see if next is NULL after it has called free(next).

A: As already stated by the other answer, the free() below is in the wrong place, as it frees the memory that is then checked in the condition of the while loop.
while(next != NULL){
    root = root->next;
    next = root;
    free(next);
}

However also, if move the first statement of that block to the end of the block as you suggested in your comment, your problem is probably the fact that this loop itself is fully sufficient to free the entire list, and so the statement free(root) AFTER the loop is likely a double free, which is usually an error. You can delete it.

A: There are couple of issues in your code which are listed bellow and the most important one is number 1.

*

*The pointer next in first item of your list (root) does not point to NULL, because it will be changed on the first for loop. So while(next != NULL) will not work because there is no item in your linked list which points to NULL.

*malloc will return pointer with type void *, so it is better to cast it to your next.

*After doing memory allocation, the result should be checked, if the memory was allocated successfully or not.
Also, I would suggest you to use typedef for defining your linked list.

Your code should be like this:
#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int x;
    struct node *next, *temp;
} node_t;

int main(int argc, char *argv[]){
  node_t *root, *next, *temp;

  root = (node_t *) malloc(sizeof(node_t));
  if(root == NULL){
    /* Do somthing */
    fprintf(stderr, "unable to allocate memory\n");
    exit(1);
  }
  root -> x = 100;
  root -> next = NULL;
  for (int i = 0; i <= 10; i++){
    next = (node_t *) malloc(sizeof(node_t));
    if(next == NULL){
      /* Do somthing */
      fprintf(stderr, "unable to allocate memory\n");
      exit(1);
    }
    next -> x = i;
    next -> next = root;
    root = next;
  }
  temp = next;
  while(temp != NULL){
    printf("x value is: %d\n", temp -> x);
    temp = temp -> next;
  }

  while(next != NULL){
    temp = next -> next;
    free(next);
    next = temp;
  }
}


text:
Q: .htaccess rewrite subdomain to above directory I got a mod_rewrite problem which i this time just can't figure out myself:
Some Javasript in a page requires to load further JS files which is denied because a CORS-Header is missing (Access-Control-Allow-Origin)
My Server structure
 Root | admin   | index.php
      | content | (...)
      | system  | wysiwyg | (Files)

My .htaccess in the root directory:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^i.cms.local
RewriteRule ^(.*)$ /content/media/getImage.php?img=$1 [QSA,NC,L]

RewriteCond %{HTTP_HOST} ^(admin|a).cms.local
RewriteRule ^(.*)$ /admin/$1 [L]

RewriteCond %{HTTP_HOST} ^cms.local
RewriteRule ^(.*)$ http://www.cms.local/$1

RewriteCond %{REQUEST_URI} \ /+index\.php\?q=([^&\ ]+)
RewriteRule ^ /%1.html [L,R]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.html$ /index.php?q=$1 [L]
RewriteRule ^(.+)/$ index.php?q=$1 [L]

The file im on is index.php in the admin direcory accessd via the subdomain a.cms.local. The additional files would normaly be access by s2.cms.local/wysisyg/.... But to avoid the CORS Header error I need to recieve them from the same URL, right? Si i though i use following link:

http://a.cms.local/wysiwyg/anyfile.js

And then the .htaccess redirects all wysiwyg request into the wysiwyg folder in system folder. Somehow I keep getting a 404 error - Hope someone has an idea?

A: Found the answer in this similar post: https://stackoverflow.com/a/27990162/1190388
Added following to the htaccess which enable CORS for all urls with the ^orgin cms.local:
SetEnvIf Origin ^(https?://.+\.cms\.local(?::\d{1,5})?)$   CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{CORS_ALLOW_ORIGIN}e   env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"


text:
Q: Пытаюсь сделать проект на Unity, возникает ошибка при обращении к объекту списка list Делаю проект по учёбе. По идее должен сохраняться набор характеристик персонажа в одном отдельном файле. В момент передачи переменной из одного файла в другой - возникает ошибка. Сообщает о том, что index должен быть неотрицательным либо меньше чем размер массива. Объясните глупому, что я сделал не так. (В С# я посредственно прохожу, ещё учусь).
По идее я в любом случае беру цифру из Dropdown.value от 0 до 4х. После чего присваиваю её переменной и с помощью функции передаю в другой файл. А там её не котируют как индекс.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
(строка где происходит первое присваивание LoadChars.character[].exist = 1)
Честно пытался разобраться с помощью интернета, и других ответов, но не доходит.
Файл LoadChar
{
    private string filepath;
    public static int cellchar;
    public Dropdown CharacterCells;
    public static List<Stats> character = new List<Stats>(5){};
    public void Start()
    {
        cellchar = Convert.ToInt32(CharacterCells.value);
        ...
        }
    }
    static public int Givecell()
    {
        return cellchar;
    }
}

Файл CreateChar1

public class CreateChars1 : MonoBehaviourPunCallbacks
{
    ...
    public Text text;
    public int createcell;
    public void CreateChar1()
    {
        createcell = LoadChars.Givecell();
        text.text = "00000";
        LoadChars.character[createcell].exist = 1;
        LoadChars.character[createcell].name = IName.text;
        LoadChars.character[createcell].nameplayer = INamePl.text;
...


text:
Q: How to properly initialise react table based on the server side data? Too many re-renders I have code like this:
import React, {Component, useState} from "react";
import DataTable from 'react-data-table-component';
import {columns} from "./table-data/data";
import RequestsPagination from "./CustomPagination";

const json = require('../stub/requests-page-1-response.json')

class RequestsPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            requests: [],
            currentPage: 0,
            elementsPerPage: 10,
            totalElements: undefined
        };

        this.fetchData = this.fetchData.bind(this)
    }

    fetchData() {
        const {currentPage, elementsPerPage} = this.state
        fetch(`/api/requests?page=${currentPage}&size=${elementsPerPage}`)
            .then(response => {
                if (response.status !== 200) {
                    throw {
                        error: {
                            status: response.status
                        }
                    }
                } else {
                    //return response.json()
                    return {}
                }
            })
            .then(pageResponse => {
                this.setState(prevState => ({
                    ...prevState,
                    requests: json.requests,
                    totalElements: json.totalElements
                }))
            })
            .catch(error => {
                console.log(error)
                this.setState(prevState => ({
                    ...prevState,
                    response: error
                }))
            })
    }

    componentDidMount() {
        this.fetchData()
    }

    render() {
        return (
            <div>
                {myPagination.call(this)}
            </div>
        )
    }
}

function myPagination() {
    const {currentPage, elementsPerPage, requests, totalElements} = this.state
    return (
        <DataTable
            title={"Все запросы"}
            columns={columns}
            data={requests}
            pagination
            paginationDefaultPage={currentPage}
            paginationTotalRows={totalElements}
            paginationPerPage={elementsPerPage}
            paginationRowsPerPageOptions={[10, 20, 50]}
        />
    )
}

export default RequestsPage;

I keep getting:
Too many re-renders. React limits the number of renders to prevent an infinite loop.

I have tried to initialize the child component inside the render and now outside, tried several examples - no result. Can someone refer me to proper documentation and a simple explanation?
My goal is to create a react table with the smallest amount of code, i.e. using libraries. Later I plan to do pagination, I want to use the property of DataTable
onChangePage={(event, page) => this.fetchData()}

A: Apparently, this didn't work and I switched to React Table library following https://react-table.tanstack.com/docs/examples/pagination-controlled it worked as a charm
Looks like data-table designed for static data when I needed to get from the server per page


text:
Q: getFromLocation using GPS Can anyone tell me what is going wrong here. I am trying to obtain the address using reverse geocoding..`
if (locationGPS != null) {
                    list = geocoder.getFromLocation(locationGPS.getLatitude(),
                            locationGPS.getLongitude(), 3);

                    if (list != null) {
                        if (list.size() > 0) {
                            strZipcode = list.get(0).getPostalCode();
                            strAdminArea = list.get(0).getAdminArea();
                            strLocality = list.get(0).getLocality();
                            strAddressLine = list.get(0).getAddressLine(0);

                            Log.d(TAG, "list of address: "+ list);
                            Log.d(TAG, "Data: "+ mobileDataEnabled);
                            Log.d(TAG, "Data: "+ mobile);

                            int count = 0;
                            while ((strZipcode == null || strAdminArea == null
                                    || strLocality == null || (strAddressLine == null || strAddressLine == "USA"))
                                    && count < list.size()) {
                                strZipcode = list.get(count).getPostalCode();
                                strAdminArea = list.get(count).getAdminArea();
                                strLocality = list.get(count).getLocality();
                                strAddressLine = list.get(count)
                                        .getAddressLine(count);
                                count++;
                            }`

This thing works fine and gives out the right address. But sometimes it gives out null for the all of the values which i am trying to retrieve despite the fact that i have a check in place for null values.. Am i missing something here?

A: Reverse Geocoder does not always return a value. It sounds weird but this is the way it is. F0r example if you hit for address 5 times, you won't be lucky enough to get response for all hits. You may get 3 instead. So workaround may be, instead of hitting geocoder one at a time, try looping your request to 2 or 3 times or more, one of the requests will work hopefully.


text:
Q: How to reload the content of my page with ajax (Using Laravel View/Layout) I'm using Laravel 4,
I want to reload a view and change the content (Basically change the langage)
When I arrive on the index :
On my controller :
public function getIndex()
    {
        $lang = $this->retrieveLang("FR");
        $this->layout->content = View::make('cv.cv', array('lang' => $lang));
    }

The content extend the layout
@extends('layout.cvlayout')
@section('content')

My ajax function :
    <script>
    $(".changeLang").click(function(event) {
        event.preventDefault();
        var url = $(this).attr("href");
        $.ajax({
            url: url,
            cache: false,
            beforeSend: function() {
                $(".loaderOverlay").fadeIn();
            },
            success: function(html) {
                $("#container").html(html);
                $(".loaderOverlay").fadeOut();
                pageCvInit();
                initAjaxHeadline();
            }
        });

    });
    </script>

the url may be ****/fr so in the controller there is a method like that :
public function getFr() {
    $lang = $this->retrieveLang("FR");
    return View::make('cv.cv', array('lang' => $lang));
}
I tried to put a condition on the
@extends()
@section()
@stop
part, but every time the ajax function is called, the whole body passes by the ajax method (even the ,  tags) and I just want to reload the body.
How do I do this?
Many thanks

A: You only need to reload the div you want that see the changes, in success put this:
$("#mydiv").load(location.href + " #mydiv");

A: Not sure how you mean by the whole body passes by ajax and you just want to reload the body.
Try changing your on success to filter out the body of the received html.
success: function(html) {
    $("#container").html($(html).filter('body').html());
    $(".loaderOverlay").fadeOut();
    pageCvInit();
    initAjaxHeadline();
}


text:
Q: Unable to sleep execution within an api subscription callback I am making an api subscription to fetch real time live data from one of the api providers,
However i only want to pull the data every few seconds (eg 5 seconds).
I am using the below code snippet, however am unable to implement the sleep or delay effectively.
Can you please help to guide why the api is not adhering to the 5 second wait ?
api_ABC_connection=apiConnect(api_key="<apikey")

api_ABC_connection.ws_connect()
abc_list=[]
# Callback to receive ticks.
def on_ticks(ticks):
    print('###################')
    print(datetime.now())
    time.sleep(5)
    fetch_time_dict = {}
    fetch_time_dict['fetch_time'] = datetime.now()
    abc_list.append(fetch_time_dict)
    #print("Ticks: {}".format(ticks))
    abc_list.append(ticks)
    print(datetime.now())

    return abc_list

# Assign the callbacks.
api_ABC_connection.on_ticks = on_ticks

# subscribe stocks feeds

api_ABC_connection.subscribe_feeds(<feeds parameters>)

A: Assuming api_ABC_connection is calling callback function asynchronously, you can try and add the lock. Try this, it may work:
lock = multiprocessing.Lock()

def on_ticks(ticks):
    print('###################')
    print(datetime.now())
    lock.acquire()
    time.sleep(5)
    lock.release()
    fetch_time_dict = {}
    fetch_time_dict['fetch_time'] = datetime.now()
    abc_list.append(fetch_time_dict)
    #print("Ticks: {}".format(ticks))
    abc_list.append(ticks)
    print(datetime.now())

    return abc_list

You may want to put both acquire() and release() methods into another place. It depends on what behavior you actually expect.


text:
Q: Tutorials/References/HowTos to learn Glade GTK+ with Ruby? I am trying to design some simple GUIs with Glade to use with Ruby. I am not having so much luck finding tutorials/references on how to actually interface glade with Ruby however. I have found maybe 1 or 2 hello world tutorials that show how to use a button to change a title of a window but is there a reference that tells me what each of the signals/handlers do and how to use functionality such as comboboxes, listboxes, tree structures etc..?
If you guys had any information to give me to help learn Glade with Ruby I would be most thankful!

A: Take a look at RSQLiteGUI. It's a small Glade app, so you get an overview really quick. Still it's bigger than HelloWorld and it should show you most concepts.


text:
Q: Webfont (@font-face) line-height issue I often embed webfont (@font-face) in sites that I develop and I have never encountered a major problem until today.
In fact, I feel there is a big issue with the line-height, I'm not extremely good at English so I'll try to illustrate it with pictures. I already contact the support from fontshop.com (where the font was bought) but they do not seem to understand / solve the problem.
What we had before with standard desktop font (= rendering is good for us):

What we had with the font-face (no change in CSS stylesheet):

Here is the CSS:
#content h1 {
    background:#000000;
    color:#FFFFFF;
    font-family:"DINPro-Bold","Helvetica Neue",Arial,Helvetica,Geneva,sans-serif;
    font-size:35px;
    line-height:30px;
    padding:10px;
    text-transform:uppercase;
}

A: Usually font websites will have ways to configure the webfont package when you download it.  I buy all my fonts from myfonts.com and under the advanced settings there are options for line-height adjustments.  Try downloading the font using native line-height adjustments if this option is available.  If not, try uploading the font to fontsquirrel's online font generator and upload the new version.

A: That's not the same font. The shape of the O and the curvature of the arm on the R give it away, which means the fallback fonts are being used, likely due to @font-face not loading properly. Different fonts will have different default spacing, as stated already, which would also lead you to believe it's a line-height issue.
Try making your fallback fonts something totally obvious, like:
font-family:"DINPro-Bold",serif;

A: This worked for me:
Generate the webfont at Font Squirrel. After uploading the fonts select 'Expert', scroll down and check the checkbox 'X-height Matching'. This resizes the height to match the x-height.

A: If you have problem with line-height of your webfont (especially if font suppose to be big in your project) try this: close your font in div or other block element and set "overflow" to "hidden". Div will have exact height of your font so any additional space will be cut off.

A: Line height according to wikipedia

In typography, leading (rhymes with heading) refers to the amount of
  added vertical spacing between lines of type.

This can be achieved like this...
.class{
line-height: 1em;
}
But if you are referring to the height of the letters then this is not something that can be adjusted. It is part of the font you have chosen to use.

A: Try adding "position: relative; top: 5px;" to the "h1" tag

A: Try position: relative; paddint-top: 5px; padding-bottom: 0px;


text:
Q: ...stream... result When using Message.CreateMessage() with XmlDictionaryReader.CreateTextReader() This code works just fine sometimes. The ErrorXml const string is below:
     public Message GetErrorMessage(string code, string message, string actor)
    {
        var bytes = Encoding.UTF8.GetBytes(string.Format(ErrorXml, code, message, actor));

        var xdr = XmlDictionaryReader.CreateTextReader(bytes,
                  new XmlDictionaryReaderQuotas());
        return Message.CreateMessage(xdr, int.MaxValue, MessageVersion.Soap11);
    }

Here is the definition of the ErrorXml const:
private const string ErrorXml = @"<env:Envelopexmlns:env""http://schemas.xmlsoap.org/soap/envelope/"">
                                   <env:Body>
                                       <env:Fault>
                                           <faultcode> {0} </faultcode>
                                           <faultstring> {1} </faultstring>
                                               <faultactor> {2} <faultactor>
                                           </env:Fault>
                                       </env:Body>
                                   </env:Envelope>

Now, the < body > tag of the result sometimes contains the following string ...stream..., which I challenge anyone to explain how I can search for without getting every Stream reference in existence. Also, how does one debug this error? Thanks!


text:
Q: Google Distance Matrix API does not return value if I am using variables of Origin and Destination I am working on a project now which needs to calculate distance between two point (either a latitude and longitude or a specific name of place).
Now, since my origin and destination comes from my database, i need to use a variable where the origin and destination be stored and eventually computed.
My code goes like this:
<?php
//request the directions
$origin="maramag";
$desti="malaybalay";
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$desti&alternatives=true&sensor=false'))-  >routes;

//sort the routes based on the distance
usort($routes,create_function('$a,$b','return intval($a->legs[0]->distance->value) - intval($b->legs[0]->distance->value);'));

//print the shortest distance
echo $routes[0]->legs[0]->distance->text;
echo $routes[0]->legs[0]->duration->text;
?>

But when I tried running the URL without using variables, such as this:
    $routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=maramag&destination=malaybalay&alternatives=true&sensor=false'))->routes;

It gives me a result of "49.0 km 45 mins" which is the result I wanted to appear.
Can anybody help me format my variable? I think it's the format or syntax of my variable contained in the URL has problem.
I browsed Google and on this site but I had never found a solution for my problem.
Thank you very much!

A: Use the string concatenation operator to create your URL:
$origin="maramag";
$desti="malaybalay";
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin='.$origin.'&destination='.$desti.'&alternatives=true&sensor=false'))-  >routes;

If the strings contain spaces or other characters that are not legal in URLs, URL encode them first.

A: The answer of @geocodezip above is right but it will trigger an error if the Origin and Destination contains spaces. So we must replace the spaces with "+" to avoid it. The complete answer to this question is below:
$origin="Dologon, Maramag, Bukidnon";
$desti="Malaybalay City, Bukidnon";

//replace the spaces with "+"
$address1 = str_replace(' ', '+', $origin);
$address2 = str_replace(' ', '+', $desti);

//use concatenation as answered by @geocodezip
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin='.$address1.'&destination='.$address2.'&alternatives=true&sensor=false'))->routes;

So instead of making our origin=$origin and our destination=#desti, we must make it origin='.$origin.' and for destination we must make it destination='.$desti.'
Happy coding! Thank you very much for helping!

A: Using your code I was able to get a proper response with an address containing spaces by using urlencode and making sure that I used double quotes instead of single quotes.
Here is all I did:
$location = urlencode($location); // May contain spaces
$routes = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/directions/json?origin=$userLat,$userLong&destination=$location&alternatives=true&sensor=false"))->routes;

The rest of your code worked perfectly and returns the correct distance and travel time. I had no need to use PHP's string concatenation syntax (ie: "Text ". $var ." more text)
In case anyone is curious, I got the user's latitude and longitude via javascript/PHP using the answer from this post


text:
Q: Are there any agressive CSS Minification tools? I'm wondering if anyone knows of a tool that will aggressively rewrite CSS to compress styles more efficiently.  e.g. I'd like:
.foo { color : red; font-size: 16px; height: 20px; }
.bar { color : red; font-size: 16px; height: 30px; }

to be compressed to:
.foo, .bar { color : red; font-size : 16px; }
.foo { height : 20px; }
.bar { height : 30px; }

To be clear, all the minifiers I know of, like YUI Compressor, only remove white-space and possibly join a few properties (like font-family and font-size into font).  I'm looking for something that's willing to do a complete re-write of the structure of a file.
Short of that, if anyone knows of any work anyone has done with regards to the compression logic behind this, that info would be appreciated.  I'm thinking of writing my own if I can't find one, but there's a million things to consider, like margin-top over-writing part of margin, selector specificity & include order, etc etc etc...  Then the job of how to efficiently compress the info, like will it be more efficient to repeat a selector or a property?

A: I don't know any aggressive CSS minification tool, but you could use the following approach:
Setup

*

*Expand your CSS (margin:1px 0 0 0; to margin-top:1px; margin-left:0px;...).

*Build a graph G = (V,E) with V as set of vertices and E as set of edges:

*

*V consists of the conjunction of the two sets A (unique selectors, eg. div, p > span, #myid) and B (unique properties, eg. display:block;, color:#deadbeef;).

*E consists of all associations between a selector (in A) and a property (in B).

*Use an appropriate weight function c for your elements in b. This could be the number of neighbors of a given element b, or accumulated lenght of properties - accumulated length of selectors. Your choice.

You may notice that by using this approach you'll get a bipartite graph. Now try the following greedy algorithm (pseudo code):
Algorithm

*

*Take an element b in B that has maximum weight and add it to an empty set Z

*Check whether another element d in B has same weight

*

*if such a d exists check whether it covers the same selectors.

*

*If d covers the same selectors: add d to Z and go to step 2.

*if d does not cover the same selectors check the next element with the same weight or go to step 3 if you checked all elements d.

*Now Z is a set of properties covering some selectors. Parse this as CSS into a buffer.

*Delete all elements in Z and their adjacent edges in G and delete Z itself.

*If B is not empty go to step 1.

*Your buffer contains a pre-minified CSS code. You can now merge some properties (eg. margin-top:0px;margin-left:1px).

Remarks
Please note that the actual compression depends on your weight function. As it is a greedy algorithm it will likely return a minified CSS, but I believe someone will post a counterexample. Note also that you have to update your weight function after deleting the elements in Z.
Runtime estimate
The algorithm will always terminate and will run in O(|B|^2*|A|) if I'm not mistaken. If you use a heap and sort the properties in each adjacency list (setup time O(|B|*|A|log(|A|))) you'll get O(|B|*|A|* (log(|B|)+log(|A|))).

A: CSS Tidy works like a champ!

*

*colours like "black" or rgb(0,0,0) are converted to #000000 or rather #000 if possible.

*Some hex-codes are replaced by their colour names if they are shorter.

*a{property:x;property:y;} becomes a{property:y;}

*(all duplicate properties are merged) margin:1px 1px 1px 1px; becomes margin:1px;

*margin:0px; becomes margin:0;

*a{margin-top:10px; margin-bottom:10px; margin-left:10px; margin-right:10px;} becomes

*a{margin:10px;}

*margin:010.0px; becomes margin:10px;

*all unnecessary whitespace is removed

*depending on the compression-level all background-properties are merged

*all comments are removed

*the last semicolon in every block can be removed

*missing semicolons are added

*incorrect newlines in strings are fixed

*missing units are added

*bad colors (and color names) are fixed

*property:value ! important; becomes property:value !important;

A: Have you seen YUI Compressor?

A: You can also  use http://www.minifycss.com/css-compressor/  or  http://www.ventio.se/tools/minify-css/

A: A project called CSS Tools claims to do this.


text:
Q: Multiple Unexpected Results in BigQuery I have a pretty huge query that join multiple tables (fact table with its dimension tables) in a destination table.
The fact table is about 40M rows.
it is of the following form:
SELECT
 ...
FROM (
  SELECT
   ...
  FROM (
    ...
  ) AS base
  LEFT JOIN  dim_table_1 ON dim_table_1.field1 = base.field1
) AS base2
LEFT JOIN dim_table_2 ON dim_table_2.field2 = base2.field2

I ran the query two times and it failed each time after several hours of computation
Here is the log in the BigQuery UI:
Errors:
Unexpected. Please try again.
Job ID: job_bVDu4XlJSpWCIeLTfrWpOHVN5nU
Start Time: 2:38pm, 4 Dec 2013
End Time: 8:38pm, 4 Dec 2013
Destination Table: <destination_table>
Write Preference: Overwrite table
Allow Large Results: true
Priority: Batch

EDIT:
Any tips on how I can optimize the query or what workflow changes to do so it will work ?

A: I'll look at this more a bit later (you've got a lot going on in your query -- 8 joins -- so it may take a little bit of digging to find the problem).
The latest query engine release has a regression when selecting a constant field (see Google BigQuery: "Unexpected" error while limiting rows), that you might be hitting (i.e. the "MSEC_TO_TIMESTAMP(NOW()/1000)" in your query may be hitting this problem). We should be releasing a fix for this today.
The other possibility is that you have a join explosion -- i.e. you're joining on non-unique keys and end up with more rows than you started out with.
As I mentioned, I'll investigate further when I get more time and I'll update this answer when I do.


text:
Q: Uploading downloadable URLs to Firestore. await on .map throw 'await' has no effect on the type of this expression I built a form using React Hook Form.
User can upload name, address, images etc. My problem is uploading images.
On the Form Submit ->  Firstly, I want to upload images to Firebase Storage. After that, I want to grab those downloadable URLs array and store them my listing in Firestore.
I can successfully upload to Firebase Storage. The problem is setting imageUrls state with the urls. For example, If I uploaded 2 files, it returns [undefined, undefined]
Since the component is shrinking, I decided to seperate uploadImages function. But I am facing some asynchronous problems.
Here is uploadFile function
import {
  getStorage,
  ref,
  uploadBytesResumable,
  getDownloadURL,
} from 'firebase/storage';

const uploadImages = (file, fileName) => {
  const storage = getStorage();
  const storageRef = ref(storage, `images/${fileName}`);

  const uploadTask = uploadBytesResumable(storageRef, file);

  // Register three observers:
  // 1. 'state_changed' observer, called any time the state changes
  // 2. Error observer, called on failure
  // 3. Completion observer, called on successful completion
  uploadTask.on(
    'state_changed',
    (snapshot) => {
      // Observe state change events such as progress, pause, and resume
      // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case 'paused':
          console.log('Upload is paused');
          break;
        case 'running':
          console.log('Upload is running');
          break;
      }
    },
    (error) => {
      // Handle unsuccessful uploads
    },
    () => {
      // Handle successful uploads on complete
      // For instance, get the download URL: https://firebasestorage.googleapis.com/...
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        console.log('File available at', downloadURL);
        return downloadURL;
      });
    }
  );
};

export default uploadImages;

Here is onSubmit event handler
  const onSubmit = async (formData) => {
    setLoading(true);
    try {
      if (geolocationEnabled) {
        const response = await fetch(
          `https://maps.googleapis.com/maps/api/geocode/json?address=${formData.location}&key=${process.env.REACT_APP_GEOCODE_API_KEY}`
        );
        const data = await response.json();

        if (data.status === 'ZERO_RESULTS') {
          setValue('location', undefined);
        } else {
          setValue('location', data.results[0]?.formatted_address);
        }

        const lat = data.results[0]?.geometry.location.lat ?? 0;
        const lng = data.results[0]?.geometry.location.lng ?? 0;

        setValue('geolocation', { lat, lng });
      } else {
        setValue('geolocation', {
          lat: formData.latitude,
          lng: formData.longitute,
        });
      }

      // uploading images
      if (formData.imageUrls.length > 0) {
        const imageURLs = Array.from(formData.imageUrls).map((file) =>
          uploadImages(file, `${formData.userRef}-${file.name}`)
        );
        setValue('imageUrls', imageURLs);
      }

      await addDoc(collection(db, 'listings'), formData);
      toast.success('Listing created successfully!');
    } catch (error) {
      console.log(error);
      toast.error(getErrorMessageForToastify(error.code));
    }
    setLoading(false);
  };

When I write
      if (formData.imageUrls.length > 0) {
        const imageURLs = Array.from(formData.imageUrls).map((file) =>
         {
           const url = await uploadImages(file, `${formData.userRef}-${file.name}`)
           return url
        }
        );
        setValue('imageUrls', imageURLs);
      }

I receive warning 'await' has no effect on the type of this expression. Since it doesn't return promise. How can I fix this problem?
Thank you

A: I found the solution by returning Promise in uploadImages function.

    const uploadImages = async (file, fileName) => {
      return new Promise((resolve, reject) => {
        const storage = getStorage();
        const storageRef = ref(storage, `images/${fileName}`);

        const uploadTask = uploadBytesResumable(storageRef, file);

        // Register three observers:
        // 1. 'state_changed' observer, called any time the state changes
        // 2. Error observer, called on failure
        // 3. Completion observer, called on successful completion
        uploadTask.on(
          'state_changed',
          (snapshot) => {
            // Observe state change events such as progress, pause, and resume
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
              case 'paused':
                console.log('Upload is paused');
                break;
              case 'running':
                console.log('Upload is running');
                break;
            }
          },
          (error) => {
            // Handle unsuccessful uploads
            reject(error);
          },
          () => {
            // Handle successful uploads on complete
            // For instance, get the download URL: https://firebasestorage.googleapis.com/...
            getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
              console.log('File available at', downloadURL);
              resolve(downloadURL);
            });
          }
        );
      });
    };

And here is the modified one

  // uploading images
  if (formData.images.length > 0) {
    setIsFileUploading(true);
    const imgUrls = await Promise.all(
      [...formData.images].map((file) =>
        uploadImages(
          file,
          `${formData.userRef}-${file.name}-${Math.random()}`
        )
      )
    ).catch(() => {
      toast.error("Image couldn't uploaded");
      return;
    });

    if (imgUrls && imgUrls.length > 0) {
      setValue('imageUrls', imgUrls);
    }
    setIsFileUploading(false);
  }


text:
Q: Creating a Multi-client Chatroom/Groupchat in Python I am having some trouble working on the client side for my groupchat application. I keep on running into this error message regarding inputs for a client since I want to be able to have multiple clients and distinguish them by inputted usernames. I am running the server and clients via terminal. I don't know if I am just writing in the completely wrong place or something else is happening.
```
# Import socket related methods
from socket import *
# Import argv related methods
from sys import *
# Import select method
from select import *

# Client needs server's contact information
if len(argv) != 3:
    print("usage:", argv[0], "<server name> <server port>")
    exit()

# Get server's whereabouts
serverName = argv[1]
serverPort = int(argv[2])

# Get Client's name
clientName = input('Enter Client Name:')

# Create a socket
sock = socket(AF_INET, SOCK_STREAM)

# Connect to the server
sock.connect((serverName, serverPort)) #changed this do to syntax error in this file and org. two way file
print(serverName, serverPort)# syntax error

# Make a file stream out of socket
sockFile = sock.makefile(mode='r')

# Make a list of inputs to watch for
inputSet = [stdin, sockFile]

# Keep sending and receiving messages from the server
while True:

    # Wait for a message from keyboard or socket
    readableSet, x, x = select(inputSet, [], [])

    # Check if there is a message from the keyboard
    if stdin in readableSet:
        # Read a line form the keyboard
        line = stdin.readline()

        # If EOF ==> client wants to close connection
        if not line:
            print('*** Client closing connection')
            break

        # Send the line to client
        sock.send(line.encode())

    # Check if there is a message from the socket
    if sockFile in readableSet:
        # Read a message from the client
        line = sockFile.readline()

        # If EOF ==> client closed the connection
        if not line:
            print('*** Server closed connection')
            break

        # Display the line
        print('Server:', line) #removed end since it kept causing errors

# Close the connection
sockFile.close()
sock.close()

**Here is the error code:**
ast login: Thu Mar 17 12:36:45 on ttys002
iamlostboy@paki-Macbook-Pro GroupChat5 % python Client5.py localhost 56000
Enter Client Name:JohnnyRocket
Traceback (most recent call last):
File "Client5.py", line 21, in <module>
 clientName = input('Enter Client Name:')
File "<string>", line 1, in <module>
NameError: name 'JohnnyRocket' is not defined
iamlostboy@paki-Macbook-Pro GroupChat5 %


text:
Q: Which Page is calling the Handler ashx I want know which page and which URL has calling my Handler .ashx, is that possible?
I need this because, I have an Handler who calls and convert images from database, but some of my URLS of images are not passing the right query argument (they don't exist in database) and I need what is the URL who call to see what is the image for that arguments.

A: why not just use
context.Request.UrlReferrer?

A: A quick solution to your immediate question is to call (in C#)
Inside your public void ProcessRequest(HttpContext context){} method, add the following 3 lines.
       IServiceProvider provider = (IServiceProvider)context;
       HttpWorkerRequest worker = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
       String referer = worker.GetKnownRequestHeader(HttpWorkerRequest.HeaderReferer);

This will give you the URL of the page that called your handler.
To go further though, you should ideally be implementing error handling to handle any missing images.


text:
Q: SQL Oracle: вывести сгруппированные подстроки определенной группы Просьба, подсказать, как более универсально можно вывести строки группировки,
допустим есть запрос
select col1, col2, col3, col4, col5 from table1

выполняю группировку:
select col1, col2, col3, sum(col5) from table1 group by  col1, col2, col3

как мне можно теперь получить строки группы где sum(col5) > n при этом в результате должны быть следующие колонки col1, col2, col3, col4, sum(col5)
т.е. найти определенную группу по колонкам col1, col2, col3 и при условие вывести сгруппированные строки этой группы по колонкам col1, col2, col3, col4

A: С оконной функцией:
select *
  from (
    select col1, col2, col3, col4,
           sum(col5) over(partition by col1, col2, col3) as sum5
      from table1
  ) X
 where sum5 > n


text:
Q: React Native Paper HelperText consumes space when invisible I am displaying error messages for input fields with React Native Paper, and I am using the HelperText. This is my code:
      <TextInput
        mode="outlined"
        label="Password"
        placeholder="Password"
        value={Password}
        secureTextEntry={true}
        onChangeText={onChangePassword}
        style={{height: 40}}
      />
      <HelperText type="error" visible={isSubmit && PasswordValid()}>
        {password_message}
      </HelperText>

And with no error message it displays like this, and the helperText consumes a space  (I did inspect it as well, there is a space) even it is invisible.

And this when it is visible:

How do I get rid of the white space when it is invisible?

A: Conditionally render it
{isTrue ? <HelperText type="error" visible={isSubmit && PasswordValid()}>
  {password_message}
</HelperText> : null}

This won't mount the element to the views until the isTrue value is true hence no empty space.
In your case you can do something like this
{isSubmit && PasswordValid() ? <HelperText type="error" visible={true}>
      {password_message}
    </HelperText> : null}

Make sure isSubmit && PasswordValid() is a boolean.

A: You can have a dynamic styling based on the visibility of the error or try as follows. Change margin value according to your need
 <View style={{marginVertical:-3}}><HelperText type="error" visible={isSubmit && PasswordValid()}>
    {password_message}</View>

or
Conditional rendering.
{hasErrorVisible ?<View> <HelperText type="error" visible={isSubmit && PasswordValid()}>
  {password_message}
</HelperText></View> : null}


text:
Q: Protobuf member by member copy from java to protobuf class and vice versa I have a question regarding "Protocol buffer generated java class".
Is there is any way to customise it, so that I do not have to copy member by member for conversion from java object to protobuf object and vice-versa.
For Instance:
I have java class:
class Dummy{
  int id;
}

I have protocol buffer (.proto) file:
message Dummy{
 required int id = 1;
}

Now, for converting the java object to the proto buf or vice versa ,I have to assign member by member to objects [java/protobuf].
In the above case for converting the java object [javaObj] to protobuf object [protoObj] :
 Dummy protoObj = null;
 Builder builder = ProtoDummy.Dummy.newBuilder();
 builder.setId(javaObj.getId());
 protoObj = builder.build();

Similarly, for coverting from protobuf to java object, I have to perform member by member copy.
Is there is a way to directly assign the object or faster way then the one i am using.


text:
Q: Install Git on Centos 6.2 I'm trying to install Git on my cloud server, where is running Centos6.2.
But running this command:
yum install git

this error block the installation process:
Error: Package: git-1.7.11.3-1.el5.rf.x86_64 (rpmforge)
       Requires: libcurl.so.3()(64bit)

Now, I see that inside /usr/lib64/ folder there are this files:
libcurl.so -> libcurl.so.4.1.1*
libcurl.so.4 -> libcurl.so.4.1.1*
libcurl.so.4.1.1*

Isn't possible to tell git to use libcurl.so.4.1.1 instead of libcurl.so.3?

A: Just went through the same problem.
It's because it tries to install the centos 5 release: git-1.7.11.3-1.el5.rf.x86_64
To check, you can issue
yum list git

This showed me the el5 (wrong) package and el6 (correct) package.
Then select the el6 one which is called git.i686 and run :
yum install git.i686

I hope it will solve your issue or at least help you to find the correct package for your system!
Correction: installing git.i686 worked but didn't help to get git functional.
Finally got it by doing this:
yum remove rpmforge-release
yum install git

This removed the el5 version of rpmforge installed on my el6 system that was messing installation of GIT.


text:
Q: Detect if Appcelerator app was opened from a push notification I am trying to determine the best way to detect if my app was opened by tapping on a push notification. I have found some different articles online that suggest different way to do this, but none seem to work in a consistent manner across app platforms and states.
Is there an official Appcelerator way to do this?

A: Yes, there is an official way.
if (Ti.Platform.getOsname() !== 'android') {

    // Wait for user settings to be registered before registering for push notifications
    Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {

        // Remove event listener once registered for push notifications
        Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);

        Ti.Network.registerForPushNotifications({
            success: deviceTokenSuccess,
            error: deviceTokenError,
            callback: receivePush
        });
    });

    // Register notification types to use
    Ti.App.iOS.registerUserNotificationSettings({
        types: [
            Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
            Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
            Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
        ]
    });
}
// For Android
else {
    var CloudPush = require('ti.cloudpush');
    var deviceToken = null;

// Initialize the module
    CloudPush.retrieveDeviceToken({
        success: deviceTokenSuccess,
        error: deviceTokenError
    });

    // Process incoming push notifications
    CloudPush.addEventListener('callback', function (evt) {
        receivePush(evt);
    });
}

// Process incoming push notifications
function receivePush(e) {
    // alert(e.data);
}


text:
Q: How to use regexp get url pattern in golang? How to use regular expression matching URL, which does decide to use the corresponding function processing
package main

import(
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/pattern", resolve)
  http.ListenAndServe(":8080", nil)
}

func resolve(w http.ResponseWriter, r * http.Request) {
  fmt.Println(r.URL.Host)
}

A: I use github.com/gorilla/mux package. So router looks like:
func main() {

    r := mux.NewRouter()

    r.HandleFunc("/{name:pattern}", handle)
    http.ListenAndServe(":8080", r)
}

where {name:pattern} could be simply {slug} (without pattern) or {id:[0-9]+} or combination of them /{category}/{id:[0-9]+}. And get them in handler func:
func handle(w http.ResponseWriter, r *http.Request) {

    params := mux.Vars(r)

    // for /{category}/{id:[0-9]+} pattern
    category := params["category"]
    id := params["id"]
}

run it and try curl http://localhost:8080/whatever/1

A: http.HandleFunc() can not be used to register a pattern to match a regular expression. In short, the pattern specified at HandleFunc() can match a fixed, rooted path (like /favico.ico) or rooted subtrees (like /images/), longer patterns take precedence over shorter ones. You can find more details at the doc of the ServeMux type.
What you can do is register your handler to a rooted subtree which may be  everything with the / pattern, and inside your handler you can do further regexp matching and routing.
For example:
func main() {
    http.HandleFunc("/", route) // Match everything
    http.ListenAndServe(":8080", nil)
}

var rNum = regexp.MustCompile(`\d`)  // Has digit(s)
var rAbc = regexp.MustCompile(`abc`) // Contains "abc"

func route(w http.ResponseWriter, r *http.Request) {
    switch {
    case rNum.MatchString(r.URL.Path):
        digits(w, r)
    case rAbc.MatchString(r.URL.Path):
        abc(w, r)
    default:
        w.Write([]byte("Unknown Pattern"))
    }
}

func digits(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Has digits"))
}

func abc(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Has abc"))
}

Or use an external library like Gorilla MUX.

A: Golang doesn't have built-in regex support for URL matching. And it's somewhat complicated to implement from scratch.
Maybe using a framework would be a better choice, such as beego or martin, etc.


text:
Q: ruby regex for two backslashes I am trying to find a regex that matches any string with two consecutive backslashes.  I'm trying every variation, any help? And info on handling backslashes
b='\\mystring'

if b=~/\\\\/
  puts "it matches"
end

I can't seem to get this to match.

A: Your regex looks good, but your string does NOT contain two backslashes, it just contains one.  It looks like it contains two but that's only in your source file, not in the actual string.  Try this:
'\\\\mystring' =~ /\\\\/

A: Backslash is still a bit magic even inside hard ' quotes. For one thing, it needs to be able to quote ' itself, and so what if your string had a \ followed by '? You need to be able to backslash-quote the backslash in order to unambiguously get a single \ before a magic character, and for sanity, everywhere else as well.
>> '\\'.length
=> 1
>> '\''
=> "'"
>> '\\'[1,1]
=> ""
>> '\\'[0,1]
=> "\\"


text:
Q: MYSQL Procedure call saved query in table That I need is

*

*Save all of query in one table
query_id | sql_query
1        | select * from ms_user
2        | select * from ms_privileges

*Create Procedure
this procedure will call
call my_procedure(query_id)

I tried the code below
DROP PROCEDURE IF EXISTS mp_test;
CREATE PROCEDURE global_procedire(IN id_query int(10));
BEGIN
  SET @Query = 'SELECT sql_query from ms_query where query_id = id_query';
  SET @Query = CONCAT(@Query);
  PREPARE stmt FROM @Query;
  EXECUTE stmt;
END


text:
Q: Reload the contents of the datatable after update or delete opertaion Hi I want to reload the content of my datatable after updating or deleting data into or from the database. I used fnDraw() but it not working. I done the deletion using ajax. Here is my code
ajax.php
<?php
$mysql_host = 'localhost';
$mysql_database = 'proj1';
$mysql_user = 'root';
$mysql_password='';
$mysqli = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if (mysqli_connect_errno($mysqli))
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
  }
 $id=$_POST['id'];
 $delete = "delete from regestration_details where eid=".$id."";
 $ss=mysqli_query( $mysqli,$delete);
?>

jquery_ajax.js
$('#myTable').on('click','.b2',function()
{
    if (confirm("Are you sure?"))
    {
        var id = $(this).val();
        var dataString = {id : id };
        $.ajax({
        type: "POST",
        url: "ajax_delete.php",
        data: dataString,
        success: function()
        {
            $("#myTable").dataTable().fnDraw();
            alert("datas are successfully deleted..");
        },
        error: function()
        {
            alert("Error occured..");
        }
        });
    }
});

Any idea for the above problem..?


text:
Q: Facebook Ads API - Actions by conversions returns total actions I'm trying to get info about a specific user's ad campaigns using an async request to /reportstats. When I add all fields to the request, everything is fine. But when I remove both total_actions and total_unique_actions, the fields actions_28d_click_by_convs and unique_actions_28d_click_by_convs return the totals instead of an object with a breakdown of totals per action. As soon as you add either total_actions or total_unique_actions back to the list, the two by_convs fields return the expected object.
With 'total_actions':
{  campaign_name: '...',
   campaign_group_name: '...',
   clicks: 337,
   reach: 80564,
   [...]
   total_actions: 335,
   actions_28d_click_by_convs: [Object],
   unique_actions_28d_click_by_convs: [Object]
}

Without 'total_actions':
{  campaign_name: '...',
   campaign_group_name: '...',
   clicks: 337,
   reach: 80564,
   [...]
   actions_28d_click_by_convs: 335,
   unique_actions_28d_click_by_convs: 335
}

Another weird thing: the summary of the response does show an object with the totals (of all campaigns combined) per action (e.g. post_likes).
I've tried this with 2 different users and 2 different apps, and both show the same weird thing. I (temporarily) solved it by just always requesting total_actions.
Anyone else who has the same problem and/or knows the cause?
Thanks!


text:
Q: How to create an arraylist from input of a single jtextfield? I want the user to be able to type in 10 different names in the same jTextField that I have implemented. I want all the names to be stored in an array, which I can then access in a document. Question: How do I implement the arraylist? I got this code from a wesbite. How do I incorporate the for loop in there to ask the user for a name 10 times?
 ArrayList<String> nameArrayList = new ArrayList<String>();
 JTextField nameTextField = new JTextField();
 nameArrayList.add(nameTextField.getText());

A: Try this:
nameArrayList.addAll(Arrays.asList(nameTextField.getText().split(",")));
If you use other separator in the input please change it accordingly!


text:
Q: Using Oracle SQL as a matching engine I am not sure if what Im looking for is possible, but its certainly interesting to think about. My goal is to optimize the layout of a warehouse, but this problem is re applicable to other scenarios.
I have a list of locations, the distance to the door and the zone they are in (e.g. Zone A= Refrigerated, Zone B= Ambient):

Location    Zone    Distance
A1          A       1
A2          A       3
A3          A       5
A4          A       7
B1          B       2
B2          B       4
B3          B       6
B4          B       8

I also have a list of products, the amount of times they were picked and their zone (Zone A= Products that need to be refrigerated, Zone B= Products that need to be outside refrigeration, Zone A/B= Products with NO restriction)

Product     Zone    Pick per day
Milk        A       8
Lettuce     A/B     7
Bread       B       6
Chocolate   B       5
Tomatoes    A/B     4
Dry Pasta   B       3
Beef        A       2
Chicken     A       1

If I was only interested in optimizing the distance traveled to pick the product, I would put the most picked closest to the door. I have done this by joining both tables through their ROW_NUMBER and ORDER BY Distance and Pick.
HOWEVER, I really care about the product Zone, since I cant store my Bread in the refrigerated area (it could go soggy). Additionally, I know that Lettuce could be stored in the refrigerated OR non refrigerated area.
ADDITIONALLY, there should be a condition that ensures ALL products are allocated a space (8 spaces 8 products)
Doing it manually I would get.

Location    Zone    Distance    Product     Zone    Pick per day
A1          A       1           Milk        A       8
B1          B       2           Lettuce     A/B     7
A2          A       3           Tomatoes    A/B     4
B2          B       4           Bread       B       6
A3          A       5           Beef        A       2
B3          B       6           Chocolate   B       5
A4          A       7           Chicken     A       1
B4          B       8           Dry Pasta   B       3

I have looked at the SQL Pattern Matching but was unsuccessful. Also, I have programmed an iterative VBA function that uses "Reserved" spaces in zones, but this is to slow for a home PC.
Finally, Thanks! I have been reading posts in stackoverflow for all my problems, but this one I cant solve!!

A: a. start with this sql:
select *
from product p left outer join location l on (INSTR(p.zone, l.zone)>0)
order by p.pickperday  desc, l.distance asc;
b. write a stored procedure where you

*

*create a hashset

*start loop over resultset

*take current element and if it is not allready in hashset and location is also not allready in hashset insert it into hashset

*return hashsetlist

how to wirte such procedures: http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheight.htm#CHDCDHJD
for testing:
CREATE TABLE "PRODUCT" (    "PRODUCT" VARCHAR2(20), "ZONE" VARCHAR2(20), "PICKPERDAY" VARCHAR2(20));
CREATE TABLE "LOCATION" (   "LOCATION" VARCHAR2(20), "ZONE" VARCHAR2(20), "DISTANCE" VARCHAR2(20));

Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('A1','A','1');
Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('B1','B','2');
Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('A3','A','5');
Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('B2','B','4');
Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('A2','A','3');
Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('B3','B','6');
Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('B4','B','8');
Insert into LOCATION (LOCATION,ZONE,DISTANCE) values ('A4','B','2');

Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Milk','A','8');
Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Tomatos','A/B','4');
Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Bread','B','6');
Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Dry Pasta','B','3');
Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Lettuce','A/B','7');
Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Beef','A','2');
Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Chocolate','B','5');
Insert into PRODUCT (PRODUCT,ZONE,PICKPERDAY) values ('Chicken','A','1');


text:
Q: ASP MVC3 - Using Regular Expression Validator to find whole word This is the first time I've had to use regular expressions and I'm not having any luck attempting to match with a whole word. I'm using the ASP MVC Regular Expression Validator on my view model with the following pattern:
    [Required(ErrorMessage = "Welcome Letter required as (Y)es or (N)o")]
    [RegularExpression(@"^[|YES|YEs|Yes|yES|yEs|YeS|yeS|yes|Y|y|NO|No|nO|N|n]{1}", ErrorMessage = "Welcome Letter required as (Y)es or (N)o")]
    [DisplayName("Welcome Letter Req")]
    public string WelcomLetterReq { get; set; }

This works great if I want to put in a Y or N (either lower or upper case) but anything else gives me an error message. Can someone help out w/the syntax?

A: Try this one:
^(([yY][eE][sS])|([nN][oO])|([yY]|[nN]))$

live example: http://rubular.com/r/CfPJnLuHqe


text:
Q: configuration of QT to code in book "opencv2 computer vision application programming cookbook" I am teaching my self the book "opencv2 computer vision application programming cookbook" using QT creator 3.2.1 / QT 5.3.2 (clang5.0 (apple)).
When I tried to build one program I had warnings as follows:
Undefined symbols for architecture x86_64:
  "cv::imread(std::string const&, int)", referenced from:
      MainWindow::on_pushButton_clicked() in mainwindow.o
      ColorDetectController::setInputImage(std::string) in mainwindow.o
  "cv::imshow(std::string const&, cv::_InputArray const&)", referenced from:
      MainWindow::on_pushButton_clicked() in mainwindow.o
      MainWindow::on_pushButton_2_clicked() in mainwindow.o
  "std::allocator<char>::allocator()", referenced from:
      MainWindow::on_pushButton_clicked() in mainwindow.o
      MainWindow::on_pushButton_2_clicked() in mainwindow.o
  "std::allocator<char>::~allocator()", referenced from:
      MainWindow::on_pushButton_clicked() in mainwindow.o
      MainWindow::on_pushButton_2_clicked() in mainwindow.o
  "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)", referenced from:
      MainWindow::on_pushButton_clicked() in mainwindow.o
      MainWindow::on_pushButton_2_clicked() in mainwindow.o
  "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()", referenced from:
      MainWindow::on_pushButton_clicked() in mainwindow.o
      MainWindow::on_pushButton_2_clicked() in mainwindow.o
ld: symbol(s) not found for architecture x86_64

**clang: error: linker command failed with exit code 1** (use -v to see invocation)
make: *** [controller.app/Contents/MacOS/controller] Error 1
14:49:33: **The process "/usr/bin/make" exited with code 2**.
Error while building/deploying project controller (kit: Desktop Qt 5.3 clang 64bit)
When executing step "Make"

And here's my .pro file:
QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = controller
TEMPLATE = app

SOURCES += main.cpp\
           mainwindow.cpp \
           ../colorDetection/colorDetector.cpp \
           colorDetectController.cpp

HEADERS  += mainwindow.h \
            ../colorDetection/colorDetector.h \
            colorDetectController.h

FORMS    += mainwindow.ui

CONFIG += c++11
QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.10

INCLUDEPATH += "/usr/local/opt/opencv/include" \

LIBS += -L"/usr/local/opt/opencv/lib" \
        -lopencv_core \
        -lopencv_highgui \
        -lopencv_imgproc

I met similar warnings before, but I solved that by adding these two lines into .pro file:
CONFIG += c++11

QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.10

However, this time it doesn't work. Can anyone explain to me how to solve this ? Thanks a lot.

A: It aren't warnings, but errors. Linker errors. In particular, the line
"std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)", referenced from:

Means that it couldn't even link a standard std::string, which is weird.
It couldn't find libraries for x64 architecture. I doesn't see in your config a switch to compile for this architecture, hence I am assumiing it is a default behavior, which in turn means that an according library (at least with std::string) should have been shipped with the compiler.
It led me to this question (though it was for gcc), where the problem was in libstdc++ being too old, and thus it didn't contained some definitions for C++11 standard.
Then I looked at the page with description for std::basic_string, and found that since c++11 in members was used std::allocator, which is what I see inside the braces of the undefined reference about a string.
Hence the problem with your c++ library being too old. You need to update your compiler. Also another interesting thing I noticed from your post: you probably saying a wrong version of clang. You told it is clang-5.0, so I looked at the version in my Kubuntu, and it was just 3.4. I wondered: did I so long not updated the system? Then I decided to peek at the clang site, and found that the latest version (which is written as being «in progress») is just 3.7.
The last thing I need to mention is the two undefined references at the beginning — you just need to add a path to a library that contains functions cv::imread, and cv::imshow.


text:
Q: Glassfish SSL error - SSL connection error I am using the following guide to setup SSL on my glassfish server hosted in EC2.
I kept getting SSL connection error while browsing the 8181 page and there isn't any warning or error on the server log.
http://aliok.wordpress.com/2011/06/04/using-your-ssl-certificate-on-glassfish-3/

*

*keytool -keysize 2048 -genkey -alias yourdomain.com -keyalg RSA -dname "CN=www.yourdomain.com,O=Your Organization,L=Your City,S=Your State,C=Your Country Code like US, CH or TR" -keystore keystore.jks -keypass changeit -storepass changeit

*keytool -certreq -alias yourdomain.com -keystore keystore.jks -storepass changeit -keypass changeit -file server.csr
Download 2 cert files from godaddy.

*

*keytool -importkeystore -srckeystore ~/ssl-stuff/keystore.jks -destkeystore $GLASSFISHHOME/domains/yourdomain/config/keystore.jks

*cd $GLASSFISH_HOME/domains/yourdomain/config
keytool -import -v -trustcacerts -alias root -file gd_bundle.crt -keystore keystore.jks -keypass changeit -storepass changeit

*keytool -import -v -trustcacerts -alias yourdomain.com -file yourdomain.com.crt -keystore keystore.jks -keypass changeit -storepass changeit
then i changed the server config SSL section, certificate nickname to yourdomain.com


text:
Q: ODE water drop modeling question I have been working on a ODE homework which involves modeling the velocity of a drop of water falling from the sky. The ODE that models its velocity is given by:
$$
mv'=kv^2-mg, \qquad
k=\frac{1}{2}C_{d}\rho _{a},
$$
$C_{d}$: friction,
$\rho_{a}$: air density,
$A$: transversal section of the water drop.
I have had to find the theoretical velocity limit of the water drop as a function of $A$ by solving directly the ODE and compare these results with Euler and Runge-Kutta IV methods on MATLAB. I have done all of that.
The last question of my homework is an open question: It asks to modify the ODE presented by imagining now that the water drop losses a fraction of mass (by evaporation) while it is falling. I will have to apply Euler and Runge-Kutta IV on this new ODE. So I am looking for suggestions to improve the equation. Mass $m$ now is going to be a function of time, it has to decrease. I have been thinking to assume that the water drops are spheres and by using $density * volume=mass$.
Thank you very much in advanced!

A: I think you should just be able to write that the mass $m$ is a function of time and perhaps assume a linear one, namely
$$ m(t)=m_0-st,$$ where $m_0$ is an initial mass and $s$ is the rate of loss (positive) in units of $\frac{mass}{time}$. Then your equation is no longer separable (but who cares if you're going to solve in numerically) and would look like
$$ v'=\frac{k}{m(t)} v^{2} -g,  $$ or
$$ v'=\frac{k}{m_0-st} v^{2} -g,  $$
Hope this helps some. Is this what you're looking for?
Cheers,
Paul Safier