text:
Q: Remove duplicate records from table, leaving one copy I have inherited a MySQL table from one of my colleagues, and am in need of a little advice.
The table has the following structure:
| PHONE_NO   | ACC_NO | GET_MAIL | DATETIME_CRE         | INT_ACC | MAIL |
| 0113313313 | 000001 |   YES    | 2003-01-01 19:00:00  | 9000001 | N/A  |

There is no primary key, as the table was not created with one. I cannot recreate the table as:

*

*It would take far too long to complete (over 2 million records and counting)

*This is a mission critical table, meaning taking it down would result in my client losing money for the duration.

I need to be able to remove duplicated rows from the table with a query, without inserting a primary key. "Duplicated" in this sense refers to all columns within the row being identical to another row.

EDIT
This is the result of show create table query, as requested by  ypercube;
CREATE TABLE `callerQue` (
  `PHONE_NO` varchar(30) DEFAULT NULL,
  `ACC_NUMBER` varchar(40) DEFAULT NULL,
  `GET_MAIL` varchar(6) DEFAULT NULL,
  `DATETIME_CRE` datetime DEFAULT NULL,
  `INT_ACC` varchar(40) DEFAULT NULL,
  `MAIL` varchar(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1'

A: Not sure if this would work in mysql since i am a MSSQL-dba but you could add an identity column -> auto_increment.
This would make all rows unique.
Then you could do a group by on duplicate records and select the highest ID for example. This way you will only delete one row.
Repeat this until no more duplicates.


text:
Q: Angular2 Currency Pipe change decimal separator Hello angular friends,
I'm working on an angular2 app (multiple actually). And I live in the Netherlands.
Currently I'm formatting my currency with the following:
{{someIntegerWithCentsToBeDivided / 100 | currency:'EUR':true:'1.0-2'}}
This displays something like 500 to be Eurosign 5 and 501 to be Eurosign 5.01.
Now we dutchies really like comma's the other way around so does anyone know how to change the . to a ,?
Bonus points if someone knows how to show 5,- optionally when there is no cents.
My thoughts now would be to extend the CurrencyPipe

A: you need import that
import { registerLocaleData } from '@angular/common';
import localeIt from '@angular/common/locales/it'
registerLocaleData(localeIt, 'it');

and add that pipe in view
{{ 1000 | currency: 'EUR':'symbol':'.2-2':'it' }}

A: I'm too late but I found a solution.
I'm just create a pipe to replace anything:
import { PipeTransform, Injectable, Pipe }     from '@angular/core';
@Pipe({
  name: 'replace'
})
@Injectable()
export class ReplacePipe implements PipeTransform {
  constructor(){}
  transform(item: any, replace, replacement): any {
    if(item == null) return "";
    item = item.replace(replace, replacement);
    return item;
  }
}

I used that twice to solve your case.
{{ 5.01999 | currency:'BRL':true | replace:'.':',' | replace:',00':',-' }}}

A: Your problem has probably been solved some time ago, but just for reference for other Dutch developers (like myself):
Create a custom Pipe:
import {Pipe} from '@angular/core';

@Pipe({
    name: 'currencyFormat'
})
export class CurrencyFormat {
    transform(value: number,
        currencySign: string = '€ ',
        decimalLength: number = 2,
        chunkDelimiter: string = '.',
        decimalDelimiter:string = ',',
        chunkLength: number = 3): string {

        value /= 100;

        let result = '\\d(?=(\\d{' + chunkLength + '})+' + (decimalLength > 0 ? '\\D' : '$') + ')';
        let num = value.toFixed(Math.max(0, ~~decimalLength));

        return currencySign+(decimalDelimiter ? num.replace('.', decimalDelimiter) : num).replace(new RegExp(result, 'g'), '$&' + chunkDelimiter);
    }
}

Now you can use:
{{someIntegerWithCentsToBeDivided | currencyFormat}}

The Pipe has already all the Dutch defaults included, but you can easily change them or use them as arguments in the template. For example:
{{1234567 | currencyFormat:'$':2:' ':'.':3}}

will give $12 345.67 as output.

A: Fast solution for thousands with "." and decimals with ",":
1) Create new Pipe with command ng g p currencySeparatorFormatter and set the definition as follows:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'currencySeparatorFormatter'
})
export class CurrencySeparatorFormatterPipe implements PipeTransform {
  transform(value: string|null): string|undefined {
    return value?.replace(/,/gi, "x")
                .replace(/\./gi, ",")
                .replace(/x/gi, ".")
                .replace(/\$/gi, "$ ");
  }
}

Notice: .replace(/\$/gi, "$ "); is optional, only sets a space between "$" symbol and number.
2) Use it inside HTML:
{{room.price | currency: 'BRL' | currencySeparatorFormatter}}

A: I find all of these solutions too big with too many lines of code to achieve something so small. The good thing about them is if you're using them a lot through your app. For smaller cases, I personally would use this approach:

{{(checkout.delivery_fee | currency).replace('.',',')}}

So I can display something like: Delivery fee: $5,50
But, if you need to display a value greather than 1.000, you could use:

