text:
Q: Dell Precision 7910 Ubuntu 14.04 freezes I am currently running Ubuntu 14.04 LTS (fresh install) on a Dell Precision 7910.  When I attempt to do any heavy analysis (ie. processing 4-10 large files at one time), the machine completely freezes.  Neither the mouse nor keyboard respond, and I end up doing a hard reboot.  ALT + PrtScn + R E I S U B did not do anything.
I looked at the log files, but there is nothing there from the time of the freeze.
Although I am quickly able to reproduce this problem running a particular java program called GATK, I have also run into it while running C programs.  Sometimes it freezes right away, and other times it takes 20-30 minutes.
The Dell ePSA diagnostics test and memtest86+ test both passed.
Can anyone provide a step-by-step way to figure out what may be causing the system to freeze?
Thanks for your help!
RC

A: I would start further investigating by monitoring system resources leading up to the freeze. Basic tools like htop or top, and iotop work well. Maybe RAM or swap is filling up, or disk I/O is being held by 1 process?
You can try setting the CPU affinity of your intensive process, or setting its niceness (I believe there is I/O niceness as well), to try to prevent resource starvation for kernel/system processes.

A: After hours of googling, I read something similar where a complete system freeze was caused by some sort of error in the processor clock (?).  I went into the BIOS and disabled the "Intel Hyperthreading Technology", and this seems to have fixed it.  Although my machine now shows 8 cores, rather than 16 cores, it is no longer crashing.  I can live with this, however, if anyone has any ideas on how to enable the hyperthreading without major crashes, I would love to try it.
Thanks,
RC


text:
Q: Tamanho de uma String usando Listas Como eu faço pra imprimir o tamanho de cada uma das strings que o usuário digitar? Toda vez que eu peço pra imprimir sai quantas strings tem dentro da lista e não a quantidade de caracteres de cada string dentro
lista = []
while True:
    nome = str(input())
    if nome == 'fim' or nome == 'FIM':
        break

    lista.append(nome)

print(len(lista))```

A: se vc quiser printar a quantidade de letras em cada string dentro de uma lista vc deve percorrer ela desta forma:
lista = []
while True:
    nome = str(input())
    if nome == 'fim' or nome == 'FIM':
        break

    lista.append(nome)

for item in lista:
  print(len(item))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I add a space between words in jQuery? I have a jQuery function that returns a row from a database table. When it is displayed in a textbox, the words all run together. For example:  Everyonepleasebecarefulwhenleavingthebuilding. I would like to separate the words to read: Every one please be careful when leaving the building. This comes from user input, so the user clicks on whatever row he wishes to be displayed in the textbox. Each row contains different data. The code listed below is what triggers the event:
$(document).ready(function() {
    $("table tr").click(function(){
        $("#txttread").val($(this).text());
    });
});

$(document).ready(function() {
    $('.pickme tr').not(':first').hover(
        function() { $(this).addClass('highlight'); },
        function() { $(this).removeClass('highlight'); }
    ).click( function() {
        $('.selected').removeClass('selected');
        $(this).addClass('selected').find('input').attr('checked','checked');
    });
});

A: When a table-row is clicked, cycle over its table-cells, adding each of their words to an array. Lastly, join that array by spaces and set its result as the value of your input field:
$("#statements").on("click", "tr", function(){
    var words = [];
    $("td", this).text(function(i,v){ words.push( v ); });
    $("#txtread").val( words.join(" ") );
});

Fiddle: http://jsfiddle.net/EXPBp/1/

A: You need to go through each cell and get its text separately, instead of just grabbing the text of the row:
$(document).ready(function(){
  $("table tr").click(function(){
       $("#txttread").val($.map($(this).children('td'), function (item) { return $(item).text() }).join(' '));
  });
});

Working fiddle at http://jsfiddle.net/kSsYD/


text:
Q: How do you create a SOAP service in CQ5 (AEM) Does anyone know how to create a SOAP service in CQ5? Found the following link but this looks more like a hack. Is there any other way to do it?

A: adaptTo is one of the more technical conferences, so a presentation there should carry a lot of weight.
The long & short of it is you will want to find the OSGi versions of whatever XML libraries you wish to use and load them into Felix, then you have access to those libraries in your servlets/services/components (the felix kind).


text:
Q: How to show JSON response in iPhone using the objective c by dynamically adding " \" to the keys? I am having a sample code which helps me to print the JSON response. In this I manually added the \ slash symbol before keys and values so it helps me to print the JSON . The code is :
NSString *jsonString = @"[{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";

Now the problem is once the JSON string gets longer I have to manually add the \ before every key.
Can someone help of how I can add "" before the keys as shown in the code above using some looping code?
Any help will be appreciated.

A: It's really not clear what you're trying to do - but maybe this will work...
Use:
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
                                        withString:(NSString *)replacement;

The target will be ", and you'll need to escape it like this:
@"\""

The replacement will be \", escaped like this:
@"\\\""

So, this:
NSString *jsonString = @"[{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";
NSLog(@"%@", [jsonString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]);

will output this to the debug console:
2022-10-11 12:35:58.958881-0400 YourProj[6562:7795515] [{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]

When receiving json from remote, it might look like this:
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSString *js = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", [js stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]);


text:
Q: Mutate across with ifelse and is.na I have data in the format outlined below, where all of the variables I need to work with are either NA or the name of the variable, and I need to change the NAs to 0 and the strings to 1. I'm trying to use dplyr::across() and ifelse(), but what gets returned is all 1s. The only solution I have right now that works is mutating each variable individually.
How would I change all NAs to 0 and all strings to 1 across multiple variables at once?
library(dplyr)
color_names <- c("black", "grey", "white", "purple")

my_colors <- tribble(
  ~black, ~grey, ~white,  ~purple,
  NA,     "grey", NA,     "purple",
  NA,     NA,     "white", NA,
  "black",NA,     NA,      NA,
  NA,     "grey",  NA,     NA
)

my_colors %>%
  mutate(across(all_of(color_names), ~ifelse(is.na(cur_column()), 0, 1)))
#> # A tibble: 4 x 4
#>   black  grey white purple
#>   <dbl> <dbl> <dbl>  <dbl>
#> 1     1     1     1      1
#> 2     1     1     1      1
#> 3     1     1     1      1
#> 4     1     1     1      1

Created on 2021-01-13 by the reprex package (v0.3.0)

A: Using across you can avoid ifelse by doing :
library(dplyr)
my_colors %>% mutate(across(.fns = ~+(!is.na(.))))

However, you can also avoid across since is.na works with dataframes/tibbles.
my_colors[] <- +(!is.na(my_colors))
my_colors

#A tibble: 4 x 4
#  black  grey white purple
#  <int> <int> <int>  <int>
#1     0     1     0      1
#2     0     0     1      0
#3     1     0     0      0
#4     0     1     0      0

!is.na(.) returns a logical vector TRUE/FALSE and + is used to convert them to 1/0.

A: I guess you could do it like this:
library(tidyverse)
color_names <- c("black", "grey", "white", "purple")

my_colors <- tribble(
  ~black, ~grey, ~white,  ~purple,
  NA,     "grey", NA,     "purple",
  NA,     NA,     "white", NA,
  "black",NA,     NA,      NA,
  NA,     "grey",  NA,     NA
)

my_colors %>%
  mutate(across(.cols = everything(),
                .fns = ~ ifelse(is.na(.x) == TRUE, 0, 1)))

# A tibble: 4 x 4
  black  grey white purple
  <dbl> <dbl> <dbl>  <dbl>
1     0     1     0      1
2     0     0     1      0
3     1     0     0      0
4     0     1     0      0

A: You can try this:
my_colors %>% mutate(across(everything(), ~if_else(is.na(.x), 0, 1)))

A: This also works, I think is the simplest way.
tribble(
  ~black, ~grey, ~white,  ~purple,
  NA,     "grey", NA,     "purple",
  NA,     NA,     "white", NA,
  "black",NA,     NA,      NA,
  NA,     "grey",  NA,     NA
) %>%
  modify(~ ifelse(is.na(.), 0, 1))

# A tibble: 4 x 4
  black  grey white purple
  <dbl> <dbl> <dbl>  <dbl>
1     0     1     0      1
2     0     0     1      0
3     1     0     0      0
4     0     1     0      0


text:
Q: Float parsing in C# In C# I declared an array of float in main()
float[] notas = new float[8];

Called the method and passed the array by reference also in main()
PopulateArray(ref notas);

Here's the implementation of the method PopulateArray(ref float[] arr1)
static void PopulateArray(ref float[] arr1)
    {
        bool vakid;

        for (int i = 0; i < arr1.Length; i++)
        {
            do
            {
                do
                {
                    Console.Write($"Insira nota {i + 1}  ==>");
                    vakid = float.TryParse(Console.ReadLine(), out arr1[i]);
                    if ((arr1[i] > 20.0) || (arr1[i] < 0.0))
                    {
                        Console.Write("\n\n\t\tAs notas só vão de 0 a 20\n\nPrima uma tecla para continuar");
                        Console.ReadKey();
                    }
                    Console.Clear();

                }while (!((arr1[i] <= 20) && (arr1[i] >= 0)));

            } while (!vakid);
        }

    }

Used two loops, one to assure that the value inputed is between [0, 20] and another to ensure that whatever input is a decimal number (float). Before this implementation, the array notas was of integer and everything was working just fine, only integers were allowed and also in between the interval of [0, 20]. When I decided to change the type of data to float, whenever I type a decimal number (i.e. 3.0) it doesn't go through the outter loop, like if I were typing a character other than a number, much in the same way as when I type a letter.
So how can I type decimal numbers to store in my array? Ty

A: I propose this alternative implementation :
static void PopulateArray(float[] arr1)
{

    for (int i = 1; i <= arr1.Length; i++)
    {
        float nota;

        Console.Write($"Insira nota {i}  ==> \n");

        while(! float.TryParse(Console.ReadLine(), out nota) || nota > 20.0f || nota < 0 )
        {
           // Bad input message
            Console.Write("\n\n\t\tAs notas só vão de 0 a 20\n\nPrima uma tecla para continuar");
        }

        arr1[i] = nota;
    }
}

Note that you don't need to pass the array by reference. It's a reference type, so a copy of the reference is passed and the method can work on it.

A: Culture issue aside (decimal separator of . vs ,), I'd get rid of one of the do loops like this:
    static void PopulateArray(float[] arr1)
    {
        bool vakid;
        for (int i = 0; i < arr1.Length; i++)
        {
            do
            {
                Console.Write($"Insira nota {i + 1}  ==>");
                vakid = float.TryParse(Console.ReadLine(), out arr1[i]);
                if (vakid)
                {
                    if ((arr1[i] > 20.0) || (arr1[i] < 0.0))
                    {
                        vakid = false;
                        Console.Write("\n\n\t\tAs notas só vão de 0 a 20\n\nPrima uma tecla para continuar");
                        Console.ReadKey();
                    }
                }
                else
                {
                    Console.Write("\n\n\t\tInvalid Entry\n\nPrima uma tecla para continuar");
                    Console.ReadKey();
                }
                Console.Clear();
            } while (!vakid);
        }
    }


text:
Q: How to load json api data to html template in angular? Can anyone help me with a simple question(I guess). I'm trying to display a json file in a table through Django into an Angular front end app. I can view the data by console logging it, however I can't seem to get the data into the webpage.
I know how to display the table in HTML. The specific problem is that the object which is fetched from the API does not appear in the HTML.
component.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild,

ViewEncapsulation } from '@angular/core';
import  ApexChart  from 'apexcharts'
import { ApexOptions } from 'ng-apexcharts';
import { FinanceService } from 'app/modules/admin/dashboards/finance/finance.service';

@Component({
  selector: 'app-finance',
  templateUrl: './finance.component.html',
  styleUrls: ['./finance.component.scss'],
  encapsulation  : ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FinanceComponent implements OnInit {

    _stockData: any;
    _portData: any;
    _effData: any;
    _calData: any;
    _labels: any;
    _table: any;

    constructor(
        private _financeService: FinanceService,
    ){
    }

    ngOnInit(): void {
        this._financeService.getFinanceData()
        .subscribe((res: any) => {
            console.log(res);
            this._stockData = res.stocks;
            this._portData = res.port;
            this._effData = res.eff;
            this._calData = res.cal;
            this._labels = res.labels;
            this._table = res.table;
            console.log(res.table);
            this._prepareChartData();
        },

        (response) => {

            // Re-enable the form
        });
    }

Service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, switchMap } from 'rxjs/operators';
import { BehaviorSubject, of, Observable } from 'rxjs';
import { environment } from 'environments/environment';

@Injectable({
  providedIn: 'root'
})
export class FinanceService {

    /**
     * Constructor
     * @param {HttpClient} _httpClient
     */
    constructor(private _httpClient: HttpClient){

    }
    // -----------------------------------------------------------------------------------------------------
    // @ Public methods
    // -----------------------------------------------------------------------------------------------------

    /**
     * get Finance Data
     */
    getFinanceData(): Observable<any>{
        return this._httpClient.get(environment.baseURL + 'apiurls/', {}).pipe(
            switchMap((response: any) => {
                return of(response);
            })
        );
    }
}

template.html

{{_table.Percentage}}

json (as presented by the django API)
{
   "stocks":[],
   "eff":[],
   "port":[],
   "cal":[],
   "labels":[],
   "table":{
      "Percentage":{
         "AD.AS":16.1,
         "ASML.AS":15.67,
         "AAPL":68.23
      },
      "Budget":{
         "AD.AS":241.5,
         "ASML.AS":235.05,
         "AAPL":1023.45
      },
      "Closing":{
         "AD.AS":25.22,
         "ASML.AS":314.3,
         "AAPL":129.04
      },
      "Number of stocks to buy":{
         "AD.AS":10.0,
         "ASML.AS":1.0,
         "AAPL":8.0
      },
      "final":{
         "AD.AS":252.0,
         "ASML.AS":314.0,
         "AAPL":1032.0
      },
      "final allocation":{
         "AD.AS":15.77,
         "ASML.AS":19.65,
         "AAPL":64.58
      },
      "Diff":{
         "AD.AS":-0.33,
         "ASML.AS":3.98,
         "AAPL":-3.65
      }
   }
}

A: To display the json data on html you may use json pipe

 {{ _table.Percentage | json }}


text:
Q: Write modular UI Tests in XCode I am pretty new to UI Testing on XCode. I found the record function pretty cool and it's working just fine but as long as you have decision points the code breaks the DRY principle. Therefore my idea is to write modular tests and invoke them depending of the user login status, role etc.
The problem is I don't find a way to tag my functions as not-tests (they are helpers invoked when appropriate from the main entry point). This is what I came up with
func testExample() {
   let exists = NSPredicate(format: "exists == true")

   let app = XCUIApplication()

   if(!app.staticTexts[""].exists){
       testLaunchScreen()
   }
   testAsRole1()

}

func testLaunchScreen(){
    let app = XCUIApplication()

    let scrollViewsQuery = app.scrollViews
    scrollViewsQuery.otherElements.containing(.image, identifier:"image0").element.swipeLeft()
    app.buttons["Continue"].tap()
    testFacebookLoginScreen()
}

func testFacebookLoginScreen() {
    let app = XCUIApplication()

    // set up an expectation predicate to test whether elements exist
    let exists = NSPredicate(format: "exists == true")
    // as soon as your sign in button shows up, press it
    let facebookSignInButton = app.buttons["Join with Facebook!"]
    expectation(for: exists, evaluatedWith: facebookSignInButton, handler: nil)
    facebookSignInButton.tap()

    self.waitForExpectations(timeout: 10, handler: nil)
    if(app.staticTexts["Confirm"].exists){
        // create a reference to the button through the webView and press it
        let webView = app.descendants(matching: .webView)
        webView.buttons["OK"].tap()
    } else {
        let webViewsQuery = app.webViews
        webViewsQuery/*@START_MENU_TOKEN@*/.textFields["Email or Phone"]/*[[".otherElements[\"Welcome to Facebook\"]",".otherElements[\"main\"].textFields[\"Email or Phone\"]",".textFields[\"Email or Phone\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.typeText("user@tfbnw.net")
        webViewsQuery/*@START_MENU_TOKEN@*/.secureTextFields["Facebook Password"]/*[[".otherElements[\"Welcome to Facebook\"]",".otherElements[\"main\"].secureTextFields[\"Facebook Password\"]",".secureTextFields[\"Facebook Password\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.typeText("password")
        webViewsQuery.buttons["Login"].tap()
    }
    // wait for your app to return and test for expected behavior here
    self.waitForExpectations(timeout: 10, handler: nil)
}

func testAsRole1(){

  ///
}

The problem is that all the testXXX functions are run in order which is not what I want, I'd like to run just testExample. I have found some post regarding extensions but I don't think those would fit in my case
Edited:
I have found https://github.com/kif-framework/KIF which seems a very nice library but I'd like to be able to just record sequences and name them as functions I can reuse, I think it would be easier to maintain
Many thanks

A: XCTest treats every method in an XCTestCase subclass that starts with test as a standalone test. Just change your  method names. Alternatively, you can put them in a separate class that doesn't inherit from XCTestCase, but then you lose the convenience methods defined there.
From the documentation:

Test methods are instance methods that have no parameters, do not return a value, and whose name begins with the lowercase word "test".

So, there are a couple of different ways you could modify those methods so that they're not treated as tests.


text:
Q: Separating positive and negative terms in an algebraic expression I want to isolate positive and negative terms in this algebraic expression, for example. I have looked at the FullForm and tried many functions like Gatherby, Split etc. but they work on lists and the -1 is imbedded in a function Rational. From the Stack Exchange questions, I found that the best result is with:

expression/._?Positive->0
expression/._?Negative->0

But it adds few terms and misses others...  Any quick help?  The expression is:
expression = (a Nb^2)/2 + c^2 f$K^2 my$i$Re mz$i$Im Cos[θ]^2 +
1/2 I bN$f c f$K my$i$Im Cos[θ] Sin[θ] -
1/2 I bN$i c f$K my$i$Im Cos[θ] Sin[θ] +
1/2 bN$f c f$K my$i$Re Cos[θ] Sin[θ] +
1/2 bN$i c f$K my$i$Re Cos[θ] Sin[θ] +
c^2 f$K^2 mx$i$Re mz$i$Im Cos[θ] Sin[θ] +
1/2 I bN$f c f$K mx$i$Im Sin[θ]^2 -
1/2 I bN$i c f$K mx$i$Im Sin[θ]^2 +
1/2 bN$f c f$K mx$i$Re Sin[θ]^2 +
1/2 bN$i c f$K mx$i$Re Sin[θ]^2 +
1/2 c^2 f$K^2 my$i$Im^2 Cos[θ]^2 Sin[θ]^2 +
1/2 c^2 f$K^2 my$i$Re^2 Cos[θ]^2 Sin[θ]^2 +
c^2 f$K^2 mx$i$Im my$i$Im Cos[θ] Sin[θ]^3 +
c^2 f$K^2 mx$i$Re my$i$Re Cos[θ] Sin[θ]^3 +
1/2 c^2 f$K^2 mx$i$Im^2 Sin[θ]^4 +
1/2 c^2 f$K^2 mx$i$Re^2 Sin[θ]^4

A: expression /. _?Internal`SyntacticNegativeQ :> 0

