text:
Q: Check if typescript class has setter/getter I have a typescript class which has the following properties:
export class apiAccount  {
    private _balance : apiMoney;
    get balance():apiMoney {
        return this._balance;
    }
    set balance(value : apiMoney) {
        this._balance = value;
    }

    private _currency : string;
    get currency():string {
        return this._currency;
    }
    set currency(value : string) {
        this._currency = value;
    }
    ...

I need to create a blank instance of this class:
let newObj = new apiAccount();

And then check if it has the setter for "currency", for example.
I thought that this is exactly what getOwnPropertyDescriptor does, however apparently I was wrong:
Object.getOwnPropertyDescriptor(newObj, 'currency')
Object.getOwnPropertyDescriptor(newObj, '_currency')

These both return undefined. But chrome seems to do it! When I hover over the instance, it shows me the properties, and shows them as undefined. How can I get a list of those property names, or check if the property descriptor exists in the object?

A: The "problem" is that Object.getOwnPropertyDescriptor - as the name implies - only returns descriptors of an object's own properties. That is: only properties that are directly assigned to that object, not those that are from one of the objects in its prototype chain.
In your example, the currency property is defined on apiAccount.prototype, not on newObj. The following code snippet demonstrates this:
class apiAccount {
    private _currency : string;
    get currency():string {
        return this._currency;
    }
    set currency(value : string) {
        this._currency = value;
    }
}

let newObj = new apiAccount();
console.log(Object.getOwnPropertyDescriptor(newObj, 'currency')); // undefined
console.log(Object.getOwnPropertyDescriptor(apiAccount.prototype, 'currency')); // { get, set, ... }

If you want to find a property descriptor anywhere in an object's prototype chain, you'll need to loop with Object.getPrototypeOf:
function getPropertyDescriptor(obj: any, prop: string) : PropertyDescriptor {
    let desc;
    do {
        desc = Object.getOwnPropertyDescriptor(obj, prop);
    } while (!desc && (obj = Object.getPrototypeOf(obj)));
    return desc;
}

console.log(getPropertyDescriptor(newObj, 'currency')); // { get, set, ... }


text:
Q: Running curl to upload file to s3 fails in detached run command on Heroku I am trying to upload a Heroku Postgres backup file into s3 via the following curl command:
heroku run:detached --app APPNAME 'curl --tlsv1 "https://PATH/TO/BACKUP/FROM/HEROKU/PGBACKUP/WITH/SIGNATURE/FILE.pgbackup" | aws s3 cp - s3://BUCKETNAME/POSTGRES_BACKUP_HEROKU_POSTGRESQL_RED_URL_2015-09-11.pgbackup'

Running the curl local as well as regular run command is working fine. Detaching it (run:detached), fails after transferring a few GB with the following error in the log:
2015-09-11T09:41:29.003185+00:00 app[run.8021]: upload failed: ./- to s3://BUCKETNAME/POSTGRES_BACKUP_HEROKU_POSTGRESQL_RED_URL_2015-09-11.pgbackup
2015-09-11T09:46:41.385893+00:00 app[run.8021]: (104, 'ECONNRESET')

What is the difference and how can I can get it going?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get json response from facebook fql query in android I am using an fql query to get the json response.I am new to this fql execution process.can I know in detail how to execute this query.I have seen some Listener class is using while getting the response,
SELECT likes.user_likes FROM stream WHERE post_id ='XXXXXXXXXXXXX_XXXXXXXXX'
Do I need to have anything to execute this and get the response?
Thanks in advance

A: private void doFQLQuery()
{
    //get the active facebook session
    Session session = Session.getActiveSession();
    //create the fql query
    String fqlQuery = "SELECT likes.user_likes FROM stream WHERE post_id ='XXXXXXXXXXXXX_XXXXXXXXX'";
    //create a bundle for the parameters(your query)
    Bundle params = new Bundle();
    params.putString("q", fqlQuery);
    //setup the request
    Request request = new Request(session, "/fql", params, HttpMethod.GET, new Request.Callback()
    {
        public void onCompleted(Response response)
        {
            //when the request is completed output the results to the log
            Log.i(TAG, "Result: " + response.toString());
        }
    });
    //execute the request
    Request.executeBatchAsync(request);
}

You can use this code to execute an fql query and get the response. Whatever processing you want to to do on the results should be done in the onCompleted method.


text:
Q: java factory pattern question I'm currently using my factory like this:
public class AbstractFactory
{
    public static AbstractHeader parseHeader(File file)
    {
            if(AFactory.canRead(file))return AFactory.parseHeader(file);
            if(BFactory.canRead(file))return BFactory.parseHeader(file);

            throw new UnsupportedOperationException("File ["+file+"] not supported");
    }

    public static AbstractContent parseContent(AbstractHeader h)
    {
            if(h instanceof AHeader){
                    return AFactory.parseContent((AHeader) h);
            }
            if(h instanceof BHeader){
                    return BFactory.parseContent((BHeader) h);
            }
            throw new UnsupportedOperationException("Header not supported");
    }
}

the parseHeader() will return an instance of either AHeader or BHeader, and in a later time will ask for the AbstractContent. Is there a better way to do this ? Get away with the instanceof checks ?

A: Add the following code to your existing classes:
public abstract class AbstractHeader {
    abstract AbstractContent parseContent();
}

public class AHeader extends AbstractHeader {
    public AbstractContent parseContent() {
         return AFactory.parseContent((AHeader) h);
    }
}

public class BHeader extends AbstractHeader {
    public AbstractContent parseContent() {
         return BFactory.parseContent((AHeader) h);
    }
}

Now you can just call h.parseContent().  This is called polymorphism.


text:
Q: Elevating to admin rights in Mac application I am making a simple application that lets you quickly enter a shell command to be run.
It works perfectly, however there is the problem of sudo commands.
Currently, it detects a sudo command, and then I try and get it to bring up an authorization window for the user's password, exactly like you would see in Installer.
Here's the code once it detects it is a sudo command:
SFAuthorization *authorization = [[SFAuthorization alloc] initWithFlags:kAuthorizationFlagPreAuthorize rights:NULL environment:kAuthorizationEmptyEnvironment];
if ([authorization obtainWithRight:"com.mycompany.myapplication" flags:kAuthorizationFlagPreAuthorize error:nil]){
    //authorized, now run the command using NSTask.
}else{
    //fail
}

Now, as far as I know, this is totally and completely wrong. This is just what I pieced together from the documentation. Any ideas?

A: You'll want to use the AuthorizationExecuteWithPrivileges function, like this:
- (IBAction)touch: (id) sender {

  NSString * filepath = [_filepathfield stringValue];
  FILE *commpipe = NULL;
  OSStatus execstatus;

  NSLog(@"file path is %@", filepath);

  char *args[] = {[filepath cString], NULL};

  SFAuthorization * authorization = [SFAuthorization authorization];

  execstatus = AuthorizationExecuteWithPrivileges([authorization authorizationRef],
                                                  "/usr/bin/touch",
                                                  kAuthorizationFlagDefaults,
                                                  args,
                                                  &commpipe);

  if (execstatus == errAuthorizationSuccess)
    NSlog(@"Toot! It worked");
  else
    NSLog(@"No dice");

}

Given that BSD is a delicate and grumpy flower I'd recommend not letting a user execute commands arbitrary from the app as root.
/lecture
The code from your example is the beginnings of the way to go if you want to limit the functions of your own program from it's own users. For example, you might have an app that only lets certain users alter data from a saved file. So you'd create an entry in the security database 'com.mycompany.LibraryApp.AlterData' and check to see if the user has that privilege when they try to change the data. But that's a whole different topic...
Hope that helps,
-p.

A: I know it is a really old question, but to those still looking for an answer, here goes. (It uses AppleScript)
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"do shell script \"[YOUR SCRIPT HERE]\" with administrator privileges"];

Of, course, replace [YOUR SCRIPT HERE] with your script, and be sure to escape the string, the cocoa way.
NSDictionary *errorInfo;
[script executeAndReturnError:&errorInfo];

For further explanation, please comment.

A: Security is hard.  I could paraphrase the documentation and provide code snippets, but I would likely be wrong.  Worse, even if my high level descriptions were right, there would most likely be a tiny bug in the code snippets that would kill security.
If you are going to mess with privilege escalation, the best approach is to read the docs and use the provided samples.
https://developer.apple.com/mac/library/documentation/Security/Conceptual/authorization_concepts/01introduction/introduction.html#//apple_ref/doc/uid/TP30000995-CH204-TP1


text:
Q: "no caching mode page found" error in Ubuntu without any drive partition [6.913785] sd 1:0:0:0 [sdb] no caching mode page found
[6.913885] sd 1:0:0:0: [sdb] assuming drve cache: write through
Busy box v1.22.1 (Ubuntu 1:1.22.0-15ubuntu1) built-in shell (ash)
Enter 'help' for a list of built-in commands
Initramfs

A: I had the same issue before and I solved it according to the following steps:

*

*I've created a USB key with the live of Mint distro and I booted the
machine with it.

*List your partitions using the following command:

sudo fdisk -l /dev/sda

I got the following output where sda the only drive on my machine, notice that your linux partition is /dev/sda1
Disk /dev/sda: 232.9 GiB, 250059350016 bytes, 488397168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xa71bc45b

Device     Boot     Start       End   Sectors   Size Id Type
/dev/sda1  *         2048 480393215 480391168 229.1G 83 Linux
/dev/sda2       480395262 488396799   8001538   3.8G  5 Extended
/dev/sda5       480395264 488396799   8001536   3.8G 82 Linux swap / Solaris

*Then, I executed the following command which rescue my disk again

sudo fsck -yv /dev/sda1

and I got the following result
fsck from util-linux 2.27.1
e2fsck 1.42.13 (17-May-2015)
/dev/sda1 contains a file system with errors, check forced.
Pass 1: Checking inodes, blocks, and sizes
Inodes that were part of a corrupted orphan linked list found.  Fix? yes

Inode 11275098 was part of the orphaned inode list.  FIXED.
Inode 11275099 was part of the orphaned inode list.  FIXED.
Inode 11275100 was part of the orphaned inode list.  FIXED.
Inode 11275101 was part of the orphaned inode list.  FIXED.
Inode 11280599 was part of the orphaned inode list.  FIXED.
Pass 2: Checking directory structure
Error reading block 51389518 (Attempt to read block from filesystem resulted in short read) while reading directory block.  Ignore error? yes

Force rewrite? yes

Directory inode 12855288, block #0, offset 0: directory corrupted
Salvage? yes

Missing '.' in directory inode 12855288.
Fix? yes

Setting filetype for entry '.' in ??? (12855288) to 2.
Missing '..' in directory inode 12855288.
Fix? yes

Setting filetype for entry '..' in ??? (12855288) to 2.
Pass 3: Checking directory connectivity
'..' in /var/lib/docker/aufs/mnt/efa5ec50cb7cda556e07082ce6f284bc89209ffc566a91212110072d83e73e91 (12855288) is <The NULL inode> (0), should be /var/lib/docker/aufs/mnt (12468994).
Fix? yes

Pass 4: Checking reference counts
Inode 2 ref count is 23, should be 24.  Fix? yes

Inode 12468994 ref count is 58, should be 57.  Fix? yes

