text:
Q: Use existing node_modules during serverless deployment using serverless-webpack I am working on a node application using serverless architecture. We are using serverless-webpack plugin to build the application. Here is the webpack.config.js
module.exports = {
  mode: isLocal ? 'development' : 'production',
  entry: slsw.lib.entries,
  externals: [nodeExternals()],
  devtool: 'inline-cheap-module-source-map',
  resolve: {
    extensions: ['.js', '.jsx', '.json', '.ts', '.tsx']
  },
  output: {
    libraryTarget: 'commonjs2',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js'
  },
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin()],
  },
  target: 'node',
  module: {
    rules: [{
        test: /\.ts$/,
        exclude: /node_modules/,
        loader: 'ts-loader',
        options: {
          // disable type checker - we will use it in fork plugin
          transpileOnly: true
        }
      },
      {
        test: /\.(graphql|gql)$/,
        exclude: /node_modules/,
        loader: 'graphql-tag/loader',
      }
    ]
  },
  // plugins: [new ForkTsCheckerWebpackPlugin()]
};

and here is the serverless.yml file :
service: app
provider:
  name: aws
  region: ${env:AWS_REGION}
  stage: ${env:STAGE}
  logRetentionInDays: 90
  role: ${env:ROLE}
  versionFunctions: false
  runtime: nodejs12.x

package:
  individually: true

plugins:
- serverless-webpack
- serverless-offline

custom:
  webpack:
    webpackConfig: './webpack-gql.config.js'
    packager: 'npm'
    includeModules: true

functions:
  ######## GraphQl ###########
  graphql:
    role: ${env:ROLE}
    runtime: nodejs12.x
    timeout: 30
    handler: aws/lambda/common/api/graphql.graphqlHandler

    events:
      - http:
          path: graphql
          method: post

      - http:
          path: graphql
          method: get

When I am running sls deploy --config serverless.yml  to deploy the application , everything is working and the lambda is getting deployed successfully.
Only thing is , during the process of deployment , it is using the package-lock.json and installing the used packages again :
Serverless: Package lock found - Using locked versions

Serverless: Packing external modules:  graphql-compose@^7.19.3, linewrap@^0.2.1, d64@^1.0.0, graphql-scalars@^1.2.6, graphql-tools@^6.0.12

Serverless: Packaging service...

My question is how to stop rerunning the npm install again during deployment instead it should use the existing node_moudles while packing the external modules.
Can anybody help me on this. ?


text:
Q: Asymptotic Notation: Proving Big Omega, O, and Theta I have a few asymptotic notation problems I do not entirely grasp.
So when proving asymptotic complexity, I understand the operations of finding a constant and the n0 term of which the notation will be true for. So, for example:
Prove 7n+4 = Ω(n)

In such a case we would pick a constant c, such that it is lower than 7 since this regarding Big Omega. Picking 6 would result in
7n+4 >= 6n

n+4 >= 0

n = -4

But since n0 cannot be a negative term, we pick a positive integer, so n0 = 1.
But what about a problem like this:
Prove that n^3 − 91n^2 − 7n − 14 = Ω(n^3).

I picked 1/2 as the constant, reaching
1/2n^3 - 91n^2 - 7n -14 >= 0.
But I am unsure how to continue. Also, a problem like this, I think regarding theta:
Let g(n) = 27n^2 + 18n and let f(n) = 0.5n^2 − 100. Find positive constants n0, c1 and c2 such
that c1f(n) ≤ g(n) ≤ c2f(n) for all n ≥ n0.

In such a case am I performing two separate operations here, one big O comparison and one Big Omega comparison, so that there is a theta relationship, or tight bound? If so, how would I go about that?

A: To show n3 − 91n2 − 7n − 14 is in Ω(n3), we need to exhibit some numbers n0 and c such that, for all n ≥ n0:

n3 − 91n2 − 7n − 14 ≥ cn3

You've chosen c = 0.5, so let's go with that. Rearranging gives:

n3 − 0.5n3 ≥ 91n2 + 7n + 14

Multiplying both sides by 2 and simplifying:

182n2 + 14n + 28 ≤ n3

For all n ≥ 1, we have:

182n2 + 14n + 28 ≤ 182n2 + 14n2 + 28n2 = 224n2

And when n ≥ 224, we have 224n2 ≤ n3. Therefore, the choice of n0 = 224 and c = 0.5 demonstrates that the original function is in Ω(n3).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does accessing array index on boolean value does not raise any kind of error? When I try to access an array by key which is not exists in this array, php will raise "undefined index" notice error. When I try to do the same on strings, "Illegal string offset " warning is raised. This is an expected behavior and I know how to deal with it.
But when I tried this on boolean or integer values nothing happens:
ini_set('display_errors', 1);
error_reporting(E_ALL);

$var = false;
var_dump($var['test']);

I expect to see some error messages, but $var['test'] just silently sets to NULL.
So why does php permit to access boolean value through an array key without any indication that you are doing something wrong?
The hole "access boolean value through an array key" phrase sounds terribly wierd to me, but you can do it in php.

A: It's sad, but it's documented behaviour.
http://php.net/manual/en/language.types.string.php

Note:
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.


text:
Q: How to make a Standard Scratch Guide? Hi I'm a beginner at coding and I've just tried my first project. It's a standard scratch score for golf. Everytime I've run the code it comes sout with a completely wrongly score. Here's the code:
import java.util.Scanner;

public class StandardScratch {
    public static void main(String[] args) {
        double Par1 = 0.0,
        Par2 = 0.0,
        Par3 = 0.0,
        difficulty = 0.0;
        String operation;
        Scanner scannerObject = new Scanner(System.in);

        System.out.println("How many par 3 holes are there?");
        Par1 = scannerObject. nextDouble();

        System.out.println("How many par 4 holes are there?");
        Par2 = scannerObject. nextDouble();

        System.out.println("How many par 5 holes are there?");
        Par3 = scannerObject. nextDouble();

        System.out.println("What is the difficulty adjustment for the course?");
        difficulty = scannerObject. nextDouble();

        System.out.println("The Standard Scratch for the course is:" + ((Par1 * 6) + (Par2 * 4) + (Par3 * 5) - difficulty));
    }
}

When every I try to run the code with the numbers being 6,10,2 and -2 it comes out with 88 while the true score should be 66. Thanks!

A: You've coded this:
 ... Par1 * 6 ...

The scratch score for a par-3 hole in golf is actually 3.
It doesn't help that you have used misleading names for your variables.


text:
Q: multiple angular material table in single page pagination issue i am using angular two material table in single html page. first table, data loaded well with proper pagination. but in second table, all data loading without pagination. i added pagination functionally to both pages. i would like to show some part of code regarding this.
table 1 pagination (working well)
 <mat-paginator #paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

table 2 pagination (pagination not working)
  <mat-paginator #errorpaginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons>

my component file