{{(checkout.delivery_fee | currency).replace(',','x').replace('.',',').replace('x','.')}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: django + uwsgi + nginx does not deliver any http response, says nothing The system seems to be running, but I don't get any normal HTTP response:
Romans-MacBook-Pro:kariera-centr.ru rreimche$ telnet yozh-studio.com 80
Trying 46.101.236.181...
Connected to yozh-studio.com.
Escape character is '^]'.
GET / HTTP/1.1
Host: yozh-studio.com

Connection closed by foreign host.
Romans-MacBook-Pro:kariera-centr.ru rreimche$ telnet yozh-studio.com 80
Trying 46.101.236.181...
Connected to yozh-studio.com.
Escape character is '^]'.
GET / HTTP/1.1
Host: yozh-studio.com
Accept: text/html,application/xhtml+xml,application/xml;
        q=0.9,*/*;q=0.8

Connection closed by foreign host.

uwsgi.log stays just as it was after starting the service:
[rreimche@rreimche-web hedgehog]$ sudo cat log/uwsgi.log
[sudo] password for rreimche:
*** Starting uWSGI 2.0.11.2 (64bit) on [Tue Nov  3 15:57:03 2015] ***
compiled with version: 4.8.3 20140911 (Red Hat 4.8.3-9) on 29 October 2015 19:27:56
os: Linux-3.10.0-123.8.1.el7.x86_64 #1 SMP Mon Sep 22 19:06:58 UTC 2014
nodename: rreimche-web
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /etc/uwsgi/sites
detected binary path: /usr/bin/uwsgi
chdir() to /var/www/hedgehog/code
your processes number limit is 7870
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /run/uwsgi/hedgehog.sock fd 3
setuid() to 1003
Python version: 2.7.5 (default, Jun 24 2015, 00:41:19)  [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)]
Set PythonHome to /home/hedgehog/.virtualenv/hedgehog
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x25c8c10
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 436608 bytes (426 KB) for 5 cores
*** Operational MODE: preforking ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x25c8c10 pid: 2938 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 2938)
spawned uWSGI worker 1 (pid: 2943, cores: 1)
spawned uWSGI worker 2 (pid: 2944, cores: 1)
spawned uWSGI worker 3 (pid: 2945, cores: 1)
spawned uWSGI worker 4 (pid: 2946, cores: 1)
spawned uWSGI worker 5 (pid: 2947, cores: 1)

the nginx logs are empty:
[rreimche@rreimche-web hedgehog]$ sudo cat log/access.log
[rreimche@rreimche-web hedgehog]$ sudo cat log/error.log
[rreimche@rreimche-web hedgehog]$

CONFIGURATIONS (CentOS 7):
/etc/uwsgi/sites/hedgehog.ini:
[uwsgi]
project = hedgehog
username = hedgehog
base = /var/www/%(username)/code

chdir = /var/www/hedgehog/code
home = /%(username)/.virtualenv/%(username)
module = %(username).wsgi:application

master = true
processes = 5

uid = %(username)
socket = /run/uwsgi/%(project).sock
chown-socket = %(username):nginx
chmod-socket = 660
vacuum = true
logto = /var/www/%(username)/log/uwsgi.log

/etc/systemd/system/uwsgi.service:
[Unit]
Description=uWSGI Emperor service

[Service]
ExecStartPre=/usr/bin/bash -c 'mkdir -p /run/uwsgi; chown hedgehog:nginx/run/uwsgi'
ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites
Restart=always
KillSignal=SIGQUIT
Type=notify
NotifyAccess=all

[Install]
WantedBy=multi-user.target

/etc/nginx/conf.d/hedgehog.conf:
server {
    listen 80;
    server_name yozh-studio.com, www.yozh-studio.com;

    access_log /var/www/hedgehog/log/access.log;
    error_log /var/www/hedgehog/log/error.log;

    location = favicaon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/hedgehog/static;
    }

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/run/uwsgi/hedgehog.sock;
    }
}


text:
Q: display certain buttons using jQuery with switch statement In my html I have many buttons and I want to be able to show only specific button once a certain imagine had been clicked by using switch statements so far, this is what i had tried
HTML:

Javascript:
jQuery
    //jQuery("#buttons").show("blind");
            console.log("buttons clicked");
            switch(jQuery(event.target).attr("data-designName")){
            case "pink Flower":
            target = "first button";
                break;
            case "red Rocks":
                break;

            }
        }

A: You can add id's to your buttons and use the show/hide to show and hide the buttons that you want.
switch(jQuery(event.target).attr("data-designName")){
            case "pink Flower":
                //target = "first button";
                $("#id_of_button_that_you_want_to_hide").hide();
                break;
            case "red Rocks":
                $("#id_of_button_that_you_want_to_hide").hide();
                break;
            }

or you can make all of them disabled and remove the attribute of the ones that you want to display

switch(jQuery(event.target).attr("data-designName")){
                case "pink Flower":
                    //target = "first button";
                    $("#firstButton").attr("disabled", false);
                    break;
                case "red Rocks":
                    $("#secondButton").attr("disabled", false);
                    break;
                }


text:
Q: training accuracy 100 percent and validation accuracy not changing I have a classification model that is clearly overfitting and the validation accuracy doesn't change.
I've tried using feature selection and feature extraction methods but they didn't help.
feature selection method:
fs = SelectKBest(f_classif, k=10)
    fs.fit(x, y)
    feature_index = fs.get_support(True)
    feature_index = feature_index.tolist()

    best_features = []

    # makes list of best features
    for index in feature_index:
        best_features.append(x[:, index])
    x = (np.array(best_features, dtype=np.float)).T

model:
def model_and_print(x, y, Epochs, Batch_Size, loss, opt, class_weight, callback):
    # fix random seed for reproducibility
    seed = 7
    np.random.seed(seed)

    # define 10-fold cross validation test harness
    kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)

    # K-fold Cross Validation model evaluation
    fold_no = 1
    for train, test in kfold.split(x, y):
        # create model
        model = Sequential()
        model.add(Dropout(0.2, input_shape=(len(x[0]),)))
        model.add(Dense(6, activation='relu', kernel_constraint=maxnorm(3)))
        model.add(Dropout(0.2))
        model.add(Dense(8, activation='relu', kernel_constraint=maxnorm(3)))
        model.add(Dropout(0.4))
        model.add(Dense(1, activation=tf.nn.sigmoid))

        # compile model
        model.compile(optimizer=opt,
                      loss=loss, metrics=['accuracy']
                      )
        history = model.fit(x[train], y[train], validation_data=(x[test], y[test]), epochs=Epochs,
                            batch_size=Batch_Size, verbose=1)

def main():
    data = ["data.pkl", "data_list.pkl", "data_mean.pkl"]
    df = pd.read_pickle(data[2])

    x, y = data_frame_to_feature_and_target_arrays(df)

    # hyper meters
    Epochs = 200
    Batch_Size = 1
    learning_rate = 0.003
    optimizer = optimizers.Adam(learning_rate=learning_rate)
    loss = "binary_crossentropy"

    model_and_print(x, y, Epochs, Batch_Size, loss, optimizer, class_weight, es_callback)

if __name__ == "__main__":
    main()

output for part of one fold:
  1/73 [..............................] - ETA: 0s - loss: 0.6470 - accuracy: 1.0000
62/73 [========================>.....] - ETA: 0s - loss: 0.5665 - accuracy: 0.7097
73/73 [==============================] - 0s 883us/step - loss: 0.5404 - accuracy: 0.7534 - val_loss: 0.5576 - val_accuracy: 0.5000
Epoch 100/200

 1/73 [..............................] - ETA: 0s - loss: 0.4743 - accuracy: 1.0000
69/73 [===========================>..] - ETA: 0s - loss: 0.6388 - accuracy: 0.6522
73/73 [==============================] - 0s 806us/step - loss: 0.6316 - accuracy: 0.6575 - val_loss: 0.5592 - val_accuracy: 0.5000
Epoch 101/200

 1/73 [..............................] - ETA: 0s - loss: 0.6005 - accuracy: 1.0000
69/73 [===========================>..] - ETA: 0s - loss: 0.5656 - accuracy: 0.7101
73/73 [==============================] - 0s 806us/step - loss: 0.5641 - accuracy: 0.7123 - val_loss: 0.5629 - val_accuracy: 0.5000
Epoch 102/200

 1/73 [..............................] - ETA: 0s - loss: 0.2126 - accuracy: 1.0000
65/73 [=========================>....] - ETA: 0s - loss: 0.5042 - accuracy: 0.8000
73/73 [==============================] - 0s 847us/step - loss: 0.5340 - accuracy: 0.7671 - val_loss: 0.5608 - val_accuracy: 0.5000
Epoch 103/200

 1/73 [..............................] - ETA: 0s - loss: 0.8801 - accuracy: 0.0000e+00
68/73 [==========================>...] - ETA: 0s - loss: 0.5754 - accuracy: 0.6471
73/73 [==============================] - 0s 819us/step - loss: 0.5780 - accuracy: 0.6575 - val_loss: 0.5639 - val_accuracy: 0.5000
Epoch 104/200

 1/73 [..............................] - ETA: 0s - loss: 0.0484 - accuracy: 1.0000
70/73 [===========================>..] - ETA: 0s - loss: 0.5711 - accuracy: 0.7571
73/73 [==============================] - 0s 806us/step - loss: 0.5689 - accuracy: 0.7534 - val_loss: 0.5608 - val_accuracy: 0.5000
Epoch 105/200

 1/73 [..............................] - ETA: 0s - loss: 0.1237 - accuracy: 1.0000
69/73 [===========================>..] - ETA: 0s - loss: 0.5953 - accuracy: 0.7101
73/73 [==============================] - 0s 820us/step - loss: 0.5922 - accuracy: 0.7260 - val_loss: 0.5672 - val_accuracy: 0.5000
Epoch 106/200

 1/73 [..............................] - ETA: 0s - loss: 0.3360 - accuracy: 1.0000
67/73 [==========================>...] - ETA: 0s - loss: 0.5175 - accuracy: 0.7313
73/73 [==============================] - 0s 847us/step - loss: 0.5320 - accuracy: 0.7397 - val_loss: 0.5567 - val_accuracy: 0.5000
Epoch 107/200

 1/73 [..............................] - ETA: 0s - loss: 0.1384 - accuracy: 1.0000
67/73 [==========================>...] - ETA: 0s - loss: 0.5435 - accuracy: 0.6866
73/73 [==============================] - 0s 833us/step - loss: 0.5541 - accuracy: 0.6575 - val_loss: 0.5629 - val_accuracy: 0.5000
Epoch 108/200

 1/73 [..............................] - ETA: 0s - loss: 0.2647 - accuracy: 1.0000
69/73 [===========================>..] - ETA: 0s - loss: 0.6047 - accuracy: 0.6232
73/73 [==============================] - 0s 820us/step - loss: 0.5948 - accuracy: 0.6301 - val_loss: 0.5660 - val_accuracy: 0.5000
Epoch 109/200

 1/73 [..............................] - ETA: 0s - loss: 0.8837 - accuracy: 0.0000e+00
66/73 [==========================>...] - ETA: 0s - loss: 0.5250 - accuracy: 0.7576
73/73 [==============================] - 0s 861us/step - loss: 0.5357 - accuracy: 0.7397 - val_loss: 0.5583 - val_accuracy: 0.5000
Epoch 110/200

final accuracy:
Score for fold 10: loss of 0.5600861310958862; accuracy of 50.0%

my question is what can I do about the overfitting if I've tried feature extraction and dropout layers and why is the validation accuracy not changing?


text:
Q: Convert dynamic rows to columns with sql select (Mysql Server)? I have a table "Organisation" :

And table when we find the other setting of organisation "setting" (is not fixed):

And the last table is "setting_value"  where we found the value of the 3 organisation :

I need to create a view to give me this result
IdOrganisation | LibelleOrganisation | DateCreation | DateModification | Mail | Tel | Pays | Code Postal | Ville | Adresse | Logo | Secteur

62 | Prevealys | 2016-10-11 10:40:24| 2016-10-11 10:40:24 | mail@gmail.com  | 002122222222 | NULL | NULL | NULL | NULL | NULL | NULL

68 | Solutions Conduite d'activité | 2016-11-01 15:06:32 | 2016-11-01 15:06:32 | NULL | NULL | Tunisie | NULL | NULL | Borj Baccouche Ariana | NULL | NULL

Thx,

A: What have you tried? You may want to take a look to the PIVOT operator.


text:
Q: How do I modify variables in the SocketServer server instance from within a RequestHandler handler instance in Python? Here's the code in question:
  class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
     __slots__ = ("loaded")

  class Handler(SocketServer.StreamRequestHandler):
     def handle(self):
        print self.server.loaded # Prints "False" at every call, why?
        self.server.loaded = True
        print self.server.loaded # Prints "True" at every call, obvious!

  server = Server(('localhost', port), Handler)
  server.loaded = False

  while True:
     server.handle_request()

Every time a new request comes in, the output I get is False followed by True. What I want is False followed by True the first time, and True followed by True henceforth.
Why aren't the modifications I made to the variable in the server instance persisting outside the scope of the handler's handle() function?
UPDATED:
So, I try using global variables to achieve what I want:
  loaded = False

  class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
     pass

  class Handler(SocketServer.StreamRequestHandler):
     def handle(self):
        global loaded
        print loaded # Prints "False" at every call still, why?
        loaded = True
        print loaded # Prints "True" at every call, obvious!

  def main():
     server = Server(('localhost', 4444), Handler)
     global loaded
     loaded = False

     while True:
        server.handle_request()

  if (__name__ == '__main__'):
     main()

And it still doesn't work, i.e. produces the same output as before. Could anyone please tell me where I'm going wrong?

A: Forking creates a new process, so you can't modify the server's variables in the original process.  Try the ThreadingTCPServer instead:
import SocketServer

class Server(SocketServer.ThreadingTCPServer):
    __slots__ = ("loaded")

class Handler(SocketServer.StreamRequestHandler):
    def handle(self):
        self.server.loaded = not self.server.loaded
        print self.server.loaded # Alternates value at each new request now.

server = Server(('localhost',5000),Handler)
server.loaded = False

while True:
    server.handle_request()

A: Your problem is that SocketServer.ForkingMixin creates a new process for every request.  Therefore, every time a new request comes in all your variables get reset to their default state.  So essentially no matter what you assign to self.server.loaded it will get reset at the next request.  This is also why globals won't work.
If you need a variable to persist between requests you'd best write that data somewhere more, er, persistent =).  Essentially, it sounds like you're trying to solve the problem of keeping session variables.  There's a million and one ways to do it and depending on your situation, one way might be more pertinent than another.  I highly recommend looking at how other Python-based SocketServer applications do it.
Just do a quick google for similar code to yours:  "filetype:py SocketServer ForkingMixIn" (one of the first results is CherryPy which I highly recommend looking at).


text:
Q: Расположение Div-ов Помогите сделать так чтобы несмотря на количество текста внутри все 4 div-а были ровными.

A: Добавьте для .job:
vertical-align: top;

A: Сделать их таблицей, если не требуется адаптив и надо именно на html/css.
С помощью JS:
1 решение
И ещё один вариант
    $(document).ready(function(){
    $.fn.equivalent = function (){
            //запишем значение jQuery выборки к которой будет применена эта функция в локальную переменную $blocks
        var $blocks = $(this),
            //примем за максимальную высоту - высоту первого блока в выборке и запишем ее в переменную maxH
            maxH    = $blocks.eq(0).height();

        //делаем сравнение высоты каждого блока с максимальной
        $blocks.each(function(){
            maxH = ( $(this).height() > maxH ) ? $(this).height() : maxH;
            /*
            Этот блок можно записать так:
            if ( $(this).height() > maxH ) {
                maxH = $(this).height();
            }
            */
        });

        //устанавливаем найденное максимальное значение высоты для каждого блока jQuery выборки
        $blocks.height(maxH);
    }

    //применяем нашу функцию в элементам jQuery выборки - $('.job')
    $('.job').equivalent();
});

Источник


text:
Q: Remove rows from dataframe that don't contain any numeric values I have an example dataframe as follows:
x <- data.frame(Var1 = c(NA,Inf,7,NA), Var2 = c(1,61, -Inf, -Inf), Var3 = c(12, 31, 49, Inf))
x
 Var1 Var2 Var3
1   NA    1   12
2  Inf   61   31
3    7 -Inf   49
4   NA -Inf  Inf

I would like to remove rows from this data frame that do not have at least one numeric value. So in this example, I'd like to only remove row 4, leaving a final data frame:
Var1 Var2 Var3
1   NA    1   12
2  Inf   61   31
3    7 -Inf   49

A: We may use is.finite in filter with if_any to subset data having any finite values in a row
library(dplyr)
x %>%
   filter(if_any(everything(), is.finite))
  Var1 Var2 Var3
1   NA    1   12
2  Inf   61   31
3    7 -Inf   49


text:
Q: Lookups in MongoDB I have multiple lookups in pipeline mongo query. if any populate field is undefined I don't want to omit this row. can I do this?
const pipeline = [
  { $unwind: "$wholesaler" },
  {
    $lookup: {
      from: "serviceproviders",
      localField: "serviceProvider",
      foreignField: "_id",
      as: "serviceProvider"
    }
  },
  { $unwind: "$serviceProvider" },
  {
    $sort: {
      createdAt: 1,
      updatedAt: 1
    }
  }
];

