问:
Firebase Crashlytics: Missing dsym files
We've moved from fabric.io to Firebase and now the dsym files are always missing. This manual tries to help but I don't really understand it:

Manual: https://firebase.google.com/docs/crashlytics/get-deobfuscated-reports?authuser=0&platform=ios

So which line do I exactly need to implement in the build phases so it does it automatic? This one?
find dSYM_directory -name "*.dSYM" | xargs -I {} $PODS_ROOT/Fabric/upload-symbols -gsp /path/to/GoogleService-Info.plist -p platform {}

But then my other questions: How can I find my dsym_directory? And I mean this is different for every build isn't it? And it also says:

Important: If you're working with an app that you previously linked
  from Fabric to Firebase Crashlytics, pass in your Fabric API Key to
  run the upload symbols script. That is, in the following options to
  run the script, use -a fabric-api-key instead of -gsp
  path/to/GoogleService-Info.plist.

So does this mean I can use the variable fabric-api-key or do I need to replace it exactly with my key? Can someone just help me and give the exact line I have to insert into the build phases?

答:
I used find ${DWARF_DSYM_FOLDER_PATH}" -name "*.dSYM" before the script to find the dsyms.

```<code>"find ${DWARF_DSYM_FOLDER_PATH}" -name "*.dSYM" | xargs -I \{\} "$PODS_ROOT/Fabric/upload-symbols" -gsp "$PODS_ROOT/../GoogleService-Info.plist" -p ios \{\}
</code>```

Body:
I used find ${DWARF_DSYM_FOLDER_PATH}" -name "*.dSYM" before the script to find the dsyms.

"find ${DWARF_DSYM_FOLDER_PATH}" -name "*.dSYM" | xargs -I \{\} "$PODS_ROOT/Fabric/upload-symbols" -gsp "$PODS_ROOT/../GoogleService-Info.plist" -p ios \{\}


来源: stackexchange

问:
Add user to a repo in Azure DevOps
I'm trying to add a user to have permissions for a repo I have recently setup. I've been able to add this same user to repos previously, it's not something that I do frequently though and looking at the online documentation it show's a '+' button should be visible (see below)

However there is no '+' button visible to me (either initially or after I search and select the person I want to add), see below:

I do not believe any permissions have changed for my login since I last did this for another repo, so I wouldn't expect the '+' button to be hidden from me.

答: I've just worked this out (was staring me in the face in fact) - basically they seem to have changed the UI; there's no '+' button now, the options appear to the left and altering these 'adds' the person to the repo!

ContentLicense: CC BY-SA 4.0

Title: Add user to a repo in Azure DevOps


问:
error downloading username by IHttpContextAccessor after publication ASP.NET
I create applications for internal use,

trying to get user login through IHttpContextAccessor

Controller:

```<code>private Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor;

var userName = _httpContextAccessor.HttpContext.User.Identity.Name;

//var userName = @"ad\LOGINUSER";
</code>```

if I extract username using _httpContextAccessor.HttpContext.User.Identity.Name; mam błąd na stronie

Error.
  An error occurred while processing your request.
  Request ID: |77762974-42ec74070b648c99.

Development Mode
  Swapping to Development environment will display more detailed information about the error that occurred.

if I use var userName = @"ad\LOGINUSER";  everything works normally

of course, the error is after publishing, everything works fine in normal compilation on computer

I'm using .net core 3.1

My startup code

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AppEcp.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace AppEcp

{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddMvc();
            services
                .AddHttpContextAccessor();
         //   services
          //      .TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
            services
                .AddAuthentication(IISDefaults.AuthenticationScheme);
            services
                .AddControllersWithViews()
                .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

            // .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });

            var connectionAd = @"Server=wsql3;Database=ActiveDirectory;Trusted_Connection=True;MultipleActiveResultSets=true";
            services.AddDbContext<UzytkownicyDbContext>(options => options.UseSqlServer(connectionAd));

            var connectionUrlop = @"Server=wsql3;Database=ECP;Trusted_Connection=True;MultipleActiveResultSets=true";
            services.AddDbContext<EcpDbContext>(options => options.UseSqlServer(connectionUrlop));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
               // app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
               // app.UseHsts();
            }
          //  app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Ewidencja}/{id?}");
            });
        }
    }
}

</code>```

does anyone know what i have done wrong?

答:
You didn't enable Authentication by UseAuthentication:

```<code>app.UseAuthentication();  // add this line
app.UseAuthorization();
</code>```

Within a Controller, you don't have to access HttpContext by _httpContextAccessor.HttpContext...., you can get the User by HttpContext.User.

Also, it's your duty to check whether the User is null :

```<code>var user = HttpContext.User;
if(user ==null)
{
    ...
}else{
    var userName = user.Identity.Name;
    ...
}
</code>```

Finally, if above changes doesn't fix the problem, could you please show us the logs?

Body:
I create applications for internal use,

trying to get user login through IHttpContextAccessor

Controller:

private Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor;

var userName = _httpContextAccessor.HttpContext.User.Identity.Name;

//var userName = @"ad\LOGINUSER";

if I extract username using _httpContextAccessor.HttpContext.User.Identity.Name; mam błąd na stronie

Error.
  An error occurred while processing your request.
  Request ID: |77762974-42ec74070b648c99.

Development Mode
  Swapping to Development environment will display more detailed information about the error that occurred.

if I use var userName = @"ad\LOGINUSER";  everything works normally

of course, the error is after publishing, everything works fine in normal compilation on computer

I'm using .net core 3.1

My startup code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AppEcp.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace AppEcp

{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddMvc();
            services
                .AddHttpContextAccessor();
         //   services
          //      .TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
            services
                .AddAuthentication(IISDefaults.AuthenticationScheme);
            services
                .AddControllersWithViews()
                .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

            // .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });

            var connectionAd = @"Server=wsql3;Database=ActiveDirectory;Trusted_Connection=True;MultipleActiveResultSets=true";
            services.AddDbContext<UzytkownicyDbContext>(options => options.UseSqlServer(connectionAd));

            var connectionUrlop = @"Server=wsql3;Database=ECP;Trusted_Connection=True;MultipleActiveResultSets=true";
            services.AddDbContext<EcpDbContext>(options => options.UseSqlServer(connectionUrlop));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
               // app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
               // app.UseHsts();
            }
          //  app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Ewidencja}/{id?}");
            });
        }
    }
}

does anyone know what i have done wrong?

Body:
You didn't enable Authentication by UseAuthentication:

app.UseAuthentication();  // add this line
app.UseAuthorization();

Within a Controller, you don't have to access HttpContext by _httpContextAccessor.HttpContext...., you can get the User by HttpContext.User.

Also, it's your duty to check whether the User is null :

var user = HttpContext.User;
if(user ==null)
{
    ...
}else{
    var userName = user.Identity.Name;
    ...
}

Finally, if above changes doesn't fix the problem, could you please show us the logs?


问:
PHPSpreadsheet - Custom Color in Data Series of Chart
Using PHPSpreadsheet to create a custom line graph. I have data loaded into the spreadsheet and it is properly building the graph. However, I am not able to adjust the color of the lines in the graph. When I try to apply a color to my series, the spreadsheet opens but there is some sort of corruption and the graph does not load. Excel tells me that it has removed the graph so that it can open the spreadsheet: 'Removed Part: /xl/drawings/drawing1.xml part.  (Drawing shape)'

I was unable to find any information in the documentation regarding custom chart colors but it was committed and merged into the project earlier this year.

I have checked the source code for my version of PHPSpreadsheet and it does have the updated files/classes that allow for custom chart coloration.

```<code><?php

require_once '/opt/sites/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Title;

$phpsheet = new Spreadsheet();

$phpsheet->setActiveSheetIndex(0);
$phpsheet->getActiveSheet()->setTitle('Worksheet');

$file = "report.xlsx";

header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=\"".$file."\"");
header('Cache-Control: max-age=0');

$phpsheet->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$phpsheet->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$phpsheet->getActiveSheet()->getColumnDimension('C')->setWidth(15);

$r = 1;

$phpsheet->getActiveSheet()->setCellValue('A' . $r, "Date");
$phpsheet->getActiveSheet()->setCellValue('B' . $r, "Val  One");
$phpsheet->getActiveSheet()->setCellValue('C' . $r, "Val Two");

$r++;

while($r<=20)
{
    $randNumOne =  rand(1,100);
    $randNumTwo =  rand(1,100);

    $phpsheet->getActiveSheet()->setCellValue('A' . $r, "2018-04-".$r);
    $phpsheet->getActiveSheet()->setCellValue('B' . $r, $randNumOne);
    $phpsheet->getActiveSheet()->setCellValue('C' . $r, $randNumTwo);

    $r++;
}

/////////////////////////////////////////////////////////
//////////////////////////Error Here/////////////////////
///If I change the two hex codes to NULL, there is no issue but of course then there is no change in color either.
/////////////////////////////////////////////////////////
//////////////////////////Error Here/////////////////////

$dsl=array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', NULL, 1, [], NULL, "d914e0"), //Cause of the error
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', NULL, 1, [], NULL, "2ce81b"), //Cause of the error
);

$x = $r - 1;

$xal=array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$'.$r, NULL, $x),
);