import { Component, OnInit, ViewChild, Input, Inject} from '@angular/core';
import { from } from 'rxjs/internal/observable/from';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { DataSource } from '@angular/cdk/collections';
import { arInvoiceHeaderService} from './ar-invoice-header.service';
import { arInvoiceHeaderModel, arInvoiceHeader } from './ar-invoice-header-model';
import { MatSort, MatSortable, MatPaginator,MatTable, MatTableDataSource } from '@angular/material';
import { Injectable } from '@angular/core';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {animate, state, style, transition, trigger} from '@angular/animations';
import { FormControl } from '@angular/forms';
import { arErrorModel } from './ar-error-model';
import { MatPaginatorModule } from '@angular/material';
@Component({
  selector: 'app-ar-invoice-header',
  templateUrl: './ar-invoice-header.component.html',
  animations: [
    trigger('detailExpand', [
      state('collapsed, void', style({height: '0px', minHeight: '0', display: 'none'})),
      state('expanded', style({height: '*'})),
      transition('* <=> *', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
    ]),
  ],
  styleUrls: ['./ar-invoice-header.component.css']
})
@Injectable()
export class ArInvoiceHeaderComponent implements OnInit {
  @ViewChild(MatSort) sort: MatSort;
  //@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild('paginator') paginator: MatPaginator;
@ViewChild('errorpaginator') errorpaginator: MatPaginator;
 @ViewChild(MatTable) table: MatTable<any>;

  isLoading = true;
  noGridData: boolean = false;
  dataSource = new MatTableDataSource(this.dataSource);
  errordataSource = new MatTableDataSource(this.errordataSource);
  //dataSource;
  //errordataSource;
  expandedElement: arInvoiceHeader;
  displayedColumns = ['id','invoiceNumber','status','orgName','setOfBooks','transactionSource','transactionType','errorCodeH','invoiceTotal','lineCount','interfaceFileLineNo','interfaceFileName','interfaceFilePath','createdBy','creationTimestamp'];
  errordisplayedColumns = ['id','invoiceNumber','lineNumber','interfaceFileName','interfaceFilePath','errorDescription'];

  constructor(private arinvoiceheaderService: arInvoiceHeaderService) {

   }

  ngOnInit() {

    this.reloadList();
    this.arErrorList();
  }

//First table data loading function (currently working well with pagination )
  reloadList() {
    this.arinvoiceheaderService.getArInvoiceHeader().subscribe(results => {
      console.log(results);
      if (!results) {
       // return;
       alert("ERRor");
      }

      this.dataSource = new MatTableDataSource(results['ArInvoiceHeaders']);
      if(results.ArInvoiceHeaders.length > 0)
      {

        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
        this.isLoading = false;
        this.noGridData = false;
      }
      else{
        this.noGridData = true;
        this.isLoading = false;
      }

    });
  }

//seconf table data loading function (all data loading without pagination)
  arErrorList(){
    this.arinvoiceheaderService.getArErrorDetails().subscribe(results => {
      console.log(results);
      if (!results) {
        return;
      }
      this.errordataSource = new MatTableDataSource(results['ArInterfaceErrors']);

      this.errordataSource.errorpaginator = this.errorpaginator;
      this.errordataSource.sort = this.sort;

    });
  }
}

can you help me to sort out second table pagination issue.

A: multiple angular material table workd for me...
Table 1 pagination
 <mat-paginator [pageSize]="10" [pageSizeOptions]="[3, 5, 10]"
  [showFirstLastButtons]="true"></mat-paginator>

Table 2 pagination
   <mat-paginator [pageSize]="10" #paginatorlist [pageSizeOptions]="[3, 5, 10]"
    [showFirstLastButtons]="true"></mat-paginator>

TS: The change detector looks for the first element..So we can use property ..
read - True to read a different token from the queried elements.
    @ViewChild('paginatorlist', { read: MatPaginator }) paginatorlist: MatPaginator;
    @ViewChild(MatPaginator) paginator: MatPaginator;

A: As posted in the comment this line of code here this.errordataSource.errorpaginator = this.errorpaginator; is wrong, there is no errorpaginator property on the datasource. It should be this.errordataSource.paginator = this.errorpaginator;.
See a stackblitz here, if you uncomment the wrong line of code and comment the correct one you can see that it doesn't work with your code, but with the correct one it does.

A: **Table 1**

<mat-paginator [pageSizeOptions]="[5, 10, 15, 20]" showFirstLastButtons>
</mat-paginator>

**Table 2**
<mat-paginator #modulePaginatpr [pageSizeOptions]="[5, 10, 15, 20]" showFirstLastButtons></mat-paginator>

**componenet.ts**
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild('modulePaginatpr') modulePaginatpr: MatPaginator;

For table1 (datasoure is sourse name in table 1 html code)
this.dataSource.paginator = this.paginator;
For table2 (datasoure2 is sourse name in table 2 html code)
this.dataSource2.paginator = this.modulePaginatpr;


text:
Q: Fill JS Array from List C# I have a List<string> in my Model C# filled on runtime, called @Model.Names in my Views.
After filling that list I want to fill an array in javascript from values of that list, in order to do the following:
 var myArray = [];

//fill myArray with values from @Model.Names

 $("#tags").autocomplete({
   source: myArray
  });

So when the user types in <input id="tags"> he will get an autocomplete with a list of the names I filled on runtime.
Any idea how to do so?

A: I prefer this way. No manual Looping, and you can do this with fairly complex viewmodels as well (as long as there are no recursive references within your types).
var myArray = @Html.Raw(Json.Encode(Model.Names))

$("#tags").autocomplete({
    source: myArray
});

A: you can try the following.
<script type="text/javascript">
    var myArray = [];
    @foreach (var name in Model.Names)
    {
        @:myArray.push("@name");
    }
</script>


text:
Q: Remove the last element's specific text For example i have a for loop which will generate some kind of words
for(var i=0;i<profile.test.length;i++){
    var wordList = wordList  + profile.test[i].text.map(function(k) {
        return k.split(/,\s*/).join('+');
    }).join(' , ') + '|';
};

and this will return something like
hhh1+hhhh2|fdsg+gsdg , 123+1232|

but i want to remove the last "|"
hhh1+hhhh2|fdsg+gsdg , 123+1232

how could i do that?

A: If you have the outer loop return an array you can use join on it.
This works because join takes the elements of an array and "joins" them together into a single string using the passed in argument as the delimiter/separator.
This means that var example = ['a', 'b', 'c'].join('|') sets example to 'a|b|c'.

Without knowing the value of profile in your example it's hard to refactor your code an know that it works. But, if you modify your existing code you should be able to do something along the lines of this:
profile.test.map(function(item) {
  return item.map(function(k) {
    return k.split(/,\s*/).join('+');
  }).join(' , ')
}.join('|');

Here's another example of a similar problem that works using the same concept as mentioned above:

// hhh1 , hhhh2|fdsg , gsdg

var items = [{text:'hhh1, hhhh2'}, {text: 'fdsg, gsdg'}]

var out = items.map(function(item) {
  return item.text.split(/,\s*/).join(' , ');
}).join('|');

console.log(out)

A: You can change '|' to
i !== profile.test.length - 1 ? '|' : ''

which would change your code to:
for(var i=0;i<profile.test.length;i++){
    var wordList = wordList  + profile.test[i].text.map(function(k) {
        return k.split(/,\s*/).join('+');
    }).join(' , ') + (i !== (profile.test.length - 1) ? '|' : '');
};

A: You can use the substr method of the generated String to remove the last character:
wordList = wordList.substr(0, wordList.length -1);

A: A general solution when the last "|" isnt the last character would be by define its position could be like this:
str ="abc|def|ghi|nope";
var lastPos = str.lastIndexOf('|');
var wordStart = str.substring(0,lastPos);
var wordEnd = str.substring(lastPos+1);
alert(wordStart + wordEnd);

JSFiddle:
https://jsfiddle.net/e59erp0h/
In real word szenarios, id recomment to shorten it (unless you want to play arond with ANYTHING ;)(

A: Add this code after your loop to remove the last character
wordList = wordList.substring(0, wordList.length - 2);


text:
Q: I get a query error 'unknown column' while the column exists I get error (1054): Unknown column 'wp_jpnx_survey_code.supplier_id' in 'field list'But that column does exist... Does anyone know why or how to fix this?
This is the code I used:
CREATE VIEW survey_codes_complete_overview AS SELECT *,
wp_jpnx_survey_code.supplier_id AS a_id,
wp_jpnx_survey_supplier_info.supplier_id AS b_id FROM
wp_jpnx_survey_code AS a LEFT JOIN wp_jpnx_survey_supplier_info AS b
ON a.supplier_id = b.supplier_id;

A: You are using aliases for those tables. So, specify the alias when selecting the column.
CREATE VIEW survey_codes_complete_overview AS
SELECT *,
a.supplier_id AS a_id,
b.supplier_id AS b_id
FROM wp_jpnx_survey_code AS a
LEFT JOIN wp_jpnx_survey_supplier_info AS b
ON a.supplier_id = b.supplier_id


text:
Q: file format is incorrect in PHPExcel Code I am trying to write mySQL data into Exlcel using PHPExcel, but I am getting file format is invalid in my above PHP code using PHPExcel. Can someone please help me to find out what is wrong in code:
$query = "SELECT company_id, userid FROM uam_user";
    $result = mysql_query($query) or die ("Error in Query".mysql_error());
    // Instantiate a new PHPExcel object
    $objPHPExcel = new PHPExcel();

    // Set document properties
        $objPHPExcel->getProperties()->setCreator("Security Team")
         ->setLastModifiedBy("System")
         ->setTitle("System")
         ->setSubject("System Security")
         ->setDescription("Non Production user Upload Data")
         ->setKeywords("User Upload")
         ->setCategory("Security");

            // Set the active Excel worksheet to sheet 0
            $objPHPExcel->setActiveSheetIndex(0);

                $objPHPExcel->getActiveSheet()->SetCellValue("A1", 'company_id');
         $objPHPExcel->getActiveSheet()->SetCellValue("B2", 'userid');

    //start of printing column names as names of MySQL fields
    $rowCount = 2;
    //$num_rows = mysql_num_rows($result);
    //echo $num_rows;
    $i = 0;
     while($row = mysql_fetch_array($result, MYSQL_ASSOC)){

        if ($row['userid'] != '')
        {
            //echo "A$rowCount=".$row['company_id']."|B$rowCount=".$row['userid']."<br>";
            $objPHPExcel->getActiveSheet()->SetCellValue("A$rowCount",$row['company_id']);
          $objPHPExcel->getActiveSheet()->SetCellValue("B$rowCount",$row['userid']);
         }
      $rowCount++;
      //echo $rowCount;
    }

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="item_list.xlsx"');
    header('Cache-Control: max-age=0');
    ob_end_clean();
    $objWriter->save ( 'php://output' );


text:
Q: python calling django's render function in an async callback not working To better understand the language I started working on building out a client that consumes the Hacker News api. The below code is supposed to pull in the first 10 items from their jobs feed. It first gathers a list of the id's, iterates through those ID's, and makes an async request to get the item details, which fires the callback function when done. All of that is working fine. It appears however that the render function isn't returning anything when nested like this. When I hit this route, I get the following error message: The view feed.views.index didn't return an HttpResponse object. It returned None instead.
If I was coding this with Node, it would work fine so I am assuming that this is just a matter of me not understanding how the language (or possibly framework) does things with async requests and/or scoping. What am I doing wrong?
 def index(request):
    job_ids = firebase.get('jobstories', None)
    stories = []

    def append_story(story):
        stories.append(story)
        print(len(stories))
        if len(stories) == 10:
            return render(request, 'feed/index.html', {'items': stories})

    count = 0
    for ts_id in job_ids:
        if count < 10:
            count += 1
            firebase.get_async('item/' + str(ts_id), None, callback=append_story)

A: First of all you probably don't want to define append_story within the index function.
Secondly, the reason you are failing is because every Django view must return a HttpResponse with something like return HttpResponse("Hello"). Since python/django doesn't support async out of the box, if you want to do async, consider using ajax instead. Here's an example of how you might do something like that: Django - How to use asynchronous task queue with celery and redis.
Basically the idea is to just generate a view then use javascript to call an ajax view that pulls your firebase info and then update your page appropriately after getting the result.


text:
Q: How to Sync Notes & Highlights from Kindle Account to iOS / Android Apps - Similar to what ReadWise does I've been researching for ways in which I could fetch Notes & Highlights from my Kindle Account to an iOS/Android App.
Things I know so far

*

*There is no official Kindle API which Amazon provides, at the moment (Sep 2021)

*There are few ways in which I could achieve this functionality but most of them are from Web-Scraping in which I would have to explicitly provide email address and password for the Amazon account for accessing highlights from Kindle Highlights Url

*There are few git projects which already help with web-scraping but again, we have to explicitly provide email address and password

*

*PHP : https://github.com/johnpaulhayes/Kindle-Highlights

*Ruby : https://github.com/kyamaguchi/kindle_manager

*Ruby : https://github.com/speric/kindle-highlights

*There are few official app which have this functionality of syncing all the highlights from Kindle to the app but I'm not sure how they achieve this

*

*ReadWise : https://readwise.io

*Calibre : https://calibre-ebook.com

*clippings.io : https://www.clippings.io
So just to summarise my question.
I'm looking for a way to access Kindle Highlights & Notes from my kindle account directly to my app both in iOS and Android. From the examples above, I know its possible but not sure how to go about implementing it.  Any help would be appreciated


text:
Q: What causes a misplaced item error in rebol? Here is the code pruned down to a minimum to show the error:
Rebol []

view center-face layout [
    fld1: field
    fld2: field
    flds: [fld1 fld2]
]

A: Here is the shortest example to show the error:
layout [ test: []]
>>Misplaced item: []

Rebol uses a number of different dialects, and the two you are using in this example are the do dialect and the view dialect.  Now inside the 'layout function, you can only have the view dialect but you have mixed the two.  So, the parser used by the 'layout function complains of the misplaced item.  The dialect expects to see after flds: one of the faces such as field, area, label etc but instead finds a block.
Regarding your clarification comment, if you wish to create a block of fields, you can just create the block first and then provide it to the 'layout function like this so that you end up with fields named var1 to var9.
lo: [ across ]

for i 1 9 1 [
    repend lo [ 'label  form join "var" i to set-word! join "var" i 'field 'return ]
]

view layout lo


text:
Q: how to sort string format like "2013-10-09" I have an array contains NSDictionary objects, and one key is Time, which contains time string format like "2013-10-09", and I need to sort the array by the Time key, but I don't know how to sort NSString with that format.

A: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSMutableArray *dates = [NSMutableArray arrayWithCapacity:datesAry.count];
for (NSString *dateString in dates)
{
    NSDate *date = [dateFormatter dateFromString:timeString];
    [dates addObject:date];
}

[dates sortUsingSelector:@selector(compare:)];

NSMutableArray *sortedDates= [NSMutableArray arrayWithCapacity:dates.count];
for (NSDate *date in dates)
{
    NSString *dateString = [dateFormatter stringFromDate:date];
    [sortedDates addObject: dateString];
}

A: - (void)testSortTimeAsString {
    NSDictionary *dict1 = @{@"key" : @"none", @"Time" : @"2013-10-01", @"optional" : @"---"};
    NSDictionary *dict2 = @{@"key" : @"none", @"Time" : @"2012-12-21", @"optional" : @"---"};
    NSDictionary *dict3 = @{@"key" : @"none", @"Time" : @"2013-02-10", @"optional" : @"---"};
    NSDictionary *dict4 = @{@"key" : @"none", @"Time" : @"2013-11-25", @"optional" : @"---"};
    NSDictionary *dict5 = @{@"key" : @"none", @"Time" : @"2013-06-15", @"optional" : @"---"};

    NSArray *array = @[dict1, dict2, dict3, dict4, dict5];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";

    NSArray *sorted = [array sortedArrayWithOptions:0 usingComparator:^(id obj1, id obj2) {
        NSString *stringDate1 = obj1[@"Time"];
        NSString *stringDate2 = obj2[@"Time"];

        NSDate *date1 = [dateFormatter dateFromString:stringDate1];
        NSDate *date2 = [dateFormatter dateFromString:stringDate2];

        NSComparisonResult result = [date1 compare:date2];
        return result;
    }];

    NSLog(@"Sorted array: \n%@", sorted);
}

A: Sorting dates with that format have the same result as sorting them as strings.
So:
  NSArray *unordered = @[
                         @{ @"Time": @"2001-01-01", @"Place" : @"Somewhere" },
                         @{ @"Time": @"1999-01-01", @"Place" : @"Elsewhere" },
                         @{ @"Time": @"1999-02-01", @"Place" : @"Nowhere" }
                         ];
  NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Time" ascending:YES selector:@selector(compare:)];
  NSArray *ordered = [unordered sortedArrayUsingDescriptors:@[ sortDescriptor ]];

will give you the sorted array.


text:
Q: Javascript: How can I get all value of selected checked checkboxes, push to an array then put in in a input HTML element? I have a list of 50 checkboxes. If users check some of them, how can I get all values of the selected ones and push them into an array then place it in a hidden text element?
Can I use the same name for all checkboxes? or I must use different name for each of them?
<input type="checkbox" name="bulk_id[]" value="1"/>
<input type="checkbox" name="bulk_id[]" value="2"/>
<input type="checkbox" name="bulk_id[]" value="3"/>
<input type="checkbox" name="bulk_id[]" value="4"/>
<input type="checkbox" name="bulk_id[]" value="5"/>
...

Thank you.

A: You tagged your question with jquery, so i'll assume you are using it.
You select checkbox with input[type=checkbox] and use the subclass :checked to filter checked ones
1- get all checked boxes in an array
var selectedValues =[]
$('input[type=checkbox]:checked').each(function(i,e){
  selectedValues.push( $(e).attr('value') )
})

2- append the content of this array in a hidden input (separated by ,)
$('#yourhiddenID').val( selectedValues.join(',') );

In this solution the name of your checkboxes does not matter.
Put your checkboxes in a container for a better selection :
$('#yourCheckboxContainerID input[type=checkbox]:checked')

A: so you have to get all checkboxes you have
 var checkboxes = document.getElementsByName("bulk_id[]");
 var arrayVal = [];
 for (var i= 0; i<checkboxes.length;i++)
  {
     if (checkboxes[i].checked === true)
     {
         arrayVal.push(checkboxes[i].value);
     }
  }


text:
Q: Databricks update files which name is on DataFrame I have a DataFrame like:
input_df = self.spark.createDataFrame(
            data=[
                ("01", "file_name_1"),
                ("02", "file_name_2"),
                ("05", "file_name_5"),
            ],
            schema=(
                "RECORD_ID: string, FILE_NAME: string"
            ),
        )

I have a folder /mnt/data/project/integration_test/ with the following files
file_name_1.json
file_name_2.json
file_name_3.json
file_name_4.json

I want to update those json files that are on the input_df
I thought the process would be:

*

*Delete json which name appears on input_df

*Save each row input_df as individual json (I already solved this)

The final files on /mnt/data/project/integration_test/ would be:
file_name_1.json (updated)
file_name_2.json (updated)
file_name_3.json
file_name_4.json
file_name_5.json (created new)

A: I think we can use Pandas and then iterate the file name and check if the file exists .
import pandas as pd
import os
input_df = spark.createDataFrame(
            data=[
                ("01", "test"),
                ("02", "test1"),
                ("05", "test2"),
            ],
            schema=(
                "RECORD_ID: string, FILE_NAME: string"
            ),
        )
display(input_df)
pandas_df = input_df.toPandas()
for index,row in pandas_df.iterrows():
    print(row['FILE_NAME'])
    if os.path.isfile(PATH):
       print("File exists ")
       // Update the existing file
    else:
       print("File NOT exists ")
       //Create a new file


text:
Q: GWT 2.4 Data Grid -- Horizontal Scroll Bar obscures last row The new DataGrid widget in GWT 2.4 automatically generates a horizontal scroll bar when the display viewport for the table is not as wide as the table itself, and a vertical scrollbar for the vertical case.  Fine so far.  But I have found that the scrollbar obscures the last row of the table.  There is no filler space after the last row to allow you to vertically scroll a bit farther to let the last row completely enter the viewing space.  That filler bar ought to be at least as tall as the scrollbar, and preferably a bit taller.
Any ideas for a work-around?  I don't want to add empty data rows since these represents real rows in a real database.

A: I just noticed that if you select a row (even with NoSelectionModel, there is a "select" where the row turns pale yellow), then tap the up and down arrows on the keyboard, the DataGrid rolls up and down, including pulling any rows obscured by the header or footer or horizontal scrollbar entirely into view.
Good to know.  Will have to train the users on that little trick.


text:
Q: Example with Yoneda Lemma This question refers to an example illustrating properties of the Yoneda lemma:
Basic Example of Yoneda Lemma?
Here the paragraph of matter in my question:

By Definition the Yoneda lemma provides a bijection between $Hom(Hom_{C}(-,A), F) $ and $F(A)$, so in this case $Hom(Hom_{M}(-,*), \phi) \cong \phi(*)$.
How do we conclude here that YL provedes the identification of a $M$-action $\phi$ (defined above as functor $M \to Set$) with a function $h: M \to \phi(*)$ with the rule $h(m_1m_2) = \phi(m_1)(h(m_2))$? I don't see where does it come.

A: It doesn't seem to be true. If there is an $M$-action on $A$ and on $B$, then there is an $M$-action on $A\sqcup B$. Which map $M\to A\sqcup B$ is this $h$?
The Yoneda lemma here says that each $x\in \phi(\star)$ there is a unique map $h_x:M\to \phi(\star)$ so that $h_x(m_1m_2)=\phi(m_1)h_x(m_2)$. That is, $h_x$ is a natural transformation from $\phi$ to $\hom_{M}(-,*)$. This map is $h_x(m)=\phi(m)(x).$
This in turn means that $\phi$ is equivalent to an $h:M\times X\to X$ with the usual definition of an action: $h(m_1,h(m_2,x))=h(m_1m_2,x).$ and $h(1,x)=x$.


text:
Q: Bootstrap sliding tabs (not tab content) I'm developing a project and using Bootstrap Tabs for my tabs. Users are able to create new tabs, so here is the problem: more than N tabs (where N depends on browser's width) result on this behaviour:

I surf a little into Bootstrap HTML tabs code, and tabs are li elements inside ul. I want to achieve something like this:

So on right side (and left side) tabs component may have a button which let my users navigate between created tabs (like an slider).
Anyone could guide me to this goal? Or is it any other tab component (from other framework for example) that implements this behaviour by default?
Thanks in advance!

A: There is nothing in Bootstrap OOTB, but you can do something like this:
http://codeply.com/go/43ARTwZuie, or https://www.codeply.com/go/Loo3CqsA7T (Bootstrap 4.3.x)
This solution uses jQuery to check the width in the tabs container, and then adjust the position of the tabs accordingly.
Another option is to put the overflowing tabs into a dropdown like this: http://www.bootply.com/7oAli9A9zL#

A: Use Horizontal timelines creatively
Below is a sample code.
Full demo  https://codyhouse.co/demo/horizontal-timeline/index.html

Horizontal Timeline

UI

Horizontal Timeline

                    <button class="btn btn-outline dropdown-toggle no-caret" type="button" data-toggle="dropdown"></button>

                        Activity
                        Messages
                        FAQ
                        Support

                        <button type="button" class="btn btn-rounded btn-success">Submit</button>

16 Jan

28 Feb

20 Mar

20 May

09 Jul

30 Aug

15 Sep

01 Nov

10 Dec

29 Jan

3 Mar

Prev

Next

 Horizontal Timeline
January 16th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
Feb 28th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
March 20th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
May 20th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
July 9th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
August 30th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
September 15th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
November 01st, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

 Horizontal Timeline
December 10th, 2018

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

                                    <button class="btn btn-info btn-outline mt-20">Read more</button>

Event title here
 January 19th, 2019

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.

Event title here
 March 3rd, 2019

 On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.


text:
Q: When developing on an old code base, should I use Best Practices or go for Consistency
Possible Duplicate:
Code maintenance: keeping a bad pattern when extending new code for being consistent, or not ?

As my experience in programming increases with each project, I look back at earlier projects and cringe at some of the ways the code is structured or how well i have implemented a design pattern.  These projects are still utilized in production environments (without issue) and have new features implemented on a yearly cycle.
Updating the entire structure is not feasible.  When implementing new features should I  structure the updates with best practices in mind, or should I keep to existing (inferior) structure to maintain consistency with the rest of the project?

A: Leave the code better than you found it
There is always an adrenaline rush to quickly implement some new feature or pattern when you find a bad piece of code but before you jump and clean it up there are few points to bear. Since this is production code and is working its not always suited to clear it off and write yours which will have to be tested rigorously.
You should identify the existing usages and how your new changes are gonna impact it, is it worth the time investing since some might need quick turn around for an issue.
Am i addressing all that was earlier because some functionality do tends to be missed out(at times not always and you find yourself staring at the code again in a weeks time)
In some cases it would be impossible to alter or could have devastating efforts in the sense of timeline, money and maintaining it could be a better option.
So try to work out on some of these lines and i presume you would find more suggestions pouring in, At all times give Readability a higher precedence than optimizations.(unless its really hampering something)

A: You may have answered your own question without realizing it:

These projects are still utilized in production environments (without issue) and have new features implemented on a yearly cycle.

If that is indeed the case, the implementation is probably not as bad as you think it is. If the software works and is relatively easy to maintain, you've nailed it. On top of that, if you can easily add new features without drastic structural changes, then you've really nailed it.
You will always look back on yesterday with what you know today and decide that yesterday is somehow inferior to today. That's what we call growth and improvement, however it doesn't imply that yesterday in some way needs to be fixed.
Why, oh why would you spend any considerable length of time making a maintainable, extendable and functional program be exactly the same thing as it was when you started? Will there be any obvious gains to users that aren't measured in millionths of a second or lines of code that they rarely (if ever) see?
If, during the life cycle of the program you realize that deprecated methods or functions make the existing design not make as much sense as it originally did, you might have to make some adjustments. You might also need to introduce a feature that eventually justifies going back and doing a lot of re-factoring.
Don't go re-factoring something in production just for the sake of re-factoring. The whole goal is to write code that doesn't have to be drastically changed in the future, and it looks like you hit that goal. Why short circuit a success?

A: You need to maintain compatibility, not consistency.

A: Follow the boy scout rule, that is, always leave it cleaner than you found it (including your new code)
That doesn't mean you have to dive in and refactor until it's perfect, it just means incremental refactoring when it makes sense to do so.

A: Tread lightly, for you tread on my dreams.
I think the key to this is buy-in. I'm always an advocate for refactoring and improving the design of existing code but if you end up going on a tangent that no-one else follows your code is going to look so foreign to them that it isn't going to be very helpful. Worse than that, they might get angry at you for revamping all their hard work without at-least some input in the process and offer resistance to it. This area is helped greatly by code reviews. With code reviews everyone in the team gets to see the direction each-other is taking and offer suggestions so that the code base evolves with continued consistency (assuming it started with consistency).
So, try to get code reviews in place if they aren't already. Also, when making a major refactoring (or as an alternative to code reviews) send an email to the team members letting them know your ideas and asking for suggestions or criticisms. If you find that none of this is working and you are getting frustrated with resistance to improvements it might be time to find a job where change is welcomed instead of feared.


text:
Q: How can I save an excel file containing images with different row height in different cells? I am trying out PHPExcel and based on its examples I have written this code:
<?php

require_once "QueryHandler.php";

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

/** Include PHPExcel */
require_once 'PHPExcel/Classes/PHPExcel.php';

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// Set document properties
$objPHPExcel->getProperties()->setCreator("Lajos Arpad")
                             ->setLastModifiedBy("Lajos Arpad")
                             ->setTitle("Import Test Foto")
                             ->setSubject("Import Test Foto")
                             ->setDescription("Import Test Foto")
                             ->setKeywords("office PHPExcel php")
                             ->setCategory("Test result file");

// Add some data
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'cod_comanda')
            ->setCellValue('B1', 'Foto 1')
            ->setCellValue('C1', 'Foto 2')
            ->setCellValue('D1', 'Foto 3')
            ->setCellValue('E1', 'Foto 4')
            ->setCellValue("F1", "Foto 5")
            ->setCellValue("G1", "Foto 6")
            ->setCellValue("H1", "Foto 7");

$objPHPExcel->getActiveSheet()->setTitle('Import Test Foto');

$toContinue = true;
$limit = 0;
$size = 100;

$pictures = QueryHandler::buildSelect("testtable", array("cod_comanda", "poze"), "Created", $limit, $size);

$index = 2;
$activeSheet = $objPHPExcel->getActiveSheet();
$columns = array("B", "C", "D", "E", "F", "G", "H");
foreach ($pictures as $picture) {
    $activeSheet->setCellValue("A".$index, $picture["cod_comanda"]);
    if (strlen($picture["poze"])) {
        $items = explode(",", $picture["poze"]);
        $itemCount = count($items);
        for ($innerIndex = 0; $innerIndex < $itemCount; $innerIndex++) {
            $activeSheet->setCellValue($columns[$innerIndex].$index, $items[$innerIndex]);
        }
    }
    $index++;
}

// Save Excel 2007 file

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("export/Import Test Foto.xlsx");

Current output

Desired output

It exports the kind of stuff which can be seen on the first picture. I would like to be able to export it like shown in the second picture, which involves the Foto columns being near several lines in the A column. Notice that the current code only exports textual data, while at the end I need to export the images, but I think I need to figure out how can I modify the relative height of cells compared to the first column's cells first. How can I achieve that?

A: If you know the resolution of your images, then you can use the methods in the PHPExcel_Shared_Drawing class to convert pixels to cell dimensions (), and vice versa


text:
Q: Simple function hide/show/toggle for a Div I'm trying to  make a Div that is initially hidden to show up and stay toggled unless i do one of the following events (so in that case they hide again):

*

*reclick on the same element that displayed the div on the first hand

*click outside the div (container)

*click outside of a div's children (descendant of the container)

This is the code i come up with :
(#menu_login being the menu on which i click to make the div appear and .bubble being the div in question)

$(document).ready(function(){

$(".bubble").hide();
$("#menu_login").click(function(){
$(".bubble").toggle();
});
$(document).mouseup(function (e)
{
    var container = $(".bubble");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

So first, the hide_on_load function works well, but the toggle and mouseup function seems to be in a conflict when running together.
They work well when i use only one of them (and i really like this mouseup function because of the way it allows me to click on the container's descendants even when outside of the div).
The thing happening is when i click on the menu and toggle the div, if i click it again to untoggle and hide the div my mouseup function creates a conflict :
It looks like because i on the menu again to untoggle and hide the div again, the mouseup function also detects that i clicked outside of my div and hide my div before my toggle function can.
So what happen is that the toggle function won't detect that i clicked the menu to untoggle and hide the div, but that i clicked to toggle and show the div because the mouseup function closed it 0.01sec before.
So i don't really know how to do to have theses two functions working together, i had some kind of idea about adding an exeption that says to the mouseup function not to hide the div if i click on the menu (the same it doesnt close it if i click on a div's descendant) so my toggle function can do it and there is no conflict, but my knowledges in JQuery are non-existent.
exemple :

$(document).mouseup(function (e)
{
    var container = $(".bubble");

    if (!container.is(e.target)  container...
        && container.has(e.target).length === 0)
        // and here : "don't close it if i click on my #menu_login neither
    {
        container.hide();
    }

Any help/suggestion is welcome, sorry if this a bit heavy to read but i tried to be as specific as possible.
Thank you !
-Apatik

A: There are three parts you have to consider:

*

*The toggling action you see when #menu_login is clicked (you have addressed this already). But what's more important is that we want to make sure the click event from this element does not bubble up to the document object, for which we will listen for click as well. This is done by using event.stopPropagation().

*To prevent clicks within the .bubble element from bubbling up, you will have to prevent the event from propagating when originating from it, too.

*Listen to click event bubbling up to the document. Since we used event.stopPropagation() on the anchor element, click events will not bubble from it, but will from the rest of the document (i.e. other elements). We conditionally hide the .bubble element if it is visible, by using .filter().

$(function(){
  $('.bubble')
  .hide()
  .click(function(event) {
    // Stops click event from bubbling to document (point #2)
    event.stopPropagation();
  });
  $('#menu_login').click(function(event){
    // Stops click event from bubbling to document (point #1)
    event.stopPropagation();

    // Toggle visibility (point #1)
    $('.bubble').toggle();
  });
  $(document).click(function() {
    // Hide bubble if visible (point #3)
    // Will listen to click events from all other elements
    // ... except for `#menu_login` because we have
    // ... prevent the click event from bubbling up
    $('.bubble').filter(':visible').hide();
  });
});

Menu login
Bubble


text:
Q: Apply function at grid cell level across layers of a raster file I have a netcdf raster object with multiple layers (time: 30 years * 12 month = 360 steps).
The raster is constituted of multiple grid-cells (say 1000). I want to linearly detrend each month separately and each grid cell separately to obtain a residual raster object with same dimensions as the input.
For a long format data frame with columns [x,y,value,month,year],  I would do it this way:
library(tidyverse)

data %>%
group_by(x, y, month) %>%
      nest() %>%
      mutate(model_trend = map(data,  ~ lm(value ~ year, data = .))) %>%
      mutate(augment_trend  = map(model_trend,  ~ broom::augment(.))) %>%
      unnest(cols = c(augment_trend)) %>%
      ungroup() %>%
      dplyr::select(x, y, year, month, .resid)

I am sure there are much more efficient and similarly easy ways of doing this operation using spatial packages such as terra, stars and so forth.
How do I do that?


text:
Q: JSR-303 inject locale into custom validator I am using Spring 3 and I have the following configuration in my applicationContext.xml:
  <bean id="validationMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
    p:basename="classpath:messages/validation_messages" p:defaultEncoding="UTF-8" p:cacheSeconds="3" />

  <bean id="globalValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource">
      <ref bean="validationMessageSource" />
    </property>
  </bean>

Everything works fine with locales etc.
However, I was wondering if it is possible to inject the locale to a custom validator I have constructed. I have created a @CheckZip annotation for validating Zip codes. But since zip codes have different formats in different countries I am curious whether I could throw the current locale into the validator.

A: Not by injection, but static LocaleContextHolder can help here:
LocaleContextHolder.setLocale(locale); // set locale for your request or based on user settings e.g. inside custom interceptor

and
LocaleContextHolder.getLocale(); // get locale inside your validator

But I'm not sure why you need the locale explicitly, because having a LocaleChangeInterceptor that should work already:
<!-- Declare the Interceptor -->
<mvc:interceptors>
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
          p:paramName="locale" />
</mvc:interceptors>

<!-- Declare the Resolver -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />


text:
Q: Excel COUNTIF Statement A---------------------------B
2012-04-12 12:52...... FC
2011-06-24 10:07......      FC
2011-06-24 10:08......      FC
2012-04-17 0:00 ......  COH
2012-04-12 12:22    ......  FC
2011-06-24 10:08......COH
2011-09-06 14:10......COH
2011-09-01 0:00 ......  COH
Goal: To count the amount of "COH" in field B, within a certian timeframe.
This example I'd like to try for June 1 2011 - June 30 2011
=COUNTIF(A1:A6, ("<2011-06-30" & ">2011-06-01") & IF(B(At current number) "=COH",1,0)
My problem is trying to get that (At current number), because I want to check the value of D at the current selection.
Ex. When the COUNTIF runs, I want it to execute like this

*

*Date is not in range       ////////////////  Count = 0

*Date is in range, B != COH /////  Count = 0

*Date is in range, B != COH /////  Count = 0

*Date is not in range    ////////////////     Count = 0

*Date is not in range       ////////////////  Count = 0

*Date is in range, B = COH  //////  Count = 1

*Date is not in range       ////////////////  Count = 1

*Date is not in range       ////////////////  Count = 1

A: Which version of Excel are you using? In Excel 2007 and later versions try using COUNTIFS with this formula in row 1 copied down
=COUNTIFS(A$1:A1,">="&DATE(2011,6,1),A$1:A1,"<"&DATE(2011,7,1),B$1:B1,"COH")
or in earlier versions you can use SUMPRODUCT
=SUMPRODUCT((A$1:A1>=DATE(2011,6,1))*(A$1:A1<DATE(2011,7,1))*(B$1:B1="COH"))

A: In the first row of column C you could enter:
=IF(AND((A1<DATE(2011,6,30)), (A1>DATE(2011,6,1)),(B1="COH")),1,0)

And then fill all the cells below with this.
Then the sum of all of the values in the C column will be your result.
DATE requires the ends of the date range as (year,month,day)
AND does logical and

If you are set on a single function:
=COUNTIFS(A1:A6,"<2011/6/30",A1:A6, ">2011/6/1",B1:B6,"=COH")

should do the trick too.

Another answer points out that COUNTIFS requires Excel 2007 or better, and an alternative if it is not available.


text:
Q: the max value of every 5 elements in one array with arbitrary length, python3 I have a one-dimensional array. I want to calculate the max value of every 5 elements. The difficult part is the length of the array can be any value, either a multiple of 5 or not.
For example
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

The 1st 5 elements are 0 to 4, so the max value is 4; the 2nd 5 elements are 5 to 9, so the max is 9; the last part has only 3 numbers, 10 to 12, the max value is 12.
The expected results will be
result = [4, 9, 12]

Note that this specific example has 13 numbers, but in reality it can be any other values.
My first idea is, when there are exactly a multiple of 5 numbers (N*5), then I can reshape the arr to a 2 dimensional array (N rows and 5 columns), then use np.amax to get the max value of each row. For example, suppose N = 4
arr = np.arange(20)
arr = arr.reshape(arr.shape[0]/5, 5)
b = np.amax(arr, axis=1)

But the difficult thing is the length of the array can be non-multiple of 5.
How to efficiently do this? Thanks?
By the way, I am using Python 3.

A: You could do this:
result = [max(arr[i:i+5]) for i in range(0, len(arr), 5)]

A: You can first slice your list in such a way that the length of the second list is between 0 and len(original_list) - 1 (using modulo like a[-(len(a) % 5):]), and then take the maximum of the second list, and appending it to the result (which is a list of maximums you get from the method you suggested above) of the first list (which you get like a[:len(a) - (len(a) % 5)]).


text:
Q: percentage formula in crystal report 8.5 I am doing one project using vb6.0+access+crystal report8.5
some error occur during the crystal report.
Query Name
seqquery:
SELECT segment_trans.division_name, sum(segment_trans.Total_value) AS total,
       division_master.Target
FROM segment_trans, division_master
GROUP BY segment_trans.division_name, division_master.Target;

crystal report percentage formula:
{(seqquery.total * 100) / seqquery.Target }

Error: This field name is not known.
note: Total_value and Target field's datatype "Text"
how to solve this ?

A: Try changing this:
sum(segment_trans.Total_value) AS total,

To this:
sum(segment_trans.Total_value) total,


text:
Q: I have multiple different objects which share most attributes, but vary on a few, what methods could I use to model them? I have a few different items which mostly share the same attributes, but then have a few extra/less. In OOP they could be modeled well with inheritance, but postgres' inheritance is limiting and doesn't seem designed for this. An example of the types might be (this isn't the actual example, so don't take it too serious):
CREATE TABLE document (
    id serial not null PRIMARY KEY,
    name text,
    created_date date,
    modified_date date
);
CREATE TABLE document_list (
    id serial not null PRIMARY KEY,
    name text,
    created_date date,
    modified_date date,
    list_length int
);
CREATE TABLE document_index (
    id serial not null PRIMARY KEY,
    name text,
    created_date date,
    modified_date date,
    num_index int,
    index_header text
);

As you can see they share most values except for a few unique ones. This would fit well with inheritance patterns, but I'm not sure of the best way to implement them in postgres.
I've tried creating document, then inheriting the others from it, but this causes problems with foreign keys, as inherit doesn't support them in postgres.
An alternative way I was thinking about was doing:
CREATE TABLE document (
    id serial not null PRIMARY KEY,
    name text,
    created_date date,
    modified_date date
);
CREATE TABLE document_list (
    document_id int not null references document(id) PRIMARY KEY,
    list_length int
);
CREATE TABLE document_index (
    document_id int not null references document(id) PRIMARY KEY,
    num_index int,
    index_header text
);

Is this a good and/or acceptable way of doing it? Or are there better methods I'm missing?


text:
Q: How to use mysql IN comparison function with JDBC This seems simple, but it is impossible to search the web for...
I have a legacy application that uses JDBC directly with no frameworks, and I'm having to add some new features. I'm having issues finding out how to use the IN() function via JDBC.
I would like to have a query like the following
SELECT * from animals WHERE animal_name IN (...)

Where the ... is an array of values.
Using JDBC i would think I would do the following.
PreparedStatement st = conn.prepareStatement("SELECT * from animals WHERE animal_name IN (?);");
st.setArray(arrayVals);
ResultSet rs = st.executeQuery();
....

But this does not work, and I'm finding it next to impossible to find any reference to this on the web.

A: Replace your code with something like:
StringBuilder sb = new StringBuilder("SELECT * from animals WHERE animal_name IN (");
// 1. assemble query parameters
for (int i = 0; i < arrayVals.size(); i++) {
    sb.append("?");
    if (i + 1 < arrayVals.size()) sb.append(",");
}
sb.append(")");
// 2. add the variables
PreparedStatement st = conn.prepareStatement(sb.toString());
for (int i = 0; i < arrayVals.size(); i++) {
    // May need to replace setter depending on type of object
    st.setObject(i + 1, o);
}

As an alternative, using spring JDBCs JdbcTemplate you would replace part 2 with this:
jdbcTemplate.query(sb.toString(), arrayVals.toArray(), animalRowMapper);

JdbcTemplate will determine the sql types needed for each parameter.


text:
Q: How can i add data from txt file to global array I want to read data from a txt file and add it to an array that will be global.
my file has the following data:
Sophia Emily Mary Linda Madison Susan Lily ...
I want them in array
name = [ 'Sophia', 'Emily', 'Mary', 'Linda', 'Madison', 'Susan', 'Lily', ...]
it -> ... means that there is still n amount of data, eg it's thousands
someone advised me to use this
with open('dane.txt') as name:
    contents = name.readlines()

but i don't know how to convert it to global data named 'name'

A: If you have a string separated by spaces, you can do this:
contents = "Sophia Emily Mary Linda Madison Susan Lily"
name = contents.split(" ")

Full code:
name = None

with open("dane.txt") as f:
    contents = f.read()

    name = contents.split(" ")

A: Python doesn't have arrays - it has lists.
Using globals is generally frowned upon. There's often a better way. Consider this:
from functools import cache

@cache
def get_names(filename):
    names = []
    with open(filename) as data:
        for line in map(str.strip, data):
            names.extend(line.split())
    return names

All we need to do is call get_names() with the path to some file that contains the names we're interested in. Providing the contents of that file don't change then second and subsequent calls to get_names() will not cause the file to be opened and read. It will simply return the cached list


text:
Q: Roulette wheel selection in GA: ArrayIndexOutOfBoundsException error Based on this answer I've tried to do my roulette wheel selection in genetic algorithm.
private static final int NUMBER_OF_TOURISTS = 20;

private static int[] roulette(int population[]) {
    int sumProb = 0;
    for (int i = 0; i < population.length; i++) {
        sumProb += population[i];
    }

    int[] rouletteIndex = new int[NUMBER_OF_TOURISTS];
    Random r = new Random();
    for (int i = 0; i < NUMBER_OF_TOURISTS; i++) {
        int numberRand = r.nextInt(sumProb);
//-------------------------------------------------------
        int j = 0;
        while (numberRand > 0) {
            numberRand = numberRand - population[j];
            j++;
        }
        rouletteIndex[i] = j-1;
//-------------------------------------------------------
    }
    return rouletteIndex;
}

after this I get:
[6, 2, -1, 19, 13, 2, 14, 2, 6, 19, 7, 14, 18, 0, 1, 9, 13, 10, 7, 2]

"-1"? But how, when  j  should be always greater than 0.
Is this happen when numberRand = 0 and than while loop doesn't start even once? But how to fix this?

A: Random.nextInt(int bound) returns 0 (inclusive) to specified bound (exclusive).
So your loop:
while (numberRand > 0) {
    numberRand = numberRand - population[j];
    j++;
}

Will not run if nextInt(int bound) returns 0, resulting in j being 0 at: rouletteIndex[i] = j-1;


text:
Q: The comma operator example in ansi c 1999 TC3 When I was trying to figure out, !0's result is implementation defined expecting that it shall be unequal to zero I just read something what confused me.
(By the way may it be on some implementations -1 or 1 or is it strict defined? If any one could me tell in comment would be nice)
But my real question is:
in

6.5.17 Comma operator 2

is said:

If an attempt is made to modify the result of a comma operator or to
  access it after the next sequence point, the behavior is undefined.

In exactly the next line there is an example how to parse a parameter into a function with use of comma operator.
f(a, (t=3, t+2), c);

But the example is in point of my knowledge so far undefined behavior, isn't it?
Since t gets assigned 3 and in the next sequence it gets increased by 2.
But the standard doesn't mention that the example isn't valid.
Or is an assignment to be not understood as modification?

A: *

*!0 evaluates to 1

*In (t=3, t+2), there is a sequence point between the assignment and the access to t. The expression is defined, it evaluates to 5 and leaves the value 3 in t. It would be undefined if there was no sequence point between the two, for instance, (t=3)+(t+2).

A: I'm not sure what prompted you to ask the question.  The section of the standard that you've picked up the example from clearly says:

As indicated by the syntax, the comma operator (as described in this subclause) cannot
  appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists
  of initializers). On the other hand, it can be used within a parenthesized expression or
  within the second expression of a conditional operator in such
  contexts. In the function call
        f(a, (t=3, t+2), c)

the function has
  three arguments, the second of which has the value 5.

Emphasised the relevant portion to clarify your doubt.

A: The comma operator introduces a sequence point, so that behavior should be well defined (first t is set to 3, then 2 is added to t yielding the result 5 but keeping 3 in t).


text:
Q: How put put one transparent button over mapview? I would like to put transparent (map visible under it) button over mapview?
How can i achieve that?

A: Try using this on the button
android:background="@null" or
android:background="@android:color/transparent"
EDIT:
to place over use a relative layout:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.maps.MapView android:id="@+id/google_maps"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="@string/maps_key"/>
<Button android:id="@+id/googlemaps_select_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Select"/>
</RelativeLayout>

A: You could wrap the map in a FrameLayout or something. Then add a button to the FrameLayout and use android:layout_alignParentRight="true" for Right, Left, Top and Bottom. The button will then align it's edges with the edges of the FrameLayout, which should be wrapping the map.


text:
Q: Table Layout setStretchAllColumns(true) inside HorizontalScrollView does not work in Lollipop I have a table layout which I placed inside a HorizontalScrollView, as the number of edittext inside each row of table is dynamic, I am programmitically putting them. The following codes work perfectly fine in version 9 (Pie) ( and also probably in Oreo Go ) but does not work in Lollipop. The xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/activity_main"
tools:context=".MainActivity">

<EditText
    android:id="@+id/mrinp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:hint="Number"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="submit"
    android:onClick="generate"
    />
<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<TableLayout
    android:id="@+id/tbl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:stretchColumns="*"
    android:layout_marginBottom="20dp" />
</HorizontalScrollView>

</LinearLayout>

Main activity
public class MainActivity extends AppCompatActivity {
EditText edr;
TableLayout tl;
LinearLayout myLayout;
int M;
int layoutWidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edr = findViewById(R.id.mrinp);
    tl = findViewById(R.id.tbl);
    tl.setStretchAllColumns(true);

    tl.setBackgroundColor(getResources().getColor(R.color._light_green));

}

public void generate(View view) {
    tl.removeAllViews();

    M = Integer.parseInt(edr.getText().toString());
    int setWidth;

    for (int i = 0; i < M; i++) {
        TableRow tr = new TableRow(this);
        tr.setBackgroundColor(getResources().getColor(R.color.cold));

        for (int j = 0; j < M; j++) {

            if(i==0){
                tl.setColumnStretchable(j, true);
                }

            EditText ed = new EditText(this);
            ed.setMinWidth(70);
            tr.addView(ed, j);
        }

        tl.addView(tr);
    }

}

}

Note that any one of android:stretchColumns="*" or tl.setStretchAllColumns(true); or tl.setColumnStretchable(j, true); works as desired in Pie. Here is the snapshot.

But the above code does not work (none of those three I mentioned) in Lollipop.
Here is the snapshot.

Note that if I replace HorizontalScrollView with LinearLayout in Lollipop it works fine.
Any suggestion?

A: As per this
Add android:fillViewport="true"
<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
     android:fillViewport="true">
<TableLayout
    android:id="@+id/tbl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:stretchColumns="*"
    android:layout_marginBottom="20dp" />
</HorizontalScrollView>


text:
Q: how to replace this part of string - • I'm pulling in a string from an API, which has the characters: •, which should instead be a bullet point, or at least a '-'.
I cant figure out how to replace this in my code using .replace()?
.replace('•', '-');

the above code does not work.
I've also noticed that in the raw string given from the API I'm pulling this from, the characters are capitalised, whereas when I display them through my code, they are lower case?
perhaps this may be part of the issue

A: String.replace does not work like that. If you pass in a string as the first parameter, it replaces instances of the string as a whole. Obviously this will do nothing unless all those characters appear one after another in the exact same order in your input.
The correct syntax to replace all instances of certain characters is using a regular expression:
str.replace(/[•]/g, '-');


text:
Q: Why JSX doesn't run while React works with no problems First thing I'd like to say is that I'm obviously new to React. I did the set up like they said on their website, even for JSX.
When I paste their code it runs, but when I add JSX it doesn't work at all. I've got node.js on my computer too and I've retried it several times but no way. The console says: Uncaught SyntaxError: expected expression, got '<'.
If anyone have any clue why this is not working it would be really helpful. This is my code:
HTML:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <link rel="stylesheet" href="./index.css">
    <link href="https://fonts.googleapis.com/css2?family=Nova+Mono&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">

JS File:
'use strict';

ReactDOM.render(

Hello, world!
,
  document.getElementById('root')
);

Thank so much! :)
EDIT
I found out the problem after watching this video: https://youtu.be/ahh65GQz74g
Basically, I didn't set up Babel correctly as I wasn't placing the folders properly. Plus I left the Babel script in my HTML, which shouldn't be there. If someone else comes here with the same problem, I recommend to do exactly what that video says.
Thanks everyone for your help!

A: Adding the following attribute to your final script tag should do the trick:

It's important to note that this isn't a good practice for production environments, as client-side compiling is slow and wasteful, so you should consider precompiling your scripts and setup your project accordingly.
Update: try modifying the source of babel to the following:

A: Maybe adding "text/babel" and its presets work as well


text:
Q: How to manage cellForRowAtIndexPath for tableViewIndexSearch? how to manage cellForRowAtindexPath Value for TableViewIndexSearch my code is :
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    alphabetDict = [NSDictionary dictionaryWithObject:tempArray forKey:@"alphabet"];

    NSLog(@"alphabetDict Is: %@", alphabetDict);

    [listArray  addObject:alphabetDict];

    NSLog(@"listArray Is: %@", listArray);

    return tempArray;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{
    return 26;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)] autorelease];

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, -5, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    for(section ; section <=[self.tempArray count];section++)

    {

        headerLabel.textAlignment = UITextAlignmentLeft;

        headerLabel.text = [self.tempArray objectAtIndex:section];

        headerLabel.textColor = [UIColor whiteColor];

        headerLabel.backgroundColor = [UIColor clearColor];

        headerLabel.font = [UIFont fontWithName:@"Verdana Bold" size:11];

        [headerView setBackgroundColor:[UIColor orangeColor]];

//        NSLog(@"headerLabel.text:%@", headerLabel.text);
        [headerView addSubview:headerLabel];

        [headerLabel release];

        return headerView;

    }

    return headerView;

}

-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return  23.0;

}

// --------- TableView Delegate and DataSource-----------

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    return [xmlParseArray count];

}

// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    DirectoryCustomCell *directoryCustomCell =(DirectoryCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (directoryCustomCell == nil) {

        directoryCustomCell = [[[DirectoryCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        directoryCustomCell.selectionStyle = UITableViewCellEditingStyleNone;

    }

    UIImageView *searchImg = [[UIImageView alloc]initWithFrame:CGRectMake(292, 0, 28, 360)];

    searchImg.image = [UIImage imageNamed:@"searchindex.png"];

    [directoryCustomCell addSubview:searchImg];

    NSString *companyName = [[xmlParseArray objectAtIndex:indexPath.row ]objectForKey:@"firstname"];
//    NSLog(@"companyName :%@",companyName);

    NSString *flName = [[xmlParseArray objectAtIndex:indexPath.row ]objectForKey:@"title"];

    [directoryCustomCell setDataForEvent1:companyName venue:flName];

    return directoryCustomCell;

}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    return [[collation sectionTitles] objectAtIndex:section];

}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

    return [collation sectionForSectionIndexTitleAtIndex:index];

}

I want to show in sorted form (I mean section headertitle A have the name start from A and so on).
Between Headertitle from A to B these data are common in every section but I want only those starts from A in SectionHeadertitle A and starts from B in headertitle B.

A: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    switch(indexPath.section)
{
// Configure based on section
// Get details corresponding to section
}
    // configure cell and return cell
}