If service provider id is not found its return rest of the object that what I want.

A: From MongoDB document:

preserveNullAndEmptyArrays
If true, if the path is
  null, missing, or an empty array, $unwind outputs the document. If
  false, $unwind does not output a document if the path is null,
  missing, or an empty array.
The default value is false.

So use below:
{
  $unwind: {
    path: "$serviceProvider",
    "preserveNullAndEmptyArrays": true
  }
}

Check here with sample data (https://mongoplayground.net/p/aljWODXfwQg)


text:
Q: How to insert values from two tables into one in PostgreSQL? I have 3 non-empty tables:

Movie

movie_id

movie_name

Actor

actor_id

last_name

first_name

And the bridge table:

Movie_actor

movie_id

actor_id

I have added 3 new movies into 'movies', and 6 new actors to 'actor', that play in these movies (2 per each).
I need to insert my updates into the bridge table 'movie_actor'.
The logic is:
for movie1 add actors A, B,
for movie2 add actors C, D
for movie3 add actors E, F
The problem is that I don't want to write this query 3 times for each movie:
INSERT INTO movie_actor (actor.actor_id, movie.movie_id)

SELECT actor.actor_id, movie.movie_id
FROM actor, movie
WHERE actor_id IN (201, 202)
AND film_id = 1;

Is there any other way to write it all into one query? I believe it must be.
thank you in advance!

A: If I understand correctly, you want to run your query once and insert 6 rows of (movie_id, actor_id) into movie_actor bridge table by select data out of the cartesian product of movie and actor based on movie_id and actor_id given.
By comparing each row returned from the Cartesian product with given pairs of (movie_id, actor_id) as below in one single insert...select...:
insert into movie_actor
 select movie_id, actor_id
  from actor, movie
 where array[(movie_id, actor_id)] <@ array[(1,201), (1,202), (2,301), (2,302), (3, 401), (3,402)];

Of course, the traditional insert always work for less but it's not the way you like it:
insert into movie_actor
values
(1,201), (1,202), (2,301), (2,302), (3, 401), (3,402);


text:
Q: Split date result sets into columns in sql server can you please assist
I have a query that shows number of teachers, the site the visited and when date they visited. This query looks at all teachers visits for the past week.
I want to split the dateattended field into columns to show daily visit for the past week. Below is how it looks.
EmployeeNumber  Name                    HomeSite    Site Attended   Day Attended
TP-000322789    Samuel Mohlamnyane  Teacher          Port Elizabeth 2014-10-18 07:23
TP-000148774    Jean Smoothie           Teacher      Hennopsview    2014-10-13 08:55
TP-000148774    Jean Smoothie           Teacher      Hennopsview    2014-10-16 08:43
TP-000148122    Anthony Mike            Teacher      Tzaneen        2014-10-19 09:19
TP-000148122    Anthony Mike            Teacher      Tzaneen        2014-10-15 08:26
TP-000328452    Geneve Gorridon         Teacher      Tzaneen        2014-10-14 07:44
TP-000346529    Edmos Dube              Teacher      Melrose        2014-10-18 07:47
TP-000321374    Anita Rene Classen      Teacher      Johannesburg   2014-10-17 07:57
TP-000324511    Anthonysia White        Teacher      Durbanville    2014-10-15 07:53
TP-000324511    Anthonysia White        Teacher      Durbanville    2014-10-18 12:26
TP-000327471    Moses Mathebula         Teacher      Polokwane      2014-10-13 05:50
TP-000148194    Nonhlanhla Ndlovu       Teacher      Vereeniging    2014-10-15 07:06
TP-000323383    Lerato Manyanka         Teacher      Bedfordview    2014-10-13 07:26
TP-000323383    Lerato Manyanka         Teacher      Bedfordview    2014-10-16 06:51
TP-000323384    Lerato Manyanka         Teacher      Bedfordview    2014-10-17 08:57

Now I want to split Day attended to show date in different columns from yesterday going down to the last seven days.
Below is the code I used to get the above result set. And how the result should look like.
EmployeeNumber Name              HomeSite   Site Attended   Day 1  Day2    Day 3             Day 4             Day 5                Day 6            Day 7
TP-000148194   Nonhlanhla Ndlovu Teacher    Vereeniging                                                        2014-10-15 07:06
TP-000323383   Lerato Manyanka   Teacher    Bedfordview                    2014-10-17 08:57  2014-10-16 06:51                                     2014-10-13 07:26

SELECT   mdet.MemRefNo                        AS 'EmployeeNumber'
       , cont.FirstName + ' ' + cont.LastName AS Name
       , s.Name                               AS 'HomeSite'
       , Attend.VisitedSite                   AS 'Site Attended'
       , Attend.Weekdays                      AS 'Day Attended'

FROM MemberDetail mdet
INNER JOIN MembershipHistory mhis ON mdet.CurrentMembershipID = mhis.ID32
INNER JOIN contacts cont ON cont.GUID = mdet.ContactGUID
INNER JOIN Sites s ON s.id = cont.HomeSiteID

INNER JOIN Packages pg ON pg.ID = mhis.PackageID

 CROSS APPLY
 (
SELECT min(a1.attenddate) AS Weekdays , a1.contactguid, a1.SiteID , s.Name as VisitedSite       FROM dbo.attendance a1
    INNER JOIN Sites s ON s.id = a1.Siteid
WHERE DATEDIFF(DAY,a1.attenddate,GETDATE()) <= 7
and ContactGuid = mdet.ContactGuid
AND a1.isswipesuccessful = 1
GROUP BY a1.ContactGuid, DATEPART(DW, a1.attenddate),a1.SiteID , s.Name
) Attend

WHERE pg.Description LIKE '%Teacher%'

A: I think this is the query you want, it uses a pivot with the results from your existing query as source through a common table expression. Ideally the code could be merged into one query, but as you didn't provide any test data from the source tables, but only the output I didn't try to rewrite it. Note that if a person visited the same site more than one time in a single day, only the latest time will be shown.
-- using original query as source
;WITH visits AS (
    SELECT   mdet.MemRefNo                        AS 'EmployeeNumber'
         , cont.FirstName + ' ' + cont.LastName AS Name
         , s.Name                               AS 'HomeSite'
         , Attend.VisitedSite                   AS 'Site Attended'
         , Attend.Weekdays                      AS 'Day Attended'

    FROM MemberDetail mdet
    INNER JOIN MembershipHistory mhis ON mdet.CurrentMembershipID = mhis.ID32
    INNER JOIN contacts cont ON cont.GUID = mdet.ContactGUID
    INNER JOIN Sites s ON s.id = cont.HomeSiteID
    INNER JOIN Packages pg ON pg.ID = mhis.PackageID
    CROSS APPLY
    (
    SELECT min(a1.attenddate) AS Weekdays , a1.contactguid, a1.SiteID , s.Name as VisitedSite       FROM dbo.attendance a1
       INNER JOIN Sites s ON s.id = a1.Siteid
    WHERE DATEDIFF(DAY,a1.attenddate,GETDATE()) <= 7
    and ContactGuid = mdet.ContactGuid
    AND a1.isswipesuccessful = 1
    GROUP BY a1.ContactGuid, DATEPART(DW, a1.attenddate),a1.SiteID , s.Name
    ) Attend
    WHERE pg.Description LIKE '%Teacher%'
)

-- query to produce results
SELECT
    EmployeeNumber,
    Name,
    HomeSite,
    [Site Attended],
    [1] AS 'Day 1',
    [2] AS 'Day 2',
    [3] AS 'Day 3',
    [4] AS 'Day 4',
    [5] AS 'Day 5',
    [6] AS 'Day 6',
    [7] AS 'Day 7'
FROM (
    SELECT *, DATEDIFF(day, [Day Attended], GETDATE()) diff
    FROM visits
    WHERE [Day Attended] > (GETDATE()-7) -- adjust this to limit date range
    ) a
PIVOT (
    MAX([Day Attended]) FOR [diff] in ([1],[2],[3],[4],[5],[6],[7])
) AS Pivoted;

It would probably be trivial to modify the existing query to get the desired results.
Sample SQL Fiddle (using the sample output data as source).
Sample results:
EmployeeNumber       Name                                     HomeSite             Site Attended        Day 1                   Day 2                   Day 3                   Day 4                   Day 5                   Day 6                   Day 7
-------------------- ---------------------------------------- -------------------- -------------------- ----------------------- ----------------------- ----------------------- ----------------------- ----------------------- ----------------------- -----------------------
TP-000148122         Anthony Mike                             Teacher              Tzaneen              NULL                    2014-10-19 09:19:00.000 NULL                    NULL                    NULL                    2014-10-15 08:26:00.000 NULL
TP-000148194         Nonhlanhla Ndlovu                        Teacher              Vereeniging          NULL                    NULL                    NULL                    NULL                    NULL                    2014-10-15 07:06:00.000 NULL
TP-000148774         Jean Smoothie                            Teacher              Hennopsview          NULL                    NULL                    NULL                    NULL                    2014-10-16 08:43:00.000 NULL                    NULL
TP-000321374         Anita Rene Classen                       Teacher              Johannesburg         NULL                    NULL                    NULL                    2014-10-17 07:57:00.000 NULL                    NULL                    NULL
TP-000322789         Samuel Mohlamnyane                       Teacher              Port Elizabeth       NULL                    NULL                    2014-10-18 07:23:00.000 NULL                    NULL                    NULL                    NULL
TP-000323383         Lerato Manyanka                          Teacher              Bedfordview          NULL                    NULL                    NULL                    2014-10-17 08:57:00.000 2014-10-16 06:51:00.000 NULL                    NULL
TP-000324511         Anthonysia White                         Teacher              Durbanville          NULL                    NULL                    2014-10-18 12:26:00.000 NULL                    NULL                    2014-10-15 07:53:00.000 NULL
TP-000346529         Edmos Dube                               Teacher              Melrose              NULL                    NULL                    2014-10-18 07:47:00.000 NULL                    NULL                    NULL                    NULL


text:
Q: three.js not rendering correctly on iPad Air 2 I've just started using an iPad Air 2 for work and wanted to start working with equirectangular panoramas. These work great on the desktop, but an iPad/iPhone add some cool options to start using device orientation as the controls.
When I pulled up my script on the iPad, it looks extremely poorly rendered. I can tell what things are, but only because I'm familiar with this photo. I'm really not sure what's causing this issue. As far as I can tell, this looks to be local to the iPad. I've tested that WebGL is available, and that's always passed with flying colors.
In my code, I'm trying to create a sphere and used the photo as the mesh. Like I said, it works on the desktop, just not the iPad. I've been looking around but haven't been able to find any real solutions or very comparable issues being reported. I'm completely stuck on this one.
Here's the sample link: http://www.freeptools.com/mapster/360/2/

A: You need to resize your image to be a power-of-two. For example, 2048 x 1024.
I would suggest updating to the current version of three.js, and make sure your handle device pixel ratio correctly.
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );

For a panorama example, see this three.js demo: http://threejs.org/examples/misc_controls_deviceorientation.html.
three.js r.70