$dsv = array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$'.$r, NULL, $x),
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$'.$r, NULL, $x),
);

$ds = new DataSeries(
    DataSeries::TYPE_LINECHART,
    DataSeries::GROUPING_STANDARD,
    range(0, count($dsv)-1),
    $dsl,
    $xal,
    $dsv
);

$pa = new PlotArea(NULL, array($ds));

$legend = new Legend(Legend::POSITION_RIGHT, NULL, false);

$title = new Title('Sample Chart');

$chart = new Chart(
    'chart1',
    $title,
    $legend,
    $pa,
    0,
    0,
    NULL,
    NULL
);

$chart->setTopLeftPosition('E1');
$chart->setBottomRightPosition('V20');

$phpsheet->getActiveSheet()->addChart($chart);

$Excel_writer = new Xlsx($phpsheet);

ob_end_clean();
$Excel_writer->setIncludeCharts(true);

$Excel_writer->save('php://output');
</code>```

I have no errors/warnings/issues on the server side of things. Everything executes as expected and I get the excel file without issue other than the 'drawing corruption'.

答:
Fixed my issue by replacing 0 with 'gap', seems a recent push changed expected int '0' to string 'gap':

```<code>$chart = new Chart(
   'chart1',
    $title,
    $legend,
    $pa,
    0,
    'gap', //change here from 0 to gap
    NULL,
    NULL
);
</code>```

The push:
https://github.com/PHPOffice/PhpSpreadsheet/commit/144a0cabbc572780d0f49db50243f15b104ce26e#diff-0fa257b790aee274c5c82d3156288e94

ContentLicense: CC BY-SA 3.0

Body:
Using PHPSpreadsheet to create a custom line graph. I have data loaded into the spreadsheet and it is properly building the graph. However, I am not able to adjust the color of the lines in the graph. When I try to apply a color to my series, the spreadsheet opens but there is some sort of corruption and the graph does not load. Excel tells me that it has removed the graph so that it can open the spreadsheet: 'Removed Part: /xl/drawings/drawing1.xml part.  (Drawing shape)'

I was unable to find any information in the documentation regarding custom chart colors but it was committed and merged into the project earlier this year.

I have checked the source code for my version of PHPSpreadsheet and it does have the updated files/classes that allow for custom chart coloration.

<?php

require_once '/opt/sites/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Title;

$phpsheet = new Spreadsheet();

$phpsheet->setActiveSheetIndex(0);
$phpsheet->getActiveSheet()->setTitle('Worksheet');

$file = "report.xlsx";

header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=\"".$file."\"");
header('Cache-Control: max-age=0');

$phpsheet->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$phpsheet->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$phpsheet->getActiveSheet()->getColumnDimension('C')->setWidth(15);

$r = 1;

$phpsheet->getActiveSheet()->setCellValue('A' . $r, "Date");
$phpsheet->getActiveSheet()->setCellValue('B' . $r, "Val  One");
$phpsheet->getActiveSheet()->setCellValue('C' . $r, "Val Two");

$r++;

while($r<=20)
{
    $randNumOne =  rand(1,100);
    $randNumTwo =  rand(1,100);

    $phpsheet->getActiveSheet()->setCellValue('A' . $r, "2018-04-".$r);
    $phpsheet->getActiveSheet()->setCellValue('B' . $r, $randNumOne);
    $phpsheet->getActiveSheet()->setCellValue('C' . $r, $randNumTwo);

    $r++;
}

/////////////////////////////////////////////////////////
//////////////////////////Error Here/////////////////////
///If I change the two hex codes to NULL, there is no issue but of course then there is no change in color either.
/////////////////////////////////////////////////////////
//////////////////////////Error Here/////////////////////

$dsl=array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1', NULL, 1, [], NULL, "d914e0"), //Cause of the error
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$C$1', NULL, 1, [], NULL, "2ce81b"), //Cause of the error
);

$x = $r - 1;

$xal=array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$'.$r, NULL, $x),
);

$dsv = array(
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$'.$r, NULL, $x),
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$'.$r, NULL, $x),
);

$ds = new DataSeries(
    DataSeries::TYPE_LINECHART,
    DataSeries::GROUPING_STANDARD,
    range(0, count($dsv)-1),
    $dsl,
    $xal,
    $dsv
);

$pa = new PlotArea(NULL, array($ds));

$legend = new Legend(Legend::POSITION_RIGHT, NULL, false);

$title = new Title('Sample Chart');

$chart = new Chart(
    'chart1',
    $title,
    $legend,
    $pa,
    0,
    0,
    NULL,
    NULL
);

$chart->setTopLeftPosition('E1');
$chart->setBottomRightPosition('V20');

$phpsheet->getActiveSheet()->addChart($chart);

$Excel_writer = new Xlsx($phpsheet);

ob_end_clean();
$Excel_writer->setIncludeCharts(true);

$Excel_writer->save('php://output');

I have no errors/warnings/issues on the server side of things. Everything executes as expected and I get the excel file without issue other than the 'drawing corruption'.

Body:
Fixed my issue by replacing 0 with 'gap', seems a recent push changed expected int '0' to string 'gap':

$chart = new Chart(
   'chart1',
    $title,
    $legend,
    $pa,
    0,
    'gap', //change here from 0 to gap
    NULL,
    NULL
);

The push:
https://github.com/PHPOffice/PhpSpreadsheet/commit/144a0cabbc572780d0f49db50243f15b104ce26e#diff-0fa257b790aee274c5c82d3156288e94


问:
Trying to connect to firebase function from React app - cors issue?
I'm creating a react application. I have code like this

```<code>async componentDidMount() {
    const questions = await axios.get('getQuestions');
    console.log(questions);
}
</code>```

(I have a baseURL set up for axios and all, so the URL is correct)

I created a firebase function as follows (typescript)

```<code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();
admin.firestore().settings({ timestampsInSnapshots: true });
const db = admin.firestore();

exports.getQuestions = functions.https.onRequest(async (request, response) => {
    const questions = [];
    const querySnapshot = await db.collection('questions').get();
    const documents = querySnapshot.docs;
    documents.forEach(doc => {
        questions.push(doc.data());
    });
    response.json({ questions: questions });
});
</code>```

Now when I build and run firebase deploy --only functions, and then visit the url directly, everything works. I see my questions.

But in the react app, I get the following error

Access to XMLHttpRequest at '.../getQuestions' from origin
  'http://localhost:3000' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

After some googling, I tried

```<code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();
admin.firestore().settings({ timestampsInSnapshots: true });
const db = admin.firestore();

const cors = require('cors')({ origin: true });

exports.getQuestions = functions.https.onRequest(
    cors(async (request, response) => {
        const questions = [];
        const querySnapshot = await db.collection('questions').get();
        const documents = querySnapshot.docs;
        documents.forEach(doc => {
            questions.push(doc.data());
        });
        response.json({ questions: questions });
    })
);
</code>```

But that just gave me an error when I ran firebase deploy --only functions

✔  functions: Finished running predeploy script. i  functions:
  ensuring necessary APIs are enabled... ✔  functions: all necessary
  APIs are enabled i  functions: preparing functions directory for
  uploading...

Error: Error occurred while parsing your function triggers.

TypeError: Cannot read property 'origin' of undefined
      at ...

And tbh, even if this command worked, I don't know if it is the correct solution

答:
This answer will help someone who facing cors error.

01 - Create Firebase Function Called BtnTrigger (You can name whatever you like)

```<code>// Include Firebase Function
const functions =  require('firebase-functions');

// Include Firebase Admin SDK
const admin =  require('firebase-admin');
admin.initializeApp();

//cors setup include it before you do this
//run npm install cors if its not in package.json file
const cors =  require('cors');

//set origin true
const corsHandler =  cors({ origin: true });