(a Nb^2)/2 + c^2 f$K^2 my$i$Re mz$i$Im Cos[θ]^2 +
  1/2 I bN$f c f$K my$i$Im Cos[θ] Sin[θ] +
  1/2 bN$f c f$K my$i$Re Cos[θ] Sin[θ] +
  1/2 bN$i c f$K my$i$Re Cos[θ] Sin[θ] +
  c^2 f$K^2 mx$i$Re mz$i$Im Cos[θ] Sin[θ] +
  1/2 I bN$f c f$K mx$i$Im Sin[θ]^2 +
  1/2 bN$f c f$K mx$i$Re Sin[θ]^2 +
  1/2 bN$i c f$K mx$i$Re Sin[θ]^2 +
  1/2 c^2 f$K^2 my$i$Im^2 Cos[θ]^2 Sin[θ]^2 +
  1/2 c^2 f$K^2 my$i$Re^2 Cos[θ]^2 Sin[θ]^2 +
  c^2 f$K^2 mx$i$Im my$i$Im Cos[θ] Sin[θ]^3 +
  c^2 f$K^2 mx$i$Re my$i$Re Cos[θ] Sin[θ]^3 +
  1/2 c^2 f$K^2 mx$i$Im^2 Sin[θ]^4 +
  1/2 c^2 f$K^2 mx$i$Re^2 Sin[θ]^4