text:
Q: Django: override form validation to get around this error My specific problem is detailed below, but the main point of my question is this: When I click "Save" on the Django admin form while editing a model, what happens? What is the order of the validation/save process? How can I override these methods to solve my problem below, which is to say updating an intermediate table at the appropriate time as a workaround for the issue I described?
I'm working on a Django application which is facing a PostgreSQL database. The database is relatively large, and I have a lot of many-to-many relationships. The one that I am currently having an issue with is the n:m relationship between People and Sources.
The app is used mainly by non-technical people to add to the database through Django's built-in admin feature. The primary issue that I was having when I started working on the app was severe page slowdown when editing a Person on the admin site. If the person  had too many Sources, each drop-down in the TabularInline representation of sources loaded thousands of entries. I found a workaround and overrode the get_formfield_for_foreignkey() method as follows:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
    field = super(SourceMaterialInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

    # We will overwrite this method to ONLY return relevant materials on this person
    materials     = SourceMaterial.objects.all()
    materials_p   = SourceMaterial.people.through.objects.all()
    person_ID     = get_ID_from_path(request.path)
    if not_integer(person_ID):
        return field
    materials_pid = materials_p.filter(person_id=person_ID)

    # The next step is to use these relevant materials to obtain the SourceMaterial objects from the SourceMaterial table
    relevant_ids = []
    for mat in materials_pid:
        relevant_ids += [mat.sourcematerial_id]
    relevant_materials = materials.filter(id__in=relevant_ids)

    # now we can set the queryset so that only relevant materials are included
    field.queryset = relevant_materials

    return field

So this accomplishes what I wanted. When you go to edit a Person object through the Admin page, the dropdown menus to select sources only load and display Sources that belong to that Person.
The problem this creates, however, is when I go to add a new Source via the Person change form. I would like to keep this functionality, but it is now broken.
If I go to add a new source, a pop-up window appears. I select the file on my machine, give it a name and click add. At this point it is added to the Sources table, but not to the intermediate table linking it to this Person. When I go to save the Person, the form asks me to correct this error: Select a valid choice. That choice is not one of the available choices.
Here is the pop-up: Add new source material pop-up for clarity
This makes sense, as there is no established link between the Person and the Source yet. So instead I try adding the Person ID as well when adding a source this way, and the error is: Sourcematerial-person relationship with this Sourcematerial and Person already exists. I'm assuming this is because when I add the Source with the Person ID, the intermediate table is populated appropriately, and when I go to save, it tries to add the source again, because the form detects it as being new.
I'm hoping I can override form validation/saving so that I can keep functionality of adding a Source to the database this way. If anybody has any suggestions as to what exactly I could override (I was very confused by the docs) or another work around, that'd be great. Thanks!


text:
Q: save a b-tree file to be read later on using python i have an algorithym that creates a B-tree using python, what I need is a way to save this B-tree in the disc and be able to read it later on with python, what is the best way of doing it?

A: One approach to write a tree to file would be to come up with a record structure (text-based or binary) and iterate over all the nodes in the tree, starting with the leaves and going up to the root. As you write each node, you write the value and its neighbours to the file and you note the position that node was written to on the node. When writing its neighbours, you write the address in the file instead.
When loading the file, you start with the root record, set its value, get the address of the left neighbour, get that record, set its value, etc. and the same for the right neighbour.
I won't write and test all the code for the existing code you linked, but here's a simple example that shows the basic idea:
from random import randint
from dataclasses import dataclass
from typing import BinaryIO, ClassVar, Union

# A simple unbalanced tree node with an add method
@dataclass
class Node:
    # write to file as 2-byte integers
    int_size: ClassVar[int] = 2
    value: int = None
    address: int = None
    left: Union['Node', int] = None
    right: Union['Node', int] = None

    def add(self, value):
        p = self
        while True:
            if value > p.value:
                if p.right is None:
                    p.right = Node(value=value)
                    break
                else:
                    p = p.right
            elif value < p.value:
                if p.left is None:
                    p.left = Node(value=value)
                    break
                else:
                    p = p.left
            else:
                # value already in tree
                break

    @classmethod
    def _write_int(cls, f: BinaryIO, i: int):
        f.write(i.to_bytes(length=cls.int_size, byteorder='big'))

    @classmethod
    def _write_node(cls, f: BinaryIO, node: 'Node'):
        f.write(node.value.to_bytes(length=cls.int_size, byteorder='big'))
        f.write((node.left.address if node.left is not None else 0).to_bytes(length=cls.int_size, byteorder='big'))
        f.write((node.right.address if node.right is not None else 0).to_bytes(length=cls.int_size, byteorder='big'))

    @classmethod
    def _read_int(cls, f: BinaryIO):
        return int.from_bytes(f.read(cls.int_size), byteorder='big')

    @classmethod
    def _read_node(cls, f: BinaryIO, node: 'Node'):
        node.value = int.from_bytes(f.read(cls.int_size), byteorder='big')
        node.left = int.from_bytes(f.read(cls.int_size), byteorder='big')
        node.right = int.from_bytes(f.read(cls.int_size), byteorder='big')

    def save(self, f: BinaryIO):
        # seek the start of the file and write a dummy root record
        f.seek(0)
        self._write_int(f, self.value)
        self._write_int(f, 0)
        self._write_int(f, 0)

        stack = []
        p = self
        while True:
            if p.left is not None and p.left.address is None:
                stack.append(p)
                p = p.left
            elif p.right is not None and p.right.address is None:
                stack.append(p)
                p = p.right
            else:
                p.address = f.tell()
                self._write_node(f, p)
                if stack:
                    p = stack.pop()
                else:
                    break

        # rewrite root node with correct location of left and right nodes
        f.seek(0)
        self._write_node(f, self)

    def load(self, f: BinaryIO):
        f.seek(0)
        self.address = 0

        def load_side(side: str):
            # this function avoids repeating this code twice for .left and .right,
            # working around Python not having pointers, otherwise you'd just point at the attributes
            nonlocal f, p, stack
            if not isinstance(getattr(p, side), int):
                return False
            if not getattr(p, side):
                setattr(p, side, None)
            else:
                f.seek(getattr(p, side))
                setattr(p, side, Node())
                stack.append(p)
                p = getattr(p, side)
                self._read_node(f, p)
            return True

        stack = []
        p = self
        self._read_node(f, p)
        while True:
            if not load_side('left') and not load_side('right'):
                if stack:
                    p = stack.pop()
                else:
                    break

    def print(self):
        stack = []
        p = self
        left_done = False
        right_done = False
        while True:
            if not left_done and p.left is not None:
                stack.append((p, True, False))
                p, left_done, right_done = p.left, False, False
            elif not right_done and p.right is not None:
                stack.append((p, True, True))
                p, left_done, right_done = p.right, False, False
            else:
                print(f'value: {p.value}, '
                      f'left: {p.left.value if p.left else "none"}, '
                      f'right: {p.right.value if p.right else "none"}')
                if stack:
                    p, left_done, right_done = stack.pop()
                else:
                    break

values = [randint(0, 100) for __ in range(10)]
root = Node(values[0])
for v in values[1:]:
    root.add(v)
print('\nTree after construction:')
root.print()

# save the tree
with open('tree.bin', 'wb') as f:
    root.save(f)

# start a new and empty tree
root = Node()
# read the tree
with open('tree.bin', 'rb') as f:
    root.load(f)
print('\nResult after load:')
root.print()

This writes the tree as a 2-byte unsigned integer binary file (changing that size is trivial) with the references to left and right children represented as the file position of the record on file.
The example avoids recursive calls, as a serious unbalanced b-tree could quickly approach maximum recursion depth.
Example result (the print function ends up printing the root at the bottom, a nicer print is certainly possible, but this is just to demonstrate it works):
Tree after construction:
value: 15, left: none, right: none
value: 18, left: 15, right: none
value: 30, left: 18, right: none
value: 41, left: 30, right: none
value: 11, left: none, right: 41
value: 54, left: none, right: none
value: 74, left: 54, right: none
value: 81, left: none, right: none
value: 78, left: 74, right: 81
value: 45, left: 11, right: 78

Result after load:
value: 15, left: none, right: none
value: 18, left: 15, right: none
value: 30, left: 18, right: none
value: 41, left: 30, right: none
value: 11, left: none, right: 41
value: 54, left: none, right: none
value: 74, left: 54, right: none
value: 81, left: none, right: none
value: 78, left: 74, right: 81
value: 45, left: 11, right: 78

Note that quite a bit of code is required even for a basic example. And in this particular example, it would probably make a lot more sense to just store the values in a file and reconstruct the tree the same way it was constructed originally, as the tree's structure is entirely deterministic.
But there are cases where you might not want to do that - for example, if you add functionality that allows rewriting of the value of a node while on file, the reconstruction would result in a different (though still correct) tree.
Also note that the code provided above has a flaw: if you try to save the same tree twice, it will fail as it uses the address to determine if a node has already been written - it's left as an exercise to the reader to fix that. Either you could keep track separately, or you could reset the addresses for the entire tree before saving.


text:
Q: Cannot read property 'form' of undefined angular 5 I have the following html form in angular
<form (ngSubmit)="signin()" #signinform="ngForm">

        Email:

          <input type="email"
                 class="form-control"
                 id="signinemail"
                 name="signinemail"
                 ngModel
                 placeholder="Email">

        Password:

          <input type="password"
                 class="form-control"
                 id="signinpassword"
                 name="signinpassword"
                 ngModel
                 placeholder="Password">

          <input class="form-check-input ml-0"
                 type="checkbox"
                 id="gridCheck"
                 name="remembercheckbox"
                 ngModel>

                Remember Me

        Forget Password?

        <button type="submit" class="btn btn-primary">Sign In</button>
        <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>

    </form>

and the following typescript for the form:
import {NgForm} from "@angular/forms";
@ViewChild('signinform') signinform: NgForm;
  signin() {
    let payload = {
      email: this.signinform.form.value.signinemail,
      password: this.signinform.form.value.signinpassword,
      localstorage: this.signinform.form.value.remembercheckbox
    };
    this.userservice.gettoken(payload);
    this.signedin = true;
  }

I have compared this to other forms I have built and yet there is no difference. What could be causing this?
the form element is on the dom when I call. The submit button is within the form. The @ViewChild element syntax is correct and properly imported. I truly don't understand and I am ready to punch a baby.

A: The code looks fine...You could just try not using view child, and instead do:
<form (ngSubmit)="signin(signinform)" #signinform="ngForm">

  signin(form: NgForm) {
    console.log(form);
  }

I'd definitely try that console though, to make sure the form is being submitted properly.


text:
Q: Installing a Package that asks debconf questions doesn't work with the Software-Center I am building an automatic configure Package for our environment and it has to ask a few debconf questions when installing. Until Ubuntu 13.10 it was no problem installing it via the GUI but since 14.04 the Software-Center just hangs when installing.
After installing libgtk2-perl separately this is no longer a problem and the questions are getting asked.
Is this a Bug in the Software-Center or how am I supposed to handle it?
My current workaround is a Pre-Depends on libgtk2-perl but this shouldn't be the final solution and sucks for people installing it via Terminal.


text:
Q: splitting csv files in pandas on python I am trying to load a spec column in pandas but it keep printing me the name of the column and also it skips the first part
can anyone help me?
this is the code i am using:
import pandas as pd

pd.set_option('display.max_colwidth', -1)

df_iter = pd.read_csv('tweets.csv', chunksize=10000, iterator=True, usecols=["text"])

df_iter = df_iter[1:]

   for iter_num in enumerate(df_iter, -1):

      for line in df_iter:

         print(line)

A: Firstly,
Since you are reading the csv in chunks, I would assume that the file is very large. You need to loop through those chunks to read all the data of the file. Then you can merge / concatenate all these chunks.
Second thing, enumerate() is not for dataframes. You need iterrows().
Something like this -
import pandas as pd
pd.set_option('display.max_colwidth', -1)
df_iter = pd.read_csv('tweets.csv', chunksize=10000, iterator=True, usecols=["text"])
df_records = [] #list
for chunk in df_iter:
    df_records.append(chunk)

df_new = pd.concat(df_records)
for iter_num, value in df_new.iterrows():
    print(value[0])


text:
Q: javascript can't find iframe after reload I'm not asking for a solution, because I solved the problem. This is more of a 'why did it happen'? Understanding is at the root of everything, and I can't figure out why it happened.
I have a web page with two layered div's (Div 1 and Div 2).
Div1 displays a button, when clicked Div 2 appears, containing a form and an iframe (named 'myframe').
When the user clicks 'cancel' in Div 2, Div 2 is emptied and it disappears, showing Div 1 again.
Everything is loaded using Ajax and PHP.
My problem:
The first time I click the button in Div 1, everything displays fine and - most important - I can acces the iframe with javascript.
Both
var b=window.frames['myframe']
and
var b=window.frames[0]

result in alert(b.name) displaying 'myframe'.
The strange thing is however when I cancel Div 2 (empty it and hiding it) and then pressing the button in Div 1 again, using exactly the same code, gives me 'NULL' in javascript when referring to the iframe.
I've checked the DOM, Div 2 is really empty after cancelling and the iframe is there the second time, displaying it's contents correctly, so why isn't javascript picking it up? I've tried waiting for a few minutes before hitting the button again, loading another page in Div 2 first, but it didn't work.
My solution is adding the time to the iframe-name, thus giving it a unique name everytime it loads. This works fine, now javascript can acces the iframe even after a 'cancel'.
My question is: why, when using a static name, can't js find the iframe the second time?
the contents of div 2 is:
//THE FORM
<form id="myform" name="myform" class="myform" action="" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="" onkeypress="return keyCheck(event)">
// some form stuff
</form>
<iframe src='imbo/php/system_fotohidden.php' id='myframe' name='myframe'></iframe>

and the javascript:
function click(){
    var b=window.frames['myframe'];
    alert(b.name);
    }

[EDIT]
Maybe to clarify what I'm doing with the div's:

*

*click button 'loadform' in Div 1

*Ajax loads a page with Form and Iframe in Div 2 (it all display's nice)

*acces the Iframe in div 2 with JS => JS finds the Iframe and pops up it's name

*cancel the form: JS => div2.innerHTML='' and div2.style.display='none'

*click button 'loadform' in Div 1

*Ajax loads the exact same page with Form and Iframe in Div 2 (it still display's nice)

*acces the Iframe in div 2 with JS => JS gives NULL instead of the Iframe-name

A: By setting the element innerHTML property to "" you delete all of its children, so they no longer exist. You can't refer to them, neither by name nor by document.frames, nor anything else.
To hide DIV element you can use DIV.style.visibility='hidden';.
Here is an example fiddle http://jsfiddle.net/ptFwE/1/; you can see that childNodes property of the div says there are no children in the DIV after setting innerHTML to the empty string.
If you need this div for other purposes consider setting visibility of IFRAME to hidden only or use another DIV.


text:
Q: Anyway to make Adobe Air Application keeping the socket open until download finish? I'm creating the Adobe Air Application working as Web browser to show the Flex Application as Flash won't be supported by any browser anymore this end of the year.
But there is a file download function in Flex Application called by using ActionForm like below url

http://localhost:8080/project/action/create

then file will be written in ResponseOutputStream like the code below.
public void download(Inputstream in, HttpServletResponse response) throws IOException
{
    OutputStream out = null;
    try
    {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"dummy.pdf\"");
        out = response.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while((len = in.read(buffer,0,1024)) != -1) { out.write(buffer,0, len); }
    }
    catch (SocketException e)
    { ...

There is no problem if I use any browser to download the file but this exception has been caught if I use Air Application to download.

java.net.SocketException: Software caused connection abort: socket
write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:741)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:432)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:347)
at org.apache.coyote.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:765)
at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:126)
at org.apache.coyote.http11.InternalOutputBuffer.doWrite(InternalOutputBuffer.java:574)
at org.apache.coyote.Response.doWrite(Response.java:560)
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:353)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:432)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:347)
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:381)
at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:370)
at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:89)