Take a look at this tutorial


text:
Q: What changed between kernels 3.2 and 3.9 that affect MiniDLNA? I'm using Debian testing, and I've problems with MiniDLNA on kernel > 3.2. The DLNA client works about 30 min, after that it lost the connection with the minidlna server and can't discover the server again.
But if I load with an old kernel (3.2) all works fine. The time that minidlna works (30 min) may be related to the notify_interval parameter, which by default is 15 min.
Problem solved. It was related to my network configuration. My network config:
iface br0 inet static
    address 192.168.5.2
    netmask 255.255.255.0
    gateway 192.168.5.1

    bridge_ports eth0
    bridge_stp off
    bridge_maxwait 0
    bridge_fd 0

In 3.5 kernel was added multicast_querier toggle and disabled queries by default which broke my DLNA on bridge interface.
Now I just enable multicast_querier and all works as before.
# echo 1 > /sys/class/net/br0/bridge/multicast_querier

A: It was related to my network configuration. My network config:
iface br0 inet static
    address 192.168.5.2
    netmask 255.255.255.0
    gateway 192.168.5.1

    bridge_ports eth0
    bridge_stp off
    bridge_maxwait 0
    bridge_fd 0

In 3.5 kernel was added multicast_querier toggle and disabled queries by default which broke my DLNA on bridge interface.
Now I just enable multicast_querier and all works as before.
# echo 1 > /sys/class/net/br0/bridge/multicast_querier