Pass 5: Checking group summary information
Block bitmap differences:  -(45219840--45220206)
Fix? yes

Free blocks count wrong for group #1380 (31392, counted=31759).
Fix? yes

Free blocks count wrong (47147739, counted=46915808).
Fix? yes

Inode bitmap differences:  -(11275097--11275101) -11280599
Fix? yes

Free inodes count wrong for group #1376 (5, counted=10).
Fix? yes

Free inodes count wrong for group #1377 (7279, counted=7280).
Fix? yes

Free inodes count wrong (14328772, counted=14270663).
Fix? yes

/dev/sda1: ***** FILE SYSTEM WAS MODIFIED *****

      745273 inodes used (4.96%, out of 15015936)
        2132 non-contiguous files (0.3%)
         607 non-contiguous directories (0.1%)
             # of inodes with ind/dind/tind blocks: 0/0/0
             Extent depth histogram: 698409/204
    13133088 blocks used (21.87%, out of 60048896)
           0 bad blocks
           3 large files

      607356 regular files
       89743 directories
          56 character device files
          25 block device files
           0 fifos
       41620 links
       48079 symbolic links (46566 fast symbolic links)
           5 sockets
------------
      786884 files

*Finally, my machine worked fine without re installation.


text:
Q: How to create a new table that only keeps rows with more than 5 data records under the same id in Bigquery I have a table like this:

Id
Date
Steps
Distance

1
2016-06-01
1000
1

There are over 1000 records and 50 Ids in this table, most ids have about 20 records, and some ids only have 1, or 2 records which I think are useless.
I want to create a table that excludes those ids with less than 5 records.
I wrote this code to find the ids that I want to exclude:
SELECT
  Id,
  COUNT(Id) AS num_id
FROM `table`
GROUP BY
  Id
ORDER BY
  num_id

Since there are only two ids I need to exclude, I use WHERE clause:
CREATE TABLE `` AS
SELECT
  *
FROM ``
WHERE
  Id <> 2320127002
  AND Id <> 7007744171

Although I can get the result I want, I think there are better ways to solve this kind of problem. For example, if there are over 20 ids with less than 5 records in this table, what shall I do? Thank you.

A: Consider this:
CREATE TABLE `filtered_table` AS
SELECT *
  FROM `table`
 WHERE TRUE QUALIFY COUNT(*) OVER (PARTITION BY Id) >= 5

Note: You can remove WHERE TRUE if it runs successfully without it.


text:
Q: Use cellvalue of other column in jqgrid formatter Can I use cell value of some other column in the formatter key of colModel.
So basically, I want to change cellvalue --> cellvalue of some other column.
    colModel.push({
        'formatter': function(cellvalue, options, rowObject) {
            return '' + cellvalue + '';
        }
    });

A: Let us you have two columns name: "mycol1" and name: "mycol2" and you want to add custom formatter in column 1, which used the property mycol1 of input data in the URL of the anchor and the the property mycol1 as the text of the anchor. The code could be the following:
colModel.push({
    name: 'mycol1',
    formatter: function(cellvalue, options) {
        return '' +
                options.rowData.mycol2 + '';
   }
});


text:
Q: Magento 1.7: "Place Order" disabled by default in PayPal Express Review Since Magento 1.7.0.1, the "Place Order" button on the review page of PayPal Express is disabled by default.
When the user ticks both checkboxes, it stays disabled. The user needs to tick the checkboxes  and click on "Update Order Data". After the site is reloaded, "Place Order"/"Kaufen" is enabled.
How can this bug be fixed? It is also present in 1.7.0.2.

A: For me this is more like a bug or unexpected behavior,
because the agreements checkbox is not related with the customer
address and it doesn't have any business with PayPal express :)
I found a workaround, that works for me, but I can't say that it's
is a example of the best development practices.
Short explanation of the problem: The problem comes from the fact, that on the PayPal Express review page we have JavaScript functions, that activate an event handler on change of all form elements. This event handler disable the "place order" button. This should work in that way if we change for element, that is related with the customer address ... Well of course the agreement checkboxes are not related with the customer address and seems, that the folks from Magento missed, that moment :)
Here is the solution:

*

*find file "template/paypal/review.phtml" ... if you don't have this file in your theme, just copy it from the base theme

*Add add the lines of code after //Workaround to unbind the event listeners for the agreement checkboxes at the bottom of the file. Take the code from here: https://gist.github.com/4503260
Basically this recreates agreement checkboxes and as side effect the new checkboxes, don't have event listeners, that disable the place order button.
Hope, that it helps :)

A: Fyi, I don't know if this helps or not but the One Step Checkout Pro extension by MageWorld may have this issue fixed in their latest release...

v1.4.2.2
*Fixed "Sales order grid" and order details in backend.
  *Fixed "place order button is disabled" on IE.

I haven't tested it though so can't be certain.

A: I think this is not a bug, this is a feature. When the customer changes any data (shipping method eg.), the price can be changed too. And to update review table the customer should press update order button. And if he agreed with the price he will press place order button. Other technique is AJAX request to validate data and calculate prices. But you will have a lot of requests from one customer and customer will wait every time when he changes data.


text:
Q: Convert missing to a numerical value in Julia 1 I am trying to convert all missing values in a df to a numerical value, e.g. 0 (yes, knowing what I am doing..).
In Julia 0.6 I can write:
julia> df = DataFrame(
              cat = ["green","blue","white"],
              v1   = [1.0,missing,2.0],
              v2   = [1,2,missing]
            )
julia> [df[ismissing.(df[i]), i] = 0 for i in names(df)]

And get:
julia> df
3×3 DataFrames.DataFrame
│ Row │ cat   │ v1  │ v2 │
├─────┼───────┼─────┼────┤
│ 1   │ green │ 1.0 │ 1  │
│ 2   │ blue  │ 0.0 │ 2  │
│ 3   │ white │ 2.0 │ 0  │

If I try it in Julia 0.7 I get instead a very weird error:

MethodError: Cannot convert an object of type Float64 to an object
  of type String

I can't get what I am trying to convert to a string ??? Any explanation (and workaround) ?

A: The reason for this problem is that broadcasting mechanism has changed between Julia 0.6 and Julia 1.0 (and it is used in insert_multiple_entries! function in DataFrames.jl). In the end fill! is called and it tries to do a conversion before checking if the collection is empty.
Actually if you want to do a fully general replacement in place (and I understand you want to) this is a bit complex and less efficient than what you have in Base (the reason is that you cannot rely on checking types of elements in vectors as e.g. you can assign Int to vector of Float64 and they have different types):
function myreplacemissing!(vec, val)
    for i in eachindex(vec)
        ismissing(vec[i]) && (vec[i] = val)
    end
end

And now you are good to go:
foreach(col -> myreplacemissing!(col[2], 0), eachcol(df))

A: While I appreciate the answer of Bogumil Kaminski (also because now I understood the reasons behind the failure), its proposed solution fails if it happens to exists missing elements in non-numeric columns, e.g.:
df = DataFrame(
  cat = ["green","blue",missing],
  v1   = [1.0,missing,2.0],
  v2   = [1,2,missing]
)

What I can instead do is to use (either or only one, depending on my needs):
[df[ismissing.(df[i]), i] = 0 for i in names(df) if  typeintersect(Number, eltype(df[i])) != Union{}]
[df[ismissing.(df[i]), i] = "" for i in names(df) if  typeintersect(String, eltype(df[i])) != Union{}]

The advantage is that I can select the type of value I need as "missing replacement" for different type of column (e.g. 0 for a number or "" for a string).
EDIT:
Maybe more readable, thanks again to Begumil's answer:
[df[ismissing.(df[i]), i] = 0 for i in names(df) if  Base.nonmissingtype(eltype(df[i])) <: Number]
[df[ismissing.(df[i]), i] = "" for i in names(df) if  Base.nonmissingtype(eltype(df[i])) <: String]


text:
Q: How can i append string to list? I am trying to completing a school assignment where i have to write  a function which takes two arguments where the first condition is the length of the list is greater than 4 which is working,however,the problems begins with appending the a variable "s" to the list.for e,g
(define SOB (λ ( s L1)

                (cond
                ((string? s)
                ((list? L1) (> 4)

                            (append  s L1))))))

this is my code i have been trying to find ways to do this but i keep getting errors.this is input test
(SOB "hi" '(1 2 3 4 5 6))

and this is the error i receive
append: contract violation
  expected: list?
  given: "hi"

i am new to racket and i would really appreciate some help with this

A: The correct function is cons, not append. append is for concatenating multiple lists, but s is not a list.
You also need to combine all your conditions with and.
(define SOB (λ ( s L1)
  (cond
    ((and (string? s) (list? L1) (> (length L1) 4))
     (cons s L1))))


text:
Q: KeyListener does not work with JTextField Sorry for my English.
I have some problems with JTextField and with KeyListener.
I have the code below :
package com.gugnovich.tasks;
@SuppressWarnings("serial")
public class Task1Panel extends Task {

    private static final String zLabel = "Please enter Z:";
    private static final String eLabel = "Please enter E:";
    private static final double K = 1.4;

    private JTextField zField;
    private JTextField eField;
    private JTextField result;

    private double zVal;
    private double eVal;
    private double resultVal;

    @Override
    protected void displayTaskPanel() {
        /** Panel settings */
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        setBorder(new EmptyBorder(10, 15, 10, 10));
        /** Add title of the task */
        JLabel title = new JLabel(Constants.TASK1_TITLE + ":");
        title.setFont(new Font("Monospaced", Font.BOLD, 18));
        add(title);
            /**
              Form builder
             */
        DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(""));
        builder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        builder.setBackground(Color.decode(Constants.BACKGROUND_COLOR));
            /**
              Add columns
             */
        builder.appendColumn("left:pref");
        builder.appendColumn("3dlu");
        builder.appendColumn("fill:max(pref; 100px)");

        builder.appendSeparator("Enter params");
            /**
              Field for Z
             */
        zField = new JTextField();
        builder.append(zLabel, zField);
        zField.addKeyListener(listener);
             /**
              Field for E
             */
        eField = new JTextField();
        builder.append(eLabel, eField, true);
        eField.addKeyListener(listener);

        builder.appendSeparator("Result");
            /**
               result field
            */
        result = new JTextField();
        result.setEnabled(false);
        result.setDisabledTextColor(Color.BLACK);
        builder.append("X = ", result);

        add(builder.getPanel());
    }
    /**
     listener
    */
    private KeyListener listener = new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            System.out.println("Typed");
            JTextField zf = (JTextField) e.getSource();
            zVal = Double.parseDouble(zf.getText());
            JTextField ef = (JTextField) e.getSource();
            eVal = Double.parseDouble(ef.getText());
            if (zVal > 0.00 && eVal > 0.00) {
                calculate();
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            System.out.println("Released");
        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("Pressed");
        }
    };

}

The problem is that the listener does not work. what could be the cause?
If i will add mouse listener that it work.
Thanks in advance.