Problem:
I think that after /action/create url is called, air application closed the socket so ResponseOutputStream won't be able to connect to socket.
Is there anyway to keep Air Application open its socket until response has been received ?
I'm trying to keep Flex Application code untouch and this is my first time create Application using Air.
or if the socket is not the real cause, is there anyway I can send back this response to Air Application?
Thank you for your answer in advance.


text:
Q: Castle Windsor assembly versioning and MSTest We have a solution that relies on Castle Windsor with some projects referencing 3.0 and some 3.1.
The tests need Windsor 3.1, but the final project to be built references 3.0, which means that it the last version copied into the OutDir folder.  This results in all our tests failing in MSTest but not locally.
Is there any way to force the tests to run using the 3.1 versions or will we need to update all projects in the solution?


text:
Q: The text in a JTextArea is not updating I find that my code does not update the text in a JTextArea.  I create a frame and add a couple of panels.  One of the panels contains my JTextArea.  Initially I set is as " ".  Then later on a button click, amongst other code, I update the JTextArea.  However, the update does not show up on the screen.
Here are snippets of my code:
static JFrame window = new JFrame("Valedictorian Voting System");
static JTextArea voteNotification = new JTextArea(" ");

static JPanel options = new JPanel();
static JPanel options1 = new JPanel();
static JPanel options2 = new JPanel();

Then in my main():
ImageIcon header;
ImageIcon side;
ImageIcon side2;
Image image = new ImageIcon("src\\Header_MICHS.jpg").getImage();
header = new ImageIcon(image.getScaledInstance(290, 55, java.awt.Image.SCALE_SMOOTH));
Image image2 = new ImageIcon("src\\lightningbolt2.png").getImage() ;
side = new ImageIcon(image2.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH));
Image image3 = new ImageIcon("src\\lightningbolt.png").getImage() ;
side2 = new ImageIcon(image3.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH));
JLabel sideLabel2 = new JLabel(side2);
JLabel sideLabel = new JLabel(side);
JLabel headerLabel = new JLabel(header);

//bottom bar add - the text field and Jbutton
JPanel studentInfo = new JPanel();
studentInfo.setLayout(new GridLayout(1,2));
studentInfo.add(studentNumber);
studentInfo.add(studentNumButton);

//add the val radio buttons to a panel
JPanel options1 = new JPanel();
options1.setLayout(new GridLayout(val2.length,0));
for(int i=0; i<val2.length;i++){
  options1.add(val2[i]);
}

//add the message box to a panel

options2.setLayout(new GridLayout(1,0));
options2.setBackground(Color.WHITE);
options2.add(voteNotification);

//add the panels to a panel

options.setLayout(new GridLayout(1,2));
options.add(options1);
options.add(options2);

//put the functional things into one panel
JPanel setup = new JPanel();
setup.setLayout(new BorderLayout());
setup.add(options, BorderLayout.CENTER);
setup.add(studentInfo, BorderLayout.SOUTH);

//put the pictures around the functional things
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(setup, BorderLayout.CENTER);
content.add(headerLabel, BorderLayout.NORTH);
content.add(sideLabel, BorderLayout.EAST);
content.add(sideLabel2, BorderLayout.WEST);

window.setLayout(new BorderLayout());
window.add(content, BorderLayout.CENTER);
window.setContentPane(content);
window.setSize(300,310);
window.setLocation(550,250);
window.setVisible(true);
window.setResizable(false);

This all works.  But when I click on the "Voted" button...everything works except the JTextArea is not updated.
public static boolean checkSelected(){
   stillVotable = checkNum();
   boolean selected = false;
   for(int i = 0; i<numVals; i++){
     if(val2[i].isSelected() && stillVotable==true){
        votes[i] +=1;

        voteNotification.setText("Student No.: " + studentNumber.getText() + " voted for: " + val.get(i));
        options2.repaint();

        System.out.println("Voted for " + val.get(i) + ":" + votes[i]);
        selected = true;
        checkWinner();//checks to see if someone won
        return true;
      }
    }
    if(selected==false && stillVotable==true)
      JOptionPane.showMessageDialog(null, "You have not selected a Valedictorian!");
    else
      selected=false;
    return false;
  }