//firebase function
export  const BtnTrigger =  functions.https.onRequest((request, response) => {
    corsHandler(request, response, async () => {
    //response.send("test");
    response.status(200).json({ data: request.body });
   });
});
</code>```

Then Run firebase deploy --only functions this will create your firebase function. if you need you can check it from your Firebase Console.

02 - Create Function Trigger from your Application from your application code

i used same BtnTrigger name to understand it properly you can change variable here but httpsCallable params should same as your Firebase Function Name you created.

```<code>var BtnTrigger =firebase.functions().httpsCallable('BtnTrigger');
BtnTrigger({ key: value }).then(function(result) {
    // Read result of the Cloud Function.
    console.log(result.data)
    // this will log what you have sent from Application BtnTrigger
    // { key: value}
});
</code>```

Don't Forget to import  'firebase/functions' from your Application Code

Body:
I'm creating a react application. I have code like this

async componentDidMount() {
    const questions = await axios.get('getQuestions');
    console.log(questions);
}

(I have a baseURL set up for axios and all, so the URL is correct)

I created a firebase function as follows (typescript)

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();
admin.firestore().settings({ timestampsInSnapshots: true });
const db = admin.firestore();

exports.getQuestions = functions.https.onRequest(async (request, response) => {
    const questions = [];
    const querySnapshot = await db.collection('questions').get();
    const documents = querySnapshot.docs;
    documents.forEach(doc => {
        questions.push(doc.data());
    });
    response.json({ questions: questions });
});

Now when I build and run firebase deploy --only functions, and then visit the url directly, everything works. I see my questions.

But in the react app, I get the following error

Access to XMLHttpRequest at '.../getQuestions' from origin
  'http://localhost:3000' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

After some googling, I tried

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();
admin.firestore().settings({ timestampsInSnapshots: true });
const db = admin.firestore();

const cors = require('cors')({ origin: true });

exports.getQuestions = functions.https.onRequest(
    cors(async (request, response) => {
        const questions = [];
        const querySnapshot = await db.collection('questions').get();
        const documents = querySnapshot.docs;
        documents.forEach(doc => {
            questions.push(doc.data());
        });
        response.json({ questions: questions });
    })
);

But that just gave me an error when I ran firebase deploy --only functions

✔  functions: Finished running predeploy script. i  functions:
  ensuring necessary APIs are enabled... ✔  functions: all necessary
  APIs are enabled i  functions: preparing functions directory for
  uploading...

Error: Error occurred while parsing your function triggers.

TypeError: Cannot read property 'origin' of undefined
      at ...

And tbh, even if this command worked, I don't know if it is the correct solution

Body:
This answer will help someone who facing cors error.

01 - Create Firebase Function Called BtnTrigger (You can name whatever you like)

// Include Firebase Function
const functions =  require('firebase-functions');

// Include Firebase Admin SDK
const admin =  require('firebase-admin');
admin.initializeApp();

//cors setup include it before you do this
//run npm install cors if its not in package.json file
const cors =  require('cors');

//set origin true
const corsHandler =  cors({ origin: true });

//firebase function
export  const BtnTrigger =  functions.https.onRequest((request, response) => {
    corsHandler(request, response, async () => {
    //response.send("test");
    response.status(200).json({ data: request.body });
   });
});

Then Run firebase deploy --only functions this will create your firebase function. if you need you can check it from your Firebase Console.

02 - Create Function Trigger from your Application from your application code

i used same BtnTrigger name to understand it properly you can change variable here but httpsCallable params should same as your Firebase Function Name you created.

var BtnTrigger =firebase.functions().httpsCallable('BtnTrigger');
BtnTrigger({ key: value }).then(function(result) {
    // Read result of the Cloud Function.
    console.log(result.data)
    // this will log what you have sent from Application BtnTrigger
    // { key: value}
});

Don't Forget to import  'firebase/functions' from your Application Code


问:
How can I combine the callback of the click event with the callback of the keydown event?
While I was coding, I have noticed that I am repeating the same code twice in two callback functions:

```<code>document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    UI.events.form.password.show();
  }
});
document.querySelector(DOM.next).addEventListener('click', (e)=>{
    e.preventDefault();
    UI.events.form.password.show();
});
</code>```

I have tried to write some algorithm which allows me to implement this goal, but still I am unable to reach that goal.

答:
Introduce a new function and move the common logic to that function.

Please have a look.

```<code>function showPassword(event) {
    event.preventDefault();
    UI.events.form.password.show();
}

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
   showPassword(e);
  }
});

document.querySelector(DOM.next).addEventListener('click', showPassword);
</code>```

I Hope this helps you.

Body:
While I was coding, I have noticed that I am repeating the same code twice in two callback functions:

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    UI.events.form.password.show();
  }
});
document.querySelector(DOM.next).addEventListener('click', (e)=>{
    e.preventDefault();
    UI.events.form.password.show();
});

I have tried to write some algorithm which allows me to implement this goal, but still I am unable to reach that goal.

Body:
Introduce a new function and move the common logic to that function.

Please have a look.

function showPassword(event) {
    event.preventDefault();
    UI.events.form.password.show();
}

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
   showPassword(e);
  }
});

document.querySelector(DOM.next).addEventListener('click', showPassword);

I Hope this helps you.


问:
HTTP POST returns 21201 - No 'To' Number Specified - MS Flow
Looking to send an HTTP POST through Microsoft Flow/Power Automate to make a voice call in Twilio.  I feel like I've tried every iteration possible, but keep getting the error 21201:

```<code>{
  "code": 21201,
  "message": "No 'To' number is specified",
  "more_info": "https://www.twilio.com/docs/errors/21201",
  "status": 400
}
</code>```

Screenshot of Power Automate HTTP Action

I've seen other vids of people using Azure Functions with C# and it feels like I should be able to do what I need here...like, really close.  But I'm not a dev, so maybe I'm way off.  Would appreciate any direction on this.

Thanks!

答:
The issue appears to be you are sending a content type of application/json where Twilio requires application/x-www-form-urlencoded

Creating or Updating Resources with the HTTP POST and PUT Methods

Also found this:

Custom connector action with x-www-form-urlencoded content-type

Body:
Looking to send an HTTP POST through Microsoft Flow/Power Automate to make a voice call in Twilio.  I feel like I've tried every iteration possible, but keep getting the error 21201:

{
  "code": 21201,
  "message": "No 'To' number is specified",
  "more_info": "https://www.twilio.com/docs/errors/21201",
  "status": 400
}

Screenshot of Power Automate HTTP Action

I've seen other vids of people using Azure Functions with C# and it feels like I should be able to do what I need here...like, really close.  But I'm not a dev, so maybe I'm way off.  Would appreciate any direction on this.

Thanks!


问:
When I click in <s:url> with params I have a Unexpected exception in class ActionSupport in Struts2

Introduction

For a project in my IT university I must create the deminer game in a Strut2 application. For the server side I use Tomcat.

You can see what look like the game for the moment :

When I click on a box we must see a number or a mine. For that a case have two params (X and Y) which is use for update the status of the clicked box. And for make a box clickable I use the code :

```<code><a href="
    <s:url action='demineur' method="connexion">
       <s:param name="x" value="#x.index"/>
       <s:param name="y" value="#y.index"/>
    </s:url>
">
</code>```

When we want play at this game, we must enter a username :

When we log in the game, we have a session which is create with the name of player, and in the session we have a save of the game.

And when we interact with the game the save of the game is update

A mine is create with a API (ModeleDemineur:1.1) give by the teacher, and display like its :

demineur.jsp

```<code>    <table>
    <s:iterator status="x" var="ligne" value="cases">
        <tr>
        <s:iterator status="y" var="case" value="ligne">
            <td>
            <s:if test="getCachee()">
                <a href="
                    <s:url action='demineur' method="connexion">
                        <s:param name="x" value="#x.index"/>
                        <s:param name="y" value="#y.index"/>
                    </s:url>
                ">

                    <img src="${pageContext.request.contextPath}/img/cellCovered.png"/>
                </a>
            </s:if>
            <s:else>
                <s:if test="getValeur() == -1">
                    <img src="${pageContext.request.contextPath}/img/mineExploded.png"/>
                </s:if>
                <img src="${pageContext.request.contextPath}/img/box<s:property value='getValeur()'/>.png"/>
            </s:else>
            </td>
        </s:iterator>
        </tr>
    </s:iterator>
    </table>
</code>```

ActionDemineur.java

public class ActionDemineur extends ActionSupport implements SessionAware {

    String username;
    GestionDemineur demineur;
    Plateau plateau;
    Case[][] cases;
    String val;
    String x,y;

    private Map<String, Object> session;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public GestionDemineur getDemineur() {
        return demineur;
    }

    public void setDemineur(GestionDemineur demineur) {
        this.demineur = demineur;
    }

    public Plateau getPlateau() {
        return plateau;
    }

    public void setPlateau(Plateau plateau) {
        this.plateau = plateau;
    }

    public Case[][] getCases() {
        return cases;
    }

    public void setCases(Case[][] cases) {
        this.cases = cases;
    }

    public String getVal() {
        return val;
    }

    public void setVal(String val) {
        this.val = val;
    }

    public String getX() {
        return x;
    }

    public void setX(String x) {
        this.x = x;
    }

    public String getY() {
        return y;
    }

    public void setY(String y) {
        this.y = y;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.session = map;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public String connexion() throws ExceptionLoginDejaPris {
        if(!session.containsKey("user"))
        {
            if(username != null)
            {
                session.put("user", username);
            }
            else {
                return INPUT;
            }
        }

        if(!session.containsKey("plateau")) {
            System.err.println("plateau not found");
            demineur = new GestionDemineur();
            demineur.connexion(username);
            plateau = demineur.getPlateau(username);
            cases = plateau.getMonPlateau();
            session.put("plateau", plateau);
            session.put("user", username);
        }

        username = (String) session.get("user");
        plateau = (Plateau) session.get("plateau");
        cases = plateau.getMonPlateau();
        System.err.println(plateau);

        if(x != null && y != null)
        {
            System.err.println("x and y not null");
            System.err.println(Integer.parseInt(x) + " -- " + Integer.parseInt(y));
            try {
                plateau.decouvrirCase(Integer.parseInt(x), Integer.parseInt(y));
            } catch (BombeException e) {
                session.remove("plateau", plateau);
                session.remove("user", username);
                return "perdu";
            }
            System.err.println(plateau.getMonPlateau()[Integer.parseInt(x)][Integer.parseInt(y)]);

        }
        return SUCCESS;
    }

}
```