text:
Q: React native Card horizontal scrollView and/or FlatList Good day I've been trying to create a scroll for my Card which contains a 4 grid of Images.
The Card is fine but the scrollView makes everything horizontal
Do you suggest I import Card from React-Native-element?
`     {
 import {Card} from 'react-native-elements'
 export default class App extends Component{
 render(){
    return(
             <ScrollView horizontal={true}>
                         <Card  >

                          {
                                <View style={styles.card}>....</View>
                              }
                         </Card>
                      </ScrollView>
      );
         }
           }

`

A: What I understand from your question is, you have multiple images and you need to arrange 4 images in a row then wrap and again 4 in the next row so on and so forth.
So I suggest flatlist. Try the below code,
renderCard = item => {
  <Card image={item} />
}

render() {
  <FlatList
    data={this.state.data}
    renderItem={(item) => this.renderCard(item)}
    horizontal={false}
    noOfColumns={4}
  />
}


text:
Q: Literature on non-Archimedean analogues of basic complex analysis results It looks like there is some literature out there on what might be called 'non-Archimedean complex analysis' e.g. Benedetto - An Ahlfors Islands Theorem for non-archimedean meromorphic functions and Cherry - Lectures on Non-Archimedean Function Theory. I am mainly working on non-Archimedean functional analysis right now and need to become better acquainted with the non-Archimedean analogues of basic results that might be encountered in a first course on complex analysis, up to and including Liouville's Theorem e.g. Cauchy integral formulas, holomorphic functions etc. for a few spectral theory proofs.
Of course I am well aware that with many results there will be no such analogue. What I would like to know is if there exists a good introduction to this area that I could look at, that starts with the fundamentals. For example, is there an analogue of 'holomorphic iff analytic'? Any advice much appreciated.
This relates to my earlier question: Non-emptiness of spectrum  σ(a)  in non-Archimedean Banach algebras