I am worried that it has to do with threading as I have not understood the descriptions in some of the other posts...
Here is all of the code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class StandaloneGUIVotingSystem/* extends JApplet*/{

  static JFrame window = new JFrame("Valedictorian Voting System");
  static HintTextField studentNumber = new HintTextField("Enter student #!");
  static JTextArea voteNotification = new JTextArea("This is where your confirmation message will show up.");
  static ButtonGroup studentGroup;
  static JRadioButton[] val2;
  static int[] votes;

  static JPanel options = new JPanel();
  static JPanel options1 = new JPanel();
  static JPanel options2 = new JPanel();

  static CreateFile creator = new CreateFile();
  static FileHandling fileH = new FileHandling();

  static int studentsVoting = 0;
  static int numVals = 0;
  static int studentsVoted = 0;
  static boolean stillVotable = false;
  static String filePath = "src//";

  static DynamicArrayOfString studentNum = new DynamicArrayOfString();
  static DynamicArrayOfString val = new DynamicArrayOfString();

  //Window window; applet stuff

  //checks the student number entered to confirm a valid vote from a student that has not voted

  public static boolean checkNum(){
    for(int i = 0; i<studentNum.size(); i++){
      if(studentNumber.getText().equals(studentNum.get(i))){
        return true;
      }
    }
    JOptionPane.showMessageDialog(null, "This is not a valid student number. Please enter a different one!");
    return false;
  }

  //checks to see if the user has selected a radio button

  public static boolean checkSelected(){
    stillVotable = checkNum();
    boolean selected = false;
    for(int i = 0; i<numVals; i++){
      if(val2[i].isSelected() && stillVotable==true){
        votes[i] +=1;

        voteNotification.setText("Student No.: " + studentNumber.getText() + " voted for: " + val.get(i));
        options2.repaint();

        System.out.println("Voted for " + val.get(i) + ":" + votes[i]);
        selected = true;
        checkWinner();//checks to see if someone won
        return true;
      }
    }
    if(selected==false && stillVotable==true)
      JOptionPane.showMessageDialog(null, "You have not selected a Valedictorian!");
    else
      selected=false;
    return false;
  }

  //resets the screen for the next user

  public static void clear(){
    studentNumber.setText("");
    studentGroup.clearSelection();
    studentNumber.showHint();
    voteNotification.setText("");
  }

  public static void write(){
    //write winner file
    CreateFile.openFile("Winner.txt");
    CreateFile.addToFile("The Results of the Voting Contest are:");
    for(int i = 0; i < val.size(); i++){
      CreateFile.addToFile(val.get(i) + " has " + votes[i] + " votes.");
    }
    CreateFile.closeFile();

    //write voter file
    CreateFile.openFile("Voters.txt");
    for(int i = 0; i < studentNum.size(); i++){
      CreateFile.addToFile(studentNum.get(i));
    }
    CreateFile.closeFile();
  }

  //removes the person who voted from the text file so they can only vote once
  public static void removeVoted(){
    for(int i = 0; i < val.size(); i++){
      if(studentNumber.getText().equals(studentNum.get(i))){
        studentNum.remove(i);
        studentsVoted++;
      }
    }
  }

  //checks if there is a winner and finishes program if there is
  public static void checkWinner(){

  if (studentsVoted == studentsVoting){
      int j=0;
      int largest = votes[0];
      for(int i = 1; i < votes.length; i++){
        if(votes[i] > largest){
          largest = votes[i];
          j = i;
        }
      }
      CreateFile.openFile("Winner.txt");
      CreateFile.addToFile("The Results of the Voting Contest are:");
      for(int i = 0; i<val.size();i++){
        CreateFile.addToFile(val.get(i) + " has " + votes[i] + " votes.");
      }
      CreateFile.addToFile("\n");
      CreateFile.addToFile("Therefore, the winner is...");
      CreateFile.addToFile("");
      CreateFile.addToFile("");
      CreateFile.addToFile("");
      CreateFile.addToFile(val.get(j) + " wins!");
      CreateFile.closeFile();
      System.exit(0);
    }
  }

  //retrieves the initial information
  public static void retrieve(){
    //takes the student numbers and adds them to the dynamic array called studentNum
  fileH.openFile("Voters.txt");
    fileH.readFile();
    studentsVoting = fileH.length();
    for(int i = 0; i<studentsVoting;i++){
      studentNum.put(i, fileH.get(i));
    }
    fileH.closeFile();

    //gets the valedictorian names and puts them in the array val
    fileH.openFile("Valedictorians.txt");
    fileH.readFile();
    numVals = fileH.length();

    //for testing
    System.out.println(numVals);

    for(int i = 0; i < numVals;i++){
      val.put(i, fileH.get(i));

      //for testing
      System.out.println(val.get(i));
    }
      val2 = new JRadioButton[numVals];
      votes = new int[numVals];

    fileH.closeFile();

    //takes the number of votes and places them in the votes array
    fileH.openFile("Winner.txt");
    fileH.readFile();
    int h = 0;
    for(int i = 9; i<fileH.length(); i += 4){

        System.out.println(fileH.get(i));

        votes[h]= Integer.parseInt(fileH.get(i));

      //for testing
      System.out.println("Votes for:" + val.get(h) + " are: "+ votes[h]);

      h++;
    }
    fileH.closeFile();

  }

  //if the user hits the vote button this method will run the steps needed to accomplish that goal
  public static void voted(){
    checkSelected();//checks student number, and adds a vote to the person selected
    removeVoted(); // removes the person who voted so that each person can only vote once

    clear();//clears the studentNumber and val selected
    write();// writes the updated info to the files Voters and Winner
    checkWinner(); //checks to see if the vote was the last

  }

  public static void main(String[] args){
    retrieve();

    studentGroup = new ButtonGroup();

    //initalizes the names of each val on to radio buttons
  //adds each radio button to the button group and sets the background to white for a clear gui look
    for(int i = 0; i<numVals;i++){
      val2[i] = new JRadioButton(val.get(i));
      studentGroup.add(val2[i]);
      val2[i].setBackground(Color.WHITE);
    }

    voteNotification.setEditable(false);

    //vote button - allows the user to let the program know that they are done entering their student number and selecting a person for their vote
    JButton studentNumButton = new JButton("Vote!");
    studentNumButton.addActionListener(new SelectionCounter());

//this code could be added to show a picture of each valedictorian *******EXTRA************
    // John.setRolloverEnabled(true);
    // John.setRolloverIcon(icon);

    //images
    //int NEW_WIDTH = 50;
    //int NEW_HEIGHT = 235;
    //int NEW_WIDTH2 = 290;
    //int NEW_HEIGHT2 = 55;

    ImageIcon header;
    ImageIcon side;
    ImageIcon side2;
    Image image = new ImageIcon("src\\Header_MICHS.jpg").getImage();
    header = new ImageIcon(image.getScaledInstance(290, 55, java.awt.Image.SCALE_SMOOTH));
    Image image2 = new ImageIcon("src\\lightningbolt2.png").getImage() ;
    side = new ImageIcon(image2.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH));
    Image image3 = new ImageIcon("src\\lightningbolt.png").getImage() ;
    side2 = new ImageIcon(image3.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH));
    JLabel sideLabel2 = new JLabel(side2);
    JLabel sideLabel = new JLabel(side);
    JLabel headerLabel = new JLabel(header);

    //bottom bar add - the text field and Jbutton
    JPanel studentInfo = new JPanel();
    studentInfo.setLayout(new GridLayout(1,2));
    studentInfo.add(studentNumber);
    studentInfo.add(studentNumButton);

    //add the val radio buttons to a panel
    JPanel options1 = new JPanel();
    options1.setLayout(new GridLayout(val2.length,0));
    for(int i=0; i<val2.length;i++){
      options1.add(val2[i]);
    }

    //add the message box to a panel

    options2.setLayout(new GridLayout(1,0));
    options2.setBackground(Color.WHITE);
    options2.add(voteNotification);

    //add the panels to a panel

    options.setLayout(new GridLayout(1,2));
    options.add(options1);
    options.add(options2);

    //put the functional things into one panel
    JPanel setup = new JPanel();
    setup.setLayout(new BorderLayout());
    setup.add(options, BorderLayout.CENTER);
    setup.add(studentInfo, BorderLayout.SOUTH);

    //put the pictures around the functional things
    JPanel content = new JPanel();
    content.setLayout(new BorderLayout());
    content.add(setup, BorderLayout.CENTER);
    content.add(headerLabel, BorderLayout.NORTH);
    content.add(sideLabel, BorderLayout.EAST);
    content.add(sideLabel2, BorderLayout.WEST);

    window.setLayout(new BorderLayout());
    window.add(content, BorderLayout.CENTER);
    window.setContentPane(content);
    window.setSize(300,310);
    window.setLocation(550,250);
    window.setVisible(true);
    window.setResizable(false);
  }
  private static class SelectionCounter implements ActionListener{
    public void actionPerformed(ActionEvent e){
      voted();
    }
  }//end of SelectionCounter class

  public static class FileHandling{
    private Scanner file;
    static DynamicArrayOfString temp;
    String name;

    public void openFile(String name){
      try{
        file = new Scanner(new File(filePath + name)); //gets name=file u want to read
      }
      catch(Exception e){
        System.out.println("Could not find file!");
      }
    }

    public void readFile(){ // retrieves one input from the file for each line
        temp = new DynamicArrayOfString();
      for(int i = 0; file.hasNext(); i++){
        temp.put(i,file.next());
       System.out.printf("%s%n", temp.get(i));
      }
    }

    public int length(){
      return temp.size();
    }

    public boolean hasNext(){
      return file.hasNext();
    }

    public String get(int position) {
      if (position >= temp.size())
        return "Nothing";
      else{
        String answer = temp.get(position);
        //System.out.println(temp.get(position));
        return answer;
      }
    }

    public void closeFile(){
      file.close();
    }
  }//end of FileHandling

  private static class CreateFile{
    private static Formatter file2;

    public static void openFile(String name){
      try{
        file2 = new Formatter(filePath + name);
      }
      catch(Exception e){
        System.out.println("you have an error");
      }
    }
    public static void addToFile(String number){
      file2.format("%s%n", number);
    }
    public static void closeFile(){
      file2.close();
    }
  }//end of CreateFile

  static class HintTextField extends JTextField implements FocusListener {

    private final String hint;
    private boolean showingHint;

    public HintTextField(final String hint) {
      super(hint);
      this.hint = hint;
      this.showingHint = true;
      super.addFocusListener(this);
    }

    public void focusGained(FocusEvent e) {
      if(this.getText().isEmpty()) {
        super.setText("");
        showingHint = false;
      }
    }

    public void focusLost(FocusEvent e) {
      if(this.getText().isEmpty()) {
        super.setText(hint);
        showingHint = true;
      }
    }

    public String getText() {
      return showingHint ? "" : super.getText();
    }
    public void showHint(){
      super.setText(hint);
    this.showingHint=true;
    }

A:
One of the panels contains my JTextArea. Initially I set is as " ".

What happens if you initially set the text area with some text? Do you see the text?
I'm guessing you don't see the text because of the way you created the textarea:
static JTextArea voteNotification = new JTextArea(" ");

Maybe try:
static JTextArea voteNotification = new JTextArea(2, 30);

so the text area has a reasonable preferred size.


text:
Q: How can I force intellij to check all files? When I'm using intellij sometimes I do very large refactors that the IDE can't help with. This often breaks a lot of files, but since I'm using either Typescript or Java it's relatively easy to find the problems.
My issue is that I can't seem to get Intellij to check those files unless I open them specifically.
The kind of checking I'm talking about isn't a specific inspection, it's just like the normal compilation problems.
So for example, I have a typescript project and I modified some stuff. When I open some of my React components intellij waits a second, and then highlights parts of it in red. I can go to those parts and see what the issue is.
I've tried forcing the inspector to run, and I've tried building the project, but neither one gives me the red squiggly love I need :^(
It feels like the project->build should force intellij to highlight all this stuff, but it seems to have no effect.


text:
Q: .NET Progressbar looks different in the designer than it does when program is running Does anyone know what my progress bar looks different in the Visual Studio designer than it does when i build and run my project?
In the designer i see the newer style. Progress is indicated with a solid green line with smoothed edges.
When I run my project the progress bar looks like the old style one. It has ten separate divisions that are blue rectangles.
Why the difference?

A: Make sure EnableVisualStyles is called before your form is loaded. This is usually in the program class before Application.Run.
Application.EnableVisualStyles();

A: Progress bars can have several different styles (as you have seen). While the designer should reflect the current style of the bar, it's possible it is simply showing a default style, while the progress bar is actually set to a different style.
You can change the ProgressBar.Style property on the progress bar to control this. You can set it to: Blocks, Continuous or Marquee - see here for the valid values and descriptions.

A: Is it running on a different PC, if so what you are seeing is the difference in windows themes.
If it is on the same machine it is not a behaviour I would have expected to see.


text:
Q: list_price and price_and_currency are empty but product page shows price I'm trying to get price info for amazon product with ASIN: B00BVRV8H0 using python-amazon-simple-product-api wrapper (https://github.com/yoavaviram/python-amazon-simple-product-api)
from amazon.api import AmazonAPI

AMAZON_ACCESS_KEY = 'A...Q'
AMAZON_SECRET_KEY = 'L...j'

amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, aws_associate_tag = 'test')
product = amazon.lookup(ItemId='B00BVRV8H0')

print(product.list_price)
print(product.price_and_currency)

Gives:
(None, None)
(None, None)

For this ASIN I get both list_price and price_and_currency equal to (None, None), but when I visit product page (https://www.amazon.com/Smoke-Pickles-Recipes-Stories-Southern-ebook/dp/B00BVRV8H0) I see price.
How can I get it using this api wrapper? For other products it works fine.


text:
Q: Trying to change custom dialog Background color Ok so I am trying change my background of my dialog box from white to a dark blue. However when I long press on one of the grid elements the dialog box looks like this:

I am trying to make it look something like this (this is a photoshop):

Here is snipet of my XML code for the edit dialog
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:background="@color/customBG">

Java code for custom dialog
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.edit_game_dialog,null);

    editTitle = view.findViewById(R.id.editTitle);
    editTitle.setText(currentTitle);
    imageView = view.findViewById(R.id.item_image_dialog);
    imageView.setImageResource(currentImage);
    changeImageBt = view.findViewById(R.id.change_image);

    changeImageBt.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {

        }
    });

    builder.setView(view).setTitle("Edit game")
            .setPositiveButton("Apply Changes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {
                    String title = editTitle.getText().toString();
                    int image = R.drawable.blank; //PLACE HOLDER CODE
                    editGameDialogListener.applyChanges(pos,title,image);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {

                }
            });

    return builder.create();
}