<h2>Struts.xml</h2>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>

    <package name="/" extends="struts-default">

        [...]

        <action name="demineur" class="struts.ActionDemineur" method="connexion">
            <result name="input">/WEB-INF/pages/connexionDemineur.jsp</result>
            <result name="success">/WEB-INF/pages/demineur.jsp</result>
            <result name="perdu">/WEB-INF/pages/perduDemineur.jsp</result>
        </action>
    </package>

</struts>
</code>```

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>fr.univ-orleans.ufrst.info.l3.pnt</groupId>
    <artifactId>HelloStruts2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.5.22</version>
        </dependency>

        [...]

        <dependency>
            <groupId>fr.miage.orleans.tp</groupId>
            <artifactId>ModeleDemineur</artifactId>
            <version>1.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>13</source>
                    <target>13</target>
                    <encoding>UTF-8</encoding>
                </configuration>
                <version>3.8.1</version>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.25.v20191220</version>
            </plugin>
        </plugins>
    </build>

    <properties>
        <maven.compiler.source>13</maven.compiler.source>
        <maven.compiler.target>13</maven.compiler.target>
    </properties>
</project>
```

<h1>Errors</h1>

```ERROR ParametersInterceptor Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'x' on 'class com.opensymphony.xwork2.ActionSupport: Error setting expression 'x' with value ['0', ]
ERROR ParametersInterceptor Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'y' on 'class com.opensymphony.xwork2.ActionSupport: Error setting expression 'y' with value ['4', ]
```

My essays

I have tried to add in struts.xml the line xml <interceptor-ref name=params /> but he remove the data in session which have the save of the game and the current user name.

Thanks you for your futur help

答:
I found the answer !

I put a argument method in  but it's a real error !

```<code><s:url var="demineurURL" action='demineur'>
    <s:param name="x" value="#x.index"/>
    <s:param name="y" value="#y.index"/>
</s:url>

<s:a href="%{demineurURL}">
    <img src="${pageContext.request.contextPath}/img/cellCovered.png"/>
</s:a>
</code>```

Body:
Introduction

For a project in my IT university I must create the deminer game in a Strut2 application. For the server side I use Tomcat.

You can see what look like the game for the moment :

When I click on a box we must see a number or a mine. For that a case have two params (X and Y) which is use for update the status of the clicked box. And for make a box clickable I use the code :

<a href="
    <s:url action='demineur' method="connexion">
       <s:param name="x" value="#x.index"/>
       <s:param name="y" value="#y.index"/>
    </s:url>
">

When we want play at this game, we must enter a username :

When we log in the game, we have a session which is create with the name of player, and in the session we have a save of the game.

And when we interact with the game the save of the game is update

A mine is create with a API (ModeleDemineur:1.1) give by the teacher, and display like its :

demineur.jsp

    <s:iterator status="x" var="ligne" value="cases">

        <s:iterator status="y" var="case" value="ligne">

            <s:if test="getCachee()">
                <a href="
                    <s:url action='demineur' method="connexion">
                        <s:param name="x" value="#x.index"/>
                        <s:param name="y" value="#y.index"/>
                    </s:url>
                ">

            </s:if>
            <s:else>
                <s:if test="getValeur() == -1">

                </s:if>
                <img src="${pageContext.request.contextPath}/img/box<s:property value='getValeur()'/>.png"/>
            </s:else>

        </s:iterator>

    </s:iterator>

ActionDemineur.java

public class ActionDemineur extends ActionSupport implements SessionAware {

    String username;
    GestionDemineur demineur;
    Plateau plateau;
    Case[][] cases;
    String val;
    String x,y;

    private Map<String, Object> session;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public GestionDemineur getDemineur() {
        return demineur;
    }

    public void setDemineur(GestionDemineur demineur) {
        this.demineur = demineur;
    }

    public Plateau getPlateau() {
        return plateau;
    }

    public void setPlateau(Plateau plateau) {
        this.plateau = plateau;
    }

    public Case[][] getCases() {
        return cases;
    }

    public void setCases(Case[][] cases) {
        this.cases = cases;
    }

    public String getVal() {
        return val;
    }

    public void setVal(String val) {
        this.val = val;
    }

    public String getX() {
        return x;
    }

    public void setX(String x) {
        this.x = x;
    }

    public String getY() {
        return y;
    }

    public void setY(String y) {
        this.y = y;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.session = map;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public String connexion() throws ExceptionLoginDejaPris {
        if(!session.containsKey("user"))
        {
            if(username != null)
            {
                session.put("user", username);
            }
            else {
                return INPUT;
            }
        }

        if(!session.containsKey("plateau")) {
            System.err.println("plateau not found");
            demineur = new GestionDemineur();
            demineur.connexion(username);
            plateau = demineur.getPlateau(username);
            cases = plateau.getMonPlateau();
            session.put("plateau", plateau);
            session.put("user", username);
        }

        username = (String) session.get("user");
        plateau = (Plateau) session.get("plateau");
        cases = plateau.getMonPlateau();
        System.err.println(plateau);

        if(x != null && y != null)
        {
            System.err.println("x and y not null");
            System.err.println(Integer.parseInt(x) + " -- " + Integer.parseInt(y));
            try {
                plateau.decouvrirCase(Integer.parseInt(x), Integer.parseInt(y));
            } catch (BombeException e) {
                session.remove("plateau", plateau);
                session.remove("user", username);
                return "perdu";
            }
            System.err.println(plateau.getMonPlateau()[Integer.parseInt(x)][Integer.parseInt(y)]);

        }
        return SUCCESS;
    }

}

Struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>

    <package name="/" extends="struts-default">

        [...]

        <action name="demineur" class="struts.ActionDemineur" method="connexion">
            <result name="input">/WEB-INF/pages/connexionDemineur.jsp</result>
            <result name="success">/WEB-INF/pages/demineur.jsp</result>
            <result name="perdu">/WEB-INF/pages/perduDemineur.jsp</result>
        </action>
    </package>

</struts>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>fr.univ-orleans.ufrst.info.l3.pnt</groupId>
    <artifactId>HelloStruts2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.5.22</version>
        </dependency>

        [...]

        <dependency>
            <groupId>fr.miage.orleans.tp</groupId>
            <artifactId>ModeleDemineur</artifactId>
            <version>1.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>13</source>
                    <target>13</target>
                    <encoding>UTF-8</encoding>
                </configuration>
                <version>3.8.1</version>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.25.v20191220</version>
            </plugin>
        </plugins>
    </build>