A: Don't use a KeyListener for this. Often I'd use a DocumentListener to listen to the JTextField's Document if I wanted to react to changes after they've been placed in the JTextField, but even this is not a good fit for this type of problem since you'd be trying to calculate before the fields have been fully filled in, and initially before one of the JTextFields has received any data at all.
Much better would be to add a JButton to your GUI and in that JButton's ActionListener extract and parse the text from the JTextFields, call the calculate method and display the results of the calculation. This way you don't get premature results but rather will only do the calculations after the user has entered information and decided that the data entered is valid and now is the time to do calculations. You can even disable the button until both JTextFields contain data (a DocumentListener can work well for this).

A: for TextComponents is there DocumentListener and for Numbers is there JFormattedTextField, and with Number Formatter doesn't allows input only numbers and decimal separator, simple example here


text:
Q: Can I disable ssl for AWS CLI "By default, the AWS CLI uses SSL when communicating with AWS services."
base on the doc
Is there a way to let AWS CLI use HTTP? I tried to read the reference but didn't find it.

A: explicitly set endpoint to use http will do the work.
e.g. "http://s3.us-east-2.amazonaws.com"
Thanks @jarmod.


text:
Q: Ayuda! Como salgo de un ciclo while cuando se queda ciclado dentro de otro ciclo while? Tengo un ciclo while para leer un archivo .csv y dentro otro ciclo while para leer un array de letras.
Dentro me debería imprimir una letra y una linea del .csv.
Pero se queda ciclado y solo imprime cada letra del abecedario pero con el mismo linea del .csv
while ((line = rd.readLine()) != null) {

            line = rd.readLine();

            while(e < alfabeto.length)
            {
             alfabeto[e]=(char)('A'+e);
             System.out.print(alfabeto[e]+";");
             System.out.println(line);
             e++;
             i++;
                }

     }

Y este es el resultado

    A;1;35654423;30-12-2010:11.02;register request;Pete;50
 B;1;35654423;30-12-2010:11.02;register request;Pete;50
 C;1;35654423;30-12-2010:11.02;register request;Pete;50
 D;1;35654423;30-12-2010:11.02;register request;Pete;50
 E;1;35654423;30-12-2010:11.02;register request;Pete;50
 F;1;35654423;30-12-2010:11.02;register request;Pete;50
.
more...
.
 X;1;35654423;30-12-2010:11.02;register request;Pete;50
 Y;1;35654423;30-12-2010:11.02;register request;Pete;50
 Z;1;35654423;30-12-2010:11.02;register request;Pete;50
 BUILD SUCCESSFUL (total time: 0 seconds)

archivo .csv

Case ID;Event ID;dd-MM-yyyy:HH.mm;Activity;Resource;Costs
1;35654423;30-12-2010:11.02;register request;Pete;50
1;35654424;31-12-2010:10.06;examine thoroughly;Sue;400
1;35654425;05-01-2011:15.12;check ticket;Mike;100
1;35654426;06-01-2011:11.18;decide;Sara;200
1;35654427;07-01-2011:14.24;reject request;Pete;200
2;35654483;30-12-2010:11.32;register request;Mike;50
2;35654485;30-12-2010:12.12;check ticket;Mike;100
2;35654487;30-12-2010:14.16;examine casually;Sean;400
2;35654488;05-01-2011:11.22;decide;Sara;200
2;35654489;08-01-2011:12.05;pay compensation;Ellen;200
3;35654521;30-12-2010:14.32;register request;Pete;50
3;35654522;30-12-2010:15.06;examine casually;Mike;400
3;35654524;30-12-2010:16.34;check ticket;Ellen;100
3;35654525;06-01-2011:09.18;decide;Sara;200
3;35654526;06-01-2011:12.18;reinitiate request;Sara;200
3;35654527;06-01-2011:13.06;examine thoroughly;Sean;400
3;35654530;08-01-2011:11.43;check ticket;Pete;100
3;35654531;09-01-2011:09.55;decide;Sara;200
3;35654533;15-01-2011:10.45;pay compensation;Ellen;200
4;35654641;06-01-2011:15.02;register request;Pete;50
4;35654643;07-01-2011:12.06;check ticket;Mike;100
4;35654644;08-01-2011:14.43;examine thoroughly;Sean;400
4;35654645;09-01-2011:12.02;decide;Sara;200
4;35654647;12-01-2011:15.44;reject request;Ellen;200
5;35654711;06-01-2011:09.02;register request;Ellen;50
5;35654712;07-01-2011:10.16;examine casually;Mike;400
5;35654714;08-01-2011:11.22;check ticket;Pete;100
5;35654715;10-01-2011:13.28;decide;Sara;200
5;35654716;11-01-2011:16.18;reinitiate request;Sara;200
5;35654718;14-01-2011:14.33;check ticket;Ellen;100
5;35654719;16-01-2011:15.50;examine casually;Mike;400
5;35654720;19-01-2011:11.18;decide;Sara;200
5;35654721;20-01-2011:12.48;reinitiate request;Sara;200
5;35654722;21-01-2011:09.06;examine casually;Sue;400
5;35654724;21-01-2011:11.34;check ticket;Pete;100
5;35654725;23-01-2011:13.12;decide;Sara;200
5;35654726;24-01-2011:14.56;reject request;Mike;200
6;35654871;06-01-2011:15.02;register request;Mike;50
6;35654873;06-01-2011:16.06;examine casually;Ellen;400
6;35654874;07-01-2011:16.22;check ticket;Mike;100
6;35654875;07-01-2011:16.52;decide;Sara;200
6;35654877;16-01-2011:11.47;pay compensation;Mike;200

De que otra manera lo puedo hacer o que otro método puedo usar para hacerlo?

A: el while para leer csv esta bien, pero te recomiendo lo siguiente, si quieres recorrer un array utiliza un ciclo "for", porque ya tienes definido tu array declarado y este tiene una longitud. Para leer tu array y que no quede ciclando seria de la siguiente manera:
while ((line = rd.readLine()) != null) {

            line = rd.readLine();

            for(int e2 = e; e2 < alfabeto.length; e2++){
               alfabeto[e]=(char)('A'+e2);
               System.out.print(alfabeto[e2]+";");
               System.out.println(line);
            }
     }


text:
Q: Rendering Graphs Is there a way to colour region bounded by edges with GRAPH in mathematica. Like if three vertices form a triangle, I want to colour the are of triangle with GRAPH option.

A: A one very easy way would be to use image processing:
g = RandomGraph[{10, 15}, ImageSize -> 600, EdgeStyle -> Thick]

MorphologicalComponents[Binarize@Image[g]] // Colorize

It is easy for planar graphs, but for the rest you may have some overlapping regions. I see you mentioned grid; this is how you can approach it:
g = GridGraph[{5, 5}, VertexSize -> .5, EdgeStyle -> Thick];
MorphologicalComponents[ColorNegate@Binarize@GradientFilter[Image[g], 1]] // Colorize


text:
Q: Getting changed attribute on change event In this global change event, is there a way I can detect which attribute was changed?
myModel.on('change', function(model) {
  // Which attribute changed?
});

I tried the following:

*

*Using myModel.previousAttributes() but it always returned latest values... I guess it only updates after a server interaction.

*Iterating trough attributes and using myModel.hasChanged(attr) but it always returned false.

It's there a way to accomplish this?

A: You can use model.changedAttributes

changedAttributes model.changedAttributes([attributes])
  Retrieve a hash of only the model's attributes that have changed, or false if
  there are none.
  Optionally, an external attributes hash can be passed
  in, returning the attributes in that hash which differ from the model.
  This can be used to figure out which portions of a view should be
  updated, or what calls need to be made to sync the changes to the
  server

For example,
var m = new Backbone.Model({
    att1: 'a',
    att2: 'b',
    att3: 'c'
});

m.on('change', function() {
    console.log(m.changedAttributes());
    console.log(_.keys(m.changedAttributes()));
});

m.set({
    att1: 'd',
    att3: 'e'
});

And a demo http://jsfiddle.net/nikoshr/NYnqM/