A: I think you should use Dialog instead of AlertDialog.
Alert Dialog has its own Title and Button.
With Dialog you will have the benefit of defining your Title and Buttons.
Create a Layout as your design needs and set it in Dialog.
class ABC(context: Context) : Dialog(context) {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.your_custom_layout)
}
}

A: When you create your dialog, you can pass theme as a second param
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyDialogTheme);

and set the custom theme to override anything you need. For background color something like this should work:
<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:background">@color/customBG</item>
</style>


text:
Q: ionic 2 angular 2 payment hi i want internal pay in my app.
in my web site i use

    <input type="hidden" name="token" value="{{pasargadModel.clientToken}}" />

    <input type="hidden" name="merchantId" value="{{pasargadModel.merchantId}}" />

    <input type="hidden" name="PaymentId" value="{{pasargadModel.PaymentId}}" />

    <button androidButton class="btn btn-primary nexus" type="submit">
        <i class="fa fa-credit-card"></i>
        اتصال به درگاه
    </button>

</form>

and worked for my. but in my app not working


text:
Q: Where should be placed htaccess file in Prestashop 1.4x? my Prestashop 1.4x installed in a subdirectory, eg: http://mydomain.com/prestashop/
on Apache server.
There is option to generate Htaccess file from admins, which are copied into the /prestashop/ directory. Is it correct location or I should put htaccess into parent(root) directory?
example:
# .htaccess automaticaly generated by PrestaShop e-commerce open-source solution
# WARNING: PLEASE DO NOT MODIFY THIS FILE MANUALLY. IF NECESSARY, ADD YOUR SPECIFIC CONFIGURATION WITH THE HTACCESS GENERATOR IN BACK OFFICE
# http://www.prestashop.com - http://www.prestashop.com/forums

<IfModule mod_rewrite.c>
# URL rewriting module activation
RewriteEngine on

# URL rewriting rules
RewriteRule ^([a-z]{2})/([0-9]+)\-[a-zA-Z0-9-]*\.html /store/product.php?id_product=$2&isolang=$1 [QSA,L]
... ... ...
... ... ...
RewriteRule ^en/best-sales$ /store/best-sales.php?isolang=en [QSA,L]
RewriteRule ^en/page-not-found$ /store/404.php?isolang=en [QSA,L]
</IfModule>

# Catch 404 errors
ErrorDocument 404 /store/404.php

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/javascript "access plus 1 week"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-javascript "access plus 1 week"
    ExpiresByType image/x-icon "access plus 1 year"
</IfModule>

FileETag INode MTime Size
<IfModule mod_deflate.c>
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE text/html text/css text/plain text/javascript application/javascript application/x-javascript
    </IfModule>
</IfModule>

A: It is correct location for http://mydomain.com/store/


text:
Q: Can't assign values to array of structs ansi c Hi have defined this struct typdef:
typedef struct{
        int pid;
        int valor;
    }hijo;

But after reserving memory to it, I iterate the array to assign value to each struct, but values are not stored correctly:
hijo *retorno;
retorno=malloc(processes*sizeof(hijo));

while (processes > 0) {
        pid = wait(&status);
        int valors = WEXITSTATUS(status);
        retorno[i].valor=valors;
        retorno[i].pid=pid;
        --processes;  // TODO(pts): Remove pid from the pids array.
    }

Thanks.

A: You need to initialize and increment i. Otherwise you keep assigning to the same array element.
hijo *retorno;
retorno=malloc(processes*sizeof(hijo));
int i = 0;

while (processes > 0) {
    pid = wait(&status);
    int valors = WEXITSTATUS(status);
    retorno[i].valor=valors;
    retorno[i].pid=pid;
    --processes;  // TODO(pts): Remove pid from the pids array.
    i++;
}

Or instead of updating two variables, you could just compare i to processes:
for (int i = 0; i < processes; i++) {
    pid = wait(&status);
    int valors = WEXITSTATUS(status);
    retorno[i].valor=valors;
    retorno[i].pid=pid;
}

A: With this code, you are decremanting processes and you want assign value to retorno I guess.
Then retorno[i] should be retorno[processes] right ?
Otherwise I don't understand what you want to do.


text:
Q: WP_Query Filtred by author name ( Return null ) I want to list all pages whose author has a specific name but WordPress returns null values
$args = array(
    'author_name '=> 'admin',
    'post_type'=>'page'
);

$pages = new WP_Query( $args );

foreach( $pages as $page ) {
    var_dump( $page->post_title );
}

result is
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL string(4) "test" NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL

A: That's not how WP_Query works, it isn't what the documentation says either. WP_Query is not a function.
foreach needs an array, or something that can be iterated on, but you've given it a WP_Query object.
Instead, look at the documentation or tutorials, all of them follow this basic pattern for a standard post loop:
$args = [
    // parameters go here
];
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // display the post
        the_title();
        the_content();
    }
    wp_reset_postdata();
} else {
    echo "no posts were found";
}


text:
Q: C# equivalent for Delphi's in What is the equivalent in C# for Delphi's in syntax, like:

  if (iIntVar in [2,96]) then
  begin
    //some code
  end;

Thanks

A: I prefer a method like defined here: Comparing a variable to multiple values
Here's the conversion of Chad's post:
public static bool In(this T obj, params T[] arr)
{
    return arr.Contains(obj);
}

And usage would be
if (intVar.In(12, 42, 46, 74) )
{
    //TODO: Something
}

or
if (42.In(x, y, z))
    // do something

A: There is no such equivalent. The closest is the Contains() extension method of a collection.
Example:
var vals = new int[] {2, 96};
if(vals.Contains(iIntVar))
{
  // some code
}

A: In .Net, .Contains is the closest, but the syntax is the opposite of what you wrote.
You could write an extension method to be able to create a .In method
public static bool In<T>(this T obj, IEnumerable<T> arr)
 {
  return arr.Contains(obj);
 }

And usage would be
if (42.In(new[] { 12, 42, 46, 74 }) )
{
    //TODO: Something
}

A: You can create this extension method:
public static class ExtensionMethods
{
    public static bool InRange(this int val, int lower, int upper)
    {
        return val >= lower && val <= upper;
    }
}

then you can do this:
int i = 56;
if (i.InRange(2, 96)) { /* ... */ }

A: To expand upon what Mason Wheeler wrote in a comment, this would be HashSet<T>.Contains (under .NET 3.5).
int i = 96;
var set = new HashSet<int> { 2, 96 };

if (set.Contains(i))
{
   Console.WriteLine("Found!");
}

A: You could write an extension method
 public static bool In(this int value, int[] range)
    {
        return (value >= range[0] && value <= range[1]);
    }


text:
Q: Date pattern in java regex I make one function Datepattern which contain array list and am adding date pattern regex
My code is as below
private ArrayList getDatePatterns() {
        ArrayList alDate = new ArrayList();
    //Thursday, the 7th December, 2006.00
    alDate.add("\\b(?i)(monday|tuesday|wednesday|thursday|friday|saturday|sunday)[ ]*[,][ ]*(the)[ ]*[0-9]+(st|th|rd|nd)?[ ]*(Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[t]?[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]*[,][ ]*[0-9]+\\b");

    //Examples: 24th July to 3rd August, 2007  24 July to 3 August, 2007
    alDate.add("\\b(?i)(?:0?[1-9]|[12][0-9]|3[01])(st|th|rd|nd)?([ ])?(Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[t]?[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]?(to)([ ])?(0?[1-9]|[12][0-9]|3[01])(st|th|rd|nd)?([ ])?(Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[t]?[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]*[\\,]?([ ])*([0-9]+)?\\b");

  //Examples: 1.4.94-to-25.1.95
   // alDate.add("\\b(?i)[0-9]+[ ]*[.][ ]*[0-9]+[ ]*[.][ ]*[0-9]+[ ]*[.][ ]*(to)[ ]*[0-9]+[ ]*[.][ ]*[0-9]+[ ]*[.][ ]*[0-9]+\\b");

    //Examples: 9th & 12th August,   9th and 12th August, 2008 9th to 12th August, 2008 9th/12th August, 2008 9th-12th August, 2008
  ////////  alDate.add("\\b(?i)(?:(from)?([ ])?0?[1-9]|[12][0-9]|3[01])[ ]*(st|th|rd|nd)?([ ])?(and|to|\\/|[\\-]|&)([ ])?(0?[1-9]|[12][0-9]|3[01])[ ]*(st|th|rd|nd)?([ ])?(of)?([ ])?(Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[t]?[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]*[\\,]*([ ])?([0-9]+)?\\b");

    //Example : 28th July 28 July 24 July 2007 24-July-2007 24th July, 2007 24 July, 2007 24th day of July, 2007  21st of May, 2008

    alDate.add("\\b(?i)(Letter No[.]?[ |-])?(?:0?[1-9]|[12][0-9]|3[01])([\\-]|[ ])?(st|th|rd|nd)?([ ])?(day[ ]of[ ])?(of[ ])?(Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[t]?[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)([ ]?[\\,]?([\\-]|[ ])?([0-9]+))\\b");

    //Example :  August 24,  07; November 26-30, 2007
    alDate.add("\\b(?i)(?:Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[.]?|Sept[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]?((0?[1-9]|[12][0-9]|3[01])[ ]?[-][ ]?)?(0?[1-9]|[12][0-9]|3[01])([ ])?[\\,]([ ])?([0-9]+)?\\b");

    //June 08 and June 2008; May'08 and June'08
    alDate.add("\\b(?i)(?:Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[.]?|Sept[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]?([\\,\\'])?([ ])?([0-9]+)?[ ]*(and)[ ]*(?:Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[.]?|Sept[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]?([\\,\\'])?([ ])?([0-9]+)?\\b");
    //Example : March, 2009;  March 2009; June-April, 2008
    alDate.add("\\b(?i)((?:Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[.]?|Sept[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]?[-][ ]?)?(?:Jan[.]?|January|Feb[.]?|February|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[.]?|Sept[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)[ ]?([\\,])?([ ])?[0-9]+\\b");

    //Examples: from dd-mm-yy to    dd-mm-yy  dd/mm/yy ,  dd.mm.yy   etc
  //  alDate.add("\\b(?i)(i[.]e[.]|viz[.]|means)\\s(from[ ])(0?[1-9]|[12][0-9]|3[01])([\\.]|[\\-]|[ \\/])+(?:0?[1-9]|1[0|1|2])([\\.]|[\\-]|[ \\/])+[0-9]+([ ]to[ ])(?:0?[1-9]|[12][0-9]|3[01])([\\.]|[\\-]|[ \\/])+(?:0?[1-9]|1[0|1|2])([\\.]|[\\-]|[ \\/])+[0-9]+\\b");
  //  alDate.add("\\b(?i)(from[ ])(0?[1-9]|[12][0-9]|3[01])([\\.]|[\\-]|[ \\/])+(?:0?[1-9]|1[0|1|2])([\\.]|[\\-]|[ \\/])+[0-9]+([ ]to[ ])(?:0?[1-9]|[12][0-9]|3[01])([\\.]|[\\-]|[ \\/])+(?:0?[1-9]|1[0|1|2])([\\.]|[\\-]|[ \\/])+[0-9]+\\b");

    // 28th Feburary
    alDate.add("\\b(?i)(the)?[ ]*[0-9]+(st|th|rd|nd)?[ ]*(Jan[.]?|January|February|Feb[.]?|Mar[.]?|March|Apr[.]?|April|May|Jun[.]?|June|Jul[.]?|July|Aug[.]?|August|Sep[t]?[.]?|September|Oct[.]?|October|Nov[.]?|November|Dec[.]?|December)");

    //Examples: dd-mm-yy    , dd/mm/yy ,  dd.mm.yy   etc
    alDate.add("\\b(?i)(?:0?[1-9]|[12][0-9]|3[01])([\\.]|[\\-]|[ \\/])+(?:0?[1-9]|1[0|1|2])([\\.]|[\\-]|[ \\/])+[0-9]+\\b");

    //2002-2003
    //alDate.add("\\b([0-9]+[\\-][0-9]+)\\b");
    return alDate;
}