A: Benedetto has a textbook that discusses basic $p$-adic analysis, although his aim is to study $p$-adic dynamics. And it's for a single variable. But might be a good place to get some information.
Dynamics in One Non-Archimedean Variable, Robert L. Benedetto, Graduate Studies in Mathematics, Volume 198, 2019, American Mathematical Society
I'll also mention that these days a lot of $p$-adic analysis is done on Berkovich space, rather than on $\mathbb Q_p$ or $\mathbb C_p$.  An introduction to analysis on the Berkovich line can be found in the book of Baker and Rumely.
Potential Theory and Dynamics on the Berkovich Projective Line,
Matthew Baker, Robert Rumely, Mathematical Surveys and Monographs
Volume 159, 2010, American Mathematical Society.

A: You might like Nonarchimedean Functional Analysis by Peter Schneider; while it's not directly concerned with $\mathbb{C}$, it does discuss properties of nonarchimedean Banach spaces and the like.


text:
Q: java xml parsing between tags What im trying to do is parse xml through java. and i only want a snippet of text from each tag for example.
xml example
<data>\nSome Text :\n\MY Spectre around me night and day. Some More: Like a wild beast
guards my way.</data>

<data>\nSome Text :\n\Cruelty has a human heart. Some More: And Jealousy a human face
</data>