text:
Q: Dynamically arrange data of jqgrid I am not able to arrange the cell data dynamically with respect to customize column. In the cell collection I want to arrange the cell values as per the column sequence.
The Column are :[COLUMN10, COLUMN3, COLUMN1, COLUMN7, COLUMN9](those are coming from database) and the column sequence will be dynamically change. In that case I am not able to arrange the cell value dynamically with respect the sequence of the column. Please find my snapshot of the code, which I am using in my code.
jsonData = new
                {
                    total = totalPages,
                    page,
                    records = totalRecords,
                    rows = (
                        from Details in ListData
                        select new
                        {
                            i = 1,
                            cell = new string[] {
                                              Details.COLUMN10,
                                              Details.COLUMN3,
                                              Details.COLUMN1,
                                              Details.COLUMN7,
                                              Details.COLUMN9
                                }
                        }
                        ).ToArray()

Please guide and let me know the flow through which I can proceed.


text:
Q: Eclipse - can't install google plugin for eclipse 4.3 I've checked the - .eclipseproduct - file and it says that my version is 4.3.0.
Now I've tried to install Google plugin for eclipse 4.3 - at the - Help-->Install new software.
And I've used the https://dl.google.com/eclipse/plugin/4.3 at the work with field.
Now when I choose the Google plugin it says that -
Cannot complete the install because one or more required items could not be found.
  Software being installed: Google Plugin for Eclipse 4.3 3.5.1.v201312301723-rel-r43 (com.google.gdt.eclipse.suite.e43.feature.feature.group 3.5.1.v201312301723-rel-r43)
  Missing requirement: Google Plugin for Eclipse 4.3 3.5.1.v201312301723-rel-r43 (com.google.gdt.eclipse.suite.e43.feature.feature.group 3.5.1.v201312301723-rel-r43) requires 'org.eclipse.persistence.jpa.jpql 0.0.0' but it could not be found

I've even tried to install the google app engine but also it says that -
Cannot complete the install because one or more required items could not be found.
  Software being installed: Google App Engine Tools for Android 3.5.1.v201312301723-rel-r43 (com.google.gdt.eclipse.mobile.android.feature.feature.group 3.5.1.v201312301723-rel-r43)
  Missing requirement: Google Managed APIs Plugin 3.5.1.v201312301719-rel-r42 (com.google.gdt.eclipse.managedapis 3.5.1.v201312301719-rel-r42) requires 'bundle org.eclipse.m2e.core 0.0.0' but it could not be found
  Missing requirement: Google Managed APIs Plugin 3.5.1.v201312301723-rel-r43 (com.google.gdt.eclipse.managedapis 3.5.1.v201312301723-rel-r43) requires 'bundle org.eclipse.m2e.core 0.0.0' but it could not be found
  Cannot satisfy dependency:
    From: Google App Engine Tools for Android 3.5.1.v201312301723-rel-r43 (com.google.gdt.eclipse.mobile.android.feature.feature.group 3.5.1.v201312301723-rel-r43)
    To: com.google.gdt.eclipse.suite 0.0.0
  Cannot satisfy dependency:
    From: Google Suite Plugin 3.5.1.v201312301719-rel-r42 (com.google.gdt.eclipse.suite 3.5.1.v201312301719-rel-r42)
    To: bundle com.google.gdt.eclipse.managedapis 0.0.0
  Cannot satisfy dependency:
    From: Google Suite Plugin 3.5.1.v201312301723-rel-r43 (com.google.gdt.eclipse.suite 3.5.1.v201312301723-rel-r43)
    To: bundle com.google.gdt.eclipse.managedapis 0.0.0

So what should I do in order to be able to install Google plugin for Eclipse 4.3?
Thanks for any kind of help.

A: Make sure you're using the newest Eclipse, Eclipse Plugin and JDK. Maybe even update your JRE.
Otherwise try installing the whole ADT-Bundle. It's kind of an Eclipse IDE with the plugin preinstalled.
The last thing that comes to my mind is that you could try the Android Studio.

A: I found out that ADT-Bundle whose version is eclipse 4.2 has this issue of installing google plugin and when I downloaded eclipse and Android SDK separately and connected them together. It solved the problem. Google plugin installation worked super fine then


text:
Q: Issue : jqgrid double header issue I tried to keep double header in my jqgrid. But I keep getting
Length of colNames < > colModel!

Code that I tried
 var grid = $("#list"),
                mydata = [
                   {date:"1",aaa:"2007-10-01",bbb:"test",cccc:"note",ddd:"200.00",eee:"10.00",fff:"210.00",ggg:"",hhh:"",proj:"",iii:""},
];

colModel:[
                    {name:'date',index:'date',key: true,width:100,sorttype:"text"},
                    {name:'time',index:'time',key: true,width:100,sorttype:"text"},
....
jQuery("#list").jqGrid('setGroupHeaders', {
     // useColSpanStyle: true,
      groupHeaders:[
        {startColumnName: 'date',numberOfColumns: 1, titleText: 'Price'},
        {startColumnName: 'time',numberOfColumns: 1, titleText: 'Shiping'}
      ]
    });

I need Date in the first header time in the second header.
Any help ?

A: It looks like you need just create multiline column headers and not grouping of some column headers together. Thus the usage of setGroupHeaders is the wrong way.
What you need to use is wrapping of long column header text (see the answer) or just including
 inside of the text of the column header (see another answer). It's important to understand that colNames or label property of colModel contains HTML fragment which will be set in the column header. Thus one can use HTML markup. Depend on the version of jqGrid which you use you could use additional CSS rule
.ui-jqgrid .ui-jqgrid-htable th div { height: auto }


text:
Q: How to get openssl to work on Debian 9.5 This is my distribution I use
  root@ci-server:~/temp# lsb_release -a
    No LSB modules are available.
    Distributor ID: Debian
    Description:    Debian GNU/Linux 9.5 (stretch)
    Release:        9.5
    Codename:       stretch

When installing openssl I receive the following message but using openssl just simply does not work
root@ci-server:~/temp# apt-get install openssl
Reading package lists... Done
Building dependency tree
Reading state information... Done
openssl is already the newest version (1.1.0j-1~deb9u1).
0 upgraded, 0 newly installed, 0 to remove and 17 not upgraded.
root@ci-server:~/temp# openssl version
openssl: error while loading shared libraries: libcrypto.so.1.1: cannot open shared object file: No such file or directory

but libcrypto.so.1.1 was found here
root@ci-server:~/temp# find / -name "libcrypto.so.1.1"
/usr/lib64/libcrypto.so.1.1

ldconfig contents
root@ci-server:~# cat /etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf

and
root@ci-server:~# ls -l /etc/ld.so.conf.d/
total 12
-rw-r--r-- 1 root root 38 Jan 17  2017 fakeroot-x86_64-linux-gnu.conf
-rw-r--r-- 1 root root 44 Mar 20  2016 libc.conf
-rw-r--r-- 1 root root 68 Jan 14  2018 x86_64-linux-gnu.conf

looking for /usr/lib64 within /etc/ld.so.conf.d did not yield any results
root@ci-server:~# grep -irl "/usr/lib64" /etc/ld.so.conf.d/
root@ci-server:~#

A: The expected location for libcrypto.so.1.1 in Debian 9.5 is /usr/lib/x86_64-linux-gnu/libcrypto.so.1.1, not /usr/lib64... and the package that contains it is libssl1.1, which contains the libraries of OpenSSL; in Debian packaging, the openssl package contains only the configuration files, the /usr/bin/openssl and /usr/bin/c_rehash command binaries and the associated man pages. The openssl package (and anything that requires OpenSSL libraries) depends on libssl1.1. This way, the package management allows you to install just the libraries if you don't need the openssl command-line tool and are building e.g. an embedded system with minimal amount of storage space available.
On a fresh installation of Debian 9.x on x86_64 architecture, /usr/lib64 should not even exist. The fact that it exists suggests that another copy of openssl may have been installed from some alternative source (perhaps by copying the binaries from another host, or by installing packets intended for other distributions).
Please run dpkg --verify libssl1.1 openssl to verify the integrity of libssl1.1 and openssl packages on your system. The output will list any files that have been modified: if e.g. the /usr/bin/openssl binary is listed in the output, you'll know that your system's openssl has been tampered with.
The worst-possible scenario is that your system has been hacked and the intruder has tried to replace your OpenSSL with a modified version that will leak your private keys to the intruder. If so, then the intruder made a mistake, probably by using a set of libraries intended for RHEL/CentOS/Fedora-style systems (where the /usr/lib64 path is typically used) on your Debian system.
If you think your system might be hacked: don't panic. Server Fault has a canonical answer on what to do if you suspect your server has been compromised by a hacker.


text:
Q: Sending JSON object successfully to ASP.NET WebMethod, using jQuery I've been working on this for 3 hours and have given up.
I am simply trying to send data to an ASP.NET WebMethod, using jQuery.
The data is basically a bunch of key/value pairs. So I've tried to create an array and adding the pairs to that array.
My WebMethod (aspx.cs) looks like this (this may be wrong for what I'm building in JavaScript, I just don't know):
[WebMethod]
public static string SaveRecord(List<object> items)
{
    ...
}

Here is my sample JavaScript:
var items = new Array;

var data1 = { compId: "1", formId: "531" };
var data2 = { compId: "2", formId: "77" };
var data3 = { compId: "3", formId: "99" };
var data4 = { status: "2", statusId: "8" };
var data5 = { name: "Value", value: "myValue" };

items[0] = data1;
items[1] = data2;
items[2] = data3;
items[3] = data4;
items[4] = data5;

Here is my jQuery AJAX call:
var options = {
    error: function(msg) {
        alert(msg.d);
    },
    type: "POST",
    url: "PackageList.aspx/SaveRecord",
    data: { 'items': items },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    success: function(response) {
        var results = response.d;
    }
};
jQuery.ajax(options);

I get the error:
Invalid JSON primitive: items.

So, if I do this:
var DTO = { 'items': items };

and set the data parameter like this:
data: JSON.stringify(DTO)

Then I get this error:
Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1[System.Object]\u0027

A: When using AJAX.NET I always make the input parameter just a plain old object and then use the javascript deserializer to covert it to whatever type I want. At least that way you can  debug and see what type of object the web method in is recieving.
You need to convert your object to a string when using jQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">

        </asp:ScriptManager>

    </form>

And the Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomEquip
{
    [ScriptService]
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static void SubmitItems(object items)
        {
            //break point here
            List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
        }
    }
}

A: The following is a code snippet from our project - I had trouble with not wrapping the object as a string and also with Date values - hopefully this helps someone:
        // our JSON data has to be a STRING - need to send a JSON string to ASP.NET AJAX.
        // if we specify an actual JSON object as jQuery's data parameter, it will serialize it as ?k=v&k=v pairs instead
        // we must also wrap the object we are sending with the name of the parameter on the server side – in this case, "invoiceLine"
        var jsonString = "{\"invoiceLine\":" + JSON.stringify(selectedInvoiceLine) + "}";

        // reformat the Date values so they are deserialized properly by ASP.NET JSON Deserializer
        jsonString = jsonString.replace(/\/Date\((-?[0-9]+)\)\//g, "\\/Date($1)\\/");

        $.ajax({
            type: "POST",
            url: "InvoiceDetails.aspx/SaveInvoiceLineItem",
            data: jsonString,
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });

The server method signature looks like this:
    [WebMethod]
    public static void SaveInvoiceLineItem(InvoiceLineBO invoiceLine)
    {

A: In your example, it should work if your data parameter is:
data: "{'items':" + JSON.stringify(items) + "}"

Keep in mind that you need to send a JSON string to ASP.NET AJAX.  If you specify an actual JSON object as jQuery's data parameter, it will serialize it as &k=v?k=v pairs instead.
It looks like you've read it already, but take another look at my example of using a JavaScript DTO with jQuery, JSON.stringify, and ASP.NET AJAX.  It covers everything you need to make this work.
Note:  You should never use JavaScriptSerializer to manually deserialize JSON in a "ScriptService" (as suggested by someone else).  It automatically does this for you, based on the specified types of the parameters to your method.  If you find yourself doing that, you are doing it wrong.

A: Decorate your [WebMethod] with another attribute:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

I believe this is in System.Web.Services.Scripting...

A: see link http://www.andrewrowland.com/article/display/consume-dot-net-web-service-with-jquery

A: This is the way you define your data (JSON)
data: { 'items': items },

and the this the way it should be
data: '{ items: " '+items +' "}',

basically you are serializing the parameter.


text:
Q: Static vs REST routing with clojure ring I'm writing an angular/clojure ring webapp. All routes to the ring side will have an "/api" prefix and will be routed with compojure.
Serving upp all other static file with ring seems a bit messy though.
Is there a good way to direct "/api/whatever" requests to ring and all other to be served up as static files using jetty? or using any other major web server, like apache, nginx, lighttpd?

A: We put nginx infront of jetty and have nginx configured to serve the static stuff (actually redirects to a CDN) directly and proxy all the app stuff to jetty. In production jetty is running on a separate load balancer though this works out the same if they are running on the same instance.

A: If you want to run clojure Ring handlers with Nginx without any Java Web Server, eg. Jetty. please try Nginx-Clojure module.


text:
Q: How to change minimum deployment iosTarget from Codemagic? I have developed a Flutter App on Windows. Now I am trying to make the build via codemagic. But I need to change the minimum deployment version for IOS.
I get this error while building app with codemagic

Specs satisfying the stripe_payment (from.symlinks/plugins/stripe_payment/ios) dependency were found, but they required a higher minimum deployment target.

A: You'll have to define the minimum platform ios version in the Podfile file.
platform :ios, '10.0'

Note: the Podfile will be created once you run flutter build ios.
If you don't have a macOS device
You'll have to run flutter build ios on a macOS device. If you don't have such a device you can create a CI build pipeline for your project (on Azure Devops for example), and run the CI build on a macOS agent.
In the pipeline you have to add a step that uploads the Podfile to an artifact, so you can download that artifact and add the Podfile to your sources.
Note: here you'll find a simple CI/CD build example for building your Flutter app for IOS and Android without the need for a macOS device.

A: I tried changing minimum target to 10.0 but it was still complaining.
I set to

platform :ios, '13.0'

worked fine for me


text:
Q: How to traverse this hash within one line? Each key in a hash has a value that's also a hash.

    {
      100 => {
        1 => 'ruby',
        2 => 'enumerables'
      },
      50 => {
        3 => 'can',
        4 => 'cause'
      },
      15 => {
        5 => 'occassional',
        6 => 'insanity'
      }
    }

For each hash object, I want to discard the top-level key, and replace it with the key and value of the nested hash objects.
{
  1 => 'ruby',
  2 => 'enumerables',
  3 => 'can',
  4 => 'cause',
  5 => 'occasional',
  6 => 'insanity'
}

I have it working, but my method uses a merge!, and requires creating another hash to store the values. I'm curious to see if it can be done in one line. I tried to use reduce(), but could not make it work.

A: I like the answer by @MarkThomas best, but for speed and memory efficiency I suggest:
flatter = {}.tap{ |h| original.values.each{ |h2| h.merge!(h2) } }

Benchmarking 200,000 iterations of the current answers shows this to be the fastest:
                          user     system      total        real
Phrogz                0.710000   0.020000   0.730000 (  0.728706)
Joshua Creek          0.830000   0.010000   0.840000 (  0.830700)
Mark Thomas symbol    1.460000   0.020000   1.480000 (  1.486463)
Mark Thomas to_proc   1.540000   0.030000   1.570000 (  1.565354)
Tim Peters            1.650000   0.030000   1.680000 (  1.678283)

Since the comment by @tokland—original.values.reduce(:update)—modifies the original hash we cannot compare it directly to the other methods. However, if we modify all tests to put a duplicate of the first hash back into the original each iteration, @tokland's answer becomes the fastest, though still not quite as fast as mine:
                          user     system      total        real
tokland's destroyer   0.760000   0.010000   0.770000 (  0.772774)
Phrogz                1.020000   0.020000   1.040000 (  1.034755)
Joshua Creek          1.060000   0.000000   1.060000 (  1.063874)
Mark Thomas symbol    1.780000   0.040000   1.820000 (  1.816909)
Mark Thomas to_proc   1.790000   0.030000   1.820000 (  1.819014)
Tim Peters            1.800000   0.040000   1.840000 (  1.827984)

If you need absolute speed and it's OK to modify the original values, use @tokland's answer. If you do so and want to preserve the original unmerged hashes unscathed, then you can:
first_k,orig_v = original.each{ |k,v| break [k,v.dup] }
merged = original.values.reduce(:update)
original[first_k] = orig_v

Note that your question title says traverse; if you don't really want to merge the values—if you might want to visit a duplicate key twice instead of last-in-wins—then simply do:
original.values.each{ |h| h.each{ |k,v|
  # hey, we're traversing inside!
} }

A: Since you don't value about the top level keys, use #values to get an array of the values (in this case, also hashes).  Then you can use #inject to build up a new hash, merging them as you go.
yourhash.values.inject{|hash, thing| hash.merge(thing)}

There are probably other ways to do it.

A: Hash[original_hash.values.flat_map(&:to_a)]

A: Just took a stab at it, first try was brute force and better methods (in both senses of the word...) are out there.
h.map {|k,v| v}.inject({}) {|i,h| i.merge(h)}

A: While it isn't as brief as some of the other answers, I think each_with_object deserves a representation.
output = input.each_with_object Hash.new do |(_,subhash), hash|
  hash.merge! subhash
end

A: This works:
hash.values.inject(&:merge)

Edit: Another option, using reduce (which is the same as inject), and noting tokland's comment that to_proc is automatically called when you use a symbol:
hash.values.reduce(:merge)

Then it becomes not only concise but very readable.


text:
Q: HG command path in TeamCity in Windows I'm configuring my build server using TeamCity with Mercurial and I don't know what is "HG command path" field.
And the field "Pull changes from"? Should I put the address I'm cloning? From i.e. http://192.168.87.143/hg/TestProject

A: HG command path is the path to hg executable on the server, put hg there if it is in the PATH. And yes, Pull changes from is for address of your repository.


text:
Q: Grails and consume SOAP webservice Being fairly new to Grails i was wondering what people use to consume a webservice in Grails projects. So the client side of the system? Any recommendations? I see people using GroovyWS, Spring-WS etc.. What is a good and easy on to use?

A: GroovyWS is very easy to use and has great documentation I would definitely recommend it.

A: Using Grails CXF plugin here. Needed:

*

*classloader workaround - DynamicClientFactoryit changed a current classloader;

*and to code WS invocations by hand.

Besides that, the consumer code is pretty slim.
Edit: sorry, no more then this, and I'm not sure I'm not breaking and NDA yet:
#1:
def arrayOfLong = objectFactory.createArrayOfLong(XXX, ids)
result = client.invoke(methodName, arrayOfLong as Object[])

#2:
def dcf = DynamicClientFactory.newInstance()
def classLoader = Thread.currentThread().getContextClassLoader()

// create a WS client
// and assign end point address to it
def client = dcf.createClient(WSDL_URL, classLoader)
client.conduit.target.address.setValue(endpointUrl)

// reacquire classloader because 'createClient' changes it
def changedClassLoader = Thread.currentThread().getContextClassLoader()
def objectFactory = changedClassLoader.
    loadClass(FACTORY_CLASS_NAME).newInstance()

A: Using Grails 1.3.7 I am consuming my own web service with WS-Client Grails plugin. It is actually based on GroovyWS, which in turn uses CXF. It is very easy to use at least in my simple scenario, where I only get Strings from the backend web service. I have no idea how it works with complex data types yet though.
I had never consumed or created a webservice before but using that plugin in the frontend and the Grails CXF plugin in the backend I got a SOAP discussion between my grails apps in two days. You don't really need to use CXF or GroovyWS directly with the very nice ws-client plugin. Speed (of development) and simplicity.


text:
Q: Vee Validate field validation not updating I have created a settings page where users can update their email addresses. Everything worked fine but suddenly the validation is not updating anymore. Only the first change of the input field triggers validateState().
Any further changes will not trigger this function so the status of that field stays as it is.
I have compared the code with other components that use the same code and they still work fine.
I am using bootstrap-vue components for the form.

<template>

                 {{$t('general.save')}}

</template>

A: The problem you're having is that the form data element is an empty object, so it will only trigger reactivity when the whole object changes.  Either you need to change your data to be this:
    data() {
        return {
            form: {email:''},
            saving: false
        }
    },

Or in your init function, explicitly add the email property as reactive:
    methods: {
        init() {
            this.$set(form,'email',this.user.email)
        },
        //...

If you're not clear on why, you can read the details here:  https://v2.vuejs.org/v2/guide/reactivity.html
A working example (minus vuex) here: https://codesandbox.io/s/x4kp93w3o
PS, when writing questions about vue, it's very helpful to boil it down to a simpler example.  Get rid of vuex, remove your translation stuff.  Sometimes the answer will jump out at you once you have it as simple as possible.


text:
Q: Magento 1.9: Cronjob notification error I am getting magento cronjob error for indexing from this week i dont know how to get rid of i tried setting up cron like:

sh /home/jsbfurniture/public_html/cron.sh
sh /home/jsbfurniture/public_html/cron.php
sh -f indexer.php reindexall

A: Have you setup the Magento cron?
you can check by using crontab -l using ssh/putty:
If cron is not set please add this using crontab -e
* * * * * /bin/bash /path of root directory where magento is installed/cron.sh


text:
Q: Full screen Here Map has black bar at the bottom I'm using Here Maps JS API within a Vue application.  When toggling into full screen mode I'm dynamically setting the height of the container within which the Here Map is rendered. (100vh and 100vw)
I also have an event listener registered for the map so that it can respond to the resize event:
  window.addEventListener('resize', () => {
    this.map.getViewPort().resize();
  });

The map does take up the entire page as I can see the logo at the bottom of the screen but there's a black bar with no map details along the bottom:

What could be causing this?

A: Looks like this was to do with the vue-fullscreen component that was being used. Calling the fullscreen API directly doesn't have the same problem so we've removed the reliance on the 3rd party and use the browser API in our own components using:
this.$refs.map.requestFullscreen(); // $refs allows the retrieval of an element based on a ref attribute on the element

and
document.exitFullscreen();


text:
Q: setMultiChoiceItems() doesn't shows items Im using a DialogFragment to show a Dialog with a multi choice items, it shows the Dialog but without the items, there is no checkboxes to select.
This is how i invoke the dialog:
    botAddMedicacion.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment fragAddMedic = new AnadirMedicacionFragment();
            fragAddMedic.show(getFragmentManager(), "addMedicacion");
        }
    });

And this is the AnadirMedicacionFragment code:
    final CharSequence[] items={".NET","J2EE","PHP"};

@Override
public Dialog onCreateDialog(Bundle savedInstanceState){

    medicSelec = new ArrayList();

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage(R.string.anadir_medicacion);

    // elementos de la lista
    builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {

            if (isChecked) {
                medicSelec.add(which);
            } else if (medicSelec.contains(which)) {
                medicSelec.remove(Integer.valueOf(which));
            }

        }
    });

    // boton ok
    builder.setPositiveButton(R.string.anadir, new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    // boton cancelar
    builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    return builder.create();
}