    <properties>
        <maven.compiler.source>13</maven.compiler.source>
        <maven.compiler.target>13</maven.compiler.target>
    </properties>
</project>

Errors

ERROR ParametersInterceptor Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'x' on 'class com.opensymphony.xwork2.ActionSupport: Error setting expression 'x' with value ['0', ]
ERROR ParametersInterceptor Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'y' on 'class com.opensymphony.xwork2.ActionSupport: Error setting expression 'y' with value ['4', ]

My essays

I have tried to add in struts.xml the line xml <interceptor-ref name=params /> but he remove the data in session which have the save of the game and the current user name.

Thanks you for your futur help

Body:
I found the answer !

I put a argument method in  but it's a real error !

<s:url var="demineurURL" action='demineur'>
    <s:param name="x" value="#x.index"/>
    <s:param name="y" value="#y.index"/>
</s:url>

<s:a href="%{demineurURL}">
    <img src="${pageContext.request.contextPath}/img/cellCovered.png"/>
</s:a>


问:
How to upload a folder to Blob Storage?
I have a worker role that I use to pull data down from Blob Storage OnStart.  Currently I'm testing this by uploading a test.txt file and then downloading it to a local directory.  This is working fine.

I now would like to upload a folder to blob storage.  This folder contains a batch script as well as several executables that the batch script calls.

What is the recommended way to accomplish this?  I think zipping the folder and uploading the *.zip file would be easy...  but then, once I download it locally for the worker role to handle, how would I unzip it without any third party libraries?

If there are better options, I'm open to any suggestions.  Thanks for the help here - this community has been a huge help for me as I ramp up :)

答:
use Azure Storage Explorer. After installing you have to log in and then you can select your Blob and upload folders like a normal upload process.

I ran into the same issue, tried to solve the problem with uploading a zipped folder but there is no option to unzip the folder in Azure.

Title: How to upload a folder to Blob Storage?


问:
why zlib deflateInit calling once not working?
I am currently writing a function which compress the char array using zlib. Since I want to optimize the performance and speed, I want to only call deflateInit() once and reuse zstream object as I want to avoid re-allocation, de-allocation repeatedly. I have tried below method which just updates input and output buffer in zstream object, but it doesn't give correct output from second iteration of while loop. Below is the code:

```<code>#include <stdio.h>

#include <iostream>

#include <string.h> // for strlen

#include <assert.h>

#include <chrono>

#include "zlib.h"

// adapted from: http://stackoverflow.com/questions/7540259/deflate-and-inflate-zlib-h-in-c
int main(int argc, char * argv[]) {
  // original string len = 36
  char a[500] = {};

  for (int i = 0; i < 498; i++) {
    a[i] = 'a';
  }
  a[499] = '\0';

  // placeholder for the compressed (deflated) version of "a"
  char b[500] = {};

  // placeholder for the UNcompressed (inflated) version of "b"
  char c[500] = {};

  printf("Uncompressed size is: %lu\n", strlen(a));
  printf("Uncompressed string is: %s\n", a);

  printf("\n----------\n\n");

  z_stream defstream;
  defstream.zalloc = Z_NULL;
  defstream.zfree = Z_NULL;
  defstream.opaque = Z_NULL;
  deflateInit( & defstream, Z_BEST_COMPRESSION);

  int i = 0;
  while (i < 5) {

    auto t1 = std::chrono::high_resolution_clock::now();

    // setup "a" as the input and "b" as the compressed output

    // STEP 1.
    // deflate a into b. (that is, compress a into b)

    // zlib struct
    int ret;
    char b[500] = {};

    defstream.avail_in = (uInt) strlen(a) + 1; // size of input, string + terminator
    defstream.next_in = (Bytef * ) a; // input char array
    defstream.avail_out = 500;

    defstream.next_out = (Bytef * ) b;
    ret = deflate( & defstream, Z_FINISH); /* no bad return value */
    std::cout << "ret" << ret << std::endl;
    std::cout << "avail_out" << defstream.avail_out << std::endl;

    assert(ret != Z_STREAM_ERROR); /* state not clobbered */

    // This is one way of getting the size of the output
    printf("Compressed size is: %lu\n", strlen(b));
    printf("Compressed string is: %s\n", b);
    std::cout << "Compressed return value is: " << ret << std::endl;
    std::cout << "Avail out is: " << defstream.avail_out << std::endl;
    std::cout << "Compressed length is: " << defstream.total_out << std::endl;

    printf("\n----------\n\n");
    memset(b, 0, 500);

    auto t2 = std::chrono::high_resolution_clock::now();

    std::cout << "Timestamp: Total compression took: " <<
      std::chrono::duration_cast < std::chrono::microseconds > (t2 - t1).count() <<
      " microseconds\n";

    i++;
  }
  deflateEnd( & defstream);

  // inflateEnd(&infstream);

  return 0;
}
</code>```

OUTPUT:

```<code>----------

ret1
avail_out35
Compressed size is: 9
Compressed string is: x�KL#
                           0
Compressed return value is: 1
Avail out is: 35
Compressed length is: 15

----------

Timestamp: Total compression took: 103 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 42 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 41 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 41 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 42 microseconds
</code>```

Here you can see that, I am getting error code -5 (Z_BUF_ERROR) and empty b array from second iteration of while loop. But if I move zlib object declaration and deflateInit() inside while loop, everything works fine. Any explanation?

答:
In the doc of zlib they write:

If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd.

So it needs more buffer, noting you have a buffer of 500 but only say avail is 50, that could be the error else you need some more logic to add more buffer.

Body:
I am currently writing a function which compress the char array using zlib. Since I want to optimize the performance and speed, I want to only call deflateInit() once and reuse zstream object as I want to avoid re-allocation, de-allocation repeatedly. I have tried below method which just updates input and output buffer in zstream object, but it doesn't give correct output from second iteration of while loop. Below is the code:

#include <stdio.h>

#include <iostream>

#include <string.h> // for strlen

#include <assert.h>

#include <chrono>

#include "zlib.h"

// adapted from: http://stackoverflow.com/questions/7540259/deflate-and-inflate-zlib-h-in-c
int main(int argc, char * argv[]) {
  // original string len = 36
  char a[500] = {};

  for (int i = 0; i < 498; i++) {
    a[i] = 'a';
  }
  a[499] = '\0';

  // placeholder for the compressed (deflated) version of "a"
  char b[500] = {};

  // placeholder for the UNcompressed (inflated) version of "b"
  char c[500] = {};

  printf("Uncompressed size is: %lu\n", strlen(a));
  printf("Uncompressed string is: %s\n", a);

  printf("\n----------\n\n");

  z_stream defstream;
  defstream.zalloc = Z_NULL;
  defstream.zfree = Z_NULL;
  defstream.opaque = Z_NULL;
  deflateInit( & defstream, Z_BEST_COMPRESSION);

  int i = 0;
  while (i < 5) {

    auto t1 = std::chrono::high_resolution_clock::now();

    // setup "a" as the input and "b" as the compressed output

    // STEP 1.
    // deflate a into b. (that is, compress a into b)

    // zlib struct
    int ret;
    char b[500] = {};

    defstream.avail_in = (uInt) strlen(a) + 1; // size of input, string + terminator
    defstream.next_in = (Bytef * ) a; // input char array
    defstream.avail_out = 500;

    defstream.next_out = (Bytef * ) b;
    ret = deflate( & defstream, Z_FINISH); /* no bad return value */
    std::cout << "ret" << ret << std::endl;
    std::cout << "avail_out" << defstream.avail_out << std::endl;

    assert(ret != Z_STREAM_ERROR); /* state not clobbered */

    // This is one way of getting the size of the output
    printf("Compressed size is: %lu\n", strlen(b));
    printf("Compressed string is: %s\n", b);
    std::cout << "Compressed return value is: " << ret << std::endl;
    std::cout << "Avail out is: " << defstream.avail_out << std::endl;
    std::cout << "Compressed length is: " << defstream.total_out << std::endl;

    printf("\n----------\n\n");
    memset(b, 0, 500);

    auto t2 = std::chrono::high_resolution_clock::now();

    std::cout << "Timestamp: Total compression took: " <<
      std::chrono::duration_cast < std::chrono::microseconds > (t2 - t1).count() <<
      " microseconds\n";

    i++;
  }
  deflateEnd( & defstream);

  // inflateEnd(&infstream);

  return 0;
}

OUTPUT:

----------

ret1
avail_out35
Compressed size is: 9
Compressed string is: x�KL#
                           0
Compressed return value is: 1
Avail out is: 35
Compressed length is: 15

----------

Timestamp: Total compression took: 103 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 42 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 41 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 41 microseconds
ret-5
avail_out50
Compressed size is: 0
Compressed string is:
Compressed return value is: -5
Avail out is: 50
Compressed length is: 15

----------

Timestamp: Total compression took: 42 microseconds

Here you can see that, I am getting error code -5 (Z_BUF_ERROR) and empty b array from second iteration of while loop. But if I move zlib object declaration and deflateInit() inside while loop, everything works fine. Any explanation?


问:
How to Find an Element to Click on Instagram Unfollow Button
I am making an Instagram bot using selenium and python. I am trying to implement a function which allows a certain amount of followers to be unfollowed. The code navigates to the unfollow screen which has many buttons that say unfollow. The buttons are hard to find with selenium though. If the find_element_by_tag('button') function is used only 3 buttons are found. The button html is:

```<code><button class="_0mzm- sqdOP  L3NKy   _8A5w5    " type="button">Following</button>
</code>```

For some reason, I cannot get selenium to select the element. Are there any ways someone can see how to click it?

答:
Copy the xpath of the button tag and create reference and use for loop to iterate from one unfollow button onto the next, see my github repository

https://github.com/asadamatic/Unfollow-All-On-Instagram/blob/master/unfollowAll.py

Body:
I am making an Instagram bot using selenium and python. I am trying to implement a function which allows a certain amount of followers to be unfollowed. The code navigates to the unfollow screen which has many buttons that say unfollow. The buttons are hard to find with selenium though. If the find_element_by_tag('button') function is used only 3 buttons are found. The button html is:

<button class="_0mzm- sqdOP  L3NKy   _8A5w5    " type="button">Following</button>

For some reason, I cannot get selenium to select the element. Are there any ways someone can see how to click it?


问:
why browser isnt storing a cookie created in a subdomain, in the referer subdomain?
i'm facing a few problems when i authenticate usign cookies to store the token, those cookies should be delivered between subdomains, for example, i have my auth code deployed in a subdomain named services.mydomain.co and my frontend in  subdomain named apps.mydomain.co,
when someone authenticates, then my auth code creates a cookie with the tag Domain like this: Domain=.mydomain.co in order to enable it to be delivered between all subdomains of mydomain.co, but the cruel reallity is that it is not working, even the browser isn't storing the cookie.

the cookie it's successful delivered in response header after authenticate but the browser isn't storing it.

im creating the cookie this way:Set-Cookie: myKey=myKeyValue;path=/;httpOnly;Max-Age=1555520000;Domain=.mydomain.co;sameSite=none

hope someone could geve me an advice and sorry for bad english.

答:
From your example, you are setting SameSite=None without Secure. This is invalid and browsers (Chrome, Edge, Firefox, etc.) will begin rejecting this.

However, you should check DevTools in Chrome on your site to see the specific error. You can check both the Console and individual requests in the Network tab to see issues with a given cookie.

You can find more detail on https://www.chromium.org/updates/same-site/test-debug


问:
How do I search through an array using a string, which is split into an array?
I currently have a half solution to this, but I was wondering if there is a better way to write this. I have the following array with equipment deliveries:

```<code>var deliveries = ["14/02/2020, 11:47,cubicles,A32", "13/02/2020,11:48,relays,A59",etc....]
</code>```

Which I search through using an input:

```<code>var pn = document.getElementById("PN").value;
pn = pn.split(" ");
</code>```

What I'm trying to achieve is to split the search word with spaces, and check if an index in the array contains all of these words. I currently search up to three words, since the code would become too long using my "solution", if I searched for more. This is my code:

```<code>var sArray = []//search results
for(var i = 0; i < deliveries.length; i++){
    if (pn.length == 2) {
        if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])) sArray.push(deliveries[i]);
    }
    else if (pn.length == 3) {
        if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])&& new RegExp(pn[2],"i").test(deliveries[i])) sArray.push(deliveries[i]);
    }
    else {if(new RegExp(pn[0],"i").test(deliveries[i])) sArray.push(deliveries[i])};
}
</code>```

What would be the correct way to search using all the words in the pn array?

I tried saving the if statements as a string, adding code to the string for each index of pn and then using eval. This turned out to slow the search to a crawl though.

Any help would be appreciated.

Example added for a user searching for "cub a32":

```<code>pn = "cub a32"
</code>```

Which turns into:

```<code>pn = ["cub, "a32"]
</code>```

Results in:

```<code>sArray = ["14/02/2020, 11:47,cubicles,A32"]
</code>```

答:
You could filter the array and check with every or some, depending if you want all or just one search string in an item of deliveries.

var deliveries = ["14/02/2020, 11:47,cubicles,A32", "13/02/2020,11:48,relays,A59"],
    input = "cub a32",
    pn = input.toLowerCase().split(' '),
    result = deliveries.filter(s => pn.every(v => s.toLowerCase().includes(v)));

console.log(result);```

Body:
I currently have a half solution to this, but I was wondering if there is a better way to write this. I have the following array with equipment deliveries:

var deliveries = ["14/02/2020, 11:47,cubicles,A32", "13/02/2020,11:48,relays,A59",etc....]

Which I search through using an input:

var pn = document.getElementById("PN").value;
pn = pn.split(" ");

What I'm trying to achieve is to split the search word with spaces, and check if an index in the array contains all of these words. I currently search up to three words, since the code would become too long using my "solution", if I searched for more. This is my code:

var sArray = []//search results
for(var i = 0; i < deliveries.length; i++){
    if (pn.length == 2) {
        if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])) sArray.push(deliveries[i]);
    }
    else if (pn.length == 3) {
        if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])&& new RegExp(pn[2],"i").test(deliveries[i])) sArray.push(deliveries[i]);
    }
    else {if(new RegExp(pn[0],"i").test(deliveries[i])) sArray.push(deliveries[i])};
}

What would be the correct way to search using all the words in the pn array?

I tried saving the if statements as a string, adding code to the string for each index of pn and then using eval. This turned out to slow the search to a crawl though.

Any help would be appreciated.

Example added for a user searching for "cub a32":

pn = "cub a32"

Which turns into:

pn = ["cub, "a32"]

Results in:

sArray = ["14/02/2020, 11:47,cubicles,A32"]


问:
How to alter a API response with Javascript
I wrote this little app that takes in a set of starwars characters and returns images in an array.

```<code>const app = require('express')();
const fetch = require('node-fetch');
const imageSearch = require('image-search-google');
const bodyParser = require('body-parser')

var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(bodyParser.json())

const options = {page:1};

const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => client.search(`${keyword} Wookieepedia`, options)))
 .then(data => firstResult = data.map(result => result[0].url));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()