Instead of this i Want one single regex that satisfies all the above conditions.In comment for more understanding I mentioned the date pattern that regex follows.
 any one help me I want to write one single regex for date pattern instead of this large code.
I want to reduce the code.
Thank u

A: Don't use RegEx for date parsing, use SimpleDateFormat. :-)

A: Unfortunately your question is very vague about what you want to achieve with your code. To me it sounds like you want to parse date strings in different formats and maybe convert them to a Date object as in DateFormat.parse(String).
Edit: I'm almost completely sure, regular expressions aren't the right tool for the task your code is trying to perform, but that you don't want to reveal for some reason. I'm quite sure, you are trying to re-implement a solution to a common and delicate problem with a shitload of pitfalls especially concerning internationalisation. Usually these can be solved with a small set of library functions which preserve the programmer (you), the future maintainer of this mess, and the (prospecting) users of the application from dealing with the aforementioned problems and their consequences.
In any way, glueing the REs together will make it even less readable/maintainable.


text:
Q: Creating SessionMgr instance for crystal reports throws error I am using below code to connect to a SAP cms server to get the reports from it.
using CrystalDecisions.Enterprise;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string username = "user";
            string password = "pwd";
            string server = "srv_name";
            string auth_type = "authType";
            // logon
            SessionMgr session_mgr = new SessionMgr();
            EnterpriseSession boEnterpriseSession = session_mgr.Logon(username , password, server, auth_type);

            //boInfoStore = (IInfoStore)boEnterpriseSession.getService("InfoStore");

            //boInfoStore = (IInfoStore)boEnterpriseSession.GetService("InfoStore");

            // get the serialized session
            //string session_str = session.SerializedSession;
            // pass the session to our custom bypass page on the CRS

        }
    }

But I am getting below mentioned error while executing following line of code : SessionMgr session_mgr = new SessionMgr();

An unhandled exception of type
  'System.Runtime.InteropServices.COMException' occurred in
  CrystalDecisions.Enterprise.Framework.dll
Additional information: Retrieving the COM class factory for component
  with CLSID {6670DE06-3F39-4C5D-9238-71FF984D2654} failed due to the
  following error: 80040154 Class not registered (Exception from
  HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

A: According to nobugz's answer here
https://social.msdn.microsoft.com/Forums/vstudio/en-US/88a6ea68-f476-4231-822f-27fabe59f458/error-80040154-retreiving-com-class-factory?forum=vbgeneral
It is suggested that you check the keys in HKCR\CLSID for the GUID. if it is not in there, It may be in another folder(c:\windows\system32...).
The another way is to debug with Regmon.
"It shows you how your app uses the registry.  Run it on yours and run it on the customer's and compare the two".

A: Try:
ISessionMgr sessionMgr = CrystalEnterprise.GetSessionMgr();

IEnterpriseSession enterpriseSession = sessionMgr.Logon("userName", "password", "cmsName", "secEnterprise");

string token = enterpriseSession.LogonTokenMgr.DefaultToken;


text:
Q: Legend problems with 2 y axis in python I have created a 2 y axis plot with the left axis has a bar graph and the right axis has 2 line graphs. I am having difficulty getting the legend to have both the bar and line graphs on it. I can plot the legends separately but I would like to have them together. Here is the work I have done so far.
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data.csv')
x = df["date"]
y1 = df["line 1"]
y2 = df["line 2"]
z = df["bar 1"]
y_pos = np.arange(len(x))

lns1 = plt.bar(y_pos,z)
plt.ylabel('bar 1')
plt.xlabel('date')
plt.legend([lns1], ["bar 1"])
plt.twinx()
lns2 = plt.plot(y_pos,y1,'r-',linewidth=2.5)
lns3 = plt.plot(y_pos,y2,color='orange',linewidth=2.5)
plt.ylabel('L-SLOC')
plt.xticks(y_pos, x)
plt.xlabel('date')
plt.title('Title of graph')

plt.legend(["line 1", "line 2"],loc="upper left")

plt.draw()
plt.show()`

A: Instead of
plt.legend([lns1], ["bar 1"])

and
plt.legend(["line 1", "line 2"],loc="upper left")

You could try this:
plt.legend([lns1, lns2, lns3], ["bar 1", "line 1", "line 2"],loc="upper left")


text:
Q: Facebook Dynamic Product Ads Can somebody help me implemented this script? Any advice is appreciated. Thank You.
For product page:
     <script>
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','//connect.facebook.net/en_US/fbevents.js');
fbq('init', '<FB_PIXEL_ID>');
fbq('track', 'PageView');
fbq('track', 'ViewContent', {
        content_type: 'product',
        content_ids: ['1234'],
        content_name: 'ABC Leather Sandal',
        content_category: 'Shoes',
        value: 0.50,
        currency: 'USD'
    });
    </script>

A:
For cart page you can use the following piece of code:
<?php $quote = Mage::getSingleton('checkout/cart')->getQuote();
$productIds = "";
foreach($quote->getAllItems() as $item):
    if($item->getParentItemId()) continue;
    if (strlen($productIds)==0){
        $productIds = "'".$item->getSku()."'";
    }
    else{
        $productIds = $productIds.",'".$item->getSku()."'";
    }
endforeach;?>

<script>
fbq('track', 'AddToCart', {
     content_name: 'Shopping Cart',
     content_ids: [<?php echo $productIds?>],
     content_type: 'product',
     value: <?php echo number_format($quote->getGrandTotal(),2,'.','');?>,
     currency: '<?php echo Mage::app()->getStore()->getCurrentCurrencyCode();?>'
});
</script>

For purchase or order confirmation page you can use the following
  piece of code -:
<?php $orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
    $order = Mage::getModel('sales/order')->load($orderId);
$productIds = "";
foreach($order->getAllItems() as $item):
    if($item->getParentItemId()) continue;
    if (strlen($productIds)==0){
        $productIds = "'".$item->getSku()."'";
    }
    else{
        $productIds = $productIds.",'".$item->getSku()."'";
    }
endforeach;?>

<script>
fbq('track', 'Purchase', {
     content_name: 'Order Confirmation',
     content_ids: [<?php echo $productIds?>],
     content_type: 'product',
     value: <?php echo number_format($order->getGrandTotal(),2,'.','');?>,
     currency: '<?php echo Mage::app()->getStore()->getCurrentCurrencyCode();?>'
});
</script>

Source:

*

*https://stackoverflow.com/a/33201068/158325

Untested, but should work.  If you are wanting all categories associated you'll need to loop over another collection of the products associated categories to build a list.
<?php $_category = Mage::registry('current_category'); ?>

<script>
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','//connect.facebook.net/en_US/fbevents.js');
fbq('init', '<FB_PIXEL_ID>');
fbq('track', 'PageView');
fbq('track', 'ViewContent', {
        content_type: 'product',
        content_ids: ['<?php echo $this->getProduct()->getEntityId() ?>'],
        content_name: '<?php echo $this->getProduct()->getName() ?>',
        content_category: '<?php echo $_category->getName(); ?>',
        value: <?php echo $this->getProduct()->getFinalPrice() ?>,
        currency: '<?php echo Mage::app()->getStore()->getCurrentCurrencyCode(); ?>'
    });
</script>


text:
Q: Play Audio using jQuery I have a list of Sound Icon images in different divs on my website. I'm trying to use jQuery to play/pause different songs on mouseenter and mouseleave dependent on which icon is hovered over. I have the first item working but am having problems understanding the best way to get the rest working.  Any help with this would be really appreciated. Thanks.
<audio preload="auto" id="songOne">
  <source src="audio/****.mp3" controls></source>
  <source src="audio/****.ogg" controls></source>
  <source src="audio/****.wav" controls></source>
  Your browser isn't invited for super fun audio time.
</audio>

$(document).ready(function(){
  var song1 = $("#songOne")[0];
  $(".topDownloads img").first().mouseenter(function() {
    song1.play();
    $(".topDownloads img").mouseleave(function() {
      song1.pause();
    });
  });
});

A: What you might be able to do is embed the specific song object name onto the element which the user is clicking. For example, assuming the .topDownloads element is a div:

You can now use that data attribute in your mouse event callback. Store all your song objects in a key->value object and retrieve them from the data attribute.
// setting up key->value song pairs
var songs = {
  'someSong':$("#someSong")[0],
  'anotherSong':$("#anotherSong")[0],
};

$(".topDownloads img").hover(function() {
   // extract song key name
   var songItem = songs[$(this).data('song')];
   songItem.play();
},function() {
   // extract song key name
   var songItem = songs[$(this).data('song')];
   songItem.pause();
});

Notice that I've used the .hover() function instead of .mouseenter() and .mouseleave(). This function receives two functions as parameters, the first function is triggered when the mouse enters the element, and the second function executes when the mouse leaves the element. I think this syntax is a bit easier to work with and makes more sense.