The item list is passed in builder.setMultiChoiceItems(items, null[...]

It seems it works, but there are no checkboxes or list.

A: The problem is that you have a setMessage and a setMultiChoiceListener. You can only have one of them. Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.anadir_medicacion);


text:
Q: What is the most popular MMO game that has an out-of-game API World of Warcraft is off the table, because of the "WOW Glider Lawsuit" of 2008. Also see: Where is Blizzards official World of Warcraft API?
But, what is the most popular (in terms of usership) MMO Game that does allow programmers to develop out-of-game things (like an Android app).

A: EVE online has an API Here


text:
Q: Where to apply the parent theme class when using :host-context(.theme_name) in Angular2? I'm building a themed Angular2 app. I have loads of nested components and I would like to change the theme for the whole app by changing one parent class. Let's say one theme is called "theme1". When I apply this to a very parent html-tag, all the nested child components will then switch style by using :host-context, like this:
:host-context(.theme1) .title-toc {
    font-family: "bookmania";
    font-weight: 700;
    font-size: 20pt;
    text-transform: uppercase;
    color: #a5a5a5;
}

However, where to put this class="theme1"? When I put it to <body>, it worked so the code itself works, but I need to change the theme dynamically so it has to be inside some Angular component instead where I can use [ngClass]. For example inside AppComponent. But when I put it inside app.component (for example router-outlet or any other wrapping tag that should wrap my whole app), it didn't work anymore.
Do I have to make it deep with ::ng-deep somehow or what could be wrong?

A: You can bind to your root component element's class attribute like this:
export class AppComponent implements OnInit {

  @HostBinding('attr.class') mainClass = 'theme1';

  changeTheme(theme) {
    this.mainClass = theme;
  }

}

A: :host-context() sees the classes applied on the document body. You can set the class of body with JavaScript after the application has loaded, like this:
var myclass = "my-theme-name";
document.querySelector('body').classList.add(myclass);

This way you can load the theme name even from server and then apply it to the body from any Angular2 component via JS:
:host-context(.my-theme-name) .my-theme-specific-style


text:
Q: store foreign key as zero instead of it's value I have a table that all the values are foreign keys ,when I store these values it save it as zero not the value that I chose ,
public function create()
{
    $type=type::query()->pluck('type');
    $color=color::query()->pluck('colore');
    $region=region::query()->pluck('country');
    $size=size::query()->pluck('size');
    $brand=brand::query()->pluck('company');
    //$price=new_product::query()->pluck('price');
    return view('sale',compact('type','color','region','size','brand'));
}