</code>```

The result of the above code looks like this :

```<code>[ 'https://vignette.wikia.nocookie.net/starwars/images/d/d6/Yoda_SWSB.png/revision/latest?cb=20150206140125',
  'https://vignette.wikia.nocookie.net/starwars/images/d/d9/Luke-rotjpromo.jpg/revision/latest?cb=20091030151422',
  'https://vignette.wikia.nocookie.net/starwars/images/a/a3/ANOVOS_Darth_Vader_1.png/revision/latest?cb=20150128225029' ]
</code>```

But i would like a result where i can know which image belongs to which keyword.  Maybe a format like this or something similar :

```<code>[{<keyword> : <url>}]
</code>```

I tried this :

```<code>const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => {return { [keyword] : [client.search(`${keyword} Wookieepedia`, options)]}    } ))
 .then(data => firstResult = data.map(result => result));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()
</code>```

Results were close but not good :

```<code>[ { yoda: [ [Promise] ] },
  { 'luke skywalker': [ [Promise] ] },
  { 'darth vader': [ [Promise] ] } ]
</code>```

答:
Without using async you could add a then clause to the search promise that combines the keyword value with the result array - or with the first result as shown:

```<code>const getImages = keywords => Promise.all(
     keywords.map( keyword =>
         client.search(`${keyword} Wookieepedia`, options)
        .then( result => ( {[keyword]: result[0]} ))
     )
)
</code>```

Body:
I wrote this little app that takes in a set of starwars characters and returns images in an array.

const app = require('express')();
const fetch = require('node-fetch');
const imageSearch = require('image-search-google');
const bodyParser = require('body-parser')

var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(bodyParser.json())

const options = {page:1};

const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => client.search(`${keyword} Wookieepedia`, options)))
 .then(data => firstResult = data.map(result => result[0].url));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()

The result of the above code looks like this :

[ 'https://vignette.wikia.nocookie.net/starwars/images/d/d6/Yoda_SWSB.png/revision/latest?cb=20150206140125',
  'https://vignette.wikia.nocookie.net/starwars/images/d/d9/Luke-rotjpromo.jpg/revision/latest?cb=20091030151422',
  'https://vignette.wikia.nocookie.net/starwars/images/a/a3/ANOVOS_Darth_Vader_1.png/revision/latest?cb=20150128225029' ]

But i would like a result where i can know which image belongs to which keyword.  Maybe a format like this or something similar :

[{<keyword> : <url>}]

I tried this :

const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => {return { [keyword] : [client.search(`${keyword} Wookieepedia`, options)]}    } ))
 .then(data => firstResult = data.map(result => result));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()

Results were close but not good :

[ { yoda: [ [Promise] ] },
  { 'luke skywalker': [ [Promise] ] },
  { 'darth vader': [ [Promise] ] } ]

Body:
Without using async you could add a then clause to the search promise that combines the keyword value with the result array - or with the first result as shown:

const getImages = keywords => Promise.all(
     keywords.map( keyword =>
         client.search(`${keyword} Wookieepedia`, options)
        .then( result => ( {[keyword]: result[0]} ))
     )
)


答:
Wrap the common code into a new function then call it from the others:</p>

```<code>function displayPassword() {
    UI.events.form.password.show();
}

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    displayPassword();
  }
});

document.querySelector(DOM.next).addEventListener('click', (e)=>{
    e.preventDefault();
    displayPassword();
});
</code>```

Title: How can I combine the callback of the click event with the callback of the keydown event?

Body:
Wrap the common code into a new function then call it from the others:

function displayPassword() {
    UI.events.form.password.show();
}

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    displayPassword();
  }
});

document.querySelector(DOM.next).addEventListener('click', (e)=>{
    e.preventDefault();
    displayPassword();
});


问:
Upsert / merge tables in SQLite
I have created a database using sqlite3 in python that has thousands of tables. Each of these tables contains thousands of rows and ten columns. One of the columns is the date and time of an event: it is a string that is formatted as YYYY-mm-dd HH:MM:SS, which I have defined to be the primary key for each table. Every so often, I collect some new data (hundreds of rows) for each of these tables. Each new dataset is pulled from a server and loaded in directly as a pandas data frame or is stored as a CSV file. The new data contains the same ten columns as my original data. I need to update the tables in my database using this new data in the following way:

Given a table in my database, for each row in the new dataset, if the date and time of the row matches the date and time of an existing row in my database, update the remaining columns of that row using the values in the new dataset.

If the date and time does not yet exist, create a new row and insert it to my database.

Below are my questions:

I've done some searching on Google and it looks like I should be using the UPSERT (merge) functionality of sqlite but I can't seem to find any examples showing how to use it. Is there an actual UPSERT command, and if so, could someone please provide an example (preferably with sqlite3 in Python) or point me to a helpful resource?

Also, is there a way to do this in bulk so that I can UPSERT each new dataset into my database without having to go row by row? (I found this link, which suggests that it is possible, but I'm new to using databases and am not sure how to actually run the UPSERT command.)

Can UPSERT also be performed directly using pandas.DataFrame.to_sql?

My backup solution is loading in the table to be UPSERTed using pd.read_sql_query("SELECT * from table", con), performing pandas.DataFrame.merge, deleting the said table from the database, and then adding in the updated table to the database using pd.DataFrame.to_sql (but this would be inefficient).

答:
Instead of going through upsert command, why don't you create your own algorithim that will find values and replace them if date & time is found, else it will insert new row. Check out my code, i wrote for you. Let me know if you are still confused. You can even do that for hundereds of tables just by replacing table name in algorithim with some variable and changing it for the whole list of your table names.</p>

```<code>import sqlite3
import pandas as pd

csv_data = pd.read_csv("my_CSV_file.csv")           # Your CSV Data Path