To replace the terms with a positive sign with 0:
Replace[expression , Except[_?Internal`SyntacticNegativeQ] :> 0, 1]

 -(1/2) I bN$i c f$K my$i$Im Cos[θ] Sin[θ] - 1/2 I bN$i c f$K mx$i$Im Sin[θ]^2


text:
Q: SAP Script Recording and Playback : Copy Paste events are not recorded as part of script While using the script recording and playback feature of SAP GUI Client, I have noticed that Cut/Copy/Paste operations performed by either key press (Ctrl + X, Ctrl + C, Ctrl + V) or from the context menu does not leave a trace in the script generated.
Is there a way to enable these operations as part of script or any workaround to make these events part of recorded script?
Any leads would be appreciated. Thanks

A: My recommendation is: take a notebook and write when you do you copy/paste actions.
I have done this when recording scripts and it helps me to know where I have done this type actions when analyzing the code.
Also, you can use a screen recorder to complete the formula.


text:
Q: Can't find error in my factoring code I'm trying to factor N! This is my code:
total = 0
i = 1
for i in range (N):
  total = total + N
  print (str(total))
  print('Final total : ' + str(total))

I keep getting this error
Program Failed for Input: 4
Expected Output: 24
Your Program Output: 4
Final total : 4
8
Final total : 8
12
Final total : 12
16
Final total : 16

I was given no examples on how to do this and only got this far because of some YouTube videos, I'm willing to put in the work if someone can tell me what I'm doing wrong.

A: There are a few erros in you code, look first factorial is multiplication, not sum, then, you have to mult the index, not the constant, it would be:
total = 1
i = 1
N = 10
for i in range (i,N):
  total = total * i
  print (str(total))
  print('Final total : ' + str(total))

A: Factorial is the product of an integer and all the  non-negative integer below
total = 1
N = 12
i = 1
for i in range (N):
  total = total * N #product of an integer
  N= N-1 #and all the integers below

print (str(total))

print('Final total : ' + str(total))


text:
Q: AngularJS and Restangular: TypeError: Cannot read property 'then' of undefined I built a service and this service return an object. But, in my controller i don't work with this object because '.then' dont't work.
My service:
var getUser = function(userId) {

    Restangular.all(userId).post(JSON.stringify()).then(function(response) {
        var obj = angular.fromJson(response);
        if (!obj.isError) {
            return obj;
        }
        else {
            console.log("ERRO getUserCard");
        }
    });
};

My controller:
var succsess = function(data){
    welcomeScope.getUser = data;
    console.log("getUser: " + welcomeScope.getUser);
};

var error = function(){
    console.log("Erro error");
};

function loadProfile(){
    welcomeSvc.getUser("203831").then(success,error);
};

Note: welcomeScope is my $scope.

A: you should add return in function getUser
var getUser = function(userId){
   return Restangular.all(userId).post(JSON.stringify()).then(function(response){
        var obj = angular.fromJson(response);
        if (!obj.isError) {
            return obj;
        }
        else{
            console.log("ERRO getUserCard");
        }
    });
};

A: Your getUser() function needs to return a promise:
var getUser = function(userId) {

return new Promise(function(resolve, reject) {
  Restangular.all(userId).post(JSON.stringify()).then(function(response) {
    var obj = angular.fromJson(response);
    if (!obj.isError) {
        resolve(obj);
    }
    else {
        reject(console.log("ERRO getUserCard"));
    }
  })
 })
};

You may need to pass resolve, reject into Restangulars promise


text:
Q: Web API best practices inserting data: nested or per entity Assume that you have the following 3 entities:

*

*Manual

*Version

*Document

1 Manual has multiple versions and 1 version has multiple Documents.
I want to build a Web API that allows customers to insert their manuals, versions and documents, but what is the best practice?
Do I accept the posted data object in a nested XML/Json structure:
<Manual>
   <Versions>
      <Documents/>
   </Versions>
</Manual>

or do I want the customers to add the data entity per entity?
Additionally, how does this work with primary keys and foreign keys between the 2 systems? My database creates a PK per entity and so does my customer's database. Should I store his reference numbers or should he store mine for future updates, deletes and related inserts?

A: *

*Do I accept the posted data object in a nested XML/Json structure, or do I want the customers to add the data entity per entity

Both, Allow the customer to bulk import/export a nested structure AND give them the ability to add a single new document to a version.

*

*Should I store his reference numbers or should he store mine

Again, Both. Use a combined key of an Id for the customer which you generate, and the customers PK for the manual/version/document.
This allows advanced customers to use their own key. Which they will prefer. and you can push back an error to them if they send a duplicate, rather than having to accept the duplicate and deal with the problem when they request it back.
For basic customers, do the same, but generate a unique key for them if it is not supplied. Allow the customer to query your db to get the key if they forget it.

A: Do I accept the posted data object in a nested XML/Json structure:
I think you should only do this if there is a requirement to do bulk inserts or updates. However if otherwise you shouldn't, and build a simple REST API. If you want to support bulk operations in the future you can always provide a new Api call. Further Implementing bulk API complicates things if you want customer to store your primary key as you need to send a complicated response with primary key to the each new item inserted.
Should I store his reference numbers or should he store mine
You should definitely store customers reference number. Unless customer want to use your reference number for the get requests, I don't think there's much use storing your primary key in customers system.


text:
Q: dynamic vertical multi column list does not work in IE Blow code works perfectly for Mozilla, Safari & Chrome but not in IE 7,8,9.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title></title>

<input type="checkbox">Francoise Barre-Sinoussi

<input type="checkbox">Rachel Carson

<input type="checkbox">Shirley M. Tilghman

<input type="checkbox">Jane Goodall

<input type="checkbox" >Marie Curie

<input type="checkbox" >Rosalind Franklin

<input type="checkbox" >Svetlana Savitskaya

<input type="checkbox" >Mae Jemison

<input type="checkbox" >Mayim Bialik

<input type="checkbox" >Sally Ride

What hack i will have to apply to make it working in IE7,8 & 9.

A: Try this css code,
ul {margin: 0; padding: 0; list-style: none;float:left;}

.column {
background-color: #fff;
border: 1px solid #999;
padding: 8px;
width:500px;
}
ul li {
float:left;
margin: 0 0 5px 0;
overflow:hidden;
width: 200px;
background-color: orange;
margin-right: 10px;
}
.column {
/* the proper rules ready for future */
column-count: 3;
column-gap: 20px;

/* Moz/Firefox rules */
-moz-column-count: 3;
-moz-column-gap: 20px;

/* Safari & Chrome rules */
-webkit-column-count: 3;
-webkit-column-gap: 20px;
}

A: IE does not support the CSS column-count.
The only solution I see is changing the html structure and css:
See the jsfiddle demo
HTML:

<input type="checkbox">Francoise Barre-Sinoussi

<input type="checkbox">Rachel Carson

<input type="checkbox">Shirley M. Tilghman

<input type="checkbox">Jane Goodall

<input type="checkbox" >Marie Curie

<input type="checkbox" >Rosalind Franklin

<input type="checkbox" >Svetlana Savitskaya

<input type="checkbox" >Mae Jemison

<input type="checkbox" >Mayim Bialik

<input type="checkbox" >Sally Ride

CSS:
ul {margin: 0; padding: 0; list-style: none;float:left;}

.column {
    background-color: #fff;
    padding: 8px;
}
.border {
    border: 1px solid #999;
    float: left;
}
label{
   float:left;
}
ul li a{
    display:block;
    float:left;
    margin: 0 5px 0 5px;
}
ul li {
    clear:both;
    margin: 0 0 5px 0;
}


text:
Q: Laravel homesetad/vagrant curl not working For some reason, I can't use CURL to send post requests in homestead/vagrant. It just returns null and here is my code.
Additional, headers are not being set, even if it's application/json it returns HTML/charset.
any clues?
$ch = curl_init(env('app_url') . 'applications/' . $position->ats_reference . '/import');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
       'token' => $user->token,
       'data' => [$data]
    ]));
curl_exec($ch);
$info = curl_getinfo($ch);
dd($info);
curl_close($ch);


text:
Q: Pyspark: Need to show a count of null/empty values per each column in a dataframe I have a spark dataframe and need to do a count of null/empty values for each column. I need to show ALL columns in the output. I have looked online and found a few "similar questions" but the solutions totally blew my mind which is why I am posting here for personal help.
Here is what I have for code, I know this part of the puzzle.
from pyspark.sql import *

sf.isnull()

After running it, this is the error I receive  AttributeError: 'DataFrame' object has no attribute 'isnull'
What's interesting is that, I did the same exercise with pandas and used  df.isna().sum() which worked great. What am I missing for pyspark?

A: you can do the following, just make sure your df is a Spark DataFrame.
from pyspark.sql.functions import col, when

df.select(*(count(when(col(c).isNull(), c)).alias(c) for c in df.columns)).show()

A: Use below, but make sure df should be your Spark DataFrame
from pyspark.sql.functions import col, when, count

df.select(*(count(when(col(c).isNull(), c)).alias(c) for c in df.columns)).show()


text:
Q: POST http://localhost:8080/something/Login 405 (Method Not Allowed) I,m trying to post some info from login form to my back end, but there is a message 405 (Method Not Allowed). Any ideas?
       Login

<input type="email" name="log_email" id="log_email" class="shortput" onfocus="if(this.value == 'Email address') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Email address'; }" value="Email address" />

<input type="password" name="log_password" id="log_password" class="shortput" onfocus="if(this.value == 'Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Password'; }" value="Password" />

<input type="button" id="logincustomer" value="Login"/>

sendingData();
values = "log_email=" +  encodeURI(document.getElementById("log_email").value);
values += "&log_password=" + encodeURI(document.getElementById("log_password").value);

sendRequest("Login",values);
xmlHttpTimeout = setTimeout(onTimeoutLoginCustomer,10000);

My sendRequest method contains:
function sendRequest(url, data) {
    ajaxRequest = createAjaxRequest();
    ajaxRequest.open("POST", url, true);
    ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    var date = new Date();
    data += "&timestamp=" + date.getTime();
    ajaxRequest.send(data);
}


text:
Q: Using ggarrange, title of plots not appearing I am trying to combine multiple plots but I don't want to write a ton of code, so I wrote a function
MYGRAPH.Leaf<-function(i){
  ggplot(Leaf.hemi, aes(x=type, y=i, group=pot))+
    geom_line(color="grey")+
    geom_point(aes(color=host))+
    #geom_text_repel()+
    facet_wrap(.~hemiparasite)+
    ylab(names(leaf.response.hemi[i]))+
    newtheme
}

graphs<-lapply(leaf.response.hemi, MYGRAPH.Leaf)
ggarrange(graphs$K, graphs$Na, graphs$P, graphs$Ca, graphs$S, graphs$Mg, common.legend=TRUE

Here is some of the code of Leaf.hemi
head(Leaf.hemi)
   X.1  X        K     Na         P        Mg        Ca         S
6    6  6 4.298202 0.0018 0.9763679 0.4000289 1.2009743 0.7394368
8    8  8 3.490799 0.0030 0.9442089 0.4924891 1.3988981 0.9508996
9    9  9 2.215777 0.0037 0.8185966 0.6482371 1.8348983 1.2879451
11  11 11 4.647563 0.0012 0.7674694 0.3947354 0.9526773 0.7056782
13  13 13 3.457349 0.0054 0.6979817 0.5680050 1.3992462 1.2307497
14  14 14 2.603297 0.0008 0.6273514 0.5238602 1.4479887 1.2073244
   hemiparasite pot.code type host pot mesh.size leaf.species
6          CAFO      41B    B ACMI  41        35         CAFO
8          CAFO      42B    B ACMI  42        35         CAFO
9          CAFO      42C    C ACMI  42        35         CAFO
11         CAFO      43B    B ACMI  43        35         CAFO
13         CAFO      44B    B ACMI  44        35         CAFO
14         CAFO      44C    C ACMI  44        35         CAFO

with leaf.response.hemi just being the 6 response variables
        K     Na         P        Mg         S        Ca
6  4.298202 0.0018 0.9763679 0.4000289 0.7394368 1.2009743
8  3.490799 0.0030 0.9442089 0.4924891 0.9508996 1.3988981
9  2.215777 0.0037 0.8185966 0.6482371 1.2879451 1.8348983
11 4.647563 0.0012 0.7674694 0.3947354 0.7056782 0.9526773
13 3.457349 0.0054 0.6979817 0.5680050 1.2307497 1.3992462
14 2.603297 0.0008 0.6273514 0.5238602 1.2073244 1.4479887

Basically, it all works great, except when I create the graphs, despite the actual points being correct ,the y-label is off
Any help would be appreciated, it is so much better to do it this way (or any other way someone might suggest)


text:
Q: La contraseña devuelve false cuando se compara Al guardar la contraseña realizo el bcryp.hash y me guarda en la base de datos algo como esto, para "1234" => (d1c8912e41fe7ae8f44717c0a2157ab9377b14a7) , pero al momento de realizar el login que uso bcrypt.compare me retorna false
add user
user: async (_, { input:{firstName, lastName, email, fullName, age, role, login, passwordHash} }, { models: { users } }) => {
      let user

      try {
        user = await users.create({
          firstName,
          lastName,
          email,
          fullName,
          age,
          role,
          login,
          passwordHash: await bcrypt.hash(passwordHash, 10)
        })
      } catch (error) {
        console.error(error)
      }
      return user
    }

login user
login: async (_, { input: { email, passwordHash } }, { models: { users } }) => {
      const user = await users.findOne({ email })

      if (!user) {
        throw new Error('No user with that email')
      }
      const valid = await bcrypt.compare(passwordHash, user.passwordHash)
       if (!valid) {
         throw new Error('Incorrect password')
       }

       //return json web token
      return jsonwebtoken.sign(
        { id: user._id, email: user.email, role: user.role },
        process.env.JWT_SECRET,
        { expiresIn: '1d' }
      )
    }


text:
Q: Ajax response is getting but not posting on the PHP page I want to retrive the data got from jquery to php via ajax.
My code to start up a modal window

here am getting id from main page.and opening a modal pop up.
modal script as follows.
$( ".modal-customeredit" ).click(function() {
    var myGroupId = $(this).attr('data-id'); // data-id
    data = {'id':myGroupId };
    $.ajax({
        type: "POST",
        url: "left.inc.php",
        data: data, // data retrieve on server-side ($_POST['id'])
        success:function(response){
            $( "#modal-customeredit" ).dialog({
                modal: true,
                minWidth: 700,
                minHeight: 200,
                dialogClass: "modal-dialog",
                show: "fadeIn"
            });
            alert('done');
            alert(response); //do the rest of operations.
        }

    });

my form code is for modal:

Update Customer Info

 Fides Admin uses colors & styles from both the default theme color schemes and the included core color helpers.

<form id="customer-edit" action="" class="col-md-12 center-margin" method="">

  Name:
  *

<input id="name" name="name" placeholder="Name" data-required="true" class="parsley-validated" type="text">

  Details :
  *

<input id="details" placeholder="Details" name="details" data-required="true" class="parsley-validated" type="text">

  Domain :
  *

<input id="domain" placeholder="Domain" name="domain" data-required="true" class="parsley-validated" type="text">

  Vertical :
  *

<input id="vertical" placeholder="Vertical" name="vertical" data-required="true" class="parsley-validated" type="text">

  Taxanomy :
  *

<input id="taxanomy" placeholder="Taxanomy" name="taxanomy" data-required="true" class="parsley-validated" type="text">

Submit

</form>

<?php } elseif ($pfile=="customer-screen.php") { ?>

The problem i face is i got response from ajax.which display the exact id i want.
But when i try in php as
<?php $id=$_POST['id'];
echo $id; ?>

I was not able to echo the id in php file.But ajax display in the response.Hope i am conveying the question properly.If u help it will be really appreciated.If you have doubts about my question.Please comment let me expalin.

A: The data you're posting is in JSON format, not URL format. The data should be 'id=' + myGroupId.


text:
Q: NodeJS googleapis batchRequest issue I am trying to use the (experimental) newBatchRequest method in the NodeJS googleapis library (https://github.com/google/google-api-nodejs-client), but the results returned all return a 401 Invalid Credentials error from Google. The exact same call with the exact same auth client (same credentials) works as expected when sending a single request without using newBatchRequest.
Here's the batch request code:
var c = client.newBatchRequest()
async.each(files, function(fileid, cb) {
  c.add(client.drive.files.get({fileId:fileid}));
  cb();
},
function(err) {
  console.log('client is')
  console.log(oauth2Client)
  c.withAuthClient(oauth2Client).execute(function(err, results) {
    console.log(err)
    console.log(results);
  })
})

This produces in console.log an array full of the following error:
{ errors: [ [Object] ],
    code: 401,
    message: 'Invalid Credentials' }

Without using batchRequest and running the exact same call (drive.files.get) with the exact same withAuthClient(oauth2Client), the following code behaves as expected. The following does NOT produce an error. Note that the oauth2Client variable being passed in is exactly the same, and within the same scope.
client.drive.files.get({fileId:fid})
    .withAuthClient(oauth2Client)
    .execute(function(err, results){
       [...etc...]

Any ideas on what could be going on here?
Thanks!


text:
Q: Woocommerce core script overwrites custom CSS styling I am writing full custom CSS for a Woocommerce shop. Most of the styling is relatively straightforward; I just don't seem to be able to style the select dropdowns:
Once the page is loaded JavaScript overwrites the custom styling on the select and applies core styles from /assets/css/chosen.css. Specifically it sets width: 100% !important.
Is there a way to stop this behaviour (stop or overwrite the script) without having to edit the core files?
Has anyone dealt with this previously?
EDIT
Actually it does not apply to all select dropdowns. It looks like it only applies to the div with class chosen-container that replaces the select. Here's a screenshot.

A: I personally find it easiest to unset all styles, copy the styles from woocommerce.css to my own stylesheet and edit them from there.
Unset all default styles
// Don't load woocommerce style sheets
add_filter( 'woocommerce_enqueue_styles', '__return_false' );

Enqueue your own stylesheet
function wp_enqueue_woocommerce_style(){
    wp_register_style( 'woocommerce', get_template_directory_uri() . '/css/woocommerce.css' );
    if ( class_exists( 'woocommerce' ) ) {
        wp_enqueue_style( 'woocommerce' );
    }
}
add_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style' );

Copy all woocommerce styles into your own stylesheet and freely edit them from there. Or you up the priority of you current custom stylesheet so it loads before woocommerce.css. Something like this:
add_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style', 15 );

A: The easiest way would be to remove !important from the CSS attribute in the corresponding Javascript file. In general, !important as CSS attribute should be avoided. When the !important attribute is removed from the Javascript, you should be able to overwrite the specific CSS attribute with your own CSS.


text:
Q: User of square brackets [ ] when appending link to head in JavaScript I have been going through some code and converting all the jQuery to vanilla JS. Below is some code I converted successfully (commented out is the jQuery). I was having some trouble appending it to the head until I added [0] at the end.I know square brackets are used when accessing an array, but I'm not exactly sure why they were needed in this instance. Could someone explain?
var head = document.getElementsByTagName('head')[0];
    var linkScript = document.createElement('link');
    linkScript.type = 'text/css';
    linkScript.rel = 'stylesheet';
    linkScript.href = purecommHostFiles + 'style.css';
    head.appendChild(linkScript);

    // $('<link>')
    //  .appendTo('head')
    //  .attr({
    //      type: 'text/css',
    //      rel: 'stylesheet',
    //      href: purecommHostFiles + 'style.css'
    //  });

A: getElementsByTagName always returns an array-like HTMLCollection of elements, so you need to take the first element to access your <head> element.


text:
Q: How to merge two repositories? How to merge two git repositories into one?
 I have got a parent folder say 'P' and two subfolders 'A' which has 5 commits and 'B' which has 5 commits.
 I want the repos in A and B to disappear and combine as one with 10 commits,this new repository must be placed in the parent directory 'P'.

A: The basic idea is to merge two repositories are as follows
Create a new empty repository New.
Make an initial commit because we need one before we do a merge.
Add a remote to old repository old A.
Merge old A/master to New/master.
Make a sub directory old A.
Move all files into sub directory old A.
Commit all of the file moves.
Repeat 3-6 for old B.


text:
Q: Facebook Submit for Login Review but still in Development Mode I am trying to post to Instagram from within my app. My Facebook Dev app is in Development mode:

I can log in to Facebook and post/share to Facebook Pages, Groups and profiles from within my app so happy with that. I am now trying to post/share to Instagram so I am calling the FB.login as follows:

Where the method PostToInstagram() ultimately is doing this:

However when I attempt to call this, I get the FB Login popup, I click to post but I keep getting the error:
(#10) Application does not have permission for this action

On the popup, I have the option to change the FB/Instagram settings, when I try saving inside here I see:

I would have thought I would be okay as I am still in development mode. My other calls to FB api work fine. Could I be missing any scopes? Any help on this is greatly appreciated!


text:
Q: MySQL query to Delete part of the value in a cell I want to delete part of the value withing a cell.  The part I want to delete begins and ends with
.
Cell Value Example:
This house is red.

I want to delete

How would I write this query?  Thank you.

A: UPDATE table_name SET fiele = REPLACE(field, 'old string', 'new_string');

But is better remove extra string server side, before insert in db.


text:
Q: Recursively remove line-endings from string values in a ruby hash I have a hash object that could be arbitrarily large - keys are always strings, but values could be strings, arrays, or other hashes. I want to recursively walk through the object and if the value of any particular key (or the value of any array) is a string, I want to strip line endings and leading and trailing whitespace (\r\n, \t, etc")
Do I need to write this algorithm myself or is there some faster ruby-esque way to do it?

A: You will need to write it yourself.  One way to do it is:
def strip_hash_values!(hash)
  hash.each do |k, v|
    case v
    when String
      v.strip!
    when Array
      v.each {|av| av.strip!}
    when Hash
      strip_hash_values!(v)
     end
  end
end

This method modifies the original hash:
hash = {:a => [" a ", " b ", " c "], :b => {:x => "xyz   "}, :c => "abc    "}

strip_hash_values!(hash)

puts hash
# returns {:b=>{:x=>"xyz"}, :c=>"abc", :a=>["a", "b", "c"]}

A: This is one way to do it.
Code
def strip_strings(o)
  case o
  when Hash
    o.each do |k,v|
      o[k] = case v
             when String
               v.strip
             else
               strip_strings(v)
             end
    end
  else # Array
    o.map do |e|
      case e
      when String
        e.strip
      else
        strip_strings(e)
      end
    end
  end
end

Example
h = { a: [b: { c: " cat ", d: [" dog ", {e: " pig " }] }], f: " pig " }
  #=> {:a=>[{:b=>{:c=>" cat ", :d=>[" dog ", {:e=>" pig "}]}}], :f=>" pig "}

strip_strings(h)
  #=> {:a=>[{:b=>{:c=>"cat", :d=>["dog", {:e=>"pig"}]}}], :f=>"pig"}


text:
Q: Delete value of a cell once used by another cell I would like to enter a value in a cell("A1") then that cell would multiply with the value of A3, and new value will replace A3. A1 is cleared.
I have entered the following code but it only does the whole column, I want it to apply to the whole column and Rows from 20 T2 all the way to AP2 so 42
    Private Sub worksheet_change(ByVal target As Range)
      If target.Column = 20 And target.Value > 0 Then
        Dim val As Double
        val = target.Value
        target.Value = 0
        Cells(target.Row, target.Column - 1).Value = val + Cells(target.Row, target.Column - 1).Value
      End If
    End Sub

A: You could use something like this:
Dim flagProgram As Boolean
Private Sub worksheet_change(ByVal target As Range)
Dim dblResult As Double
If flagProgram = False Then
    flagProgram = True
    dblResult = Cells(1, 1) * Cells(1, 3)
    Cells(1, 1) = ""
    flagProgram = False
End If

End Sub

A: You could use this.
Private Sub worksheet_change(ByVal target As Range)

  Dim rng As Range
  Dim db As Double
  Set target = Range("a1")
  If target.Value > 0 Then
    db = target.Value * Cells(1, 3)
    MsgBox db
    target.Value = ""
  End If
End Sub

A: Private Sub worksheet_change(ByVal target As Range)
  If target.Address = "$A$1" And target.Value > 0 Then
    Dim val As Double
    val = target.Value
    Range("A1").Value = 0
    Cells(3, 1) = val * Cells(3, 1)
  End If
End Sub

added into the Sheet1 module:

Seems to test ok:


text:
Q: Share a String Variable Between AppleScript & Objective C I have perhaps 1% Objective C knowledge, and am more comfortable using AppleScript for small tasks.
I'm developing an app that requires a more attractive alert window though, so I have started to learn more about AppleScriptObjC.
My question is, how do I get my AppleScript variable 'serialNumber', which is set to a string from the clipboard that will be something like "* 1234567890 *", into the Objective C side of things so that I can display the string through the label object?
I've already got my label set up as
'property serialNumberLabel: missing value'
I just don't know how to transfer the variable between the two languages, so that I can set the serialNumberLabel value to the string currently stored in the serialNumber variable.
Thanks!!!

A: AppleScript strings are implicitly bridged to NSString, so you can write
set serialNumber to the clipboard
serialNumberLabel's setStringValue:serialNumber

In the opposite direction you need to coerce the NSString object to text
set serialNumber to serialNumberLabel's stringValue() as text


text:
Q: Confusion in xml attributes and attributes value comparision I have some what confusion in XML ! my xml file is given below
<rootnode>
<childnode id="1" quantity="3" type="auto">0000-000</childnode>
<childnode id="2" quantity="3" type="prop">1111-111</childnode>
<childnode id="2" quantity="3" type="toy">2222-222</childnode>
<childnode id="3" quantity="3" type="auto">0000-000</childnode>
</rootnode>

I am creating one function that takes two parameter as arrays of attributes and attributevalues. Now I am little bit confuse how to compare the node's each and every attributes with each other ?? Have a glance at my code
 ComparableAttributes = new string[]{ "id","quantity"};

 ComparableAttributesValue = new string[]{ "2","3"};

As per my requirement i must be got two nodes (2nd and 3rd). Because attribute and attributes value matches to that particular node !
  public List<XmlNode> getXmlNodeList()
    {
        XmlDocument Xdoc = new XmlDocument();
        Xdoc.Load(Filename);

        List<XmlNode> xmlList = new List<XmlNode>();

        foreach (XmlNode node in Xdoc.SelectNodes("//" + Childnode))
        {
            for (int i = 0; i < ComparableAttributes.Count() - 1; i++)
            {
                if (node.Attributes[ComparableAttributes[i]].Value == ComparableAttributesValue[i] &&
                    node.Attributes[ComparableAttributes[i + 1]].Value == ComparableAttributesValue[i + 1])
                    xmlList.Add(node);
            }
        }

        return xmlList;
    }

It gives me output for only two value ... ! If i want to make it dynamic then how can i iterate loop ? I mean how can i put up the condition ! I am just little bit confused !

A: You have it almost exactly correct. There are some small problems:
for (int i = 0; i < ComparableAttributes.Count() - 1; i++)

Suppose ComparableAttributes.Count() is 5. Then this loop will give i the values 0, 1, 2, 3 and then stop. But this is omitting 4! The correct way to iterate here is either
for (int i = 0; i < ComparableAttributes.Count(); i++)

OR
for (int i = 0; i <= ComparableAttributes.Count() - 1; i++)

The next problem is that in the i loop, you are testing two indexes, i and i+1- I suspect you put this in because in your example you were only going round the loop once.

Finally, and most significantly, at the moment you are accepting a node if any of the magic attributes are correct, but it sounds like you only want to accept a node if all of the magic attributes are correct. To do this we need to introduce a new variable which tracks if a node is good, and make sure to check every attribute we need to.
What we end up with looks like this:
foreach (XmlNode node in Xdoc.SelectNodes("//" + Childnode))
{
    bool nodeIsGood = true;

    for (int i = 0; i < ComparableAttributes.Count(); i++)
    {
        if (node.Attributes[ComparableAttributes[i]].Value
                         != ComparableAttributesValue[i])
        {
            // the attribute doesn't have the required value
            // so this node is no good
            nodeIsGood = false;
            // and there's no point checking any more attributes
            break;
        }
    }

    if (nodeIsGood)
        xmlList.Add(node);
}

Give that a go and see if it works.


text:
Q: How to resolve "internal table overflow" in Applescript When attempting to load the iTunes XML/plist file, I get "internal table overflow."  After Googling, it looks like Applescript has run out of memory.  The file is 18 meg on disk, so while on the larger side of things, it should still work on a Mac with 2 gigs.
How can I resolve this?
Obviously, since it's created by iTunes, I can't control the generate of it much.
Update:  The relevant snippet:
tell application "System Events"
    tell property list file (itunes_xml_file as string)
        tell contents
            set my_tracks to value of property list item "Tracks"
            repeat with t in items of my_tracks

A: I guess that AppleScript is simply not made to handle this amount of data. I tried to use AppleScript a while back as well and tried to do something similar (reading an iTunes library). AppleScript's original intention was to automate applications by sending AppleEvents to them - which in combination with the weird syntax of AppleScript, confuses a lot and makes it difficult to do a lot of simple things.
After some frustrating time I decided to use Python instead, as it provides a simple module for reading the plist files: http://docs.python.org/dev/library/plistlib.html
Possibly not what you wanted to hear, but the problem with AppleScript is that it is easily overloaded with data, as the abstraction of data it works with is rather bulky and takes up lot of memory.
I'm sure if you give Python a try, you'll have something up and running in less than a hour. Python is installed on all Macs by default and is really easy to learn.

A: OS version 10.6.8
Update: Confirmation of validity
After initially writing the below I tried to revert the code at hand but could not reproduce the error and hid the post by "deleting" it.
Just now the error happened when loading one non-existant and one existent file-path in an options-parsing script loaded with a load script call, initially handled by run handler, called by the CLI osascript(1) program. This time it is revertible and I feel confident to un-"delete" it.
In short, my solution is to change anyone_else's POSIX file path_posix to AppleScript's POSIX file path_posix
Some relation
After writing the below I now realize that i first only saw "iTunes" and missed the relevant first line with tell app "system events" and the use of it's property list file which perhaps/actually/somehow could be related to my issue with info for a POSIX file.
A note related to OP/question: file or alias as string gives a colon-separated "HFS"-path. System Events handles both.
My issue
In a script-loading script i got error "Internal table overflow." number -2707 from the block below.
It was issued when i called the block's handler using ~IPC~ (app app_name's handler_name()) (when i investigated it more thoroughly but, i had come across it before - without IPC).
try
    set file_modified_date to (info for my POSIX file file_path_posix)'s modification date
    true
on error error_message number error_number from error_source partial result error_result to error_class
    if {error_number} is not in {-43, -37} then error error_message number error_number from error_source partial result error_result to error_class
    false
end try

A (the(?)) parent (used for my) of this script, worth mentioning, is current application (with some levels in between) (compiled and bundled in "AppleScript Editor" to be run as a stand-alone .app)
My solution
Changing
set file_modified_date to (info for my POSIX file file_path_posix)'s modification date

to
set file_modified_date to (info for AppleScript's POSIX file file_path_posix)'s modification date

solved the issue - for now.
Thoughts
I'm guessing different ~modules~ has different "tables" (don't now much C) for handling a thing like POSIX file and info for (open "Scripting Addition" / extension (OSAX) "Standard Additions", as it (both) still is, is it not?).
Hope this helps, and that my level of detail (and parentheses) didn't loose or confuse you :) Good night.
Diggin' 'round the cradles
Around the AS memory grave: (Spam prevention made me downgrade all but 2 hyperlinks - give me some rep. and i'll fix it :p)
• The eminent ~has [on this error code] (http://lists.apple.com/archives/applescript-users/2005/Jul/msg00166.html) with a related but perhaps other source (and mentioning his library loader) via list.apple.com.
• Some [good questioning] (http://lists.apple.com/archives/applescript-implementors/2005/Jun/msg00104.html), some to which the below might be a slightly yawning answer:
• cs.cmu.edu provides (120625) a pascal source from 1992 that defines the same limits as my local /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/OpenScripting.framework/Versions/A/Headers/AppleScript.h
• And finally a more distantly related [issue with large scripts] (http://macscripter.net/viewtopic.php?id=11760) from macscripter.net - a good forum of knowledge and collection of resources around applescript.


text:
Q: Why would I use declare / typeset in a shell script instead of just X=y? I've recently come across a shell script that uses
declare -- FOO="" which apparently is spelled typeset -- FOO="" in non-bash shells.
Why might I want to do that instead of plain FOO="" or export FOO?

A: The most important purpose of using declare is to control scope, or to use array types that aren't otherwise accessible.

Using Function-Local Variables
To give you an example:
print_dashes() { for (( i=0; i<10; i++; do printf '-'; done; echo; }

while read -p "Enter a number: " i; do
  print_dashes
  echo "You entered: $i"
done

You'd expect that to print the number the user entered, right? But instead, it'll always print the value of i that print_dashes leaves when it's complete.
Consider instead:
print_dashes() {
  declare i  # ''local i'' would also have the desired effect
  for (( i=0; i<10; i++; do printf '-'; done; echo;
}

...now i is local, so the newly-assigned value doesn't last beyond its invocation.

Declaring Explicitly Global Variables
Contrariwise, you sometimes want to declare a global variable, and make it clear to your code's readers that you're doing that by intent, or to do so while also declaring something as an array (or otherwise where declare would otherwise implicitly specify global state). You can do that too:
myfunc() {
  declare arg                     # make arg local
  declare -g -A myfunc_args_seen  # make myfunc_args_seen a global associative array
  for arg; do
    myfunc_args_seen["$arg"]=1
  done

  echo "Across all invocations of myfunc, we have seen the following arguments:"
  printf ' - %q\n' "${!myfunc_args_seen[@]}"
}

Declaring Associative Arrays
Normal shell arrays can just be assigned: my_arr=( one two three )
However, that's not the case for associative arrays, which are keyed as strings. For those, you need to declare them:
declare -A my_arr=( ["one"]=1 ["two"]=2 ["three"]=3 )

A: declare -i cnt=0

declares an integer-only variable, which is faster for math and always evaluates in arithmetic context.
declare -l lower="$1"

declares a variabl that automatically lowercases anything put in it, without any special syntax on access.
declare -r unchangeable="$constant"

declares a variable read-only.
Take a look at https://unix.stackexchange.com/questions/254367/in-bash-scripting-whats-the-different-between-declare-and-a-normal-variable for some useful discussion - you might not need these things often, but if you don't know what's available you're likely to work harder than you should.

A: A great reason to use declare, typeset, and/or readonly is code compartmentalization and reuse (i.e. encapsulation). You can write code in one script that can be sourced by others.
(Note declared/typeset/readonly constants/variables/functions lose their "readonly-ness" in a subshell, but they retain it when a child script sources their defining script since sourcing loads a script into the current shell, not a subshell.)
Since sourcing loads code from the script into the current shell though, the namespaces will overlap. To prevent a variable in a child script from being overwritten by its parent (or vice-versa, depending on where the script is sourced and the variable used), you can declare a variable readonly so it won't get overwritten.
You have to be careful with this because once you declare something readonly, you cannot unset it, so you do not want to declare something readonly that might naturally be redefined in another script. For example, if you're writing a library for general use that has logging functions, you might not want to use typeset -f on a function called warn, error, or info, since it is likely other scripts will create similar logging functions of their own with that name. In this case, it is actually standard practice to prefix the function, variable, and/or constant name with the name of the defining script and then make it readonly (e.g. my_script_warn, my_script_error, etc.). This preserves the values of the functions, variables, and/or constants as used in the logic in the code in the defining script so they don't get overwritten by sourcing scripts and accidentally fail.


text:
Q: Error summary not shown in CActiveForm - Yii Below i am using CActiveForm to render a form with multiple instances of same model. On submitting the form, ajax validation error for individual attributes are shown but error summary is not shown. What could be the possible problem? Thanks a lot
<?php
    $form=$this->beginWidget('CActiveForm', array(
        'id'=>'task-form',
        'enableClientValidation'=>false,
        'enableAjaxValidation' =>true,
        'clientOptions'=>array(
            'validateOnSubmit'=>true,
            'validateOnChange'=>false,
        ),
    ));
    Yii::app()->session['form'] = $form;
    ?>

    <?php echo $form->errorSummary($models); ?>

        <?php foreach($models as $index=>$model): ?>
            <?php $this->renderPartial('_task', array(
                'model' => $model,
                'index' => $index,
                'form' => $form,
            )); ?>
        <?php endforeach; ?>

        <?php echo CHtml::submitButton('Save')?>

    <?php $this->endWidget(); ?>

A: Well an extreme case of CActiveForm. Why you ever need this many Forms as in array. You can use them in single Form. But the problem is again due to multiple instance of form. Here
<?php echo $form->errorSummary($models); ?>

Use it just like this-
 foreach($models as $model)
 {
 echo $form->errorSummary($model);
 }

But again you need to change implementation and avoid using that many duplicate forms.
Cheers

A: Try to change
'enableClientValidation'=>true,

or try to use
 <?php echo CHtml::errorSummary(array($a,$b)); ?>


text:
Q: Stuck my modal wont open instead lists the info on my page Having issues with my model window. I want it to open the modal to show a larger version of the photo and description when click the thumbnail. I cant get it to work right the only time ive been able to get it to pop up the info it also doubled my thumbnail image. right now it instead of popping up it just puts the info on the original page.

.modalWindow {
position: fixed;
font-family: arial;
font-size:80%;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.2);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalHeader h2 { color: #189CDA; border-bottom: 2px groove #efefef; }
.modalWindow:target {
opacity:1;
pointer-events: auto;
}
.modalWindow > div {
width: 500px;
position: relative;
margin: 10% auto;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
background: #fff;
}
.modalWindow .modalHeader { padding: 5px 20px 0px 20px; }
.modalWindow .modalContent { padding: 0px 20px 5px 20px; }
.modalWindow .modalFooter { padding: 8px 20px 8px 20px; }
.modalFooter {
background: #F1F1F1;
border-top: 1px solid #999;
-moz-box-shadow: inset 0px 13px 12px -14px #888;
-webkit-box-shadow: inset 0px 13px 12px -14px #888;
box-shadow: inset 0px 13px 12px -14px #888;
}
.modalFooter p {
color:#D4482D;
text-align:right;
margin:0;
padding: 5px;
}
.ok{
background: #606061;
color: #FFFFFF;
line-height: 25px;
text-align: center;
text-decoration: none;
font-weight: bold;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
-moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000;
box-shadow: 1px 1px 3px #000;
}
.ok {
position: absolute;
right: 5px;
top: 5px;
width: 22px;
height: 22px;
font-size: 10px;
}
.ok, {
width:80px;
float:right;
margin-left:20px;
}
.ok:hover { background: #189CDA; }
.ok { float:none; clear: both; }

RX-0 Unicorn 02
        Banshee Norn

      <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="YZER6V8UMEATA">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

</form>

Gundam Unicorn

                 X

Line1

Line 2

                 OK

A:

.modalWindow {
position: fixed;
font-family: arial;
font-size:80%;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.2);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalHeader h2 { color: #189CDA; border-bottom: 2px groove #efefef; }
.modalWindow:target {
opacity:1;
pointer-events: auto;
}
.modalWindow > div {
width: 500px;
position: relative;
margin: 10% auto;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
background: #fff;
}
.modalWindow .modalHeader { padding: 5px 20px 0px 20px; }
.modalWindow .modalContent { padding: 0px 20px 5px 20px; }
.modalWindow .modalFooter { padding: 8px 20px 8px 20px; }
.modalFooter {
background: #F1F1F1;
border-top: 1px solid #999;
-moz-box-shadow: inset 0px 13px 12px -14px #888;
-webkit-box-shadow: inset 0px 13px 12px -14px #888;
box-shadow: inset 0px 13px 12px -14px #888;
}
.modalFooter p {
color:#D4482D;
text-align:right;
margin:0;
padding: 5px;
}
.ok{
background: #606061;
color: #FFFFFF;
line-height: 25px;
text-align: center;
text-decoration: none;
font-weight: bold;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
-moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000;
box-shadow: 1px 1px 3px #000;
}
.ok {
position: absolute;
right: 5px;
top: 5px;
width: 22px;
height: 22px;
font-size: 10px;
}
.ok {
width:80px;
float:right;
margin-left:20px;
}
.ok:hover { background: #189CDA; }
.ok { float:none; clear: both; }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

RX-0 Unicorn 02
        Banshee Norn

      <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="YZER6V8UMEATA">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

</form>

Gundam Unicorn

                 X

Line1

Line 2

                 OK


text:
Q: How to draw this in Android with xml? I'm trying to draw in Android XML the form in the image. But so far none of my attempts are successful.  How can I do it?

Thanks in Advance

A: If you use a RelativeLayout you can do a black rectangle and then put a white triangle image over the top. I don't see how you would get a Triangle without the image.
OK, I must have been a little brain dead yesterday. Here is a better solution.
The layout:

  <RelativeLayout android:layout_width="300dp"
                  android:layout_height="100dp"
                  android:layout_centerVertical="true"
                  android:layout_centerHorizontal="true"
                  android:background="@android:color/black">

       <View android:layout_width="100dp"
             android:layout_alignParentRight="true"
             android:layout_height="match_parent"
             android:background="@drawable/background_triangle_right"/>

  </RelativeLayout>

The Drawable that makes the triangle:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="87%"
            android:pivotY="140%">
        <shape
                android:shape="rectangle">
            <stroke android:color="@android:color/white" android:width="10dp"/>
            <solid
                    android:color="@android:color/white"/>
        </shape>
    </rotate>
</item>

</layer-list>


text:
Q: python scipy integrate - changing parameter that is dependent on state space I am working on a project that requires finding the trajectory of a system of ODEs with 6 state variables. The issue is that some of the parameters depend on the state space. The system itself isn't important, but if you're interested, it is Figure 2.1 in Adams et al 2004. I understand how to vary parameters by time but I am unsure about how to make it a function of the state space itself
Here is an example of what I am looking for (a is a function of time)
from scipy import integrate
import numpy as np

t = np.linspace(1, 10,  0.5)
X0 = [0.1]
def func(X,t)
    a = 0.5 * t
    return [a * b * X[0]**2]

X, infodict = integrate.odeint(func, X0, t, full_output=True, mxstep=5000000)

How do I make the parameter b a function of the state space, such as b = 1/X[0]?

A: Using the help from the comments, I just implemented the parameter as a function of the state space. Here it is below:
from scipy import integrate
import numpy as np

t = np.linspace(1, 10,  0.5)
X0 = [0.1]
def func(X,t)
    a = 0.5 * t
    b = 1/X[0]
    return [a * b * X[0]**2]

X, infodict = integrate.odeint(func, X0, t, full_output=True, mxstep=5000000)


text:
Q: play sound clip when php/mysql if statement is true? hi i have a message alert box that appears when a user gets a new message, what i want to do is add sound to this box when it pops up, i am using a php if statement to check when a user gets a new message and i have tried adding sound by doing the following but its not working please can someone show me how to do this. thanks.
<?php
$check_new_chats = check_new_chats();
while ($chat = mysql_fetch_array($check_new_chats))
if (isset($_SESSION['user_id'])) {
        if ($chat['to_user_id'] == $_SESSION['user_id']){
        echo( "<embed name='sound_file' src='/assets/music/sound_file.mp3' loop='true' hidden='true' autostart='true'/>"); ?>

A: <?php
$check_new_chats = check_new_chats();
while ($chat = mysql_fetch_array($check_new_chats))
if (isset($_SESSION['user_id'])) {
    if($chat['to_user_id'] == $_SESSION['user_id']){
        echo '<script type="text/javascript">play_sound();</script>';
    }
}
?>

Here's the Javascript function:
<script type="text/javascript">
    function play_sound() {
        var audioElement = document.createElement('audio');
        audioElement.setAttribute('src', '/assets/music/sound_file.mp3');
        audioElement.setAttribute('autoplay', 'autoplay');
        audioElement.load();
        audioElement.play();
    }
</script>

A: According to the question:

hi i have a message alert box that appears when a user gets a new
  message, what i want to do is add sound to this box when it pops up

You already have some sort of javascript function that displays an alert box when needed. Use the info from this answer to play a sound with it.
<audio id="soundHandle" style="display: none;"></audio>
<script>
  soundHandle = document.getElementById('soundHandle');
  soundHandle.src = '/assets/music/sound_file.mp3';
</script>

//With your message alert function....
alert("Message box");
soundHandle.play();


text:
Q: Dropdown Menu not displaying properly in ie7 or ie8 I am currently working on a project and I am having problems with the dropdown menu and how it is displaying in ie7 and ie8.
You can view it here:
http://getsmarta.co/_cms/topflight/
Here is the css I am using:
 nav {  width:1026px;
height: 50px;
background-image:url(../img/nav.png);
padding:0 0px 0 0px;
text-align:center;
margin-bottom:30px;

}
nav ul li  {
display:inline-block;
position:relative;

}
nav ul li div.sub {
display:none;
position:absolute;
background-color:#003e88;
top:38px;
width:260px;
text-align:left;
border-radius: 0px 0px 7px 7px;
-o-border-radius: 0px 0px 7px 7px;
-moz-border-radius: 0px 0px 7px 7px;
-khtml-border-radius: 0px 0px 7px 7px;
-webkit-border-radius: 0px 0px 7px 7px;

}
nav ul li div.sub a{
background-image:none;

}
nav li a {
padding:13px 20px 11px 20px;
display:inline-block;
margin-top:-10px;
background-image:url(../img/nav-divider.png);
background-position:top right;
background-repeat:no-repeat;
font-family:champ, myriad, Arial, Helvetica, sans-serif;
font-size:16px;
text-transform:uppercase;
font-weight:bold;
text-decoration:none;
margin-right:-4px;

}
nav li a:hover {border: 0;
background-image:url(../img/hover.png);

}
nav li.current a {
color:#47cacd;

}
I am at a loss with it and any help would be greatly appreciated, Thanks.

A: I think HTML 5 elements are not supported in IE, if you put a DIV with a ID of nav and put your all CSS on it, it will work.
If you want to use HTML5 then there are javascript hacks which can help you :)

A: Your problem is much simpler then that, IE for some reason is not accepting your display:inline-block declaration for your menu nav items. Though you can fix it by targeting your nav menu in IE by using the .oldie class provided by the html5-boilerplate and setting it to float:left instead, so try this in your CSS:
.oldie nav li {
  float:left;
  z-index:9999;
}

By the way, you need to declare a z-index value to your nav elements as well in order for them to appear on top of everything else, try this:
nav ul li {
    z-index: 999;
}


text:
Q: answer file for chef installs Opsworks I have an install for Linux that requires a few answers beyond yes and no. One is directory location ( which has a default) and accept for the EULA, the rest are yes and no answers.
I have a script in a recipe that runs bash, and I get to a certain point and it hangs, looking for input is my guess.
The important part is
echo "/opt/mydir"  # directory location
echo "yes" \n      # confirm directory location
sleep 10           # added a pause while it did its thing. Needed?
echo "yes" \n      # another question asked
sleep 10           #another pause
echo "accept" \n   # EULA agreement, requires accept or decline
echo "y" \n        # another question asked
sleep 10           # another pause
echo "y" \n        #another question asked
sleep 10           # another pause before the next command is sent that runs another stage of the install.

According to the logfile, it is hanging at the EULA agreement, which makes me believe that it is waiting on accept. If I run it manually it will prompt for accept or decline with every input unless it sees accept or decline.
So what can I do different to make this work?  I searched a few days looking for an answer and have not found any as it is not a simple yes or no script.

A: I finally stumbled on it from a coworker.  Even simpler than I thought.
script 'Install Software' do
interpreter "bash"
cwd "/opt/fidir"
code <<-EOH
cp /home/user/installs/fidir/Install/oskey.lic /opt/fidir/insttemp/oskey.lic
/opt/fidir/fast psx <<-EOFFIDIR02
y
n
AEC
02
n
/var/fidir
1
n
EOFFIDIR02
EOH

end


text:
Q: How to delete a string only containing a word using regex? 1 line: "*hello:  "
2 line: "*hello:    "
3 line: "*hello: person answered"

Would like to delete line 1 and 2 entirely, but want to keep line 3, without it becoming:
"*hello:person answered"

tried:
line = line.replaceAll("*hello:(\\s*)","");

A: You can simply do
line = line.replaceAll("^\\*hello:\\s*$","");

or
line = line.replaceAll("\\*hello:\\s*(?!.*\\w)","");

This should do it for you.See demo.
https://regex101.com/r/mT0iE7/24


text:
Q: How to make an logic to separate the data from SQL with Cakephp2? Currently, I have a site that shows a list of Developers name that I pulled out from the MySQL from the database in Cakephp2. What I want to achieve is to separate "Developers" into two types like "developer" and "programmer". I tried to give an extra field for the id to separate the developers with the programmers in the table that contains the developer's name. But I'm stuck with how I can do this. My explanation might be confusing so I will put the sample of what I want to do below. Some tips and examples with be a great help. I would love to hear from you.
    Currently, Employee table consitsts of list of names
     of all developers and is retrieved and displayed in cakephp2.
             (Developer)
                    ------------------------------
                        Tim
                        Jim
                        Joe
                        Blake
                        Mike
                        Ron
                ------------------------------

            Now, I want to separate the Developers into two parts "Developer" and "Programmer" maybe by adding a programmer_id field .

                (Developers)
                ------------------------------
                        Tim
                        Jim   ← programmer_id
                        Joe
                        Blake
                        Mike ← programmer_id
                        Ron
                 ------------------------------

Want to show the separated data in cakephp2 like the following.

                (Developer)
                        Tim
                        Joe
                        Blake
                        Ron

                ------------------------------
                (Programmer)
                        Jim
                        Mike

A: I am not getting exactly what you are asking but as per your table structure you can do something like this.
     developer   Tim
     programer   Jim   ← programmer_id
     developer   Joe
     developer   Blake
     programer   Mike ← programmer_id
     developer   Ron

  $developer = $this->Employee->find('all', array(
        'conditions' => array('Employee.category' => 'developer')
    ));

  $programmer = $this->Employee->find('all', array(
        'conditions' => array('Employee.category' => 'programmer')
    ));


text:
Q: Bigquery select rows where the logtime is below min(value) of other table logtime Let say I have the following two tables :
Table 1:
ID     log_time
1      2013-10-12
1      2014-11-15
2      2013-12-21
2      2016-12-21
3      2015-09-21
3      2018-03-21

Table 2:
ID     log_time
1      2011-10-12
1      2012-11-15
2      2012-12-21
2      2017-12-21
3      2014-09-21
3      2019-03-21

I want to get rows of Table 2 which are below min(log_time) of Table1 for each ID.
The result should be like this:
ID     log_time
1      2011-10-12
1      2012-11-15
2      2012-12-21
3      2015-09-21

A: This is join and aggregation:
select t2.*
from table2 t2 join
     (select t1.id, min(t1.log_time) as min_log_time
      from table1 t1
      group by t1.id
     ) t1
     on t2.id = t.id and t2.timestamp < t1.timestamp;

You can also express this as a correlated subquery:
select t2.*
from table2 t2
where t2.log_time < (select min(t1.log_time) from t1 where t1.id = t2.id);

Note that both of these formulations will return no rows for ids missing from table1 (which is quite consistent with your question).


text:
Q: Can I reuse my pointer after it's been added to a mutable array? Let's say I've got an array with strings.
NSArray *names = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];

What I want is to initiate objects of some custom class and them add them to a mutable array. I'm using a custom init method that takes a string argument.
To be more specific, I want to [SomeClass alloc] initWithName: aName] and add the resulting object to a NSMutableArray.
I'm thinking of using Objective-C fast enumeration. So what I get is:
NSMutableArray *objects = [NSMutableArray arrayWithCapacity: [names count];

for (NSString *name in names) {
    [objects addObject: [[[SomeClass alloc] initWithName: name] autorelease]];
}

The problem is that I can't add nil to the array and I don't like exception handling. However, my initiation method may return nil. So I decide to check first before adding (prevention). My new for-in-loop is:
SomeClass *someObject;

for (NSString *name in names) {
    someObject = [[[SomeClass alloc] initWithName: name] autorelease];
    if (someObject) {
        [objects addObject: someObject];
    }
}

Now, instead of immediately passing the new object to the array, I'm setting up a pointer someObject first and then passing the pointer to the array instead.
This example raises a question to me. When I someObject = [[[SomeClass alloc] initWithName: name] autorelease] in the loop, do the existing objects (which are added using the same pointer) in the array change too?
To put it in other words: does the addObject: (id)someObject method make a new internal copy of the pointer I pass or do I have to create a copy of the pointer — I don't know how — and pass the copy myself?
Thanks a lot! :-)

A: It's fine to reuse someObject; if you think about it, you're already reusing name each time you go through the loop.
-addObject: may or may not copy the object that you pass in. (It doesn't -- it retains the object rather than copying it, but it's conceivable that some NSMutableArray subclass could copy instead.) The important thing is that this code really shouldn't care about what -addObject: does.
Also, don't lose sight of the distinction between a pointer and the object that it points to. Pointers are just references, and a pointer is copied each time you pass it into a method or function. (Like C, Objective-C passes parameters by value, so passing a pointer into a method results in putting the value of the pointer on the stack.) The object itself isn't copied, however.

A: Short answer: no, you don't have to worry about reusing someObject.
Slightly longer answer: the assignment—someObject = ... assigns a new pointer value to the someObject variable; addObject: is then getting that value, not the address of someObject itself.

A: I think you're getting confused in the concept of pointer here. When you say someObject = [[[SomeClass alloc] init... you are basically pointing the someObject pointer to a new object. So to answer your question- your current code is fine.
As for whether arrays maintain copies of the objects added to them - NO, the array retains the object you add to it. However, that doesn't matter to your code above.

A: Three20 provides the answer!


text:
Q: JTextField's setText method doesn't work from a KeyListener I'm puzzled as to why a JTextField doesn't seem to just "clear out" by using the setText("") method on it, when this is coming from a KeyListener. It works fine from an ActionListener, except that, most amazingly, if the KeyListener method tries to invoke the ActionListener method, with a dummy action event (created on the fly as a simple test), it still leaves the typed text in place.
In other words, when you run it from the command line, if you type, for example, a "3" into the field, you will see the setText("test") method does not wipe out the 3, as I would expect and desire, but rather leaves it in place. You will then see "test3" in the display. I have noted this line with a comment. Clicking the JButton will wipe out the text properly. The JButton and JLabel will change text properly. but the JTextField won't. If you then press the button, you will see that the action event clears out the JTextField properly. Now, if you toggle the commented out line, you can see an attempt to invoke the actionPerformed method from the KeyTyped method!!! And still, when you type a "3" into the text field, it will not get wiped out. I would expect the setText("") method to clear it out, which it won't. And this is even when the keyTyped() method is invoking the same actionPerformed() method as the JTextButton.
Motivation here may help a little. I have a need to trap one particular hot-key which will clear out the JTextField at the moment it is typed, just as if you pressed the "clear" button. And this doesn't seem to work.
I haven't done that much with Swing before, but this is quite puzzling.
My SSCCE code follows:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class P2 implements KeyListener, ActionListener
{
  JTextField fld;
  JButton btn;
  JLabel  lbl;

  P2()
  {
    JFrame frm = new JFrame("Test");
           fld = new JTextField(10);
    JPanel pnl = new JPanel();
           btn = new JButton("Clear it out");
           lbl = new JLabel("This is a test");

    fld.addKeyListener(this);

    btn.addActionListener(this);

    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frm.setSize(400,400);
    frm.setLayout(new FlowLayout() );
    pnl.add(fld);
    pnl.add(btn);
    pnl.add(lbl);
    frm.getContentPane().add(pnl);
    frm.setVisible(true);
  }
  public void keyPressed(KeyEvent ke) {}
  public void keyReleased(KeyEvent ke) {}
  public void keyTyped(KeyEvent ke)
  {
     System.out.println("got a pressed key");

//this is the setText method that ought to wipe clean the field comments:
    this.fld.setText("test");
    this.btn.setText("try again");
    this.lbl.setText("got a presseed key");

//toggle this comment to see the invocation of the action event:
//    this.actionPerformed(new ActionEvent( new Object(), 2, "test")  );

  }
  public void actionPerformed(ActionEvent ae)
  {
     fld.setText("");
     fld.selectAll();
  }
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater
    (
      new Runnable()
      {
        public void run()
        {
          new P2();
        }
      }
    );
  }
}

A: This behavior is due to the fact that the KeyEvent will be processed by the field after your KeyListener was fired. You can circumvent it by consuming the event via
ke.consume();

inside your method keyTyped.
Depending on your requirements another way would be to encapsulate the clearing calls inside a SwingUtilities.invokeLater which will be processed after your current event and thus clear the field after it was updated.

A: Here's a code snippet using key bindings to wipe out all text on pressing 'a', implemented to use actions already registered in the field's action map (note that you still need to wrap the code into SwingUtilities.invokeLater - as Howard already suggested - that guarantees it to be processed after the fields internal processing)
    JTextField normal = new JTextField("just a normal field", 10);
    final Action selectAll = normal.getActionMap().get("select-all");
    final Action cut = normal.getActionMap().get("cut-to-clipboard");
    Action combine = new AbstractAction() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    selectAll.actionPerformed(e);
                    cut.actionPerformed(e);

                }
            });
        }

    };
    normal.getActionMap().put("magic-delete-all", combine);
    normal.getInputMap().put(KeyStroke.getKeyStroke("A"), "magic-delete-all");


text:
Q: Python 3.7 install fails with anaconda I try to install python 3.7 for anaconda with the following command:
conda install -c anaconda python=3.7

And its showing the following failure message:
Solving environment: failed

UnsatisfiableError: The following specifications were found to be in conflict:
  - _license -> python=3.6
  - python=3.7
Use "conda info <package>" to see the dependencies for each package.

A: The following page provides a solution: https://github.com/ContinuumIO/anaconda-issues/issues/9686
and could solve it by creating a new virtual environment with the following command and without the default packages:
conda create -n python37 python=3.7 --no-default-packages


text:
Q: php multiple strings to multiple variables I've the string block:
Size : Size 13 - 950-975
Easygrip_Locking_System : No
Veranda_pole : No
Safelock_tie_down : No
Storm_Pole : No
Tall_Annexe : Yes
Inner_tent : Yes

What I need is to create variables from the above block like :
$Size = "Size 13 - 950-975";
$Easygrip_Locking_System = "No";
$Veranda_pole = "No";
...
$Inner_tent = "Yes";

All of this are product options and depending on a product type possible to be more ore less and different.
I've already tried with preg_split than to put in array and eval() but not get what I need.
$keywords = preg_split('/[\,]+/', '$Size= "Size 13 - 950-975";,$Easygrip_Locking_System= "No";');
print_r($keywords);

A: You can achieve this by exploding your string in to array then separate variable and value by :
$str = "Size : Size 13 - 950-975
Easygrip_Locking_System : No
Veranda_pole : No
Safelock_tie_down : No
Storm_Pole : No
Tall_Annexe : Yes
Inner_tent : Yes
";
$arr =explode("
",$str);
var_dump($arr);
foreach ($arr as $key => $value) {
  $tmp = explode(":", $value);
  if(count($tmp) > 1)
    ${trim($tmp[0])} = trim($tmp[1]);
}

//Here you can get your variables like:

echo $Size;

A: Prepare the string with appropriately placed = and &, then parse, then extract.
$string="Size : Size 13 - 950-975
Easygrip_Locking_System : No
Veranda_pole : No
Safelock_tie_down : No
Storm_Pole : No
Tall_Annexe : Yes
Inner_tent : Yes
";
$string=str_replace([' : ', '
'], ['=', '&'], $string);
parse_str($string, $out);
extract($out);

echo "Size = $Size\n";
echo "Easygrip_Locking_System = $Easygrip_Locking_System\n";
echo "Veranda_pole = $Veranda_pole\n";
echo "Safelock_tie_down = $Safelock_tie_down\n";
echo "Storm_Pole = $Storm_Pole\n";
echo "Tall_Annexe = $Tall_Annexe\n";
echo "Inner_tent = $Inner_tent\n";

Output:
Size = Size 13 - 950-975
Easygrip_Locking_System = No
Veranda_pole = No
Safelock_tie_down = No
Storm_Pole = No
Tall_Annexe = Yes
Inner_tent = Yes

Demo: https://3v4l.org/ppv3G
If you want to perform validation or sanitize or make any other preparations, I recommend doing so before calling extract.
Alternatively, if you want to have greater control of the key and value substrings via a regex pattern, you can use pre_match_all().
if (preg_match_all ('~([a-z_]+) : (.+?)
~i', $string, $out, PREG_PATTERN_ORDER)) {
    extract(array_combine($out[1], $out[2]));

    echo "Size = $Size\n";
    echo "Easygrip_Locking_System = $Easygrip_Locking_System\n";
    echo "Veranda_pole = $Veranda_pole\n";
    echo "Safelock_tie_down = $Safelock_tie_down\n";
    echo "Storm_Pole = $Storm_Pole\n";
    echo "Tall_Annexe = $Tall_Annexe\n";
    echo "Inner_tent = $Inner_tent\n";
}

Demo:   https://3v4l.org/vjYiK

A: $str = 'Size : Size 13 - 950-975
Easygrip_Locking_System : No
Veranda_pole : No
Safelock_tie_down : No
Storm_Pole : No
Tall_Annexe : Yes
Inner_tent : Yes
';

$result = array();

foreach (explode('
', trim($str, '
')) as $key => $value) {
    $key = trim(strstr($value, ':', true));
    $value = trim(substr(strstr($value, ':'), 1));
    $result[$key] = $value;
}

// May be unsafe
extract($result);


text:
Q: Why is my script's directory not in the Python sys.path? Python 3.6.5
I am aware of this one: Why does my python not add current working directory to the path?
But the problem there is that he's doing something more complicated (referring to a  sub-folder but executing from a main folder). The answers there are to either simplify things or to add package definitions.
And the selected answer even says: "It is the script's directory that is added"
However, my problem is really more simple: My script's directory ISN'T added.
Basically, all the tutorials on the internet say: import mymodule
When I do that, I get a name error...
My folder structure:
C:/Projects/interner
    interner.py   # this is the main program body
    aux.py        # this is the auxiliary file I would like to import into the above

I've tried both coding 'import aux' inside interner.py, and also using the interactive console:
cd c:/Projects/interner
python
import aux

To no avail (ModuleNotFoundError: No module named 'aux')
My sys.path:
['C:\\Tools\\Python\\python365\\python36.zip', 'C:\\Tools\\Python\\python365']

(both from inside the script and from interactive console)
Could you please tell me why I can't import local scripts? Is it because my sys.path is missing the PWD? If so, why is it missing it?
Edit: Doing this to help investigation:
>>> import os; print(os.listdir("."))
['aux.py', 'hw.py', 'interner.py', 'my_funcs.py']

A: I believe this is a Python bug, specific to the embeddable (ZIP file without an installer) Windows distribution. I've filed https://bugs.python.org/issue34841.
Removing the python37._pth file (presumably python36._pth in your case) from the distribution fixed it for me.

A: I don't know why but it seems that "" is missing from your sys.path variable, and that prevents from importing modules from current directory all right!
I can somehow reproduce your issue (eatcpu.py is in my current dir):
$ python.exe
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', 'C:\\Windows\\system32\\python27.zip', 'D:\\AppX64\\Python27\\DLLs', ... etc...]
>>> import eatcpu

works. Now in another python session:
$ python.exe
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.remove("")
>>> import eatcpu
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named eatcpu
>>>

So the quickfix for you is to do:
import sys
sys.path.append("")

A: It looks like you are using the embeddable distribution of CPython rather than one of the regular installers. As described on the documentation page:

The embedded distribution is a ZIP file containing a minimal Python environment. It is intended for acting as part of another application, rather than being directly accessed by end-users.

Since you seem to be directly accessing Python rather than embedding it, you should consider using the regular (or Microsoft Store) installer (also described on the page I linked above).

A: Try making it explicit:
from . import aux