public function store(Request $request)
{

    new_product::create($request->all());
    return redirect()->route('sale.index');
}

the model:
class new_product extends Model
{
    protected $table = 'enter_new_product';
    protected $fillable = ['type_id', 'color_id', 'region_id', 'size_id', 'brand_id','price'];

    public function type()
    {
        return $this->hasMany(type::class);
    }

    public function size()
    {
        return $this->hasMany(size::class);
    }

    public function color()
    {
        return $this->hasMany(color::class);
    }

    public function region()
    {
        return $this->hasMany(region::class);
    }

    public function brand()
    {
        return $this->hasMany(brand::class);
    }
}

the sale  view
{!! Form::open(['route' => 'sale.store', 'method' => 'post','files'=>true]) !!}

                    {!! Form::label('type_id', 'اسم الصنف') !!}
                    {!!Form::select('type_id',$type ,null, ['class'=>'form-control','placeholder'=>'ادخل اسم الصنف '])!!}

                    {!! Form::label('color_id', 'اللون') !!}
                    {!!Form::select('color_id', $color,null,['class'=>'form-control','placeholder'=>'ادخل  اللون '])!!}

{!! Form::submit('اضافة',array('class'=>'btn btn-primary btn-lg'))!!}
                {!!Form::close()!!}

it's a part of the view not all but the region,size and brand are the same as the color and type>

A: It would be nice to know how your request is looking (dd($request->all()) as a comment mentioned before, however I see one problem already, which probably would not help your main problem: The product has the foreign key so it does not have many of the regions and brands and the other stuff. The product hasOne of these relations.


text:
Q: Partial dependency Suppose we have a relation R(A,B,C,D,E) with candidate keys {A,B} , {C,D} and let E be a non prime attribute.
If there is a dependency C->E then it is partial dependency as E depends on a part of candidate key {C,D}
Is dependency BC->E partial?

A:
If there is a dependency C->E then it is partial dependency as E depends on a part of candidate key {C,D}

That "as" is unsound. It doesn't appeal to the definition of "partial functional dependency". We need to memorize & apply definitions exactly. (What published academic reference(s) are you using?)
FD X → Y is partial when it holds and some proper/smaller subset of X also determines Y. If all X attributes are in the relation then FD X → Y is partial when some proper/smaller subset of X also determines Y. (Because Armstrong's axioms say that the subset FD implies the X FD.)
Here FD C → E is partial when {} → E. (Ie when all rows have the same E value.) Armstrong's axioms say certain other FDs also hold since AB & CD are keys. The combined FDs that hold can't make E prime. But it turns out that we still can't know whether {} → E holds. So if C → E then we can't know whether C partially determines E.

Is dependency BC->E partial?

Here FD BC → E is partial when some proper/smaller subset of BC determines E. Ie when B → E, C → E or {} → E. It turns out that we can't know whether any of those four FDs hold. So we can't know whether BC → E, let alone whether it is partial. Although if B → E or C → E then FD BC → E is partial. (Because B & C are proper/smaller subsets of BC.)
(Normally we know a cover for the FDs that hold, which determines all FDs that hold, which determines the CKs and the non-prime attributes. Then because we know all the FDs that hold, we can determine which ones are partial. CKs are irrelevant to whether a FD is partial.)


text:
Q: json dataType is not working in jquery ajax method i'm just trying to query the database and display the result the jquery's ajax method but if i put the dataType property as json it is only logging the result which has only one object the following is my code:
//this is a method is an object which will be triggered after a selection was made
lister: function () {
    //this is to target the object as it is inside an event
    var self = users;
    //the ajax call
    $.ajax({
        url: 'index.php',
        type: 'POST',
        data: self.config.form.serialize(),
        //this is the dataType
        dataType: 'json',
        success: function (results) {
            //this for logging the result
            console.log(results);
        }
    });
}

the php code
if(isset($_POST['q']) && !empty($_POST['q'])){
    $na = $_POST['q'];
    $query = mysql_query("SELECT id,first_name, last_name
                          FROM users WHERE users.first_name LIKE '$na%'");

    $num=mysql_num_rows($query);
    if($num >= 1){
        while($row = mysql_fetch_array($query)){
            //encoding the result as json
            echo json_encode($row);
        }
     } else{
        echo "no results found ";
     }

     //here we return so it won't display all of the pages
     return;
}

A: You are generating invalid JSON. You are encoding every row of your table independently, which generates something like this:
{"foo": "bar"}{"foo": "bar"}{"foo": "bar"}

This is isn't valid. It's just a concatenation of objects. What you need is an array of objects:
[{"foo": "bar"}, {"foo": "bar"}, {"foo": "bar"}]

You can achieve that by creating an array first, add each row to it and encode the array:
$data = array();
while(...) {
    $data[] = $row;
}
echo json_encode($data);

Another problem is that in case no results are found, you are simple returning plain text, not JSON. This will probably result in an error on the client side. If you tell jQuery to expect JSON, then every possible response must be JSON. So you might want something like:
echo json_encode(array('error' => 'no results found'));

or even better, return an empty array:
echo json_encode(array());

It should be fairly obvious to the client that no results have been found if an empty array is returned.


text:
Q: Why does nobody use indentation in css? I find css quite hard to read sometimes. Indents, depending on the dom structure, would greatly increase readability. Consider the following example:
#page {
    text-align:center;
    font-weight:bold;
}
    #page p {
        white-space:nowrap;
    } #page p:hover {
            display:inline-block;
    }
    #page .myclass {
        text-align:left;
    }
        #page .myclass a {
            text-decoration: none;
        }
#footer {
    display:none;
}

Simple question: Why is nobody using intends in any way near to this? Even phpstorm does not support such indents by default: I have to navigate with -> and del inconveniently.
It seems that by convention, all css selectors have to start at the leftmost indent. This doesn't make sense to me, since I have literally never seen a stylesheet which even reached the rightmost edge of my monitor. Typical css sheet below.

A: No one is doing that because it does not make sense from a syntactical perspective. While it conceptually makes sense to indent items that have a child relationship with a parent item, it does not work well in practice for CSS.
Keep in mind that there is a distinction between DOM nodes and CSS selectors. Although elements may be nested within each other in the DOM, selectors are not nested within each other. In your example, #page p is actually not a child of #page; they refer to two distinct paths within the DOM.


text:
Q: M210 RTK V2 - OSDK 3.8/3.8.1 and Video stream not working (samples not working) I have successfully executed all the OSDK 3.8/3.8.1 samples regarding telemetry, FPV camera, etc. with an M210 RTK V2 (Frimware 1.0.0450) and a Zenmuse X4S. However, I have tested OSDK 3.8 and 3.8.1 in Ubuntu 16.04 and I have not succeed with the pre-made main camera samples (in this case, the camera-stream-callback-sample for retrieving the main camera image).
The problem is that the (OSDK 3.8.1) camera-stream-callback-sample is not working (RC turned ON). It is giving the following error:
Please enter the type of camera stream you want to view
m: Main Camera
f: FPV  Camera
m
Read App ID
User Configuration read successfully.

STATUS/1 @ init, L55: Attempting to open device /dev/ttyUSB0 with baudrate 921600...

STATUS/1 @ init, L65: ...Serial started successfully.

STATUS/1 @ parseDroneVersionInfo, L727: Device Serial No. = 1DADG3E00100TW

STATUS/1 @ parseDroneVersionInfo, L729: Hardware = PM420

STATUS/1 @ parseDroneVersionInfo, L730: Firmware = 3.4.3.31

ERRORLOG/1 @ initVirtualRC, L1103: Virtual RC is not supported on this platform!

STATUS/1 @ init, L49: Looking for USB device...

STATUS/1 @ init, L65: Found 13 USB devices, identifying DJI device...

STATUS/1 @ init, L83: Found a DJI device...

STATUS/1 @ init, L96: Attempting to open DJI USB device...

STATUS/1 @ init, L134: ...DJI USB device started successfully.

STATUS/1 @ activate, L1313: version 0x304031F

STATUS/1 @ activate, L1326:
STATUS/1 @ verify, L244: Verify subscription successful.
STATUS/1 @ initGimbal, L890: Checking if gimbal is connected ...
STATUS/1 @ startPackage, L350: Start package 0 result: 0.
STATUS/1 @ startPackage, L352: Package 0 info: freq=50, nTopics=1.

STATUS/1 @ removePackage, L468: Remove package 0 successful.
STATUS/1 @ init, L55: Attempting to open device  with baudrate 230400...

ERRORLOG/1 @ _serialOpen, L175: cannot open device

ERRORLOG/1 @ init, L60: ...Failed to start serial

STATUS/1 @ keep_camera_x5s_state, L44: Sending heart beat

ERRORLOG/1 @ sendData, L189: Port closed
STATUS/1 Connect to MAIN_CAMERA successful

STATUS/1 All components for decoding initialized ...

STATUS/1 User callback thread created successfully!

STATUS/1 **** MAIN_CAMERA data reading thread start! ****

STATUS/1 ****** Decoder Callback Thread Start ******

ERRORLOG/1 @ sendData, L189:
STATUS/1 @ keep_camera_x5s_state, L44:
ERRORLOG/1 @ sendData, L189:
STATUS/1
STATUS/1 @ keep_camera_x5s_state, L44:
ERRORLOG/1 @ sendData, L189:
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
ERRORLOG/1 @ sendData, L189:
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1 @ keep_camera_x5s_state, L44:
ERRORLOG/1 @ sendData, L189:
STATUS/1
STATUS/1
STATUS/1
STATUS/1
ERRORLOG/1 @ sendData, L189:
STATUS/1
STATUS/1
STATUS/1
STATUS/1
ERRORLOG/1 @ sendData, L189:
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1 @ keep_camera_x5s_state, L44:
ERRORLOG/1 @ sendData, L189:
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1
STATUS/1 @ keep_camera_x5s_state, L44:
ERRORLOG/1 @ sendData, L189:

With OSDK 3.8, the result is the following

I don't know what else to do, since it is official OSDK with supported M210RTK V2 and Zenmuse X4S. I have tested the FPV and it works successfully.
Can anybody provide some help? Thank you in advance.

A: Solution: In Ubuntu 16.04 and OSDK 3.8.1 with M210 RTK V2 (all the checklist met and the RC turned on) the sample has to be called like this:
./camera-stream-callback-sample UserConfig.txt /dev/ttyACM0
Hope it helps.


text:
Q: Changing a C# delegate's calling convention to CDECL I have had this problem with C# when I was using DotNet1.1
The problem is this. I have an unmanaged dll, which has a function which takes a function pointer (among other arguments). When I declare the DLLImport in C# code, I pass a delegate. But the delegates in C# have stdcall calling convention whereas the unmanaged function expects a cdecl function pointer. Thus my naive approach resulted in crashes. Then I found the following: http://www.codeproject.com/KB/cs/cdeclcallback.aspx Some guy wrote an excellent library that enables changing calling convention of the delegate by, as I understood, MSIL-hacking. Things went well, until...
I migrated to VS2008 and the new version of .NET. Under this version the abovementioned library doesn't work. I am not really a C# or .NET expert, and, to tell the truth, I barely understand what his library does (although it's open-source), so I don't even want to try to adapt it to new .NET. However I am hoping that newer version of C# has some better solution available for my problem.
So, SO experts, please help me with my pain in the buttocks :)