def manual_upsert():
    con = sqlite3.connect(connection_str)
    cur = con.cursor()
    cur.execute("SELECT * FROM my_CSV_data")        # Viewing Data from Column
    data = cur.fetchall()

    old_data_list = []                          # Collection of All Dates already in Database table.
    for line in data:
        old_data_list.append(line[0])           # I suppose you Date Column is on 0 Index.

    for new_data in csv_data:
        if new_data[0] in old_data_list:
            cur.execute("UPDATE my_CSV_data SET column1=?, column2=?, column3=? WHERE my_date_column=?",        # it will update column based on date if condition is true
                                                (new_data[1],new_data[2],new_data[3],new_data[0]))
        else:
            cur.execute("INSERT INTO my_CSV_data VALUES(?,?,?,?)",                                              # It will insert new row if date is not found.
                                                (new_data[0],new_data[1],new_data[2],new_data[3]))
    con.commit()
    con.close()

manual_upsert()
</code>```

Title: Upsert / merge tables in SQLite

Body:
Instead of going through upsert command, why don't you create your own algorithim that will find values and replace them if date & time is found, else it will insert new row. Check out my code, i wrote for you. Let me know if you are still confused. You can even do that for hundereds of tables just by replacing table name in algorithim with some variable and changing it for the whole list of your table names.

import sqlite3
import pandas as pd

csv_data = pd.read_csv("my_CSV_file.csv")           # Your CSV Data Path

def manual_upsert():
    con = sqlite3.connect(connection_str)
    cur = con.cursor()
    cur.execute("SELECT * FROM my_CSV_data")        # Viewing Data from Column
    data = cur.fetchall()

    old_data_list = []                          # Collection of All Dates already in Database table.
    for line in data:
        old_data_list.append(line[0])           # I suppose you Date Column is on 0 Index.

    for new_data in csv_data:
        if new_data[0] in old_data_list:
            cur.execute("UPDATE my_CSV_data SET column1=?, column2=?, column3=? WHERE my_date_column=?",        # it will update column based on date if condition is true
                                                (new_data[1],new_data[2],new_data[3],new_data[0]))
        else:
            cur.execute("INSERT INTO my_CSV_data VALUES(?,?,?,?)",                                              # It will insert new row if date is not found.
                                                (new_data[0],new_data[1],new_data[2],new_data[3]))
    con.commit()
    con.close()

manual_upsert()


问:
Getting null while Parsing XML
I'm trying to parse strig xml using JaxB API.

Below is my code

XML

```<code>http://www.devx.com/supportitems/showSupportItem.php?co=38898&supportitem=listing1
</code>```

Pojo Classes

```<code>@XmlRootElement(name = "employees")
public class FileWrapper {
    private LinkedHashSet<Employee> employees;

    public LinkedHashSet<Employee> getEmployees() {
        return employees;
    }

    @XmlElement(name = "employee")
    public void setEmployees(LinkedHashSet<Employee> employees) {
        this.employees = employees;
    }

}
</code>```

Employee.java

```<code>import javax.xml.bind.annotation.XmlAttribute;

public class Employee {
    private String division;

    private String firstname;

    private String id;

    private String title;

    private String building;

    private String room;

    private String supervisor;

    private String lastname;

    public String getDivision() {
        return division;
    }

    @XmlAttribute
    public void setDivision(String division) {
        this.division = division;
    }

    public String getFirstname() {
        return firstname;
    }

    @XmlAttribute
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getId() {
        return id;
    }

    @XmlAttribute
    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    @XmlAttribute
    public void setTitle(String title) {
        this.title = title;
    }

    public String getBuilding() {
        return building;
    }

    @XmlAttribute
    public void setBuilding(String building) {
        this.building = building;
    }

    public String getRoom() {
        return room;
    }

    @XmlAttribute
    public void setRoom(String room) {
        this.room = room;
    }

    public String getSupervisor() {
        return supervisor;
    }

    @XmlAttribute
    public void setSupervisor(String supervisor) {
        this.supervisor = supervisor;
    }

    public String getLastname() {
        return lastname;
    }