so far i have this
NodeList ageList = firstItemElement.getElementsByTagName("data");
Element ageElement =(Element)ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
out.write("Data : " + ((Node)textAgeList.item(0)).getNodeValue().trim());

im trying to just get the "Some More:....." part i dont want the whole tag
also im trying to get rid of all the \n

A: If you're not restricted to the standard DOM API, you could try to use jOOX, which wraps standard DOM. Your example would then translate to:
// Use jOOX's jquery-like API to find elements and their text content
for (String string : $(firstItemElement).find("data").texts()) {

  // Use standard String methods to replace content
  System.out.println(string.replace("\\n", ""));
}

A: I would take all of the element text and use regular expressions to capture the relevant parts.


text:
Q: TypeScript error when using the Function.prototype.call() method I'm getting an error in TypeScript when I try to use the 'call' method to switch out the 'this' reference.  Is there a more 'correct' way to do this that will get rid of the error?
I can distill it down to this code (although I encountered it when doing the tutorial here: http://www.angular-meteor.com/tutorials/socially/angular2/privacy-and-publish-subscribe-functions on step 9.10.  Using the code of that tutorial directly from github produces the same problem.
Code to reproduce (in addition to 9.10 in the above tutorial):
function testIt(): Object{

    return {};
}

testIt.call(this);

Error generated:
[ts] Supplied parameters do not match any signature of call target.

Edit: Note that I'm getting this issue specifically in Visual Studio Code, and others have demonstrated the error does not arise in all environments.

A: I'm with version 1.5.2 of VSCode and I'm not getting error, try to update it.


text:
Q: Deleting Single Element From Same Function For the following code:
    document.getElementById('text_one').onkeypress = function (e) {
        if (!e) e = window.event;
        var keyCode = e.keyCode || e.which;
        if (keyCode == '13') {
            text = document.getElementById('text_one').value;
            if (text == "" || text === null || text.length > 50) {
                $('#error_msg').show('slow');
                document.getElementById('text_one').disabled = true;
                document.getElementById('text_one').value = "";
                return false;
            } else {
                $('#list').append('
' + text + '

');
                document.getElementById('text_one').value = "";
            }
        }
    };

How would one go about making a function that deletes the element which was clicked? I was thinking that you could somehow create a specific number that increases every time the function is run and use that number to create custom ID's but I'm not sure how to do that.
JS Fiddle: http://jsfiddle.net/2dd5L/ (The CSS is messed up for some reason)

A: Since you are using jQuery it's very simple (in pure JS also just 2 more lines of code):
$('#list').on('click', 'li', function() {
    $(this).remove();
});

Demo: http://jsfiddle.net/2dd5L/1/


text:
Q: (Mongo/Mongoose) How to handle waiting for the result of multiple queries I'm writing a Discord bot that generates weekly Guild stats for text and voice channel usage. My code divides several Mongo queries up into separate methods:
function getTopActiveTextChannels() {
  let topTextChannels = []
  ChannelModel.find({}).sort({"messageCountThisWeek": -1}).limit(topLimit)
   .exec(channels => {
    channels.forEach(c => {
      topTextChannels.push({"name": c.name, "messageCount": c.messageCount})
    })
    console.log(topTextChannels)
    return topTextChannels
  })
}

function getTopActiveVoiceMembers() {
  let topVoiceMembers = []
  UserModel.find({}).sort({"timeSpentInVoice": -1}).limit(topLimit)
  .exec(users => {
    users.forEach(u => {
      topVoiceMembers.push({"username": u.username, "timeSpentInVoice": u.timeSpentInVoice})
    })
    console.log(topVoiceMembers)
    return topVoiceMembers
  })
}

I then have one method that calls both those and (for now) prints the values to console:
function getWeeklyGuildStats(client) {
  let topActiveTextChannels = getTopActiveTextChannels()
  let topVoiceMembers = getTopActiveVoiceMembers()
  let promisesArray = [topActiveTextChannels, topVoiceMembers]

  Promise.all(promisesArray).then(values => {console.log(values)})
}

Executing getWeeklyGuildStats(client) outputs: [ undefined, undefined ]. I am sure I'm not using promises correctly, but when I follow Mongoose's documentation, it tells me to use exec() instead of then(), but I get a channels = null error with that.
Does anything jump out to anyone? This seems like a fairly common pattern. Does anyone have a solution for how to resolve multiple Mongoose queries in a single method?

A: Promise.all should take an array of promises, while your functions are returning normal array, so you need to return the whole query in the helper method which getting the users and channels, then do your logic after the promise.all
your functions may look something like that
function getTopActiveTextChannels() {
  return ChannelModel.find({}).sort({"messageCountThisWeek": -1}).limit(topLimit).exec();
}

function getTopActiveVoiceMembers() {
  return UserModel.find({}).sort({"timeSpentInVoice": -1}).limit(topLimit).exec();
}

then the function that calls these two methods will be something like
function getWeeklyGuildStats(client) {
  let topActiveTextChannels = getTopActiveTextChannels()
  let topVoiceMembers = getTopActiveVoiceMembers()
  let promisesArray = [topActiveTextChannels, topVoiceMembers]

  Promise.all(promisesArray).then(values => {
     console.log(values);
     // here you could do your own logic, the for loops you did in the helper methods before
  });
}

A: You do not have any return statements in the root level of your functions, so they are always synchronously returning undefined. I'm not familiar with the library you're using, but if for example ChannelModel.find({}).exec(callback) returns a promise with the return value of callback as your code implies, then you just need to add a return statement to your functions.
For example:
function getTopActiveTextChannels() {
  let topTextChannels = []
  // Return this! (Assuming it returns a promise.) Otherwise you're always returning `undefined`.
  return ChannelModel.find({}).sort({"messageCountThisWeek": -1}).limit(topLimit)
   .exec(channels => {
    channels.forEach(c => {
      topTextChannels.push({"name": c.name, "messageCount": c.messageCount})
    })
    console.log(topTextChannels)
    return topTextChannels
  })
}


text:
Q: Azure Hybrid Connection SSPI handshake failed I have an instance of Azure Hybrid Connections running on a server where SQL Server is installed.
I hosted an WebApp on azure, set up the hybrid connection and I'm consistently getting the same SSPI Handshake error

SSPI handshake failed with error code 0x8009030c, state 14 while establishing a connection with integrated security; the connection has been closed. Reason: AcceptSecurityContext failed. The operating system error code indicates the cause of failure. The logon attempt failed   [CLIENT: 1x.xx.xx.xxx]

As described here I added the clients ip in the local security policy.
I also tried adding the DisableLoopbackCheck=1 in HKLM\System\CurrentControlSet\Control\LSA, but it didn't help either.
Do I have to fix it on a database level perhaps?

A: As per https://github.com/Huachao/azure-content/blob/master/articles/app-service-web/web-sites-hybrid-connection-connect-on-premises-sql-server.md

[AZURE.NOTE] To ensure that your application uses the database that you created in SQL Server Express, and not the one in Visual Studio's default LocalDB, it is important that you complete this step before running your project.

Edit the connectionStrings section to point to the SQL Server database on your local machine, following the syntax in the following example:

I added user credentials to my connection string in appsettings.json and it now works.


text:
Q: What is most common and correct practice to get a CGFloat from an NSNumber? The working code for me is something like:
NSNumber *n = @42.42;
CGFloat cgf = 0;
CFNumberRef cfn = CFBridgingRetain(n);
CFNumberGetValue(cfn, kCFNumberCGFloatType, &cgf);
CFRelease(cfn);

There could be also
CGFloat cgf = (CGFLOAT_IS_DOUBLE) ? [n doubleValue] : [n floatValue];

But this smells even uglier for me.
It seems to me there should be better API for doing such a common thing. Are there any?

A: Just always get the double value. If CGFloat is only a 'float' on your machine the double will be instantly truncated, so you don't care.

A: This will get the correct result in any case:
 NSNumber *n = @42.42;
 CGFloat cgf = [n doubleValue];

because CGFloat is either float or double.

NSNumber does not have a CGFloatValue method. You could define one
using the toll-free bridge to CFNumberRef:
@interface NSNumber (MyCGFloatValue)
-(CGFloat)myCGFloatValue;
@end

@implementation NSNumber (MyCGFloatValue)
-(CGFloat)myCGFloatValue{
    CGFloat result;
    CFNumberGetValue((__bridge CFNumberRef)(self), kCFNumberCGFloatType, &result);
    return result;
}
@end

or using the C11 feature "Generic selection", where the compiler chooses the appropriate
code depending on the type of CGFloat:
@implementation NSNumber (MyCGFloatValue)
-(CGFloat)myCGFloatValue{
    CGFloat result;
    result = _Generic(result,
            double: [self doubleValue],
            float: [self floatValue]);
    return result;
}
@end

And then
NSNumber *n = @42.24;
CGFloat f = [n myCGFloatValue];

but I doubt that it is worth the hassle.

A: The older answers are both correct. Just for my 2¢, here's my implementation:
@implementation NSNumber (TypeConversion)

- (CGFloat)cgFloatValue
{
#if CGFLOAT_IS_DOUBLE
    return self.doubleValue;
#else
    return self.floatValue;
#endif
}

@end

This relies on the definition of CGFLOAT_IS_DOUBLE in CGBase.h for Objective C, or CoreGraphics.h for Swift:
// Don't write this code; it's already included in Foundation :)

#if defined(__LP64__) && __LP64__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif

typedef CGFLOAT_TYPE CGFloat;
#define CGFLOAT_DEFINED 1

From CoreGraphics.h


text:
Q: Prevent Fancybox from fitting it's height to the view / autoresizing I'm displaying a simple div with some content in a popup, and everything looks fine as long as I'm using Fancybox 1.3.1. In version 2.1.3, if the window is shorter, a vertical scrollbar occurs on the popup and part of the inner content is being hidden.
I've tried setting following options to false, but none of these attempts worked:
$("a.popup").fancybox({
    autoSize : false,
    autoHeight : false,
    autoResize : false,
    fitToView : false
});

Did anyone encounter similar issues?


text:
Q: Listing ec2 details with boto3 in Lambda Is there a way to get results of EC2 describe instances using boto3 in AWS Lambda? The output is preferably in JSON so that it can be parsed by another function. All EC2 instances in the JSON output.

A: Does the provided describe_instances function not do what you need?
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances
import boto3
client = boto3.client('ec2')
client.describe_instances()

You'll find that for almost all of the tools you can access through the AWS CLI, there is a boto3 equivalent, and in many cases, boto3 offers a more refined option in addition to the expected one.


text:
Q: C++ is it possible to have a container of specialized templates objects with different types parameters? I have a templated class Parameter which can (or must) be specialized.
I want to put all my parameters in a container.
How to do this if my parameters are instanciated with different types?
In the class Container, I would like to have a vector<Parameter*> from different types (int, double, ...) or something equivalent which seems to not possible.
If the Parameter class is derived from a base class, then The Container can declare the vect as vector<Base*>. But in this case, we can do nothing specific in Container::foo.
Below is my source example. One of my parameters is a QString which is not compatible with ostream.
Thanks for your comments.

    #include <QString>
    #include <vector>
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;

    #define P(a) cout << #a << ":" << a << endl

    /*
    class Base {

    };
    */

    template<typename T> class Parameter /*: public Base */ {
    private:
        T val;
    public:
        void setVal(const T &val) {
            this->val = val;
        }
        const T &getVal() {
            return val;
        }
        string getFoo() {
            stringstream s;
            s << val;
            return s.str();
        }
    };

    template<>
    string Parameter<QString>::getFoo() {
        stringstream s;
        s << val.toStdString();
        return s.str();
    }

    class Container {
    public:
        void push_back(Parameter *base) {
            vect.push_back(base);
        }
        void foo() {
            /* do something with the parameters */
        }
    private:
        vector<Parameter*> vect;
    };

    int main() {
        Parameter<int> pi;
        Parameter<QString> ps;

        pi.setVal(10);
        ps.setVal("QString");

        P(pi.getVal());
        P(ps.getVal().toStdString());

        P(pi.getFoo());
        P(ps.getFoo());

        Container container;
        container.push_back(&pi);
        container.push_back(&ps);
    }

Many thanks to you comments. I will follow your advice and use boost::any.
Here is the updated version :

    #include <boost/any.hpp>
    #include <QString>
    #include <vector>
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;

    #define P(a) cout << #a << ":" << a << endl

    template<typename T> class Parameter {
    private:
        T val;
    public:
        void setVal(const T &val) {
            this->val = val;
        }
        const T &getVal() {
            return val;
        }
        string getFoo() {
            stringstream s;
            s << val;
            return s.str();
        }
    };

    template<>
    string Parameter<QString>::getFoo() {
        stringstream s;
        s << val.toStdString();
        return s.str();
    }

    class Container {
    public:
        void push_back(boost::any base) {
            vect.push_back(base);
        }
        void foo() {
            cout << "do something with the parameters\n";
            for (vector<boost::any>::iterator i = vect.begin(); i != vect.end(); ++i) {
                boost::any a = (*i);
                if (a.type() == typeid(Parameter<int>*)) {
                    Parameter<int> *ai = boost::any_cast<Parameter<int> *>(a);
                    cout << ai->getFoo() << endl;
                } else if (a.type() == typeid(Parameter<QString>*)) {
                    Parameter<QString> *aq = boost::any_cast<Parameter<QString> *>(a);
                    cout << aq->getFoo() << endl;
                } else {
                    cout << "unknown type:" << a.type().name() << endl;
                }
            }
        }
    private:
        vector<boost::any> vect;
    };

    int main() {
        Parameter<int> pi;
        Parameter<QString> ps;

        pi.setVal(10);
        ps.setVal("QString");

        P(pi.getVal());
        P(ps.getVal().toStdString());

        P(pi.getFoo());
        P(ps.getFoo());

        Container container;
        container.push_back(&pi);
        container.push_back(&ps);
        container.foo();
    }

A: You could use Boost.Any which can hold any type of data. You would then use boost::any_cast<> to convert the object back to the correct type.
Other than that, you'll have to go for the base class approach, but as you mentioned, it could be hard to then make Container::foo do anything useful.
One way you could solve this problem is to have all your foo functions take a string as a parameter, then each specific implementation of the function would parse that string and convert it to the correct type.
Edit: Boost.Any example:
#include <iostream>
#include <boost/any.hpp>

int main()
{
    boost::any param = 89;

    // This will fail because `param` is currently holding an int
    // not a char
    char ch = boost::any_cast<char>(param);

    // This works
    int i = boost::any_cast<int>(param);

    // You can always change the value and type of what
    // `param` is holding
    param = "example";
}

A: The correct solution is to write good enough interface for the Base class so that you can do everything you need to do:
class Base {
public:
  virtual void *GetVal() const=0;
  virtual void SetVal(void *ptr)=0;
  virtual std::string Type() const=0;
  virtual std::string GetAsString() const=0;
};

While this might not be what you want, it still allows passing values from one parameter to the next. Once you want the actual value, you do need to know the type on compile-time. Switch-case for the type might help with making it runtime.

A: Every thing inside a container has to be the same type.  I have done something similar to your approach where I made a base class that had some useful generic interface and the derived class was templated.  The only other way to approach a solution would involve defining a base class function to return a value to indicate the type and then downcasting the base.