A: By default the p/invoke system wraps your delegate in a stdcall function. You can change the generated wrapper's calling convention by using the UnmanagedFunctionPointer attribute:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MyDelegate();


text:
Q: How do I get package versions in c++? (linux) I've been writing a program that needs a wine version of 2.6 or later. I'd like to get it as a boolean, so I've been trying to use the code below:
#include <string>
#include <iostream>
#include "WineCheck.h"
#include <cstdlib>

using namespace std;

bool checkForWine()
{
    // Create variables for checking wine state
    bool wineIsThere   = false;
    bool wineIsVersion = false;

    // Check dpkg if wine is there
    if (string(system("dpkg -l | cut -c 4-9 | grep \\ wine\\ ")) == " wine ")
        {
        wineIsThere = true;
        // Check version
        if (double(system("wine --version | cut -c 6-8")) >= 2.6)
            wineIsVersion = true;
        }

    // Return
    if (wineIsThere && wineIsVersion)
        return true;
    else
        return false;
}

A: First, it's my opinion you shouldn't bother with this. Wine 2.6 should just be included as a dependency in your configuration script, and/or your package file. Targeting a specific package management system in your program source code is not a good idea if you want to maintain portability to other GNU/Linux distributions that don't use that packager.
To answer your question though. There are two ways I found you can do this. You can check /var/lib/dpkg/status. Read through the file line by line until you get to this section. If you don't find the section, or the Status: ... line doesn't say installed then wine is not installed. The Version: ... line will tell you what version is installed. I verified this method works by installing and uninstalling Wine on Debian Wheezy. You didn't say what distro you're working with, but it's obvious you're using the Debian Packaging system, so this should work on Ubuntu and other Debian based distributions as well.
$cat /var/lib/dpkg/status
...
Package: wine
Status: install ok installed
Priority: optional
Section: otherosf
Installed-Size: 80
Maintainer: Debian Wine Party <pkg-wine-party@lists.alioth.debian.org>
Architecture: amd64
Version: 1.4.1-4
...

The other option is use libdpkg. I found an example that lists all installed packages.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>

#include <dpkg/dpkg.h>
#include <dpkg/dpkg-db.h>
#include <dpkg/pkg-array.h>
#include "filesdb.h"

const char thisname[] = "example1";

int
main(int argc, const char *const *argv)
{
    struct pkg_array array;
    struct pkginfo *pkg;
    int i;
    enum modstatdb_rw msdb_status;

    standard_startup();
    filesdbinit();
    msdb_status = modstatdb_open(msdbrw_readonly);
    pkg_infodb_init(msdb_status);

    pkg_array_init_from_db(&array);
    pkg_array_sort(&array, pkg_sorter_by_name);

    for (i = 0; i < array.n_pkgs; i++) {
        pkg = array.pkgs[i];
        if (pkg->status == stat_notinstalled)
            continue;
        printf("Package --> %s\n", pkg->set->name);
    }

    pkg_array_destroy(&array);

    modstatdb_shutdown();
    standard_shutdown();

}


text:
Q: PostGresqL full-text Search characters problème Well my problem is : I am using the full-text search of postgresql with a french dictionnary,
and I have in my data base some descriptions that contains names with one character for exemple :
Amphi 'A' , Amphi 'C, Amphi 'D' ...
well, for that, when I use tsvector auto creation trigger, somme names don't appear,
for Amphi A I got 'amphi':1 'a':2 but for Amphi 'C' is 'amphi':1 without the it's name.
please help me :D

A: That's because f.ex. C and D considered to be stop words in the french dictionary:
SELECT to_tsvector('french', 'Amphi A'); -- 'a':2 'amphi':1
SELECT to_tsvector('french', 'Amphi C'); -- 'amphi':1

You can create a custom dictionary (& a configuration for that) without stop words by:
CREATE TEXT SEARCH DICTIONARY french_stem_nostop(
    TEMPLATE = snowball,
    LANGUAGE = 'french'
);

CREATE TEXT SEARCH CONFIGURATION french_nostop(COPY = french);
ALTER TEXT SEARCH CONFIGURATION french_nostop
    ALTER MAPPING FOR asciihword WITH french_stem_nostop;
ALTER TEXT SEARCH CONFIGURATION french_nostop
    ALTER MAPPING FOR asciiword WITH french_stem_nostop;
ALTER TEXT SEARCH CONFIGURATION french_nostop
    ALTER MAPPING FOR hword WITH french_stem_nostop;
ALTER TEXT SEARCH CONFIGURATION french_nostop
    ALTER MAPPING FOR hword_asciipart WITH french_stem_nostop;
ALTER TEXT SEARCH CONFIGURATION french_nostop
    ALTER MAPPING FOR hword_part WITH french_stem_nostop;

SELECT to_tsvector('french_nostop', 'Amphi C'); -- 'amphi':1 'c':2


text:
Q: Can you transfer attributes from one class instance to another without using inheritance? I'm building a Tkinter app and it is currently all one big class. I'm trying to split it into smaller pieces to make it easier to work on. The problem is some of the smaller pieces contain elements that are referenced elsewhere in the larger app.
editing to add more code:
OK so say I am using init_library to make a big complicated frame which then becomes self.library.
class GUI:
  def __init__(self):
    self.root = tk.Tk()
    self.init_library()
    self.root.mainloop()
    return

  def init_library(self):
    self.library = tk.Frame(self.root)
    [...]
    self.library_var = tk.StringVar("HEY")
    self.library_label = tk.Label(self.library, textvariable=self.library_var)
    [...]

  def action(self, new_text):
    [...]
    self.library_var.set(new_text)
    [...]

So assume that init_library is large and I would like to put it in a different file to make life easier. Now instead of a class function, I just instantiate LibraryClass.
from pieces import LibraryClass

class App:
  def __init__(self):
    self.root = tk.Tk()
    self.library = LibraryClass()
    self.root.mainloop()
    return

The problem is library_var is now a child of self.library instead of App. So we would have to change action.
  def action(self, new_text):
    [...]
    self.library.library_var.set(new_text)
    [...]

Is there a way to directly assign the LibraryClass functions and attributes of self.library to App?
(I know it seems like a small thing but it would really make my life easier)


text:
Q: Simple email forwarding server I need to forward emails for a several domains to other email addresses. Previously I have used hMailServer on my Windows server to perform this forwarding function, but I am looking for something simpler that I can interface with from a .NET application.
Is there a simple email forwarding server I can easily manage from .NET? Spam filtering or email storage is not required.

A: I've never used hMailServer but according to the documentation there's a COM API that looks like it would be automation compatible (since they've got VBScript samples) so you should be able to access this from .Net.
I'd suggest looking at the Rule object or the forum


text:
Q: Rename values not contained in a specific list I need your assistance in completeing the following task:
I would like to change all values of a column in pandas to 'others' expect specific 10 values.
Example :
Column a
1
2
3
4
5
5
5
6
6
6

List_not_change = ['1','2','3']
rest change to 'other'
Expected Result :
Column a
1
2
3
other

A: Use Series.isin for mask and replace by mask in DataFrame.loc:
#if values are integers
List_not_change = [1,2,3]

#if values are strings
#List_not_change = ['1','2','3']

df.loc[~df['Column a'].isin(List_not_change), 'Column a'] = 'other'


text:
Q: After rsync folders have different sizes I have used rsync to copy a folder from one machine to another. The folder is very large and has thousands of subdirectories and in total millions of files. After the transfer (which was interrupted a couple of times) I check the folder on each machine. The results do not match:
Source Folder: 430 Gb
Target Folder: 415 Gb
I tried rsyncing again but all the subdirectories are skipped. I have also tried adding the --checksum to the command and it still skips everything. Is this difference of 15Gb explainable? If not is there some way to find which files do not match?
Update
The rsync command I use is:
rsync user@source:folder target

A: There are a couple of reasons why there may be, or one may see, differences in sizes reported.

*

*Reported sizes depend on the command you use, and what specifically is measured. The space used by the file, moreover, may depend on the file system and formatting options used to format the drive. Linux file systems also support sparse files. That means that parts of the files (e.g. binaries) that are empty are not physically stored on disk. Thus, the physical size of the file on disk (as reported by du) is smaller than its logical file size (as reported by du --apparent-size or ls).

*Another factor that may cause sizes of an rsync copy to differ is the presence of hard links. By default, hard links, i.e. different files pointing to the same information on disk, will be copied as separate files, thus take twice the space.

*Yet another possible cause of a size difference is that you repeated the backup. By default, rsync will preserve files on the copy that may have been deleted in the source. One must add the --delete option to also delete these files on the targer.
The two latter reasons would lead to a target folder larger than the source folder, so this will not be an explanation in your current case.
rsync is a very reliable tool, and its file comparison algorithms are robust. It compares files based on time stamp and byte size (logical size) of the file. Thus, if rsync reports no further files need to be transferred, then you can trust that.


text:
Q: Problemas en código INSERT INTO en MySQL Tengo un sitio en go daddy pero el código que tengo no me permite subir la tabla, por favor si alguien puede tener una solución se lo agradezco mucho, a continuación dejo el código que actualmente manejo:
if(isset($_POST['new'])){

    $id = $_POST['id'];
    $nombre = $_POST['nombre'];
    $categoria = $_POST['categoria']; //categoria
    $username = $_POST['username'];
    $password = $_POST['password'];
    $fechacreacion = date('d-m-Y');

    if (empty($nombre)) {
        echo '<script> window.location="?p=administradores-new&id='.$id.'&error=1"; </script>';
        return;
    }if (empty($categoria)) {
        echo '<script> window.location="?p=administradores-new&id='.$id.'&error=1"; </script>';
        return;
    }
    if (empty($username)) {
        echo '<script> window.location="?p=administradores-new&id='.$id.'&error=1"; </script>';
        return;
    }
    if (empty($password)) {
        echo '<script> window.location="?p=administradores-new&id='.$id.'&error=1"; </script>';
        return;
    }

    $nuevo_usuario=mysqli_query($conexion, "SELECT nombre FROM administracion WHERE nombre='$nombre'");
    if(mysqli_num_rows($nuevo_usuario)>0){
        echo '<script> window.location="?p=administradores-new&id='.$id.'&error=2"; </script>';
        return;
    }

    $consulta = "INSERT INTO administracion (id, status, nombre, categoria, username, password, fechacreacion) VALUES ('', 1, '$nombre', '$categoria', '$username', '$password', '$fechacreacion')";
    $resultado = $conexion -> query($consulta)|| die("Ha ocurrido un error al guardar los datos");
    if($resultado)
    {
    echo "Enhorabuena, la acción ha sido llevada a cabo con éxito";
    }
    else
    {
    echo "Ha ocurrido un error";
    }

}


text:
Q: JLabel only showing the last label I'm trying to create multiple labels on a Frame. Every example I've seen has done it exactly how I've done it...
JLabel label1 = new JLabel("Label 1");
JLabel label2 = new JLabel("Label 2");
//... goes on through label5

frame.add(label1);
frame.add(label2);
//... etc through label 5.

Only label 5 is being display. If I comment out 5, only label 4 is display. It's only displaying whatever the last label is.

A: It depends on which LayoutManager you have set. Probably you left the default BorderLayout and therefore all of them are added to center and streched to window size. So the last added one - of course - covers all the previously added labels. Try using a FlowLayout or something else: See this A Visual Guide to Layout Managers
So assuming you are creating the GUI elements within a child of JFrame, this is how a layout manager is set:
setLayout(new FlowLayout());
//...
add(label1);
add(label2);
add(label3);
//...


text:
Q: Поиск картинок, изображений на сайте Как сделать поиск на сайте, на языке php который выводит только изображения.
К моему сожалению, получилось сделать только не сложную форму форму для получения данных.
Посоветуйте, пожалуйста, какие можно использовать парсеры сайта?
Желательно с примерами, так как нет в этом опыта.
Спасибо.


text:
Q: jQuery UI Tabs in table offsetting content in other cells? I've built up a template using a 3 column layout using a table (according to the advice given here).  Then, I'm putting in some jQuery UI tabs into one of the cells.  However, the content in the other cells appears to be offset by the tabs header.  I'm quite stumped by what is happening and cannot trace back to where this offset is coming from using Firebug or how to shift the vertical position of the content in the other cells.

Left

Lorem ipsum...

 Tab1

 Tab2

Nunc volutpat ...

Lorem ipsum ...

Any ideas on how to fix this?  Here is a site with this issue.

A: In the resets.css you can set the vertical align to 'top' instead of 'baseline'
vertical-align: top;

A: Your real problem is this:
.ui-helper-clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

And in particular, the clear:both;. Try changing the clearfix technique:
#right .ui-helper-clearfix {
    clear: none;
    overflow: hidden;
}