    @XmlAttribute
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Override
    public String toString() {
        return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
                + title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
                + ", lastname = " + lastname + "]";
    }
}
</code>```

MainEntry

```<code>public class TestEntryPoint {

    public static void main(String[] args) throws JAXBException {

        JAXBContext jaxbContext = JAXBContext.newInstance(FileWrapper.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        StringReader reader = new StringReader("XML from above link as String");
        FileWrapper person = (FileWrapper) unmarshaller.unmarshal(reader);

        List<Employee> emp = new ArrayList<Employee>(person.getEmployees());

        System.out.println(emp.get(0).getFirstname());
    }

}
</code>```

So when am trying to extract any tag's value its showing null. Is there any problem with my XML's data structure or pojo classes ? I'm stuck in this from last couple of hours.

What am doing wrong ? Canyone suggest please  ?

Thanks

答:
Annotations in Employee class refer to XML attributes instead of the elements.

Here is corrected version:

```<code>public class Employee {

    private String division;

    private String firstname;

    private String id;

    private String title;

    private String building;

    private String room;

    private String supervisor;

    private String lastname;

    public String getDivision() {
        return division;
    }

    @XmlElement(name = "division")
    public void setDivision(String division) {
        this.division = division;
    }

    public String getFirstname() {
        return firstname;
    }

    @XmlElement(name = "firstname")
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getId() {
        return id;
    }

    @XmlAttribute
    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    @XmlElement(name = "title")
    public void setTitle(String title) {
        this.title = title;
    }

    public String getBuilding() {
        return building;
    }

    @XmlElement(name = "building")
    public void setBuilding(String building) {
        this.building = building;
    }

    public String getRoom() {
        return room;
    }

    @XmlElement(name = "room")
    public void setRoom(String room) {
        this.room = room;
    }

    public String getSupervisor() {
        return supervisor;
    }

    @XmlElement(name = "supervisor")
    public void setSupervisor(String supervisor) {
        this.supervisor = supervisor;
    }

    public String getLastname() {
        return lastname;
    }

    @XmlElement(name = "lastname")
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Override
    public String toString() {
        return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
                + title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
                + ", lastname = " + lastname + "]";
    }
}
</code>```

Title: Getting null while Parsing XML

Body:
I'm trying to parse strig xml using JaxB API.

Below is my code

XML

http://www.devx.com/supportitems/showSupportItem.php?co=38898&supportitem=listing1

Pojo Classes

@XmlRootElement(name = "employees")
public class FileWrapper {
    private LinkedHashSet<Employee> employees;

    public LinkedHashSet<Employee> getEmployees() {
        return employees;
    }

    @XmlElement(name = "employee")
    public void setEmployees(LinkedHashSet<Employee> employees) {
        this.employees = employees;
    }

}

Employee.java

import javax.xml.bind.annotation.XmlAttribute;

public class Employee {
    private String division;

    private String firstname;

    private String id;

    private String title;

    private String building;

    private String room;

    private String supervisor;

    private String lastname;

    public String getDivision() {
        return division;
    }

    @XmlAttribute
    public void setDivision(String division) {
        this.division = division;
    }

    public String getFirstname() {
        return firstname;
    }

    @XmlAttribute
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getId() {
        return id;
    }

    @XmlAttribute
    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    @XmlAttribute
    public void setTitle(String title) {
        this.title = title;
    }

    public String getBuilding() {
        return building;
    }

    @XmlAttribute
    public void setBuilding(String building) {
        this.building = building;
    }

    public String getRoom() {
        return room;
    }

    @XmlAttribute
    public void setRoom(String room) {
        this.room = room;
    }

    public String getSupervisor() {
        return supervisor;
    }

    @XmlAttribute
    public void setSupervisor(String supervisor) {
        this.supervisor = supervisor;
    }

    public String getLastname() {
        return lastname;
    }

    @XmlAttribute
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Override
    public String toString() {
        return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
                + title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
                + ", lastname = " + lastname + "]";
    }
}

MainEntry

public class TestEntryPoint {

    public static void main(String[] args) throws JAXBException {

        JAXBContext jaxbContext = JAXBContext.newInstance(FileWrapper.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        StringReader reader = new StringReader("XML from above link as String");
        FileWrapper person = (FileWrapper) unmarshaller.unmarshal(reader);

        List<Employee> emp = new ArrayList<Employee>(person.getEmployees());

        System.out.println(emp.get(0).getFirstname());
    }

}

So when am trying to extract any tag's value its showing null. Is there any problem with my XML's data structure or pojo classes ? I'm stuck in this from last couple of hours.

What am doing wrong ? Canyone suggest please  ?

Thanks

Body:
Annotations in Employee class refer to XML attributes instead of the elements.

Here is corrected version:

public class Employee {

    private String division;

    private String firstname;

    private String id;

    private String title;

    private String building;

    private String room;

    private String supervisor;

    private String lastname;

    public String getDivision() {
        return division;
    }

    @XmlElement(name = "division")
    public void setDivision(String division) {
        this.division = division;
    }

    public String getFirstname() {
        return firstname;
    }

    @XmlElement(name = "firstname")
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getId() {
        return id;
    }

    @XmlAttribute
    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    @XmlElement(name = "title")
    public void setTitle(String title) {
        this.title = title;
    }

    public String getBuilding() {
        return building;
    }

    @XmlElement(name = "building")
    public void setBuilding(String building) {
        this.building = building;
    }

    public String getRoom() {
        return room;
    }

    @XmlElement(name = "room")
    public void setRoom(String room) {
        this.room = room;
    }

    public String getSupervisor() {
        return supervisor;
    }

    @XmlElement(name = "supervisor")
    public void setSupervisor(String supervisor) {
        this.supervisor = supervisor;
    }

    public String getLastname() {
        return lastname;
    }

    @XmlElement(name = "lastname")
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Override
    public String toString() {
        return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
                + title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
                + ", lastname = " + lastname + "]";
    }
}


问:
Limited pods in Kubernetes (EKS) and Airflow
Despite increasing the values of the variables that modify Airflow concurrency levels, I never get more than nine simultaneous pods.

I have an EKS cluster with two m4.large nodes, with capacity for 20 pods each. The whole system occupies 15 pods, so I have room to have 25 more pods but they never reach more than nine.
I have created an escalation policy because the scheduler gets a bit stressed by throwing 500 dags at the same time, but EKS creates an additional cluster that all it does is distribute the nine pods.
I have also tested with two m4.2xlarge nodes, with capacity for almost 120 pods and the result the same despite multiplying by 4 the performance of the system and increasing the number of threads from 2 to 6.

These are the environment variable values that I handle.

```<code>AIRFLOW__CORE__PARALLELISM = 1000
AIRFLOW__CORE__NON_POOLED_TASK_SLOT_COUNT = 1000
AIRFLOW__CORE__DAG_CONCURRENCY = 1000
AIRFLOW__CORE__SQL_ALCHEMY_POOL_SIZE = 0
AIRFLOW__CORE__SQL_ALCHEMY_MAX_OVERFLOW = -1
</code>```

That could be happening?

答:
Something is wrong. If I have two nodes that can host 100 pods. And every pod takes a minute to finish, if I run five hundred pods simultaneously, all the work should end in five minutes. But it always takes between 16-20 minutes. The nodes are never full of pods at full capacity and the pods finish their work but take some time to be deleted. What makes it so slow?

Use Airflow 1.10.9 with this configuration:

```<code>ENV AIRFLOW__CORE__PARALLELISM=100
ENV AIRFLOW__CORE__NON_POOLED_TASK_SLOT_COUNT=100
ENV AIRFLOW__CORE__DAG_CONCURRENCY=100
ENV AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG=100

ENV AIRFLOW__CORE__SQL_ALCHEMY_POOL_SIZE=0
ENV AIRFLOW__CORE__SQL_ALCHEMY_MAX_OVERFLOW=-1

ENV AIRFLOW__KUBERNETES_WORKER_PODS_CREATION_BATCH_SIZE=10
ENV AIRFLOW__SCHEDULER__MAX_THREADS=6
</code>```

Body:
Despite increasing the values of the variables that modify Airflow concurrency levels, I never get more than nine simultaneous pods.

I have an EKS cluster with two m4.large nodes, with capacity for 20 pods each. The whole system occupies 15 pods, so I have room to have 25 more pods but they never reach more than nine.
I have created an escalation policy because the scheduler gets a bit stressed by throwing 500 dags at the same time, but EKS creates an additional cluster that all it does is distribute the nine pods.
I have also tested with two m4.2xlarge nodes, with capacity for almost 120 pods and the result the same despite multiplying by 4 the performance of the system and increasing the number of threads from 2 to 6.

These are the environment variable values that I handle.

AIRFLOW__CORE__PARALLELISM = 1000
AIRFLOW__CORE__NON_POOLED_TASK_SLOT_COUNT = 1000
AIRFLOW__CORE__DAG_CONCURRENCY = 1000
AIRFLOW__CORE__SQL_ALCHEMY_POOL_SIZE = 0
AIRFLOW__CORE__SQL_ALCHEMY_MAX_OVERFLOW = -1

That could be happening?

Body:
Something is wrong. If I have two nodes that can host 100 pods. And every pod takes a minute to finish, if I run five hundred pods simultaneously, all the work should end in five minutes. But it always takes between 16-20 minutes. The nodes are never full of pods at full capacity and the pods finish their work but take some time to be deleted. What makes it so slow?

Use Airflow 1.10.9 with this configuration:

ENV AIRFLOW__CORE__PARALLELISM=100
ENV AIRFLOW__CORE__NON_POOLED_TASK_SLOT_COUNT=100
ENV AIRFLOW__CORE__DAG_CONCURRENCY=100
ENV AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG=100

ENV AIRFLOW__CORE__SQL_ALCHEMY_POOL_SIZE=0
ENV AIRFLOW__CORE__SQL_ALCHEMY_MAX_OVERFLOW=-1

ENV AIRFLOW__KUBERNETES_WORKER_PODS_CREATION_BATCH_SIZE=10
ENV AIRFLOW__SCHEDULER__MAX_THREADS=6


问:
What does it really mean that api configuration exposes depedencies whereas implementation does not, in Gradle?
I have gone through the official doc and many StackOverflow questions about the difference betweenapi and implementation configurations. I think I understand the basic, but I really want to understand what it means by dependencies are exposed or not exposed.

This is what I have got so far. When I publish my Java library (written in Kotlin, but not relevant), the dependency scope in the published pom file is either complie when api is used or runtime when implementation is used, i.e.

```<code>dependencies {
    api "..."
}
<dependency>
      <groupId>...</groupId>
      <artifactId>...</artifactId>
      <version>...</version>
      <scope>compile</scope>
</dependency>
</code>```

```<code>dependencies {
    implementation "..."
}
<dependency>
      <groupId>...</groupId>
      <artifactId>...</artifactId>
      <version>...</version>
      <scope>runtime</scope>
</dependency>
</code>```

So does exposing dependencies in this case really just mean adding them to classpath (compile scope)?

One of the many answers about api vs implementation says it is merely about build optimization, it makes sense that the build time will be reduced if we not adding everything in the classpath maybe?

And a bonus question, the Gradle doc says api configuration comes with java-library plugin, but apparently, I can use it without applying the plugin, how is this possible?

```<code>// Gradle 6.1.1
plugins {
    id 'org.jetbrains.kotlin.jvm' version 'XXX'
}
dependencies {
    api "myLibrary"
}
</code>```

答:
So does exposing dependencies in this case really just mean adding them to classpath (compile scope)?

Yes, it's pretty much just a matter of having them on the consumer's compile classpath or not.

One of the many answers about api vs implementation says it is merely about build optimization, it makes sense that the build time will be reduced if we not adding everything in the classpath maybe?

Well, good software design advocates not exposing internal implementation details. This is why you have public and private class members in the code. You could argue that this principal is solid when it comes to dependencies as well. I see the following benefits:

A consumer does not implicitly start relying on "internal" transitive dependencies. If they did, it would mean that you can't remove them from the library without breaking the consumers.

A reduced classpath may make compilation slightly faster. I don't think it matters a whole lot for normal projects though. Maybe it is more impactful if you rely on Java or Kotlin annotation processors or Groovy AST transformations that feels like scanning the entire classpath through each time.

Not having unnecessary modules on the compilation classpath means a library will not have to be recompiled if those modules changes.

The last one is the biggest benefit in my opinion. Let's say you have a big multi-project where a shared sub-project internally relies on Apache Commons Lang. If you have declared Lang as an api dependency and update it, then all other projects relying on this shared project need to be recompiled. If you declare it as an implementation dependency instead, this will not happen. All those projects will still need to be re-tested of cause as the runtime behaviour might have changed (this is handled correctly by default in Gradle).

And a bonus question, the Gradle doc says api configuration comes with java-library plugin, but apparently, I can use it without applying the plugin, how is this possible?

This is because the Kotlin plugin also declares an api configuration. It has the same semantics as configured by the java-library plugin.

If your project is a multi-project, you can still add the java-library plugin even if it is using the Kotlin plugin. An additional change that this will cause is that consumers will see the output directory for the compiled classes instead of the final jar file. This removes the need to construct the jar during normal development, which should reduce build time. On the other hand, there is apparently a potential performance problem on Windows if you have a lot of classes in a single project, so the usual your mileage may vary disclaimer applies here as well (I don't know how many "a lot" is though).

Body:
I have gone through the official doc and many StackOverflow questions about the difference betweenapi and implementation configurations. I think I understand the basic, but I really want to understand what it means by dependencies are exposed or not exposed.

This is what I have got so far. When I publish my Java library (written in Kotlin, but not relevant), the dependency scope in the published pom file is either complie when api is used or runtime when implementation is used, i.e.

dependencies {
    api "..."
}
<dependency>
      <groupId>...</groupId>
      <artifactId>...</artifactId>
      <version>...</version>
      <scope>compile</scope>
</dependency>

dependencies {
    implementation "..."
}
<dependency>
      <groupId>...</groupId>
      <artifactId>...</artifactId>
      <version>...</version>
      <scope>runtime</scope>
</dependency>

So does exposing dependencies in this case really just mean adding them to classpath (compile scope)?

One of the many answers about api vs implementation says it is merely about build optimization, it makes sense that the build time will be reduced if we not adding everything in the classpath maybe?

And a bonus question, the Gradle doc says api configuration comes with java-library plugin, but apparently, I can use it without applying the plugin, how is this possible?

// Gradle 6.1.1
plugins {
    id 'org.jetbrains.kotlin.jvm' version 'XXX'
}
dependencies {
    api "myLibrary"
}