This question is starting to look at lot like this one: CSS Layout: 2 column fixed-fluid (again)


text:
Q: Inserting data into a related database. C# I've got two tables that i'm trying to insert data into with my C# application. They related with the ID.
I've read afew questions on how to do this but none of them have worked, I've now decided to do them as separate sql queries.
 private void btnSave_Click(object sender, EventArgs e)
        {
            //table 1
            String acctCode = tbAcctCode.Text;
            String address1 = tbAdd1.Text;
            String address2 = tbAdd2.Text;
            String address3 = tbAdd3.Text;
            String balance = tbBalance.Text;
            String yearSales = tbSales.Text;
            String yearCost = tbCost.Text;
            //table 2
            String date = tbDate.Text;
            String transaction = tbTrans.Text;
            String docNum = tbDocNum.Text;
            String grossVal = tbGross.Text;
            String vatVal = tbVat.Text;

            //SQL statement set to Add a new value
            sql = String.Format("INSERT INTO "+ table1 + "(Account_Code,Address1,Address2,Address3,Balance,Sales_Year_To_Date,Cost_Year_To_Date) " +
                                 "VALUES " +
                                 "('{0}'," + "{1}," + "{2}," + "'{3}'," + "'{4}'," + "{5}," + "'{6}');", acctCode, address1, address2, address3, balance, yearSales, yearCost);

            sql2 = String.Format("INSERT INTO " + table2 + "(Date,Transaction_Type,Document_No,Gross_Transaction_Value,Vat_Value) " +
                                 "VALUES " +
                                 "('{0}'," + "'{1}'," + "'{2}'," + "'{3}'," + "'{4}');", date, transaction, docNum, grossVal, vatVal);

            try
            {
                dbConn = new OleDbConnection(conString);
                dbCmd = new OleDbCommand(sql, dbConn);

                dbConn.Open();
                dbCmd.ExecuteNonQuery();
                dbCmd = new OleDbCommand(sql2, dbConn);
                dbCmd.ExecuteNonQuery();
            }
            catch (SqlException E)
            {
                MessageBox.Show(E.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                dbConn.Close();
            }

        }
    }

The data is inserted into the first table fine but the problem comes in at the OleDbCommand of the sql2. "It throws a System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'"
I've got a feeling something in my sql syntax is wrong but I can't spot it.

A: Try This Would Be Prefect

private void btnSave_Click(object sender, EventArgs e)
{
    //SQL statement set to Add a new value
        sql = String.Format("INSERT INTO " + table1 + "(Account_Code,Address1,Address2,Address3,Balance,Sales_Year_To_Date,Cost_Year_To_Date) " +
                             "VALUES " + (@acctCode, @address1, @address2, @address3, @balance, @yearSales, @yearCost));

        sql2 = String.Format("INSERT INTO " + table2 + "([Date],Transaction_Type,Document_No,Gross_Transaction_Value,Vat_Value)" +
                             "VALUES " + (@date, @transaction, @docNum, @grossVal, @vatVal));

        try
        {
            dbConn = new OleDbConnection(conString);
            cmd = new OleDbCommand(sql, dbConn);

            //table 1
            cmd.Parameters.AddWithValue("@acctCode", tbAcctCode.Text);
            cmd.Parameters.AddWithValue("@address1", tbAdd1.Text);
            cmd.Parameters.AddWithValue("@address2", tbAdd2.Text);
            cmd.Parameters.AddWithValue("@address3", tbAdd3.Text);
            cmd.Parameters.AddWithValue("@balance", tbBalance.Text);
            cmd.Parameters.AddWithValue("@yearSales", tbSales.Text);
            cmd.Parameters.AddWithValue("@yearCost", tbCost.Text);

            dbConn.Open();
            cmd.ExecuteNonQuery();
            cmd = new OleDbCommand(sql2, dbConn);

            //table 2
            cmd.Parameters.AddWithValue("@date", tbDate.Text);
            cmd.Parameters.AddWithValue("@transaction", tbTrans.Text);
            cmd.Parameters.AddWithValue("@docNum", tbDocNum.Text);
            cmd.Parameters.AddWithValue("@grossVal", tbGross.Text);
            cmd.Parameters.AddWithValue("@vatVal", tbVat.Text);

            cmd.ExecuteNonQuery();
        }
        catch (SqlException E)
        {
            MessageBox.Show(E.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            dbConn.Close();
        }
    }


text:
Q: organizing technical and user-facing error messages in php I'm having a little trouble organizing my error messages for two interacting classes. One object has states that are 'error-ish', where something went wrong, or happened unexpectedly, but the situation is still salvageable. I don't want to use exceptions, 1. because they only have a single string for the message, and 2. because I want to access the object after the error. At the very least, I want to use some of its get() methods to construct a useful error message after the exception!
Ultimately I have two messages I want to communicate: one to myself as the coder, that something went wrong. This string would have the technical details of the file, line, function/method, arguments, and results. Obviously, I don't want to show this to the user, so there is another string of an error message that I want to show the user ("That email address was not found" kind of thing ).
So the thought occurs to me to build an error message array, which could use the error code from exceptions, or a status code, as keys for various messages. ( Though if I do this, where do I store the array of messages? ) Another option might be to make an error status object.
Is there anything like "error patterns", similar to design patterns?

A: Exceptions really are your best option, they do everything you asked. Even multiple messages are possible, since exceptions are just classes that you can extend. You could just pass the object that causes the exception to said exception.
<?php
class ExampleException extends Exception {
  private $secondMessage;
  private $objectThatCausedIt;
  public function __construct( $secondMessage, $objectThatCausedIt ) {
    parent::__construct(
      "Descriptive message for developer",
      // error code for this type of error
      1000 );
    $this->secondMessage = $secondMessage;
    $this->objectThatCausedIt = $objectThatCausedIt;
  }
  public function getSecondMessage() {
    return $this->secondMessage;
  }
  public function getObjectThatCausedIt() {
    return $this->objectThatCausedIt;
  }
}

class Example {
  public function causeException() {
    throw new ExampleException( "Second Message", $this );
  }
}

Now you just use the class and wrap the call that might throw the exception in a try-catch block.
<?php
$example = new Example();
try {
  $example->causeException();
}
catch ( ExampleException $e ) {
  // kind of pointless here, just an illustration
  // get object that caused it and do something with it.
  dump_and_log_function( $e->getObjectThatCausedIt() );
  // or just use $example, which is still "alive"
  // and references the same instance
  dump_and_log_function( $example );
}

Extending Exception has the benefit that you also get a stack backtrace. The backtrace contains information like in what file, line and function the exception occured. You can also access the error code, the message and more. I suggest you read the PHP documentation on Exceptions (http://php.net/manual/en/class.exception.php) for more information.
Regarding the error messages and logging, I usually use a singleton class for that. A singleton class has only one instance of itself (in case you didn't know.) Here is an extremely simple example:
<?php
class Log {
  private $logFile;
  private static $instance;
  /* Log instances may only be constructed in Log::getInstance */
  private function __construct() {
    $this->logFile = fopen( "path/to/log/file", "a" );
  }
  public logMessage( $message ) {
    fwrite( $this->logFile, $message );
  }
  public static getInstance() {
    if ( !self::$instance ) self::$instance = new self();
    return self::$instance;
  }
}

Now going back to the exception handling throw-catch block, you can change it to something like this:
<?php
$example = new Example();
try {
  $example->causeException();
}
catch ( ExampleException $e ) {
  // log developer message and backtrace
  Log::getInstance()->logMessage( $e->getMessage() );
  Log::getInstance()->logMessage( $e->getTraceAsString() );
  // or more compact by casting to string
  Log::getInstance()->logMessage( (string)$e );
  // and now print error for users
  echo "
An Error has occured: {$e->getSecondMessage()}
";
}

Instead of echoing the error message right away, you could make the Log class have a property with an array of messages. Then you could list them later in a view script all at once. You could also make the logMessage method store the messages in the session so they could be displayed after a refresh (just don't forget to clear the messages from the session or they will be displayed over and over again ;-).

A:
I don't want to use exceptions, 1.
  because they only have a single string
  for the message, and 2. because I want
  to access the object after the error.
  At the very least, I want to use some
  of its get() methods to construct a
  useful error message after the
  exception!

You can create your own exception classes and you can extend PHP's exception classes, adding the support you need. However, possibly you can have two settings, developer and client, where client errors goto the display and developer errors don't instead going to a log file or something.
Which, translates into two custom exception types (though you could have many more, I'm saying two distinct base classes).


text:
Q: Decoding python data Sorry for what might be a quite simple question. I know a few languages, but I'm new regarding python.
I'm collecting via an IOT device the following data and here are all the info I can get :
print('This is my data : %s' % (data)) => "This is my data : b'\x95\xfe683475065015121'"
print(type(data)) => "<class 'str'>"

The thing is, I'd like to get numeric values extracted from data such as :

*

*Discard the \x95\xfe at the begining

*a = 68.3 (3 first digits / 10)

*b = 475 or 475.0 (3 next digits)

*c = 065 or 65.0 (3 next digits)...

*... (I'll get the rest from here I think.)

Thanks a lot for your help and have a great day.
PS : I already tried float.fromhex(data[y:Z]) - or data.decode("hex"), but no luck... bytes.fromhex(data[y:z]) got me a strange result as well...

A: Sure:
t = b'\x95\xfe683475065015121'
t = t[2:]  # disregard \x95\xfe
print(t)

a = int(t[:3]) / 10
b = int(t[3:6])
c = int(t[6:9])
print(a, b, c)  # >>> 68.3 475 65